Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
loop historical price series for each stock in Q500US universe

Hi the Mighty Community,

It seems to be a super easy thing to do but I just cant seem to get it work..

Basically I'm trying to write some index arbitrage strategy:

Some pseudo code ###

for each stock in Q500US():
check_cointegration_with_spy(stock, window_length)

My question is: how to use make_pipeline() to generate an output (maybe pandas DataFrame) that has every stock in Q500US() for a given time window?

I tried to output just USEquityPricing.close with 'screen=Q500US()', but there's no way to define a time window?

Thanks in advance!!

2 responses

Factors return a single scaler value per output. There's no way to get a time series or dataframe from a factor.

One could simply use the 'data.history method (https://www.quantopian.com/help#ide-history) to get a dataframe of prices for each security. Use the pipeline to fetch all the securities in Q500US then pass that list to the 'data.history' method. Finally, do whatever calculations one wishes with those prices. However, that approach would be slower than doing the same calculations inside the pipeline. For arbitrarily complex calculations consider writing a custom factor.

Here is an example of how one can pass log returns for the universe of securities, along with the log returns for a single security, to the 'compute' function of a custom factor.

class Mean_Diff_Log_Return_From_SPY(CustomFactor):  
    '''  
     Returns the mean of the difference of 1 day log returns from SPY.  
     window_length is the number of days to average. Default is a single day but can can be over-ridden.  
    '''


    returns = Returns(window_length=2).log1p()  
    returns_spy = returns[symbols('SPY')]  
    inputs = [returns, returns_spy]  


    # Set window_length to number of days returns to average  
    window_length = 1  


    def compute(self, today, assets, out, returns, returns_spy):  
        # This is just a sample of the kind of logic one could do inside of the compute method  
        out[:] =  (returns - returns_spy).mean(axis=0)  

Attached is a notebook with this same example in action. This may be the approach to use to check for co-integration with SPY?

Oops. Forgot to attach the notebook...