Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Pipeline: How do I create a factor for the standard deviation of past daily returns?

Hello, I cant seem to make a functional factor. Below is my closest attempt.

class pathquality(CustomFactor):  
    def compute(self, today, assets, out, values):  
        out[:] = np.nanstd(np.diff(values), axis = 0)

def make_pipeline():  
    base_universe = Q1500US()

    # Factor of yesterday's close price.  
    yesterday_close = USEquityPricing.close.latest  
    lastyearsreturns = Returns(window_length = 252)  
    quality = pathquality(inputs = [USEquityPricing.close], window_length = 252)  
    pipe = Pipeline(  
        screen = base_universe,  
        columns = {  
            'pathquality' : quality,  
            'close': yesterday_close,  
            'annual_returns': lastyearsreturns  
        }  
    )  
    return pipe  
result = run_pipeline(make_pipeline(), start_date = '2012-01-01', end_date = '2012-02-01')  
result.head()  

What happens instead is an error: could not broadcast input array from shape (7906) into shape (7907)
I would imagine its because of the NaN value at the start of the np.diff calculation?
I would appreciate any help at all

Thank you!

2 responses

You need to specify the '.diff' method to take the differences of rows (ie the dates) and not the columns (ie the securities). Set axis = 0. Something like this..

class pathquality(CustomFactor):  
    def compute(self, today, assets, out, values):  
        out[:] = np.nanstd(np.diff(values, axis=0), axis = 0)

Good luck.

Thank you very much!