I used a RSI example and I tried to add EMA crossover using TA-lib, however the algorithm does not execute any orders.
import talib
# Setup our variables
def initialize(context):
context.stocks = symbols('AMZN', 'AAPL')
context.target_pct_per_stock = 1.0 / len(context.stocks)
context.LOW_RSI = 30
context.HIGH_RSI = 70
schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
# Rebalance daily.
def rebalance(context, data):
# Load historical data for the stocks
prices = data.history(context.stocks, 'price', 20, '1d')
rsis = {}
emas = {}
# Loop through our list of stocks
for stock in context.stocks:
# Get the rsi of this stock.
rsi = talib.RSI(prices[stock], timeperiod=14)[-1]
rsis[stock] = rsi
# Get EMA13 & EMA48
ema13 = talib.EMA(prices[stock], timeperiod=13)[-1]
ema48 = talib.EMA(prices[stock], timeperiod=48)[-1]
emas[stock] = ema13, ema48
current_position = context.portfolio.positions[stock].amount
# RSI is above 70 and we own shares, time to sell
if rsi > context.HIGH_RSI and ema13 < ema48 and current_position > 0 and data.can_trade(stock):
order_target(stock, 0)
# RSI is below 30 and we don't have any shares, time to buy
elif rsi < context.LOW_RSI and ema13 > ema48 and current_position == 0 and data.can_trade(stock):
order_target_percent(stock, context.target_pct_per_stock)