Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with Simple Moving Average Crossover

Hi all,
I have searched the forum and found many simple moving average crossover strategies but all of them use intra-day data to calculate the crossover and execute at the moment of the crossover.

I was hoping for some help with a simple moving average crossover that calculates 10 and 30 day simple moving averages using adjusted price on closing price of the day. If the short SMA > long SMA an order to buy the stock is made the next day at the opening price (using all of cash). If the short SMA < long SMA an order is made to sell the stock (converting to all cash) the next day at the opening price. I was hoping for someone to help me with this. Thanks so much.

2 responses

@Zach

Try something like this:

# MAC for next day open  
# ------------------------------------------  
STOCK = symbol('AAPL'); MA_F = 10; MA_S = 30;  
# ------------------------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_open())

def before_trading_start(context, data):  
    context.mavg_f = data.history(STOCK, 'close',  MA_F, '1d').mean()  
    context.mavg_s = data.history(STOCK, 'close',  MA_S, '1d').mean()  
    record(leverage = context.account.leverage)        

def trade(context, data):  
    position = context.portfolio.positions[STOCK].amount 

    if ( position == 0 ) & ( context.mavg_f > context.mavg_s ):  
        order_target_percent(STOCK, 1.0)

    elif ( position > 0 ) & ( context.mavg_f < context.mavg_s ):  
        order_target(STOCK, 0)  

Thanks so much for your help!