Lets say I have the following.  How would I best go about being able to keep track of rolling windows for multiple stocks?  Ultimately I want to be able to check from a list of stocks, if a stock's price is higher than it was in the past 30 and 180 days

 

  1. from QuantConnect.Data.Market import TradeBar
  2. class RollingWindowAlgorithm(QCAlgorithm):
  3. '''Example on how to use Rolling Window with bar and indicator'''
  4. def Initialize(self):
  5. '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
  6. self.SetStartDate(2013,10,1) #Set Start Date
  7. self.SetEndDate(2013,11,1) #Set End Date
  8. self.SetCash(100000) #Set Strategy Cash
  9. # Find more symbols here: http://quantconnect.com/data
  10. self.AddEquity("SPY", Resolution.Daily)
  11. # Creates a Rolling Window indicator to keep the 2 TradeBar
  12. self.window = RollingWindow[TradeBar](2) # For other security types, use QuoteBar
  13. # Creates an indicator and adds to a rolling window when it is updated
  14. self.SMA("SPY", 5).Updated += self.SmaUpdated
  15. self.smaWin = RollingWindow[IndicatorDataPoint](5)
  16. def SmaUpdated(self, sender, updated):
  17. '''Adds updated values to rolling window'''
  18. self.smaWin.Add(updated)
  19. def OnData(self, data):
  20. '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
  21. # Add SPY TradeBar in rollling window
  22. self.window.Add(data["SPY"])
  23. # Wait for windows to be ready.
  24. if not (self.window.IsReady and self.smaWin.IsReady): return
  25. currBar = self.window[0] # Current bar had index zero.
  26. pastBar = self.window[1] # Past bar has index one.
  27. self.Log("Price: {0} -> {1} ... {2} -> {3}".format(pastBar.Time, pastBar.Close, currBar.Time, currBar.Close))
  28. currSma = self.smaWin[0] # Current SMA had index zero.
  29. pastSma = self.smaWin[self.smaWin.Count-1] # Oldest SMA has index of window count minus 1.
  30. self.Log("SMA: {0} -> {1} ... {2} -> {3}".format(pastSma.Time, pastSma.Value, currSma.Time, currSma.Value))
  31. if not self.Portfolio.Invested and currSma.Value > pastSma.Value:
  32. self.SetHoldings("SPY", 1)
+ Expand

Author

Axist

March 2023