Overall Statistics
Total Orders
2654
Average Win
0.12%
Average Loss
-0.09%
Compounding Annual Return
52.610%
Drawdown
10.800%
Expectancy
0.607
Start Equity
100000
End Equity
200335.18
Net Profit
100.335%
Sharpe Ratio
1.996
Sortino Ratio
2.653
Probabilistic Sharpe Ratio
94.259%
Loss Rate
33%
Win Rate
67%
Profit-Loss Ratio
1.38
Alpha
0.134
Beta
1.207
Annual Standard Deviation
0.151
Annual Variance
0.023
Information Ratio
1.99
Tracking Error
0.082
Treynor Ratio
0.25
Total Fees
$2686.61
Estimated Strategy Capacity
$11000000.00
Lowest Capacity Asset
CMB R735QTJ8XC9X
Portfolio Turnover
4.65%
from AlgorithmImports import *
from hmmlearn import hmm

class HMMRegimeDetection(QCAlgorithm):
    
    def initialize(self):
        self.set_start_date(2023, 1, 1)
        self.add_universe(lambda fundamental: [f.symbol for f in sorted(fundamental, key=lambda x: x.market_cap, reverse=True)[:10]])
        self.set_warm_up(timedelta(3))

    def on_securities_changed(self, changes):
        for added in changes.added_securities:
            added.roc = RateOfChange(1)
            added.roc.window.size = 150
            added.model = hmm.GaussianHMM(n_components=3, n_iter=100, random_state=100)
            added.model_month = -1
            added.consolidator = TradeBarConsolidator(timedelta(minutes=5))
            added.consolidator.data_consolidated += self.on_consolidated
            self.subscription_manager.add_consolidator(added.symbol, added.consolidator)

    def on_consolidated(self, _, bar):
        security = self.securities[bar.symbol]
        security.roc.update(bar.end_time, bar.price)
        if security.roc.window.is_ready:
            if security.model_month != bar.end_time.month:
                security.model.fit(np.array([point.value for point in security.roc.window])[::-1].reshape(-1, 1))
                security.model_month = bar.end_time.month
            post_prob = security.model.predict_proba(np.array([security.roc.current.value]).reshape(1, -1)).flatten()
            self.set_holdings(bar.symbol, 0.1 if post_prob[2] > post_prob [0] else -0.1)