Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Custom Factor to calculate percentage change for different time windows

Hello,
I am trying to figure out how to develop a custom factor that gives me the percentage change of the configured time window.
In my example pct_10days is supposed to give me the percentage change of the closing price between 10 days ago and yesterday.
pct_1days should give me the percentage change between the day before yesterday and yesterday.

The Formula used is ( (close[-1] - close[0]) / close[0]) *100

However when I compare the result with the chart in the stock the result doesnt match.
And the pct_1days only returns 0
Can you guys help me out with this formula.
Thanks.

3 responses

In order to get the n day percent change, one needs to use n+1 data points. Simply set the window length in your custom factors to n+1 (where n is the desired percent change window). So for a 1 day return set window_length to 2, for a 10 day return set it to 11.

class pct_10days(CustomFactor):  
    inputs = [USEquityPricing.close]  
    # to get n day returns one needs n+1 data points  
    window_length = 10+1

    def compute(self, today, assets, out, close):  
        out[:] = ((close[-1] - close[0]) / close[0]) * 100  

If all one really wants is the percent change, there is a built in factor Returns (https://www.quantopian.com/help#built-in-factors).

return_10_day = Returns(window_length = 11)

Hi Dan,
thank for your quick reply.
I assumed that close[0] will give me the close from yesterday and close[1] the close from day before yesterday and so on
Not sure why +1 but it is working
Thank you so much.

ps. the build in factor Returns is very useful

just noticed that pct_1days is showing me the condition from yesterday