from datetime import timedelta
class EtfEmaMultiAssetCrossoverExample(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2017,6,1)
self.SetEndDate(2017,12,1)
self.SetCash(25000)
# Add equities and store the Symbol object
self.etfs = [
self.AddEquity("VXX", Resolution.Minute).Symbol,
self.AddEquity("VONE", Resolution.Minute).Symbol,
self.AddEquity("ILTB", Resolution.Minute).Symbol,
]
# add indicator dicts(to store an indicator per asset)
self.ema13 = {}
self.ema49 = {}
for symbol in self.etfs:
self.ema13[symbol] = self.EMA(symbol, 13, Resolution.Daily)
self.ema49[symbol] = self.EMA(symbol, 49, Resolution.Daily)
# Fire rebalance on open each day
self.AddEquity("SPY", Resolution.Minute)
self.Schedule.On(self.DateRules.EveryDay("SPY"),
self.TimeRules.AfterMarketOpen("SPY", 0),
Action(self.Rebalance))
# Charting is cool for debugging, but careful not to overdo it and run out of quota
self.charting_mode = True
if self.charting_mode:
stockPlot = Chart('Indicators')
# On the Trade Plotter Chart we want 3 series: trades and price:
for i, symbol in enumerate(self.etfs):
stockPlot.AddSeries(Series('%s'%str(symbol), SeriesType.Line, i)) #y axis label only
stockPlot.AddSeries(Series('%s_Price'%str(symbol), SeriesType.Line, i))
stockPlot.AddSeries(Series('%s_13'%str(symbol), SeriesType.Line, i))
stockPlot.AddSeries(Series('%s_49'%str(symbol), SeriesType.Line, i))
self.AddChart(stockPlot)
# warmup to prepare the indicators so they work on day 1(which are in daily mode, but algo steps in minute mode)
self.SetWarmUp(int(6.5*60*49))
def OnData(self, data):
# fires every minute
if self.IsWarmingUp: return
pass
def Rebalance(self):
# loop through universe
for symbol in self.etfs:
# Ensure the Indicators are ready and not returning 0.0
if self.ema13[symbol].IsReady and self.ema49[symbol].IsReady:
#Long
if self.ema13[symbol].Current.Value > self.ema49[symbol].Current.Value:
if self.Portfolio[symbol].Quantity <= 0:
self.SetHoldings(symbol, 1./float(len(self.etfs)), tag="Long")
# Short
elif self.ema13[symbol].Current.Value < self.ema49[symbol].Current.Value:
if self.Portfolio[symbol].Quantity >= 0:
self.SetHoldings(symbol, -1./float(len(self.etfs)), tag="Short")
if self.charting_mode:
self.Plot('Indicators', '%s_Price'%str(symbol), self.Securities[symbol].Price)
self.Plot('Indicators', '%s_13'%str(symbol), self.ema13[symbol].Current.Value)
self.Plot('Indicators', '%s_49'%str(symbol), self.ema49[symbol].Current.Value)