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?
# region imports
from AlgorithmImports import *
from alpha import RandomForestAlphaModel
from portfolio import MeanVarianceOptimizationPortfolioConstructionModel
# endregion
class RandomForestAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetCash(100000)
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
self.AddEquity("SPY", Resolution.Daily)
self.SetBenchmark("SPY")
self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
# Use the following method for a Classic Algorithm
self.AddUniverse(self.Universe.ETF("SPY", Market.USA, self.UniverseSettings, self.ETFConstituentsFilter))
symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA)
# Use the following method for a Framework Algorithm
self.AddUniverseSelection(ETFConstituentsUniverseSelectionModel(symbol, self.UniverseSettings, self.ETFConstituentsFilter))
self.AddAlpha(RandomForestAlphaModel(
self,
self.GetParameter("minutes_before_close", 5),
self.GetParameter("n_estimators", 100),
self.GetParameter("min_samples_split", 5),
self.GetParameter("lookback_days", 360)
))
self.SetPortfolioConstruction(MeanVarianceOptimizationPortfolioConstructionModel(self, lambda time: None, PortfolioBias.Long, period=self.GetParameter("pcm_periods", 5)))
self.AddRiskManagement(NullRiskManagementModel())
self.SetExecution(ImmediateExecutionModel())
self.SetWarmUp(timedelta(5))
def ETFConstituentsFilter(self, constituents):
# Get the 10 securities with the largest weight in the index
selected = sorted([c for c in constituents if c.Weight],
key=lambda c: c.Weight, reverse=True)[:10]
self.weightBySymbol = {c.Symbol: c.Weight for c in selected}
return list(self.weightBySymbol.keys())
Derek Melchin
Hi David,
To avoid this error, we need to re-train the model when the universe changes. Add self.train_model() to the bottom of OnSecuritiesChanged in alpha.py
Best,
Derek Melchin
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.
David L
Thank you so much Derek! I had no idea it was so simple.
David L
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!