hmm-regime 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mehmetoaltekin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,270 @@
1
+ Metadata-Version: 2.4
2
+ Name: hmm-regime
3
+ Version: 0.2.0
4
+ Summary: Walk-forward Gaussian HMM market regime detection with causal forward filtering
5
+ Author: Mehmet Altekin
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/mehmetoaltekin/hmm-regime-detection
8
+ Project-URL: Changelog, https://github.com/mehmetoaltekin/hmm-regime-detection/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/mehmetoaltekin/hmm-regime-detection/issues
10
+ Keywords: hidden markov model,regime detection,walk-forward,volatility,quantitative finance
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Financial and Insurance Industry
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy>=1.24.0
26
+ Requires-Dist: pandas>=2.0.0
27
+ Requires-Dist: hmmlearn>=0.3.0
28
+ Provides-Extra: data
29
+ Requires-Dist: yfinance>=0.2.40; extra == "data"
30
+ Provides-Extra: plot
31
+ Requires-Dist: matplotlib>=3.7.0; extra == "plot"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
34
+ Requires-Dist: matplotlib>=3.7.0; extra == "dev"
35
+ Requires-Dist: scipy>=1.10.0; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # hmm-regime-detection
39
+ Quantitative market regime identification via Gaussian HMMs: walk-forward parameter estimation, state sorting, and information criteria (AIC/BIC) selection.
40
+
41
+ ## Disclaimer
42
+ This repository is strictly for academic and quantitative research purposes.
43
+ Nothing contained herein constitutes financial, investment, or trading advice.
44
+ The authors accept no responsibility for any financial losses incurred through
45
+ the use of these models or strategies.
46
+
47
+ ## References
48
+
49
+ * **Alizadeh, S., Brandt, M. W., & Diebold, F. X. (2002).** *Range-Based Estimation of Stochastic Volatility Models.* The Journal of Finance, 57(3), 1047–1091.
50
+ * **Hamilton, J. D. (1989).** *A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.* Econometrica, 57(2), 357–384.
51
+ * **López de Prado, M. (2018).** *Advances in Financial Machine Learning.* John Wiley & Sons. (Chapter: Structural Breaks).
52
+ * **Parkinson, M. (1980).** *The Extreme Value Method for Estimating the Variance of the Rate of Return.* The Journal of Business, 53(1), 61–65.
53
+ * **Rabiner, L. R. (1989).** *A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition.* Proceedings of the IEEE, 77(2), 257–286.
54
+
55
+ # Market Regime Detection via Walk-Forward Gaussian HMM
56
+ [![CI Status](https://github.com/mehmetoaltekin/hmm-regime-detection/actions/workflows/ci.yml/badge.svg)](https://github.com/mehmetoaltekin/hmm-regime-detection/actions)
57
+
58
+ An econometric and quantitative research framework for out-of-sample market regime detection: rolling re-calibration, causal forward filtering, variance-sorted state labels and per-window model selection.
59
+
60
+ ## 1. Theoretical Framework
61
+
62
+ Financial return series rarely follow a single stationary distribution. In practice, markets alternate between distinct market regimes shifting rapidly between tranquil periods and sudden crisis states. To capture these structural shifts and the resulting time varying volatility, we model returns using a Hidden Markov Model (HMM).
63
+ Let $Y_t$ denote the observed return at time $t$. We assume the data generating process is driven by an unobserved discrete Markov chain $S_t \in \{1, \dots, K\}$, with state transition probabilities given by:
64
+
65
+ $$P(S_t = j \mid S_{t-1} = i) = A_{ij}$$
66
+
67
+ where $A$ is the $K \times K$ transition probability matrix. Conditional on being in regime $S_t = k$, observations are drawn from a Gaussian distribution:
68
+
69
+ $$Y_t \mid (S_t = k) \sim \mathcal{N}(\mu_k, \sigma_k^2)$$
70
+
71
+
72
+ # Methodological & Implementation Details
73
+
74
+ Applying regime switching models to sequential financial data introduces three specific estimation challenges that require structural safeguards:
75
+
76
+ Preventing Look Ahead Bias: Full sample inference techniques (such as the Viterbi algorithm or two sided smoothing) calculate smoothed probabilities $P(S_t \mid Y_{1:T})$. Because this conditions state assignment at time $t$ on future data ($t+1 \dots T$), it creates severe look ahead bias in backtests.
77
+
78
+ To maintain strict out of sample validity, we use only the forward algorithm to compute real time filtered probabilities:
79
+
80
+ $$P(S_t \mid Y_{1:t})$$
81
+
82
+ Resolving Label Switching: Because Expectation Maximization (EM / Baum-Welch) is an unsupervised procedure, state labels are arbitrary and can switch unpredictably between rolling estimation windows.
83
+ To ensure economic consistency over time, we sort and re index the regimes by their estimated return variance ($\sigma_k^2$) at each calibration step, pinning State 0 to the lowest volatility regime.
84
+
85
+ Model Selection ($K$): The number of hidden states is selected by balancing fit against parameter bloat using the Bayesian Information Criterion (BIC) and Akaike Information Criterion (AIC):
86
+
87
+ $$\text{BIC} = -2\ln(\hat{L}) + p \ln(T)$$
88
+
89
+ where $\hat{L}$ is the maximized likelihood, $p$ is the number of free parameters, and $T$ is the number of observations.
90
+
91
+
92
+ ## 2. Installation & Quickstart
93
+
94
+ To use the library in your own project:
95
+
96
+ ```bash
97
+ pip install hmm-regime # core: numpy, pandas, hmmlearn
98
+ pip install "hmm-regime[data]" # also yfinance, for fetch_returns()
99
+ ```
100
+
101
+ The package is imported as `hmm_regime`. The latest unreleased code: `pip install git+https://github.com/mehmetoaltekin/hmm-regime-detection.git`.
102
+
103
+ To run the examples and tests:
104
+
105
+ ```bash
106
+ git clone https://github.com/mehmetoaltekin/hmm-regime-detection.git
107
+ cd hmm-regime-detection
108
+ pip install -e ".[dev]"
109
+ PYTHONPATH=. python examples/demo.py # offline demo on synthetic data, with the whipsaw filter
110
+ PYTHONPATH=. python examples/whipsaw_seeds.py # feature sets and whipsaw filter over seeds 0-9 (several minutes)
111
+ python -m pytest tests -v # look-ahead & regression tests
112
+ ```
113
+
114
+ ### Minimal usage
115
+
116
+ ```python
117
+ from hmm_regime import WalkForwardHMM, add_filtered_regime, fetch_returns
118
+
119
+ # 1. Stationary features: log return + per-bar log range variance
120
+ features = fetch_returns("XAUUSD", start="2015-01-01", end="2024-01-01", vol_feature="bar")
121
+
122
+ # 2. Walk-forward HMM: refit every 21 bars on the last 252 bars.
123
+ # Passing a list lets BIC choose K inside each training window.
124
+ model = WalkForwardHMM(n_components=[2, 3], window_size=252, step_size=21)
125
+
126
+ # 3. Out-of-sample filtered probabilities P(S_t | Y_1:t)
127
+ out = model.fit_predict_filtered(features)
128
+ out[["prob_regime_0", "prob_regime_1", "regime", "n_states", "prob_stress"]].tail()
129
+
130
+ # 4. A calm / stress label that does not flip on every noisy bar
131
+ out = add_filtered_regime(out, binary=True) # adds stress_filtered: 0 calm, 1 stress
132
+ ```
133
+
134
+ Offline alternative: `fetch_sample_data()` + `prepare_hmm_features()` (see `examples/demo.py`).
135
+
136
+ Code written against version 0.1 (`from src.hmm_model import WalkForwardHMM`) still runs from a checkout; [`CHANGELOG.md`](https://github.com/mehmetoaltekin/hmm-regime-detection/blob/main/CHANGELOG.md) lists what changed in the numbers and how to get the old behaviour, and [`AUDIT.md`](https://github.com/mehmetoaltekin/hmm-regime-detection/blob/main/AUDIT.md) the findings behind it.
137
+
138
+ ### How the walk-forward avoids look-ahead
139
+
140
+ At every refit time *t* the following uses only bars `< t`:
141
+
142
+ | Step | What is estimated | Data used |
143
+ |---|---|---|
144
+ | Feature scaling | mean / std of each feature | training window |
145
+ | Model selection | K by AIC/BIC (if a list is given) | training window |
146
+ | EM calibration | start, transition, means, covariances (best of `n_init` restarts) | training window |
147
+ | Filter warm-start | state belief at *t-1* | training window, forward filter |
148
+ | Output | P(S_t \| Y_1:t) for bars *t … t+step-1* | causal forward filter |
149
+
150
+ `tests/test_fixes.py::test_walk_forward_has_no_lookahead` corrupts all data after a cutoff and asserts every earlier output is unchanged.
151
+
152
+ ### Implementation notes
153
+
154
+ * **Scaling.** Raw returns (~0.01) and annualised volatility (~0.2) differ by an order of magnitude, which makes full covariance matrices near-singular. Features are standardised with training-window statistics; `MarketRegimeHMM.means_` / `.covars_` report parameters back in original units.
155
+ * **Multi-start EM.** `n_init` (default 10) independent EM runs; the highest log-likelihood is kept.
156
+ * **Continuous filtering.** `predict_filtered_proba(X, prior_proba=...)` carries the previous belief through the transition matrix instead of restarting from `startprob_`, so there is no artificial jump at each refit.
157
+ * **First bar.** Without a `prior_proba` the filter starts from the stationary distribution of the transition matrix. EM estimates `startprob_` from the single first training bar, so it puts all its mass on one state and would fix the state of the first bar whatever the data say.
158
+ * **State order.** State 0 is the state with the lowest return volatility: the spread of feature 0 (the return) around the training-window mean (`sort_by="variance:0"`). Alternatives: `"mean:j"` (e.g. the mean of a volatility feature) and `"trace"` (total variance of all standardised features, the rule before 0.2).
159
+ * **`prob_stress`.** The summed probability of the states that are more volatile than their training window's average. With K = 2 it is `prob_regime_1`. With K = 3 it does not call a second calm state "stress", which `1 - prob_regime_0` does; use it instead of a state number whenever K can change between refits.
160
+ * **One regime.** Add 1 to the candidates (`n_components=[1, 2, 3]`) to let a window without a second regime say so; `prob_stress` is then 0. With `[2, 3]` a split is forced on every window.
161
+ * **Covariance regulariser.** `covar_prior` (default 0.01, standardised units) is a ridge on the covariance diagonal in every M-step. It keeps a state that explains a handful of bars from collapsing to a singular covariance. `min_covar` only initialises EM (hmmlearn does not apply it afterwards).
162
+ * **Fit quality.** Every refit records `converged`, `min_state_obs` (expected training bars in the rarest state), `bic`, `aic` and `warnings` in `history_`; one summary line is logged if any refit has a warning.
163
+ * **Covariance types.** `"full"` and `"diag"` are supported. `"tied"` has no per-state variance to sort by; `"spherical"` is stored inconsistently by hmmlearn 0.3.x.
164
+ * **Choosing K.** Rolling volatility is highly autocorrelated, so information criteria favour more states that slice volatility levels: on synthetic data with two regimes BIC picks K = 3 in 98% of the windows with a 21-bar volatility and in 64% with a 5-bar one, against 7% with the per-bar feature (`fetch_sample_data`, seeds 0–9). The per-bar feature is not immune: on bars built from an intrabar path (`simulate_regime_ohlc`) its distribution is not exactly Gaussian and BIC picks K = 3 almost always. `prob_stress` is what keeps the calm / stress reading stable in those windows. Compare K candidates on economic interpretability, not BIC alone.
165
+
166
+ ### Choosing the volatility feature
167
+
168
+ `prepare_hmm_features` builds two features: the log return and a volatility measure.
169
+
170
+ | `vol_feature` | Second feature | Notes |
171
+ |---|---|---|
172
+ | `"rolling"` (default) | annualised volatility over the last `vol_window` bars (Parkinson with High/Low, else close-to-close) | the 0.1 behaviour |
173
+ | `"bar"` | log of the bar's own Parkinson variance, `ln(ln(H/L)² / (4 ln 2))` | needs High/Low; no window |
174
+
175
+ A Gaussian HMM assumes that, given the regime, each bar is a fresh draw. A rolling volatility is not: neighbouring windows share all bars but one, so the model sees the same information many times and treats it as certainty, and for `vol_window` bars after a change the window still contains the old regime. The per-bar log range is one noisy reading per bar, close to Gaussian (Alizadeh, Brandt & Diebold, 2002), and leaves the smoothing over time to the HMM, which is what the transition matrix is for.
176
+
177
+ Accuracy of the unfiltered calm / stress label (`prob_stress > 0.5`) against the true state, mean over seeds (min–max), 728 out-of-sample bars per seed. "True parameters" is a forward filter that knows the data generating process (`oracle_stress_proba` in `examples/demo.py`): the ceiling for any estimated model.
178
+
179
+ | Data | vol 21 | vol 5 | bar | True parameters |
180
+ |---|---|---|---|---|
181
+ | `fetch_sample_data`, seeds 0–9 | 0.77 (0.70–0.89) | 0.94 (0.92–0.95) | 0.96 (0.94–0.98) | 0.98 (0.96–0.99) |
182
+ | `fetch_sample_data`, seeds 10–29 | 0.76 (0.70–0.84) | 0.93 (0.90–0.95) | 0.96 (0.88–0.98) | 0.97 (0.96–0.99) |
183
+ | `simulate_regime_ohlc`, Gaussian returns, seeds 0–9 | 0.78 (0.68–0.83) | 0.93 (0.84–0.96) | 0.98 (0.97–0.99) | |
184
+ | `simulate_regime_ohlc`, Student-t(4) returns, seeds 0–9 | 0.75 (0.65–0.81) | 0.88 (0.80–0.93) | 0.89 (0.83–0.93) | |
185
+ | the same, whipsaw-filtered label | 0.74 (0.63–0.80) | 0.86 (0.79–0.91) | 0.92 (0.86–0.96) | |
186
+
187
+ Reading:
188
+ * With Gaussian returns the per-bar feature is the most accurate and close to the ceiling, and it returns to calm about 1 bar after the true change, against 3–4 bars (5-bar window) and 15–18 bars (21-bar window).
189
+ * With fat-tailed returns one extreme bar looks like stress to a per-bar feature: its unfiltered label is no more accurate than the 5-bar window's and flips 116 times per seed against 18 true changes. With the whipsaw filter it drops to 30 switches and is the most accurate of the three. Use `"bar"` together with the filter.
190
+ * All of this is synthetic data, where the true state is known. On real data there is no true state to score against; the argument for `"bar"` there is the one above (independent readings, no window memory), not these numbers.
191
+
192
+ Reproduce: `examples/whipsaw_seeds.py` (seeds 0–9), `... 10 30`, `... 0 10 0` (Gaussian path simulator), `... 0 10 4` (Student-t(4)).
193
+
194
+ ### Whipsaw filter
195
+
196
+ The raw label (argmax of the filtered probabilities) flips whenever the probabilities hover near a boundary, and every flip is a trade. `hmm_regime/whipsaw.py` turns the probabilities into a stickier label with three causal rules:
197
+
198
+ | Rule | Parameter | Effect |
199
+ |---|---|---|
200
+ | Hysteresis | `threshold` (default 0.7) | switch only to a state with P ≥ threshold; an ambiguous bar keeps the current regime |
201
+ | Confirmation | `confirm_bars` (default 2) | the same new state must pass the threshold on this many consecutive bars |
202
+ | Minimum dwell | `min_dwell` (default 0) | hold a regime at least this many bars before the next switch |
203
+
204
+ ```python
205
+ from hmm_regime import add_filtered_regime, switch_stats
206
+
207
+ out = model.fit_predict_filtered(features)
208
+ out = add_filtered_regime(out, binary=True) # adds stress_filtered: 0 calm, 1 stress
209
+ switch_stats(out["stress_filtered"]) # switches, switches per year, run lengths
210
+ ```
211
+
212
+ * **Causal.** The label at bar *t* uses probabilities up to *t* only: it is known at the close of *t*; act on it at the next bar's open. `tests/test_whipsaw.py` checks every cut point, for the filter and for the DataFrame wrapper on walk-forward output (both label types), and shows that the check catches planted one-bar leaks.
213
+ * **K changes.** `binary=True` filters `prob_stress` (the states more volatile than their training window's average), which keeps one meaning when the walk-forward switches K between refits; its unfiltered counterpart is `prob_stress > 0.5`. `stress_from="state0"` gives the rule before 0.2, calm = state 0 and stress = everything else (unfiltered counterpart `prob_regime_0 < 0.5`). With `binary=False` the label follows the K-state `regime`: if K shrinks and the held state disappears, the filter moves to the argmax at once (pass `n_states` when calling `filter_regimes` directly); if K grows, the held label keeps its number although the states were re-estimated.
214
+ * **Edge cases.** The first valid bar starts at the argmax and counts as a switch for `min_dwell`. A NaN row after that keeps the held regime, breaks a running confirmation and counts toward `min_dwell`. Use `threshold` > 0.5: at 0.5 or below a switch can happen on a tie.
215
+ * Every switch goes to that bar's argmax, so the filtered label never switches more often than the raw argmax of the same probabilities.
216
+ * **Cost: later detection.** `change_lags` lists every true change with its status and lag: *detected*, *missed* (the true state changed again first), *censored* (the data ended first) or *untracked* (on the bar before, the label was not on the old state, e.g. after missing the previous regime). `detection_lag` summarises it and can split by direction (`into=1`: onset of stress, `into=0`: return to calm). Two labels time different changes, so compare their lags on matched changes. `examples/whipsaw_seeds.py` (several minutes) runs the demo's comparison on synthetic seeds 0–9 with the filter at 0.7 × 2 bars. Switches, accuracy and lags: mean (min–max) over seeds; timed and missed changes: summed over seeds; lags in bars over detected changes:
217
+
218
+ | Feature | Label | Switches | Accuracy | To stress: timed / missed | Lag to stress | To calm: timed / missed | Lag to calm |
219
+ |---|---|---|---|---|---|---|---|
220
+ | | true state | 19.6 (12–28) | 1.00 | 98 / 0 | 0 | 98 / 0 | 0 |
221
+ | | true parameters | 29.1 (24–38) | 0.98 (0.96–0.99) | 97 / 2 | 0.4 (0.1–0.6) | 94 / 0 | 0.9 (0.3–1.3) |
222
+ | vol 21 | raw | 17.9 (8–22) | 0.77 (0.70–0.89) | 71 / 5 | 2.5 (0.5–5.3) | 91 / 24 | 15.3 (10.7–19.8) |
223
+ | vol 21 | filtered | 16.3 (8–22) | 0.75 (0.68–0.87) | 71 / 7 | 3.7 (1.5–6.3) | 89 / 23 | 16.6 (11.7–20.8) |
224
+ | vol 5 | raw | 21.8 (18–30) | 0.94 (0.92–0.95) | 94 / 3 | 0.8 (0.2–1.4) | 94 / 4 | 3.3 (2.9–4.1) |
225
+ | vol 5 | filtered | 19.8 (15–26) | 0.91 (0.88–0.93) | 91 / 7 | 1.9 (1.2–2.4) | 90 / 6 | 4.5 (3.5–5.2) |
226
+ | bar | raw | 32.8 (22–55) | 0.96 (0.94–0.98) | 97 / 4 | 0.8 (0.3–1.4) | 91 / 0 | 1.0 (0.4–2.0) |
227
+ | bar | filtered | 19.4 (12–25) | 0.94 (0.91–0.95) | 95 / 10 | 2.0 (1.4–2.6) | 86 / 2 | 2.4 (1.9–4.2) |
228
+
229
+ Reading:
230
+ * The filter matters most for the per-bar feature, whose raw label follows every noisy bar: it removes 13.4 switches per seed (−2 to −30) and brings the count to that of the true state. The rolling features are already smooth, so there is little to remove (−1.6 and −2.0 per seed).
231
+ * It costs about 0.02–0.03 accuracy for every feature.
232
+ * On every change both labels detect, the filtered label is at least one bar later, because confirmation needs two bars: per seed +1.0 to +2.0 bars to stress and +1.0 to +2.4 bars to calm (up to +8 for a single change).
233
+ * It misses more short regimes: stress onsets missed over the ten seeds go from 5 to 7 (vol 21), 3 to 7 (vol 5) and 4 to 10 (bar).
234
+ * The 21-bar feature returns to calm about 15 bars late and never shows 24 of the calm spells it was tracking. After such a miss the label is already in stress, so 27 of the 98 stress onsets are never timed.
235
+ * Even a filter that knows the true parameters switches 29 times against 20 true changes: part of the flipping is the noise in the data, not estimation error.
236
+
237
+ `examples/demo.py` shows one seed (42) and plots it.
238
+
239
+ Synthetic regimes are clean draws; real data (fat tails, intraday noise) flips more. With Student-t(4) returns the per-bar raw label switches 116 times per seed and the filter is no longer a cost: it removes 86 of them and raises accuracy from 0.89 to 0.92 (`examples/whipsaw_seeds.py 0 10 4`). Judge the filter by the costs it saves against the moves it misses, in the strategy itself, and fix its parameters before the backtest: each setting tried is one more trial.
240
+
241
+ ## 3. Limitations
242
+
243
+ While standard pitfalls like look ahead bias and arbitrary state switching are controlled for, several structural constraints remain inherent to the framework:
244
+
245
+ Detection Lag: Because forward filtering relies strictly on past and contemporaneous information ($P(S_t \mid Y_{1:t})$), regime changes require confirming bars to register. Consequently, the model naturally lags behind sudden liquidity cascades, flash crashes, or sharp exogenous shocks: the initial move is absorbed before the regime shift is registered. A rolling volatility feature adds its own window to that lag.
246
+
247
+ Gaussian Tail Underestimation: Asset returns systematically exhibit skewness and heavy tails (leptokurtosis). While Gaussian emissions ensure numerical stability and fast convergence during calibration, they structurally underestimate the frequency and impact of extreme tail events compared to fat-tailed alternatives like Student's $t$-distributions. In practice a single extreme bar is read as a change of regime; the per-bar feature is the most exposed to this (see the Student-t rows above).
248
+
249
+ Sensitivity to Initialization (Local Optima): Expectation-Maximization (Baum-Welch) is a hill climbing algorithm inherently sensitive to starting parameter vectors. The implementation mitigates this with multi-start EM (`n_init` restarts, best likelihood kept), but a global maximum is still not guaranteed.
250
+
251
+ Relative Regimes: "Calm" and "stress" are defined inside each training window. A window that contains only one regime is still split in two unless K = 1 is among the candidates, and a level of volatility that counts as stress in a quiet year can count as calm in a turbulent one.
252
+
253
+ Whipsaw & Turnover Drag: In noisy or transitional market phases, probabilities can hover near decision boundaries, causing the model to flip rapidly between regimes. In live execution, this regime jitter leads to excessive turnover, accumulating bid-ask spreads, exchange fees and execution slippage. The whipsaw filter (`hmm_regime/whipsaw.py`, see above) reduces the flips at the price of a later detection.
254
+
255
+ No Real-Data Results: Everything measured in this repository is on synthetic data, where the true state is known. It is a library, not a strategy.
256
+
257
+ ## Citation
258
+
259
+ If you use this architecture or reference this implementation in your research, please cite the repository:
260
+
261
+ ```bibtex
262
+ @software{altekin_hmm_regime_detection,
263
+ author = {Altekin, Mehmet},
264
+ title = {hmm-regime-detection: Quantitative market regime identification via Gaussian HMMs: walk-forward parameter estimation, state sorting, and information criteria (AIC/BIC) selection},
265
+ year = {2026},
266
+ version = {0.2.0},
267
+ publisher = {GitHub},
268
+ howpublished = {\url{https://github.com/mehmetoaltekin/hmm-regime-detection}}
269
+ }
270
+ ```
@@ -0,0 +1,233 @@
1
+ # hmm-regime-detection
2
+ Quantitative market regime identification via Gaussian HMMs: walk-forward parameter estimation, state sorting, and information criteria (AIC/BIC) selection.
3
+
4
+ ## Disclaimer
5
+ This repository is strictly for academic and quantitative research purposes.
6
+ Nothing contained herein constitutes financial, investment, or trading advice.
7
+ The authors accept no responsibility for any financial losses incurred through
8
+ the use of these models or strategies.
9
+
10
+ ## References
11
+
12
+ * **Alizadeh, S., Brandt, M. W., & Diebold, F. X. (2002).** *Range-Based Estimation of Stochastic Volatility Models.* The Journal of Finance, 57(3), 1047–1091.
13
+ * **Hamilton, J. D. (1989).** *A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.* Econometrica, 57(2), 357–384.
14
+ * **López de Prado, M. (2018).** *Advances in Financial Machine Learning.* John Wiley & Sons. (Chapter: Structural Breaks).
15
+ * **Parkinson, M. (1980).** *The Extreme Value Method for Estimating the Variance of the Rate of Return.* The Journal of Business, 53(1), 61–65.
16
+ * **Rabiner, L. R. (1989).** *A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition.* Proceedings of the IEEE, 77(2), 257–286.
17
+
18
+ # Market Regime Detection via Walk-Forward Gaussian HMM
19
+ [![CI Status](https://github.com/mehmetoaltekin/hmm-regime-detection/actions/workflows/ci.yml/badge.svg)](https://github.com/mehmetoaltekin/hmm-regime-detection/actions)
20
+
21
+ An econometric and quantitative research framework for out-of-sample market regime detection: rolling re-calibration, causal forward filtering, variance-sorted state labels and per-window model selection.
22
+
23
+ ## 1. Theoretical Framework
24
+
25
+ Financial return series rarely follow a single stationary distribution. In practice, markets alternate between distinct market regimes shifting rapidly between tranquil periods and sudden crisis states. To capture these structural shifts and the resulting time varying volatility, we model returns using a Hidden Markov Model (HMM).
26
+ Let $Y_t$ denote the observed return at time $t$. We assume the data generating process is driven by an unobserved discrete Markov chain $S_t \in \{1, \dots, K\}$, with state transition probabilities given by:
27
+
28
+ $$P(S_t = j \mid S_{t-1} = i) = A_{ij}$$
29
+
30
+ where $A$ is the $K \times K$ transition probability matrix. Conditional on being in regime $S_t = k$, observations are drawn from a Gaussian distribution:
31
+
32
+ $$Y_t \mid (S_t = k) \sim \mathcal{N}(\mu_k, \sigma_k^2)$$
33
+
34
+
35
+ # Methodological & Implementation Details
36
+
37
+ Applying regime switching models to sequential financial data introduces three specific estimation challenges that require structural safeguards:
38
+
39
+ Preventing Look Ahead Bias: Full sample inference techniques (such as the Viterbi algorithm or two sided smoothing) calculate smoothed probabilities $P(S_t \mid Y_{1:T})$. Because this conditions state assignment at time $t$ on future data ($t+1 \dots T$), it creates severe look ahead bias in backtests.
40
+
41
+ To maintain strict out of sample validity, we use only the forward algorithm to compute real time filtered probabilities:
42
+
43
+ $$P(S_t \mid Y_{1:t})$$
44
+
45
+ Resolving Label Switching: Because Expectation Maximization (EM / Baum-Welch) is an unsupervised procedure, state labels are arbitrary and can switch unpredictably between rolling estimation windows.
46
+ To ensure economic consistency over time, we sort and re index the regimes by their estimated return variance ($\sigma_k^2$) at each calibration step, pinning State 0 to the lowest volatility regime.
47
+
48
+ Model Selection ($K$): The number of hidden states is selected by balancing fit against parameter bloat using the Bayesian Information Criterion (BIC) and Akaike Information Criterion (AIC):
49
+
50
+ $$\text{BIC} = -2\ln(\hat{L}) + p \ln(T)$$
51
+
52
+ where $\hat{L}$ is the maximized likelihood, $p$ is the number of free parameters, and $T$ is the number of observations.
53
+
54
+
55
+ ## 2. Installation & Quickstart
56
+
57
+ To use the library in your own project:
58
+
59
+ ```bash
60
+ pip install hmm-regime # core: numpy, pandas, hmmlearn
61
+ pip install "hmm-regime[data]" # also yfinance, for fetch_returns()
62
+ ```
63
+
64
+ The package is imported as `hmm_regime`. The latest unreleased code: `pip install git+https://github.com/mehmetoaltekin/hmm-regime-detection.git`.
65
+
66
+ To run the examples and tests:
67
+
68
+ ```bash
69
+ git clone https://github.com/mehmetoaltekin/hmm-regime-detection.git
70
+ cd hmm-regime-detection
71
+ pip install -e ".[dev]"
72
+ PYTHONPATH=. python examples/demo.py # offline demo on synthetic data, with the whipsaw filter
73
+ PYTHONPATH=. python examples/whipsaw_seeds.py # feature sets and whipsaw filter over seeds 0-9 (several minutes)
74
+ python -m pytest tests -v # look-ahead & regression tests
75
+ ```
76
+
77
+ ### Minimal usage
78
+
79
+ ```python
80
+ from hmm_regime import WalkForwardHMM, add_filtered_regime, fetch_returns
81
+
82
+ # 1. Stationary features: log return + per-bar log range variance
83
+ features = fetch_returns("XAUUSD", start="2015-01-01", end="2024-01-01", vol_feature="bar")
84
+
85
+ # 2. Walk-forward HMM: refit every 21 bars on the last 252 bars.
86
+ # Passing a list lets BIC choose K inside each training window.
87
+ model = WalkForwardHMM(n_components=[2, 3], window_size=252, step_size=21)
88
+
89
+ # 3. Out-of-sample filtered probabilities P(S_t | Y_1:t)
90
+ out = model.fit_predict_filtered(features)
91
+ out[["prob_regime_0", "prob_regime_1", "regime", "n_states", "prob_stress"]].tail()
92
+
93
+ # 4. A calm / stress label that does not flip on every noisy bar
94
+ out = add_filtered_regime(out, binary=True) # adds stress_filtered: 0 calm, 1 stress
95
+ ```
96
+
97
+ Offline alternative: `fetch_sample_data()` + `prepare_hmm_features()` (see `examples/demo.py`).
98
+
99
+ Code written against version 0.1 (`from src.hmm_model import WalkForwardHMM`) still runs from a checkout; [`CHANGELOG.md`](https://github.com/mehmetoaltekin/hmm-regime-detection/blob/main/CHANGELOG.md) lists what changed in the numbers and how to get the old behaviour, and [`AUDIT.md`](https://github.com/mehmetoaltekin/hmm-regime-detection/blob/main/AUDIT.md) the findings behind it.
100
+
101
+ ### How the walk-forward avoids look-ahead
102
+
103
+ At every refit time *t* the following uses only bars `< t`:
104
+
105
+ | Step | What is estimated | Data used |
106
+ |---|---|---|
107
+ | Feature scaling | mean / std of each feature | training window |
108
+ | Model selection | K by AIC/BIC (if a list is given) | training window |
109
+ | EM calibration | start, transition, means, covariances (best of `n_init` restarts) | training window |
110
+ | Filter warm-start | state belief at *t-1* | training window, forward filter |
111
+ | Output | P(S_t \| Y_1:t) for bars *t … t+step-1* | causal forward filter |
112
+
113
+ `tests/test_fixes.py::test_walk_forward_has_no_lookahead` corrupts all data after a cutoff and asserts every earlier output is unchanged.
114
+
115
+ ### Implementation notes
116
+
117
+ * **Scaling.** Raw returns (~0.01) and annualised volatility (~0.2) differ by an order of magnitude, which makes full covariance matrices near-singular. Features are standardised with training-window statistics; `MarketRegimeHMM.means_` / `.covars_` report parameters back in original units.
118
+ * **Multi-start EM.** `n_init` (default 10) independent EM runs; the highest log-likelihood is kept.
119
+ * **Continuous filtering.** `predict_filtered_proba(X, prior_proba=...)` carries the previous belief through the transition matrix instead of restarting from `startprob_`, so there is no artificial jump at each refit.
120
+ * **First bar.** Without a `prior_proba` the filter starts from the stationary distribution of the transition matrix. EM estimates `startprob_` from the single first training bar, so it puts all its mass on one state and would fix the state of the first bar whatever the data say.
121
+ * **State order.** State 0 is the state with the lowest return volatility: the spread of feature 0 (the return) around the training-window mean (`sort_by="variance:0"`). Alternatives: `"mean:j"` (e.g. the mean of a volatility feature) and `"trace"` (total variance of all standardised features, the rule before 0.2).
122
+ * **`prob_stress`.** The summed probability of the states that are more volatile than their training window's average. With K = 2 it is `prob_regime_1`. With K = 3 it does not call a second calm state "stress", which `1 - prob_regime_0` does; use it instead of a state number whenever K can change between refits.
123
+ * **One regime.** Add 1 to the candidates (`n_components=[1, 2, 3]`) to let a window without a second regime say so; `prob_stress` is then 0. With `[2, 3]` a split is forced on every window.
124
+ * **Covariance regulariser.** `covar_prior` (default 0.01, standardised units) is a ridge on the covariance diagonal in every M-step. It keeps a state that explains a handful of bars from collapsing to a singular covariance. `min_covar` only initialises EM (hmmlearn does not apply it afterwards).
125
+ * **Fit quality.** Every refit records `converged`, `min_state_obs` (expected training bars in the rarest state), `bic`, `aic` and `warnings` in `history_`; one summary line is logged if any refit has a warning.
126
+ * **Covariance types.** `"full"` and `"diag"` are supported. `"tied"` has no per-state variance to sort by; `"spherical"` is stored inconsistently by hmmlearn 0.3.x.
127
+ * **Choosing K.** Rolling volatility is highly autocorrelated, so information criteria favour more states that slice volatility levels: on synthetic data with two regimes BIC picks K = 3 in 98% of the windows with a 21-bar volatility and in 64% with a 5-bar one, against 7% with the per-bar feature (`fetch_sample_data`, seeds 0–9). The per-bar feature is not immune: on bars built from an intrabar path (`simulate_regime_ohlc`) its distribution is not exactly Gaussian and BIC picks K = 3 almost always. `prob_stress` is what keeps the calm / stress reading stable in those windows. Compare K candidates on economic interpretability, not BIC alone.
128
+
129
+ ### Choosing the volatility feature
130
+
131
+ `prepare_hmm_features` builds two features: the log return and a volatility measure.
132
+
133
+ | `vol_feature` | Second feature | Notes |
134
+ |---|---|---|
135
+ | `"rolling"` (default) | annualised volatility over the last `vol_window` bars (Parkinson with High/Low, else close-to-close) | the 0.1 behaviour |
136
+ | `"bar"` | log of the bar's own Parkinson variance, `ln(ln(H/L)² / (4 ln 2))` | needs High/Low; no window |
137
+
138
+ A Gaussian HMM assumes that, given the regime, each bar is a fresh draw. A rolling volatility is not: neighbouring windows share all bars but one, so the model sees the same information many times and treats it as certainty, and for `vol_window` bars after a change the window still contains the old regime. The per-bar log range is one noisy reading per bar, close to Gaussian (Alizadeh, Brandt & Diebold, 2002), and leaves the smoothing over time to the HMM, which is what the transition matrix is for.
139
+
140
+ Accuracy of the unfiltered calm / stress label (`prob_stress > 0.5`) against the true state, mean over seeds (min–max), 728 out-of-sample bars per seed. "True parameters" is a forward filter that knows the data generating process (`oracle_stress_proba` in `examples/demo.py`): the ceiling for any estimated model.
141
+
142
+ | Data | vol 21 | vol 5 | bar | True parameters |
143
+ |---|---|---|---|---|
144
+ | `fetch_sample_data`, seeds 0–9 | 0.77 (0.70–0.89) | 0.94 (0.92–0.95) | 0.96 (0.94–0.98) | 0.98 (0.96–0.99) |
145
+ | `fetch_sample_data`, seeds 10–29 | 0.76 (0.70–0.84) | 0.93 (0.90–0.95) | 0.96 (0.88–0.98) | 0.97 (0.96–0.99) |
146
+ | `simulate_regime_ohlc`, Gaussian returns, seeds 0–9 | 0.78 (0.68–0.83) | 0.93 (0.84–0.96) | 0.98 (0.97–0.99) | |
147
+ | `simulate_regime_ohlc`, Student-t(4) returns, seeds 0–9 | 0.75 (0.65–0.81) | 0.88 (0.80–0.93) | 0.89 (0.83–0.93) | |
148
+ | the same, whipsaw-filtered label | 0.74 (0.63–0.80) | 0.86 (0.79–0.91) | 0.92 (0.86–0.96) | |
149
+
150
+ Reading:
151
+ * With Gaussian returns the per-bar feature is the most accurate and close to the ceiling, and it returns to calm about 1 bar after the true change, against 3–4 bars (5-bar window) and 15–18 bars (21-bar window).
152
+ * With fat-tailed returns one extreme bar looks like stress to a per-bar feature: its unfiltered label is no more accurate than the 5-bar window's and flips 116 times per seed against 18 true changes. With the whipsaw filter it drops to 30 switches and is the most accurate of the three. Use `"bar"` together with the filter.
153
+ * All of this is synthetic data, where the true state is known. On real data there is no true state to score against; the argument for `"bar"` there is the one above (independent readings, no window memory), not these numbers.
154
+
155
+ Reproduce: `examples/whipsaw_seeds.py` (seeds 0–9), `... 10 30`, `... 0 10 0` (Gaussian path simulator), `... 0 10 4` (Student-t(4)).
156
+
157
+ ### Whipsaw filter
158
+
159
+ The raw label (argmax of the filtered probabilities) flips whenever the probabilities hover near a boundary, and every flip is a trade. `hmm_regime/whipsaw.py` turns the probabilities into a stickier label with three causal rules:
160
+
161
+ | Rule | Parameter | Effect |
162
+ |---|---|---|
163
+ | Hysteresis | `threshold` (default 0.7) | switch only to a state with P ≥ threshold; an ambiguous bar keeps the current regime |
164
+ | Confirmation | `confirm_bars` (default 2) | the same new state must pass the threshold on this many consecutive bars |
165
+ | Minimum dwell | `min_dwell` (default 0) | hold a regime at least this many bars before the next switch |
166
+
167
+ ```python
168
+ from hmm_regime import add_filtered_regime, switch_stats
169
+
170
+ out = model.fit_predict_filtered(features)
171
+ out = add_filtered_regime(out, binary=True) # adds stress_filtered: 0 calm, 1 stress
172
+ switch_stats(out["stress_filtered"]) # switches, switches per year, run lengths
173
+ ```
174
+
175
+ * **Causal.** The label at bar *t* uses probabilities up to *t* only: it is known at the close of *t*; act on it at the next bar's open. `tests/test_whipsaw.py` checks every cut point, for the filter and for the DataFrame wrapper on walk-forward output (both label types), and shows that the check catches planted one-bar leaks.
176
+ * **K changes.** `binary=True` filters `prob_stress` (the states more volatile than their training window's average), which keeps one meaning when the walk-forward switches K between refits; its unfiltered counterpart is `prob_stress > 0.5`. `stress_from="state0"` gives the rule before 0.2, calm = state 0 and stress = everything else (unfiltered counterpart `prob_regime_0 < 0.5`). With `binary=False` the label follows the K-state `regime`: if K shrinks and the held state disappears, the filter moves to the argmax at once (pass `n_states` when calling `filter_regimes` directly); if K grows, the held label keeps its number although the states were re-estimated.
177
+ * **Edge cases.** The first valid bar starts at the argmax and counts as a switch for `min_dwell`. A NaN row after that keeps the held regime, breaks a running confirmation and counts toward `min_dwell`. Use `threshold` > 0.5: at 0.5 or below a switch can happen on a tie.
178
+ * Every switch goes to that bar's argmax, so the filtered label never switches more often than the raw argmax of the same probabilities.
179
+ * **Cost: later detection.** `change_lags` lists every true change with its status and lag: *detected*, *missed* (the true state changed again first), *censored* (the data ended first) or *untracked* (on the bar before, the label was not on the old state, e.g. after missing the previous regime). `detection_lag` summarises it and can split by direction (`into=1`: onset of stress, `into=0`: return to calm). Two labels time different changes, so compare their lags on matched changes. `examples/whipsaw_seeds.py` (several minutes) runs the demo's comparison on synthetic seeds 0–9 with the filter at 0.7 × 2 bars. Switches, accuracy and lags: mean (min–max) over seeds; timed and missed changes: summed over seeds; lags in bars over detected changes:
180
+
181
+ | Feature | Label | Switches | Accuracy | To stress: timed / missed | Lag to stress | To calm: timed / missed | Lag to calm |
182
+ |---|---|---|---|---|---|---|---|
183
+ | | true state | 19.6 (12–28) | 1.00 | 98 / 0 | 0 | 98 / 0 | 0 |
184
+ | | true parameters | 29.1 (24–38) | 0.98 (0.96–0.99) | 97 / 2 | 0.4 (0.1–0.6) | 94 / 0 | 0.9 (0.3–1.3) |
185
+ | vol 21 | raw | 17.9 (8–22) | 0.77 (0.70–0.89) | 71 / 5 | 2.5 (0.5–5.3) | 91 / 24 | 15.3 (10.7–19.8) |
186
+ | vol 21 | filtered | 16.3 (8–22) | 0.75 (0.68–0.87) | 71 / 7 | 3.7 (1.5–6.3) | 89 / 23 | 16.6 (11.7–20.8) |
187
+ | vol 5 | raw | 21.8 (18–30) | 0.94 (0.92–0.95) | 94 / 3 | 0.8 (0.2–1.4) | 94 / 4 | 3.3 (2.9–4.1) |
188
+ | vol 5 | filtered | 19.8 (15–26) | 0.91 (0.88–0.93) | 91 / 7 | 1.9 (1.2–2.4) | 90 / 6 | 4.5 (3.5–5.2) |
189
+ | bar | raw | 32.8 (22–55) | 0.96 (0.94–0.98) | 97 / 4 | 0.8 (0.3–1.4) | 91 / 0 | 1.0 (0.4–2.0) |
190
+ | bar | filtered | 19.4 (12–25) | 0.94 (0.91–0.95) | 95 / 10 | 2.0 (1.4–2.6) | 86 / 2 | 2.4 (1.9–4.2) |
191
+
192
+ Reading:
193
+ * The filter matters most for the per-bar feature, whose raw label follows every noisy bar: it removes 13.4 switches per seed (−2 to −30) and brings the count to that of the true state. The rolling features are already smooth, so there is little to remove (−1.6 and −2.0 per seed).
194
+ * It costs about 0.02–0.03 accuracy for every feature.
195
+ * On every change both labels detect, the filtered label is at least one bar later, because confirmation needs two bars: per seed +1.0 to +2.0 bars to stress and +1.0 to +2.4 bars to calm (up to +8 for a single change).
196
+ * It misses more short regimes: stress onsets missed over the ten seeds go from 5 to 7 (vol 21), 3 to 7 (vol 5) and 4 to 10 (bar).
197
+ * The 21-bar feature returns to calm about 15 bars late and never shows 24 of the calm spells it was tracking. After such a miss the label is already in stress, so 27 of the 98 stress onsets are never timed.
198
+ * Even a filter that knows the true parameters switches 29 times against 20 true changes: part of the flipping is the noise in the data, not estimation error.
199
+
200
+ `examples/demo.py` shows one seed (42) and plots it.
201
+
202
+ Synthetic regimes are clean draws; real data (fat tails, intraday noise) flips more. With Student-t(4) returns the per-bar raw label switches 116 times per seed and the filter is no longer a cost: it removes 86 of them and raises accuracy from 0.89 to 0.92 (`examples/whipsaw_seeds.py 0 10 4`). Judge the filter by the costs it saves against the moves it misses, in the strategy itself, and fix its parameters before the backtest: each setting tried is one more trial.
203
+
204
+ ## 3. Limitations
205
+
206
+ While standard pitfalls like look ahead bias and arbitrary state switching are controlled for, several structural constraints remain inherent to the framework:
207
+
208
+ Detection Lag: Because forward filtering relies strictly on past and contemporaneous information ($P(S_t \mid Y_{1:t})$), regime changes require confirming bars to register. Consequently, the model naturally lags behind sudden liquidity cascades, flash crashes, or sharp exogenous shocks: the initial move is absorbed before the regime shift is registered. A rolling volatility feature adds its own window to that lag.
209
+
210
+ Gaussian Tail Underestimation: Asset returns systematically exhibit skewness and heavy tails (leptokurtosis). While Gaussian emissions ensure numerical stability and fast convergence during calibration, they structurally underestimate the frequency and impact of extreme tail events compared to fat-tailed alternatives like Student's $t$-distributions. In practice a single extreme bar is read as a change of regime; the per-bar feature is the most exposed to this (see the Student-t rows above).
211
+
212
+ Sensitivity to Initialization (Local Optima): Expectation-Maximization (Baum-Welch) is a hill climbing algorithm inherently sensitive to starting parameter vectors. The implementation mitigates this with multi-start EM (`n_init` restarts, best likelihood kept), but a global maximum is still not guaranteed.
213
+
214
+ Relative Regimes: "Calm" and "stress" are defined inside each training window. A window that contains only one regime is still split in two unless K = 1 is among the candidates, and a level of volatility that counts as stress in a quiet year can count as calm in a turbulent one.
215
+
216
+ Whipsaw & Turnover Drag: In noisy or transitional market phases, probabilities can hover near decision boundaries, causing the model to flip rapidly between regimes. In live execution, this regime jitter leads to excessive turnover, accumulating bid-ask spreads, exchange fees and execution slippage. The whipsaw filter (`hmm_regime/whipsaw.py`, see above) reduces the flips at the price of a later detection.
217
+
218
+ No Real-Data Results: Everything measured in this repository is on synthetic data, where the true state is known. It is a library, not a strategy.
219
+
220
+ ## Citation
221
+
222
+ If you use this architecture or reference this implementation in your research, please cite the repository:
223
+
224
+ ```bibtex
225
+ @software{altekin_hmm_regime_detection,
226
+ author = {Altekin, Mehmet},
227
+ title = {hmm-regime-detection: Quantitative market regime identification via Gaussian HMMs: walk-forward parameter estimation, state sorting, and information criteria (AIC/BIC) selection},
228
+ year = {2026},
229
+ version = {0.2.0},
230
+ publisher = {GitHub},
231
+ howpublished = {\url{https://github.com/mehmetoaltekin/hmm-regime-detection}}
232
+ }
233
+ ```
@@ -0,0 +1,58 @@
1
+ """
2
+ hmm_regime: walk-forward Gaussian HMM regime detection with causal filtering.
3
+
4
+ from hmm_regime import WalkForwardHMM, prepare_hmm_features, add_filtered_regime
5
+ """
6
+
7
+ from hmm_regime.data_loader import (
8
+ compute_log_range_variance,
9
+ compute_log_returns,
10
+ compute_parkinson_volatility,
11
+ compute_realized_volatility,
12
+ fetch_returns,
13
+ fetch_sample_data,
14
+ prepare_hmm_features,
15
+ simulate_regime_ohlc,
16
+ )
17
+ from hmm_regime.hmm_model import MarketRegimeHMM, WalkForwardHMM, stationary_distribution
18
+ from hmm_regime.model_selection import (
19
+ count_free_parameters,
20
+ evaluate_regime_models,
21
+ select_model,
22
+ select_n_components,
23
+ )
24
+ from hmm_regime.whipsaw import (
25
+ add_filtered_regime,
26
+ calm_vs_stress,
27
+ change_lags,
28
+ detection_lag,
29
+ filter_regimes,
30
+ switch_stats,
31
+ )
32
+
33
+ __version__ = "0.2.0"
34
+
35
+ __all__ = [
36
+ "MarketRegimeHMM",
37
+ "WalkForwardHMM",
38
+ "stationary_distribution",
39
+ "prepare_hmm_features",
40
+ "compute_log_returns",
41
+ "compute_realized_volatility",
42
+ "compute_parkinson_volatility",
43
+ "compute_log_range_variance",
44
+ "fetch_returns",
45
+ "fetch_sample_data",
46
+ "simulate_regime_ohlc",
47
+ "count_free_parameters",
48
+ "evaluate_regime_models",
49
+ "select_model",
50
+ "select_n_components",
51
+ "filter_regimes",
52
+ "add_filtered_regime",
53
+ "calm_vs_stress",
54
+ "switch_stats",
55
+ "change_lags",
56
+ "detection_lag",
57
+ "__version__",
58
+ ]