Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Historical average of daily returns

All,
I have I think a simple question, I've checked other older posts but still I'm not sure I understand how to achieve the following.
Just to avoid misunderstanding, assuming today is say Feb 15,2006, for daily percent return I mean the price change from yesterday's (Feb 14) to today's close price.

Checking online historical data I can see the historical daily returns are:
Feb 13, 2006 daily return = -0.18%
Feb 14, 2006 daily return = 1.06%
Feb 15, 2006 daily return = 0.35%

My goal is to have the average of the last 3 daily returns. In this case I would want to schedule a function, run it one minute before the market close and on Feb 15, 2006 see something very very close to (-0.18% + 1.06% + 0.35%) / 3 = 0.41%

I tried to use what discussed in:
https://www.quantopian.com/posts/calculate-daily-returns-for-the-past-x-days

but I get really wrong results.
Basically I'm trying to implement a strategy that needs to enter a trade at the end of the day if the average of the 3 most recent daily returns is above or below a specific value.

As easy as it sound, I'm so bad I can't figure out how to get the right data :(
Any chance somebody could help me?
Many thanks,

Angel

5 responses

Hi Angel,

Typically, for this type of help, it's much easier if you share your code so that we the community can see what you're doing and potentially suggest a fix or improvement. If you don't feel comfortable sharing your strategy, perhaps you could create a copy that highlights the problem without revealing important parts of your algorithm?

My suggestion for a 3-day mean Returns factors would be to use Pipeline. Pipeline allows you to create factors which you can then use to select and weight securities. Check out the Pipeline Tutorial. In particular, I think lessons 3 and 4 might be helpful.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hello Jamie,
Many thanks for your suggestion, much appreciated. I will definitely share this weekend the code. It's literally a few lines of code.
I thought to ask you because perhaps other people had already coded something similar.
If in the meantime you could also shed some light, all I'd really need is the code to calculate a simple moving average of the last X daily returns.
Even the simplest of the code would be of great help.
Thanks,
Angel

Hi,
this is the code that, as mentioned, I copied from the post above.
I think the code isn't right, but I can't figure out why.
Thanks!


import numpy as np  
import datetime  
import pandas as pd

def initialize(context):  
    context.security = sid(8554) #spy  
def handle_data(context, data):  
    context.exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')  
    hist = data.history(context.security, "close", 3, "1d")  

    # Getting the daily returns  
    simple_returns = hist.pct_change()  
    log_returns = np.log(hist / hist.shift(1))  
    # Getting the average return  
    avg_simple_return = simple_returns.mean()  
    avg_log_return = log_returns.mean()  
    if context.exchange_time.hour == 15 and context.exchange_time.minute == 59:  
        print "3 most recent close prices:"  
        print str(round(hist[-3],3)) + ", " + str(round(hist[-2],3)) + ", " + str(round(hist[-1],3))  
        #print str(round(avg_simple_return[-1],6)*100) + "%"  

    # Standard deviation of returns  
    stdev = simple_returns.std()  

Angel, your code looks close, with one big problem. And there are a handful of things that can be better.

  • If you want the returns of 3 days, you actually need 4 days worth of close prices. The returns calculation depends on 2 days of data, and if you try to compute a return with only one price, you get a NaN.
  • Don't run things in handle_data() unless you need it every minute. It slows your backtest down. Use schedule_function() instead.
  • You have standard deviation in your code, but you don't use it. Delete the useless stuff.

I'm attaching a backtest for you to look like. (It's much easier to share backtests than copy-and-paste code). It has some better coding practices and it logs and records the data you're looking for. You still have to add the ordering logic. You can choose the time of day for the orders by editing the schedule function.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Dan, thank you so much, this is very useful and I'll be more careful in the future, sharing/attaching directly my backtest file.
Angel