Back to Community
50/200MA Crossover Strategy SPY, no short component

Simple 50/200MA Crossover Strategy for $SPY, no short component

Clone Algorithm
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
# 50/200 MA strategy

#initialize the strategy 
def initialize(context):
    context.etf = sid(8554)
    context.invested = False
def handle_data(context, data):
    price = data[context.etf].price
    fastMA = data[context.etf].mavg(50)
    slowMA = data[context.etf].mavg(200)
    #shortSig = data[context.etf].mavg(10)
    qty = round(
    #and price > shortSig                  
    if (fastMA > slowMA ) and not context.invested:
        order(context.etf , qty) 
        buyAmount = round(context.portfolio.starting_cash / price)"Bot {0} shares at {1}, Short MA  = {2}, Long MA = {3}".format(buyAmount, price, fastMA, slowMA))
        context.invested = True
    elif (fastMA < slowMA) and  context.invested:
        # liquidate
        order(context.etf,-(context.portfolio.positions[context.etf].amount))"Going to cash, ETF = {0}, Short MA  = {1}, Long MA = {2}".format(price, fastMA, slowMA))      
        context.invested = False
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
3 responses

Thank you for this code, helpful in getting started with this API. A question for Quantopian, when are moving averages available for trading decisions versus the start dates for the backtest? It appears that the benchmark starts right away (at the start date) but the moving average for the stock to be compared is computed after X periods from the start date so there is a delay when a trade can be made (e.g. 50 days for a 50 day MA). Therefore, the benchmark has a running start, 50 days of trading activity, before the comparison, giving it a positive advantage if trading up or will lag behind if trading down. Is this accurate and, if so, can this be corrected?

Claus, you may want to take a look at the posts in the moving average versus benchmark posts. There is a good response there about how time can affect the results of the call to the moving averages.

Cool, will do, thanks Steve.