Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trades not executed with basic SMA algorithm

Hi everyone,

Newbie here. I'm learning Quantopian and going through the sample materials in the community. However, the following strategy does not seem to generate any trade no matter how I change the parameters. I used the record variable function to confirm that the two moving averages did cross from time to time.

Any help is much appreciated.

def initialize(context):  
    # Parameters  
    context.shorto = 12   #  shorter period average  
    context.longo = 26   #  longer period average  
    context.assets = 1 #  times my capital  
    # Set comissions  
    set_commission(commission.PerShare(cost=0.000, min_trade_cost=0.0))

    # Choosing the stock and benchmark  
    context.future = continuous_future('CL', offset=0, roll='volume', adjustment='mul')  
    #set_benchmark(context.future) 

    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())  
    schedule_function(rebalance,  
                      date_rules.every_day(),  
                      time_rules.market_open())


def rebalance(context, data):  
    spot = data.current(context.future, 'contract')  
    context.MovingAvg1 = data.history(context.future, 'price', context.shorto,'1d').mean()  
    context.MovingAvg2 = data.history(context.future, 'price', context.longo,'1d').mean()  
    if (context.MovingAvg1 < context.MovingAvg2):  
        order_target_percent(spot, 0)  
    if (context.MovingAvg1 > context.MovingAvg2) :  
        order_target_percent(spot, context.assets)

def my_record_vars(context, data):  
    """  
    Plot variables at the end of each day.  
    """  
    record(MA_s = context.MovingAvg1)  
    record(MA_l = context.MovingAvg2)  
    record(Diff = context.MovingAvg1 - context.MovingAvg2) 
3 responses

Hmm. Seems to work for me.

BTW in the future attach a backtest. It makes it easier for others to help out.

Hi Dan,

Thanks very much for the reply. I tried doing the backtest using the same period as yours and here's the result. Not sure what went wrong.

Thanks Dan. I just compared our tests and figured it was the initial capital that caused the issue. The level was too low in my test making trades impossible. Thanks very much for the help.