| Overall Statistics |
|
Total Trades 3 Average Win 0.79% Average Loss -0.53% Compounding Annual Return 59.565% Drawdown 0.500% Expectancy 0.241 Net Profit 0.642% Sharpe Ratio 5.454 Probabilistic Sharpe Ratio 64.831% Loss Rate 50% Win Rate 50% Profit-Loss Ratio 1.48 Alpha 2.247 Beta -0.73 Annual Standard Deviation 0.092 Annual Variance 0.008 Information Ratio -9.611 Tracking Error 0.196 Treynor Ratio -0.686 Total Fees $6.50 Estimated Strategy Capacity $880000000.00 Lowest Capacity Asset SPY R735QTJ8XC9X |
# 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)