I've been trying for days without success and I can't quite figure it out. I have indicators working, getting warmed up with history and then keeping updated with a rolling window. So how can I implement a closewindow with a few days of close prices and have this warmed up?
class WellDressedSkyBlueSardine(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2019, 1, 1)
self.SetEndDate(2019, 3, 1)
self.SetCash(100000)
self.rebalanceTime = datetime.min
self.activeStocks = set()
self.AddUniverse(self.CoarseFilter)
self.UniverseSettings.Resolution = Resolution.Daily
self.universe = set()
self.portfolioTargets = []
self.indicators = {}
self.EMA_Period_Fast = 20
self.EMA_Period_Slow = 50
#self.closeWindows = {}
def CoarseFilter(self, coarse):
# Rebalancing time
if self.Time <= self.rebalanceTime:
return self.Universe.Unchanged
self.rebalanceTime = self.Time + timedelta(1)
sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
self.universe = [x.Symbol for x in sortedByDollarVolume if x.Price > 10 and x.HasFundamentalData][:10]
return self.universe
def OnSecuritiesChanged(self, changes):
# close positions in removed securities
for x in changes.RemovedSecurities:
self.Liquidate(x.Symbol)
for security in changes.AddedSecurities:
self.indicators[security.Symbol] = SymbolData(security.Symbol, self, self.EMA_Period_Fast, self.EMA_Period_Slow)
def OnData(self, data):
for symbol in self.universe:
if not data.ContainsKey(symbol):
continue
if data[symbol] is None:
continue
if not symbol in self.indicators:
continue
#-------------------------------------------------------
if not (self.indicators[symbol].fast_ema_window.IsReady and self.indicators[symbol].slow_ema_window.IsReady):
continue #return
if (not self.Portfolio[symbol].Invested):# and (self.Portfolio.MarginRemaining > 0.9*self.percentagebuy*self.Portfolio.TotalPortfolioValue):
if (self.indicators[symbol].fast_ema_window[1] >= self.indicators[symbol].slow_ema_window[2]):
self.SetHoldings(symbol, 0.2)
self.Debug("buying " + str(symbol.Value) + " for " + str(data[symbol].Price))
#self.Debug("Close Window is: " + str(self.indicators[symbol].closeWindow[0]))
if self.indicators[symbol].fast_ema_window[1] <= self.indicators[symbol].slow_ema_window[1] and (self.indicators[symbol].fast_ema_window[4] > self.indicators[symbol].slow_ema_window[4]):
invested = [ x.Symbol.Value for x in self.Portfolio.Values if x.Invested ]
self.Debug("invested: " + str(invested))
self.Liquidate(symbol)
#-------------------------------------------------------
class SymbolData(object):
rolling_window_length = 5
def __init__(self, symbol, context, fast_ema_period, slow_ema_period):
self.symbol = symbol
self.fast_ema_period = fast_ema_period
self.slow_ema_period = slow_ema_period
self.fast_ema = context.EMA(symbol, self.fast_ema_period, Resolution.Daily)
self.slow_ema = context.EMA(symbol, self.slow_ema_period, Resolution.Daily)
self.fast_ema_window = RollingWindow[float](self.rolling_window_length)
self.slow_ema_window = RollingWindow[float](self.rolling_window_length)
#self.daily_rw = RollingWindow[TradeBar](4)
self.closeWindow = RollingWindow[float](4)
#self.closeWindow = RollingWindow[float](4)
#self.close_window = RollingWindow[float](4)
#self.closeWindows[symbol] = RollingWindow[float](4)
# Warm up EMA indicators
history = context.History([symbol], slow_ema_period + self.rolling_window_length, Resolution.Daily)
for time, row in history.loc[symbol].iterrows():
self.fast_ema.Update(time, row["close"])
self.slow_ema.Update(time, row["close"])
#self.close_window.Add(time, row["close"])
# Warm up rolling windows
if self.fast_ema.IsReady:
self.fast_ema_window.Add(self.fast_ema.Current.Value)
if self.slow_ema.IsReady:
self.slow_ema_window.Add(self.slow_ema.Current.Value)
# if self.closeWindow.IsReady:
# self.closeWindow.Add(time, row["close"])
#def CloseUpdated(self, sender, bar):
'''Event holder to update the close Rolling Window values'''
# self.closeWindow.Add(bar.Close)
def get_fast_EMA(self):
return self.fast_ema.Current.Value
def get_slow_EMA(self):
return self.slow_ema.Current.Value
Varad Kabade
Hi John J,
We can implement the RollingWindow logic inside the SymbolData class, and to update the window, we do not need time as the input parameter:
Refer to the following docs for more information. We have implemented the logic inside the code snippet attached above, and we are updating it in the OnData method. Refer to the attached backtest.
Best,
Varad Kabade
John J
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!