Overall Statistics
Total Orders
266
Average Win
1.00%
Average Loss
-0.90%
Compounding Annual Return
-1.828%
Drawdown
24.200%
Expectancy
-0.005
Start Equity
100000
End Equity
96724.45
Net Profit
-3.276%
Sharpe Ratio
-0.349
Sortino Ratio
-0.402
Probabilistic Sharpe Ratio
4.987%
Loss Rate
53%
Win Rate
47%
Profit-Loss Ratio
1.10
Alpha
-0.092
Beta
0.504
Annual Standard Deviation
0.142
Annual Variance
0.02
Information Ratio
-0.948
Tracking Error
0.141
Treynor Ratio
-0.098
Total Fees
$517.55
Estimated Strategy Capacity
$740000000.00
Lowest Capacity Asset
SPY R735QTJ8XC9X
Portfolio Turnover
60.49%
# region imports
from AlgorithmImports import *
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
import joblib
# endregion

class ScikitLearnExampleAlgorithm(QCAlgorithm):
    
    def initialize(self):
        self.set_start_date(2022, 7, 4)
        self.set_cash(100000)
        self.symbol = self.add_equity("SPY", Resolution.DAILY).symbol

        training_length = 252*2
        self.training_data = RollingWindow[TradeBar](training_length)
        history = self.history[TradeBar](self.symbol, training_length, Resolution.DAILY)
        for trade_bar in history:
            self.training_data.add(trade_bar)

        if self.object_store.contains_key("model"):
            file_name = self.object_store.get_file_path("model")
            self.model = joblib.load(file_name)

        else:
            param_grid = {'C': [.05, .1, .5, 1, 5, 10], 
                          'epsilon': [0.001, 0.005, 0.01, 0.05, 0.1], 
                          'gamma': ['auto', 'scale']}
            self.model = GridSearchCV(SVR(), param_grid, scoring='neg_mean_squared_error', cv=5)

        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):
        training_df = self.pandas_converter.get_data_frame[TradeBar](list(self.training_data)[::-1])
        daily_pct_change = training_df.pct_change().dropna()

        features = []
        labels = []
        for i in range(len(daily_pct_change)-n_steps):
            features.append(daily_pct_change.iloc[i:i+n_steps].values.flatten())
            labels.append(daily_pct_change['close'].iloc[i+n_steps])
        features = np.array(features)
        labels = np.array(labels)

        return features, labels

    def my_training_method(self):
        features, labels = self.get_features_and_labels()
        if isinstance(self.model, GridSearchCV):
            self.model = self.model.fit(features, labels).best_estimator_
        else:
            self.model = self.model.fit(features, labels)

    def on_data(self, slice: Slice) -> None:
        if self.symbol in slice.bars:
            self.training_data.add(slice.bars[self.symbol])

        features, _ = self.get_features_and_labels()
        prediction = self.model.predict(features[-1].reshape(1, -1))
        prediction = float(prediction)

        if prediction > 0:
            self.set_holdings(self.symbol, 1)
        elif prediction < 0:            
            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)