Back to Community
Need help in calculating returns

How do I calculate the monthly returns over a six-month period?

2 responses

There are many ways to do this.
Here is one for IDE using data.history():

# Monthly Returns  
# -----------------------------------------------------  
STOCK, DAYS_IN_PERIOD, N_PERIODS = symbol('SPY'), 21, 6  
# -----------------------------------------------------  
def initialize(context):  
    schedule_function(monthly_return, date_rules.month_end(), time_rules.market_close())

def monthly_return(context, data):  
    bars_d = (N_PERIODS + 1)*DAYS_IN_PERIOD  
    Monthly_Close = data.history(STOCK, 'close', bars_d, '1d').resample('M').last()  
    Monthly_Returns = Monthly_Close.pct_change()[-N_PERIODS:]

    print Monthly_Returns