Overall Statistics
Total Trades
6
Average Win
1.40%
Average Loss
0%
Compounding Annual Return
20.574%
Drawdown
3.900%
Expectancy
0
Net Profit
2.807%
Sharpe Ratio
1.254
Probabilistic Sharpe Ratio
53.202%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
-0.024
Beta
0.482
Annual Standard Deviation
0.118
Annual Variance
0.014
Information Ratio
-1.701
Tracking Error
0.123
Treynor Ratio
0.308
Total Fees
$7.07
Estimated Strategy Capacity
$510000000.00
Lowest Capacity Asset
SPY R735QTJ8XC9X
# region imports
from AlgorithmImports import *
from hmmlearn import hmm
import joblib
# endregion

class HmmlearnExampleAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2022, 7, 4)
        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.hmm"):
            file_name = self.ObjectStore.GetFilePath("model.hmm")
            self.model = joblib.load(file_name)
        
        else:
            self.model = hmm.GaussianHMM(n_components=2, covariance_type="full", n_iter=100)

        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(self):
        training_df = np.array(list(self.training_data)[::-1])
        daily_pct_change = (np.roll(training_df, 1) - training_df) / training_df

        return daily_pct_change[1:].reshape(-1, 1)

    def my_training_method(self):
        features = self.get_features()
        self.model.fit(features)

    def OnData(self, slice: Slice) -> None:
        if self.symbol in slice.Bars:
            self.training_data.Add(slice.Bars[self.symbol].Close)

        new_feature = self.get_features()
        prediction = self.model.predict(new_feature)
        prediction = float(prediction[-1])

        if prediction == 1:
            self.SetHoldings(self.symbol, 1)
        else:            
            self.Liquidate(self.symbol)

    def OnEndOfAlgorithm(self):
        model_key = "model.hmm"
        file_name = self.ObjectStore.GetFilePath(model_key)
        joblib.dump(self.model, file_name)