Back to Community
Mavg vs history discrepancy

I am trying to understand and reconcile behavior differences I'm seeing between hist(2*390, 'd', 'close_price')[symbol].mean() and mavg(2).

I would expect them to be equal or at least very close at the end of every day but instead, I'm seeing big differences. Interestingly, they align perfectly at the end of the second day (no matter when I start the back-tests). Visually, it looks like mavg(2) is far too slow and the hist-based numbers look about right.

Clone Algorithm
4
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import numpy as np
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    pass

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    # Implement your algorithm logic here.

    SPY = sid(8554)
    mavg = data[SPY].mavg(2)
    hist_close = history(390*2, '1m', 'close_price')[SPY].mean()
    hist_price = history(390*2, '1m', 'price')[SPY].mean()
    #hist_day = history(2, '1d', 'close_price')[SPY].mean()
    
    record(mavg=mavg,hist_close=hist_close, hist_price=hist_price, close=data[SPY].close_price)
    
There was a runtime error.
5 responses

Hi Alex,

The built-in mavg() function will return the true moving average once the window is full. So a 2-day moving average will have the correct values after 2 days. When you use panda's mean() with history, it automatically has the data in the first bar and can access the historical data. You can see a more thorough explanation here: https://www.quantopian.com/posts/why-are-these-two-moving-averages-different

We're working to make the mavg (and other simple transformations such as vwap) "smarter" to immediately have the data available rather than waiting for the window to fill.

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.

So why are the values very different after 3+ days on the plot above?

Double-checking again, mavg looks completely broken. Attached is a run of the moving average comparison over a longer time period. There's no way that the 2-day moving average is actually taking a moving average over 2 days ... from what I see it's maybe cumulative average since the start of the backtest period?

As further evidence, data[sec].mavg(2) is exactly equal to data[sec].mavg(5).

Clone Algorithm
4
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import numpy as np
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    pass

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    # Implement your algorithm logic here.

    SPY = sid(8554)
    mavg = data[SPY].mavg(2)
    vwap = data[SPY].vwap(2)
    
    hist_close = history(390*2, '1m', 'close_price')[SPY].mean()
    hist_price = history(390*2, '1m', 'price')[SPY].mean()
    #hist_day = history(2, '1d', 'close_price')[SPY].mean()
    
    record(mavg=mavg, vwap=vwap,
           hist_close=hist_close, 
           hist_price=hist_price, 
           close=data[SPY].close_price)
    
There was a runtime error.

Hi Alex,

We are working to fix this behavior and also improve it - to have the built-in mavg() function return the value immediately (and correctly!). It will behave identically to calling

history(bars, frequency, field).mean()  

In this improved world if you call mavg(2) in minute mode, it will return 2 days mavg with minutes as the data points. You will get the average of yesterday's minutes + today's trailing minutes.

In the meantime, I'd suggest to use history's mean function for your calculations.

Hi Alisa, until mavg does the right thing, is it possible to update the doc to tell people to use history.mean() instead? Docs don't mention anything wrong about mavg but after reading this thread, it's clear that it's broken and should be avoided.