Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Computing YTD equity % returns in Quantopian Notebook

Hello, I am trying to come up with a way to compute YTD stock price % returns and later on, 6,3, and 1 month returns on stock equities. I believe that you would be able to compare the returns if the start date and end date were a year apart and you compared the pipeline output from the first and last day...but this seems very computationally expensive.

I also considered having two pipelines pull up snapshots of certain days, but this feels very redundant and not a good idea...

Is there anything in Fundamentals or USEquityPricing that can let me compute this information so that I can have this all in the pipeline dataframe output?

2 responses

Not sure if this is exactly what you want...

Use the 'resample' method to get the 1mo, 3mo,and annual returns. Something like this.

prices = get_pricing([msft, ibm], start_date="2016-1-1", end_date="2018-2-1", fields=['price'], frequency='daily')  
prices_first_of_the_month = prices.price.resample('M', label='left', loffset='1d').first()  
monthly_returns = prices.price.resample('M', label='left', loffset='1d').first().pct_change()

You will want to play around with how prices are filled in the case that the first isn't a trading day. See attached notebook.

Good luck.

This code for IDE may help you.

# ------------------------------------------  
stk, m1, m3, m6 = symbol('QQQ'), 21, 63, 126  
# ------------------------------------------  
def initialize(context):  
    schedule_function(record_returns, date_rules.month_start(), time_rules.market_open(minutes = 35))

def record_returns(context, data):  
    R_m1 = data.history(stk, 'price', m1 + 1, '1d').pct_change(m1)[-1]  
    R_m3 = data.history(stk, 'price', m3 + 1, '1d').pct_change(m3)[-1]  
    R_m6 = data.history(stk, 'price', m6 + 1, '1d').pct_change(m6)[-1] 

    record(R_m1 = R_m1, R_m3 = R_m3, R_m6 = R_m6)