Back to Community
Can't get a simple moving average crossover to work

I know some python (not an expert, though) and I created an algo with my own pandas dataframe and connected it with IB. But I would like to backtest it on quantopian, but I really can't get it to work. All algo's I see are old and use deprecated bits of code.

For example this code seems very basic, but backtesting takes ages. Just for timespan of a few years it takes many hours : while I realize it's checking every minute, this makes no sense to me.

What should I do to get this kind of simpel moving average crossovers to work?

 def initialize(context): = symbol('SPY')  
def handle_data(context, data):  
    m50 = data[].mavg(50)  
    m200 = data[].mavg(200)  
    current_price = data[].price  
    current_positions = context.portfolio.positions[symbol('SPY')].amount  
    cash =  
    #buying condition  
    if (m50 > m200) and current_positions == 0:  
      number_of_shares = int(cash/current_price)  
      order(, number_of_shares)'Buying shares')  
    #selling condtion  
    elif (m50 < m200) and current_positions != 0:  
      order_target(, 0)'Selling shares')  
      record(m50 = m50, m200 = m200, price = current_price)  
1 response

Try this:

# ---------------------------------------  
SEC = symbol('SPY'); MA_F = 50; MA_S = 200  
# ---------------------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes = 65))    

def trade(context, data):  
    mavg_f = data.history(SEC, 'price', MA_F, '1d').mean()  
    mavg_s = data.history(SEC, 'price', MA_S, '1d').mean()  
    current_price = data.current(SEC, 'price')  
    current_positions = context.portfolio.positions[SEC].amount  
    cash =      

    if (mavg_f > mavg_s) and current_positions == 0:  
        number_of_shares = int(cash/current_price)  
        order(SEC, number_of_shares)         

    elif (mavg_f < mavg_s) and current_positions != 0:  
        order_target(SEC, 0)          

    record(mavg_f = mavg_f, mavg_s = mavg_s, price = current_price)  
    record(leverage = context.account.leverage)