So I was checking out Quantconnect's example demo code for XGBoost in Python from
(https://www.quantconnect.com/docs/v2/writing-algorithms/machine-learning/popular-libraries/xgboost#09-Clone-Example-Algorithm).
However, I when I cloned the demo and tried running the backtest with the code unchanged, I keep on receiving the error
"During the algorithm initialization, the following exception has occurred: Can't get attribute 'NeuralNetwork' on at _getattribute".
I tried asking Mia AI but couldn't find a working solution. I'm pretty new to machine learning libraries so I'm stuck on this one.
# region imports
from AlgorithmImports import *
import xgboost as xgb
import joblib
# endregion
class XGBoostExampleAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2022, 7, 4)
self.SetEndDate(2022, 7, 8)
self.SetCash(100000)
self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol
training_length = 252*2
self.training_data = RollingWindow[float](training_length)
history = self.History[TradeBar](self.symbol, training_length, Resolution.Daily)
for trade_bar in history:
self.training_data.Add(trade_bar.Close)
if self.ObjectStore.ContainsKey("model"):
file_name = self.ObjectStore.GetFilePath("model")
self.model = joblib.load(file_name)
else:
self.Train(self.my_training_method)
self.Train(self.DateRules.Every(DayOfWeek.Sunday), self.TimeRules.At(8,0), self.my_training_method)
def get_features_and_labels(self, n_steps=5):
close_prices = np.array(list(self.training_data)[::-1])
df = (np.roll(close_prices, -1) - close_prices) * 0.5 + close_prices * 0.5
df = df[:-1]
features = []
labels = []
for i in range(len(df)-n_steps):
features.append(df[i:i+n_steps])
labels.append(df[i+n_steps])
features = np.array(features)
labels = np.array(labels)
features = (features - features.mean()) / features.std()
labels = (labels - labels.mean()) / labels.std()
d_matrix = xgb.DMatrix(features, label=labels)
return d_matrix
def my_training_method(self):
d_matrix = self.get_features_and_labels()
params = {
'booster': 'gbtree',
'colsample_bynode': 0.8,
'learning_rate': 0.1,
'lambda': 0.1,
'max_depth': 5,
'num_parallel_tree': 100,
'objective': 'reg:squarederror',
'subsample': 0.8,
}
self.model = xgb.train(params, d_matrix, num_boost_round=2)
def OnData(self, slice: Slice) -> None:
if self.symbol in slice.Bars:
self.training_data.Add(slice.Bars[self.symbol].Close)
new_d_matrix = self.get_features_and_labels()
prediction = self.model.predict(new_d_matrix)
prediction = prediction.flatten()
if float(prediction[-1]) > float(prediction[-2]):
self.SetHoldings(self.symbol, 1)
else:
self.SetHoldings(self.symbol, -1)
def OnEndOfAlgorithm(self):
model_key = "model"
file_name = self.ObjectStore.GetFilePath(model_key)
joblib.dump(self.model, file_name)
self.ObjectStore.Save(model_key)
Mia Alissi
Hmm, I don't know enough to give you a confident answer yet. However, it seems like there might be an issue with the initialization of the 'NeuralNetwork' attribute in your algorithm.
You might want to check the way you're defining and initializing your 'NeuralNetwork' attribute. Make sure it's properly defined and initialized before you try to get its attribute.
Also, you might want to check out the QuantConnect forum for similar issues or post your question there. The community is very active and might be able to help you out. Here is the link to the forum: QuantConnect Forum
Additionally, you can check out the QuantConnect documentation on machine learning libraries, which might provide some insights: QuantConnect Machine Learning Documentation
Remember, debugging is a normal part of coding, especially when you're learning something new like machine learning libraries. Don't get discouraged, keep trying different solutions, and ask for help when you need it. Good luck!
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
Hi Mia, can you giving me an example of a working code for a XGBoost algorithm taking that into consideration?
Derek Melchin
Hi David,
We couldn't reproduce the issue. If you try running the algorithm again now, does the issue still occur?
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
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!