Hi All,

I was working on the template code for “Forecasting of Tech Stocks with ML” and was interested in swapping the initial ticker bracket out for the SP500's 10 most weighted equities at any given timeframe. So far I have come up with the code below in the main.py file, but I can't get the return list to represent the values of each stock. When I backtest the code I get "Runtime Error: X has 11 features, but RandomForestRegressor is expecting 1 features as input." in response. So I was wondering if at all possible, how could I add a bracket of tickers for the random forest regression to properly run?

  1. # region imports
  2. from AlgorithmImports import *
  3. from alpha import RandomForestAlphaModel
  4. from portfolio import MeanVarianceOptimizationPortfolioConstructionModel
  5. # endregion
  6. class RandomForestAlgorithm(QCAlgorithm):
  7. def Initialize(self):
  8. self.SetStartDate(2020, 1, 1)
  9. self.SetCash(100000)
  10. self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
  11. self.AddEquity("SPY", Resolution.Daily)
  12. self.SetBenchmark("SPY")
  13. self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
  14. # Use the following method for a Classic Algorithm
  15. self.AddUniverse(self.Universe.ETF("SPY", Market.USA, self.UniverseSettings, self.ETFConstituentsFilter))
  16. symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA)
  17. # Use the following method for a Framework Algorithm
  18. self.AddUniverseSelection(ETFConstituentsUniverseSelectionModel(symbol, self.UniverseSettings, self.ETFConstituentsFilter))
  19. self.AddAlpha(RandomForestAlphaModel(
  20. self,
  21. self.GetParameter("minutes_before_close", 5),
  22. self.GetParameter("n_estimators", 100),
  23. self.GetParameter("min_samples_split", 5),
  24. self.GetParameter("lookback_days", 360)
  25. ))
  26. self.SetPortfolioConstruction(MeanVarianceOptimizationPortfolioConstructionModel(self, lambda time: None, PortfolioBias.Long, period=self.GetParameter("pcm_periods", 5)))
  27. self.AddRiskManagement(NullRiskManagementModel())
  28. self.SetExecution(ImmediateExecutionModel())
  29. self.SetWarmUp(timedelta(5))
  30. def ETFConstituentsFilter(self, constituents):
  31. # Get the 10 securities with the largest weight in the index
  32. selected = sorted([c for c in constituents if c.Weight],
  33. key=lambda c: c.Weight, reverse=True)[:10]
  34. self.weightBySymbol = {c.Symbol: c.Weight for c in selected}
  35. return list(self.weightBySymbol.keys())
+ Expand

Author

David L

June 2023