Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with forward returns and addition of (trading) days

My goal is to:

  • find stocks that meet my criteria on trading days,
  • buy them (at the closing price for that day)
  • and analyze returns in 1D, 5D (or really any # of days).

In research, Pipeline gives me back a list of stocks in a multi-index dataframe.

                                                   Close  
2017-01-03 00:00:00+00:00 Equity(2127 [DE])      103.050  
                          Equity(3455 [HAR])     111.170  
                          Equity(7041 [TRV])     122.450  
                          Equity(19675 [BP])      37.385  
2017-01-04 00:00:00+00:00 Equity(2127 [DE])      104.045  
                          Equity(6653 [T])        43.000  
                          Equity(19675 [BP])      38.000  
                          Equity(27487 [RDS_A])   55.230  
                          Equity(33655 [HYG])     86.950  
                          Equity(33748 [RSX])     21.630  
                          Equity(35175 [JNK])     36.625  
                          Equity(39116 [HEDJ])    58.120  
                          Equity(41636 [MPC])     52.930  

My current strategy is to simply to loop to calculate percentage change.

start = '2017-01-03'  
end = '2017-01-09'

for date, new_df in stocks.groupby(level=0):  
    walk_forward_returns = get_pricing(new_df.index.get_level_values(1), fields='price', start_date=start, end_date=end).pct_change()[1:]  
    walk_forward_returns = np.mean(walk_forward_returns)  
    print walk_forward_returns  

My questions are:

  1. How do I add 5 (or x) trading days
  2. Is there a different approach I should be taking?

Thanks.

3 responses

Hi Max, great questions.

Quantopian provides a tool called Alphalens that allows you to do just this! Just pass a multi-indexed dataframe from a pipeline and corresponding pricing data to alphalens.utils.get_clean_factor_and_forward_returns(). Lesson 2 of the Alphalens tutorial shows you how to do this.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thanks Cal! I reviewed it and had some questions here.

The way I'm using pipeline is to select stocks on a certain day that I would've purchased based on a combination of rules (SMA, SPY movements, close price near 52 week high). I'm having trouble understanding what factor to return from pipeline to use in get_clean_factor_and_forward_returns()? Pipeline seems to be acting more as a screen for me.

Am I thinking about this correctly? Thanks

Max,

Pipeline API allows you to define a trading universe with filter terms, and express alpha factors with factor terms. A rule like "close price near 52 week high" is a true or false statement, and is best expressed as a filter. A factor is something that returns a number, like "fast moving average's distance from slow moving average."

The essence of using pipeline is creating factor terms that predict the future movement of asset prices, then filtering those results using filter terms. You then pass the numbers produced by the pipeline to Quantopian's Optimizer, which goes long on assets with high factor values, and short on assets with low factor values.

The pipeline below expresses the following idea: Go long on stocks whose fast moving average is above it's slow moving average. Only consider stocks that have had positive returns in the past year.

from quantopian.pipeline import Pipeline  
from quantopian.research import run_pipeline  
from quantopian.pipeline.factors import Returns, SimpleMovingAverage  
from quantopian.pipeline.data import USEquityPricing  
from quantopian.pipeline.filters import QTradableStocksUS

def make_pipeline():  
    fast_SMA = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=5)  
    slow_SMA = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=21)

    # This is a factor that will produce numbers. Factors go in a pipeline column  
    fast_SMA_minus_slow_SMA = fast_SMA - slow_SMA

    yearly_returns = Returns(window_length=252)

    # This is a filter that will produce a true / false value. Filters go in a pipeline screen  
    has_positive_yearly_returns = yearly_returns > 0

    return Pipeline(  
        columns = {'fast_SMA_minus_slow_SMA': fast_SMA_minus_slow_SMA},  
        screen=QTradableStocksUS() & fast_SMA_minus_slow_SMA.notnull() & has_positive_yearly_returns  
    )

run_pipeline(make_pipeline(), '2016-1-1', '2017-1-1')  

For more information on how to create and combine factors, I recommend checking out the Combining Factors lesson on the Pipeline API tutorial.