Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Comparing SMA vs EMA

Hey guys, I'm trying to write a 13EMA/20SMA cross algo but I'm running into an error whenever I compare the two, any advice?

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
...

def handle_data(context, data):
hist = data.history(context.spy, fields="price", bar_count=30, frequency="1d")
ema_result = talib.EMA(hist, timeperiod=13)
record(ema=ema_result[-1])
sma_result = talib.SMA(hist, timeperiod=20)
record(sma=sma_result[-1])

open_orders = get_open_orders()  

if ema_result > sma_result:  
    if context.spy not in open_orders:  
        order_target_percent(context.spy, 1.0)  
elif sma_result > ema_result:  
    if context.spy not in open_orders:  
        order_target_percent(context.spy, -1.0)  
2 responses

This may help you:

import talib 

def initialize(context):  
    context.spy = symbol('SPY')  
    schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes = 15))

def trade(context, data):  
    if get_open_orders(): return 

    hist = data.history(context.spy, 'price', 30, '1d')  
    ema_result = talib.EMA(hist[-13:], 13)[-1]  
    sma_result = talib.SMA(hist[-20:], 20)[-1]  
    record(ema = ema_result, sma = sma_result)

    if data.can_trade(context.spy):  
        if ema_result > sma_result:  
            order_target_percent(context.spy, 1.0)  
        elif sma_result > ema_result:  
            order_target_percent(context.spy, 0.0)  

Thanks for the reply, it fixed my error! However, I was wondering if there was a way to have the algo operate on a 5m timeframe rather than daily.