Back to Community
Simple Moving Average vs Current Price Compare

I would like to compare Simple Moving Average of a stock and compare it to it current price to make my trading decision. I do see that current API do support ta.SMA but I am not able to find any examples. Any suggestion?

7 responses

Hi Jaydip,
There are a few ways to do what you want, and you actually don't need TA-Lib here. The most simple is to use the mavg() transform. I've attached a backtest with that below.

However, that mavg() function requires a warmup period. So if you are using the moving average over many days, say 200, it will take 200 days for your algorithm to begin running.

To fix this, you can use the history function instead of mavg(). If you are only trading one security, this code will work to get the moving average if you put it in handle_data:

prices = history(200, '1d', 'price')  
moving_average = prices.mean()  

Note the above code only works in minute mode. Do these methods work for you? Another option is to use an array or deque of recent prices and just average the values of that.


Clone Algorithm
Backtest from to with initial capital
Total Returns
Max Drawdown
Benchmark Returns
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
# Backtest ID: 53c42d9dcf29950730302895
There was a runtime error.

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.

Also, I saw your other thread here:

Have you sorted that out, or do you still need help there?

Thanks Gus, I haven't shorted out price vs vwap yet. For that purpose I was looking to find a way to get to moving average.
Thank you again!!!

Hi Gus,

Looks like the history function is not supported in daily mode. Is there a workaround to retrieve daily historical data?
I wanted to run some custom algo on historical daily prices.


There's the '1d' option, and then maybe something like this to only act once a day:

def handle_data(context, data):  
    if str(get_datetime().time()) != '14:44:00':  

You still have to run in minute mode to use history(), maybe that could speed it up a bit.

Jaydip, since the built-in mavg() requires an integer and I wanted to use a variable I just use my own (do the append of the latest price to the list before calling sma_calc()):

def sma_calc(prices_list, window_size):  
    return sum(prices_list[-window_size:]) / window_size  

Soumyajit, there are a few ways. One way is to just run the backtest in minute mode and only run the strategy once per day, like Gary said. Another way would be to run the algorithm in daily mode, create a deque (which is a list with a maximum length) in initialize, then every time handle_data is run you append to that deque. That way you would store the 20, or whatever, most recent values in a list format. I would use Gary's approach, but if that's not ideal for you, you can look into what I described. Let me know if you need any more help with that!

what is the rationale behind this algorithm? any idea