Hi, Trying to implement talib ema as you explained. i think i have the Ema setup correctly but formula wont run. Im trying to get it to short when price closes below EMA, keep that position (without adding to it) until buy signal occurs, then go long and stay long (without adding to pos.) until short signal happens again.
The formula was running without errors when i used the default .mavg(value) but the values of it seemed to be wrong, so wanted to go over to talib.
Thanks
import talib
def initialize(context):
context.security = symbol('AAPL')
def handle_data(context, data):
price_history = history(bar_count=11, frequency='1d', field='price')
maseries = price_history[context.security]
maverage = talib.EMA(maseries, timeperiod=11)
current_price = data[context.security].price
position = context.portfolio.positions[context.security].amount
if current_price < maverage and position == 0:
order_target_percent(context.security, -1)
# log.info("SHORT %s" % (context.security.symbol))
elif current_price > maverage and position <= 0:
order_target_percent(context.security, 0)
# log.info("COVER SHORT %s" % (context.security.symbol))
if current_price > maverage and position == 0:
order_target_percent(context.security, 1)
# log.info("LONG %s" % (context.security.symbol))
elif current_price < maverage and position >= 0:
order_target_percent(context.security, 0)
# log.info("COVER LONG %s" % (context.security.symbol))