Rolling pct_ret in pipeline

I am new to quantopian but have some experience with python. I am having trouble wrapping my head around pipeline and how to manipulate the values. I would like to find the total pct return for n number of days, something that is easily done in pandas.

import pandas as pd
def rolling_pct(n)
df.rolling(n).pct()


is there a way to do the same function in pipeline so I can use it as a factor?

1 response

If what you want is simply the n day return for each security (ie price_yesterday/price_n_days_ago - 1) then use the built in 'Returns' factor (see https://www.quantopian.com/help#built-in-factors). Set the 'window_length' to the number of days over which to calculate the returns.

return_5_day = Returns(window_length = 5)



You could create a custom factor to do this too.

class My_Returns(CustomFactor):
# Define inputs
inputs = [USEquityPricing.close]
# Set window_length to whatever number of days to lookback as a default
window_length = 2
def compute(self, today, assets, out, close):
# Note that close is a numpy array and NOT a pandas dataframe
out[:] = (close[-1] / close[0]) -1


If you need to get the log returns then make a custom factor something like this

class Log_Returns(CustomFactor):
# Define inputs
inputs = [USEquityPricing.close]
# Set window_length to whatever number of days to lookback as a default
window_length = 2
def compute(self, today, assets, out, close):
out[:] = np.log(close[-1]) - np.log(close[0])



If you are having trouble understanding pipelines maybe look at this post https://www.quantopian.com/posts/need-help-with-pipeline-just-a-beginner. Some good info.