Overall Statistics
Total Orders
1
Average Win
0%
Average Loss
0%
Compounding Annual Return
247.407%
Drawdown
0.100%
Expectancy
0
Start Equity
100000
End Equity
101720.56
Net Profit
1.721%
Sharpe Ratio
16.656
Sortino Ratio
0
Probabilistic Sharpe Ratio
98.933%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-0.536
Beta
1.038
Annual Standard Deviation
0.116
Annual Variance
0.013
Information Ratio
-31.32
Tracking Error
0.014
Treynor Ratio
1.855
Total Fees
$1.34
Estimated Strategy Capacity
$920000000.00
Lowest Capacity Asset
SPY R735QTJ8XC9X
Portfolio Turnover
19.88%
# region imports
from AlgorithmImports import *
import xgboost as xgb
import joblib
# endregion

class XGBoostExampleAlgorithm(QCAlgorithm):
    
    def initialize(self):
        self.set_start_date(2022, 7, 4)
        self.set_end_date(2022, 7, 8)
        self.set_cash(100000)
        self.symbol = self.add_equity("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.object_store.contains_key("model"):
            file_name = self.object_store.get_file_path("model")
            self.model = joblib.load(file_name)
        else:
            self.train(self.my_training_method)
            
        self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.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 on_data(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.set_holdings(self.symbol, 1)
        else:            
            self.set_holdings(self.symbol, -1)

    def on_end_of_algorithm(self):
        model_key = "model"
        file_name = self.object_store.get_file_path(model_key)
        joblib.dump(self.model, file_name)
        self.object_store.save(model_key)