Back to Community
How to get the past N periods of returns?

I'm trying to create an indicator which is a function of the asset's past N days of returns. How do I obtain this?

Given that I have:

def initialize(context):  
    context.spy = sid(8554)  
    spy_price = context.spy

I'd like to get the daily returns of SPY, and then create a function which is the average daily return over the past N days. For example, something like this:

spy_returns = (The daily returns of SPY....)

spy_returns_ave = spy_returns.rolling(60).mean()

In the end, I want to create an indicator that behaves like this: If spy_returns_ave < x, Buy SPY... etc.

3 responses

Hi Yan, this may get you started in the right direction. It takes the 60 day avg returns of each asset minus SPY's 60 day avg. Here's the link for reference

class Mean_Diff_Return_From_SPY(CustomFactor):  
    # Daily return  
    returns = Returns(window_length=2)  
    # Daily return of SPY ETF  
    returns_spy = returns[symbols('SPY')[0]]  
    # inputs for compute function below  
    inputs = [returns,returns_spy]  
    # Set window-length to 60 days (number of days returns to average)  
    window_length = 60  
    def compute(self, today, assets, out, returns, returns_spy):  
        # Calculates the average 60-day return against SPY  
        out[:] =  (returns - returns_spy).mean(axis=0)  
def make_pipeline():

    # Base universe set to the QTradableStocksUS  
    base_universe = QTradableStocksUS()  
    avg_outperf=Mean_Diff_Return_From_SPY()  
    # filter for stocks to sell  
    sell_signal=avg_outperf>0.05  
    # filter for stocks to buy  
    buy_signal=avg_outperf<-0.05  

Hi, thanks for that. Though I was wondering if there was just a simple way to obtain the past return series.

For example, I use this function to obtain the trailing 26 days of prices:

    hist = data.history(context.spy, 'price', 26, '1d')  

But is there something like this for periodic returns? i.e. :

    hist = data.history(context.spy, 'return', 26, '1d')  

Try this:

# -------------------------------  
SEC = symbol('SPY'); PERIOD = 26;  
# -------------------------------  
def initialize(context):  
    schedule_function(indicator, date_rules.every_day(), time_rules.market_close(minutes = 1))    

def indicator(context, data):  
    average_dayly_returns = data.history(SEC, 'price', PERIOD + 1, '1d').pct_change()[1:].mean()        

    record(average_dayly_returns = average_dayly_returns)