Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help shortening my code

Is there a way to shorten this code so that I don't have 4 different SMA's? I tried combining context.xly & context.xlf into a list but wasn't able to get the " if sma_1_20 > sma_1_50:" line to run. Thanks!

def initialize(context):  
    context.xly = sid(19662)  
    context.xlf = sid(19656)  

    schedule_function(ma_crossover_handling, date_rules.every_day(), time_rules.market_close(hours=1, minutes=0))  
               #calls ma_crossover function once a day, 1 hour after open  
def ma_crossover_handling(context, data):  
    hist_1 = data.history(context.xly, 'price', 50, '1d')  
    hist_2 = data.history(context.xlf, 'price', 50, '1d')  

    #gives 50 periods of 1minute data for apple

    sma_1_50 = hist_1.mean()  
    sma_1_20 = hist_1[-20].mean()  
    sma_2_50 = hist_2.mean()  
    sma_2_20 = hist_2[-20].mean()  
    open_orders = get_open_orders()  
# ****************************1**************************  
    if sma_1_20 > sma_1_50:  
        if context.xly not in open_orders:  
            #this prevents from double buying, to limit leverage  
            order_target_percent(context.xly, 0.5)  
    elif sma_1_20 < sma_1_50:  
        if context.xly not in open_orders:  
            order_target_percent(context.xly, -0.5)  
# ****************************2**************************  
    if sma_2_20 > sma_2_50:  
        if context.xlf not in open_orders:  
            #this prevents from double buying, to limit leverage  
            order_target_percent(context.xlf, 0.5)  
    elif sma_2_20 < sma_2_50:  
        if context.xlf not in open_orders:  
            order_target_percent(context.xlf, -0.5)

1 response

Alex,
Try something like this:


def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_close( minutes=60))  

def trade(context, data):  
    stocks = symbols('xly','xlf',)  
    ma_s, ma_f = 50, 20

    sma_s = data.history(stocks, 'price', ma_s, '1d').mean()  
    sma_f = data.history(stocks, 'price', ma_f, '1d').mean() 

    if get_open_orders() : return  
    wt = 1.0/len(stocks)

    for stock in stocks:  
        if  sma_f[stock] > sma_s[stock]:  
            if data.can_trade(stock):  
                order_target_percent(stock, wt)  
        elif sma_f[stock] < sma_s[stock]:  
            if data.can_trade(stock):  
                order_target_percent(stock, -wt)