market-regime-classification 0.1.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.
Files changed (25) hide show
  1. market_regime_classification-0.1.0/LICENSE +21 -0
  2. market_regime_classification-0.1.0/MANIFEST.in +3 -0
  3. market_regime_classification-0.1.0/PKG-INFO +245 -0
  4. market_regime_classification-0.1.0/README.md +217 -0
  5. market_regime_classification-0.1.0/market_regime_classification/__init__.py +8 -0
  6. market_regime_classification-0.1.0/market_regime_classification/config.py +66 -0
  7. market_regime_classification-0.1.0/market_regime_classification/data.py +167 -0
  8. market_regime_classification-0.1.0/market_regime_classification/detectors.py +464 -0
  9. market_regime_classification-0.1.0/market_regime_classification/evaluate.py +223 -0
  10. market_regime_classification-0.1.0/market_regime_classification/features.py +77 -0
  11. market_regime_classification-0.1.0/market_regime_classification/plotting.py +160 -0
  12. market_regime_classification-0.1.0/market_regime_classification/run.py +211 -0
  13. market_regime_classification-0.1.0/market_regime_classification/walkforward.py +120 -0
  14. market_regime_classification-0.1.0/market_regime_classification.egg-info/PKG-INFO +245 -0
  15. market_regime_classification-0.1.0/market_regime_classification.egg-info/SOURCES.txt +23 -0
  16. market_regime_classification-0.1.0/market_regime_classification.egg-info/dependency_links.txt +1 -0
  17. market_regime_classification-0.1.0/market_regime_classification.egg-info/entry_points.txt +2 -0
  18. market_regime_classification-0.1.0/market_regime_classification.egg-info/requires.txt +5 -0
  19. market_regime_classification-0.1.0/market_regime_classification.egg-info/top_level.txt +1 -0
  20. market_regime_classification-0.1.0/pyproject.toml +61 -0
  21. market_regime_classification-0.1.0/setup.cfg +4 -0
  22. market_regime_classification-0.1.0/tests/test_detectors.py +138 -0
  23. market_regime_classification-0.1.0/tests/test_features.py +69 -0
  24. market_regime_classification-0.1.0/tests/test_package.py +16 -0
  25. market_regime_classification-0.1.0/tests/test_walkforward.py +172 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The market-regime-classification authors
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,3 @@
1
+ include README.md
2
+ include LICENSE
3
+ recursive-include tests *.py
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.4
2
+ Name: market-regime-classification
3
+ Version: 0.1.0
4
+ Summary: Honest baseline for market regime detection: filtered HMM / GMM / vol-threshold with walk-forward economic evaluation
5
+ License-Expression: MIT
6
+ Keywords: market regimes,regime detection,hidden markov model,gaussian mixture,quantitative finance,walk-forward
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Financial and Insurance Industry
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Office/Business :: Financial :: Investment
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy>=1.26
23
+ Requires-Dist: pandas>=2.1
24
+ Requires-Dist: scikit-learn>=1.4
25
+ Requires-Dist: matplotlib>=3.8
26
+ Requires-Dist: yfinance>=0.2.40
27
+ Dynamic: license-file
28
+
29
+ # Market Regime Classification — Baseline Pipeline
30
+
31
+ [![PyPI](https://img.shields.io/pypi/v/market-regime-classification.svg)](https://pypi.org/project/market-regime-classification/)
32
+ [![Python versions](https://img.shields.io/pypi/pyversions/market-regime-classification.svg)](https://pypi.org/project/market-regime-classification/)
33
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
34
+
35
+ A deliberately simple, honest baseline for **detecting market regimes** with
36
+ statistical and machine-learning models, plus the evaluation discipline that
37
+ usually decides whether a regime model is real or an artifact.
38
+
39
+ The point of this scaffold is not to produce a trading system. It is to give
40
+ you a runnable reference for:
41
+
42
+ 1. **Filtered (causal) inference** — never forward-backward-smoothed
43
+ probabilities, which secretly use future data.
44
+ 2. **Walk-forward evaluation** — refit on a trailing window, predict the next
45
+ block out-of-sample.
46
+ 3. **Economic evaluation** — because "regime" has no ground truth, accuracy is
47
+ mostly meaningless. What matters is whether regime-conditional allocations
48
+ improve risk-adjusted return with acceptable turnover.
49
+
50
+ Distribution name: `market-regime-classification`.
51
+ Import package: `market_regime_classification`.
52
+ CLI command: `market-regime`.
53
+
54
+ ## Models included
55
+
56
+ | Name | Type | Notes |
57
+ |---|---|---|
58
+ | `vol_threshold` | Rule baseline | Trailing-window quantiles of 21-day realized vol. Hard labels, one-hot "probabilities". |
59
+ | `gmm` | Unsupervised ML | Gaussian mixture on standardized features; per-sample posterior, no temporal persistence. |
60
+ | `hmm` | Unsupervised ML | Full-covariance Gaussian HMM with EM (Baum-Welch), **forward-filtered only** at prediction time. States sorted by volatility. |
61
+
62
+ All three run through the same walk-forward harness and the same economic
63
+ scorecard. If the ML models cannot beat a simple vol quantile rule
64
+ out-of-sample, that is a finding, not a bug.
65
+
66
+ ## Install from PyPI
67
+
68
+ ```bash
69
+ pip install market-regime-classification
70
+
71
+ market-regime --help
72
+ market-regime --source synthetic --outdir outputs
73
+ ```
74
+
75
+ ## Development setup (uv)
76
+
77
+ This project is managed with [uv](https://docs.astral.sh/uv/). `pyproject.toml`
78
+ declares the dependencies and the `market-regime` console script; `uv.lock`
79
+ pins the full resolution.
80
+
81
+ ```bash
82
+ # Install uv if you don't have it
83
+ curl -LsSf https://astral.sh/uv/install.sh | sh
84
+
85
+ # Create .venv, install the project + dev dependencies from uv.lock
86
+ uv sync
87
+ ```
88
+
89
+ ## Quick start
90
+
91
+ ```bash
92
+ # No network needed: synthetic market with known latent regimes
93
+ # (~1–2 minutes for the default 5,000 days, mostly the HMM refits)
94
+ uv run market-regime --source synthetic --outdir outputs
95
+
96
+ # Real data (yfinance is a project dependency)
97
+ uv run market-regime --source yfinance --tickers SPY,TLT \
98
+ --start 2005-01-01 --outdir outputs
99
+
100
+ # Your own price CSV (date index, one or more price columns)
101
+ uv run market-regime --source csv --csv data/prices.csv --outdir outputs
102
+ ```
103
+
104
+ `uv run market-regime` invokes the console script declared in `pyproject.toml`:
105
+
106
+ ```toml
107
+ [project.scripts]
108
+ market-regime = "market_regime_classification.run:main"
109
+ ```
110
+
111
+ `uv run python -m market_regime_classification.run ...` is equivalent.
112
+
113
+ Run the tests:
114
+
115
+ ```bash
116
+ uv run pytest -q
117
+ ```
118
+
119
+ If you need a plain requirements file for a non-uv environment:
120
+
121
+ ```bash
122
+ uv export --format requirements-txt --no-hashes > requirements.txt
123
+ ```
124
+
125
+ ## What gets written
126
+
127
+ ```
128
+ outputs/
129
+ ├── features.csv
130
+ ├── vol_threshold_probabilities.csv
131
+ ├── vol_threshold_labels.csv
132
+ ├── vol_threshold_regime_stats.csv
133
+ ├── gmm_*.csv
134
+ ├── hmm_*.csv
135
+ ├── metrics.csv # economic scorecard, all detectors + buy & hold
136
+ ├── metrics.json
137
+ ├── agreement.csv # pairwise adjusted Rand index between detectors
138
+ ├── regimes.png # price shading, filtered probabilities, equity curves
139
+ └── true_states.csv # synthetic source only
140
+ ```
141
+
142
+ ## Features
143
+
144
+ Built from daily prices only (no look-ahead):
145
+
146
+ - `rv_5`, `rv_21`, `rv_63` — annualized realized volatility
147
+ - `vol_ratio` — `rv_5 / rv_63` (vol acceleration)
148
+ - `trend_21`, `trend_63` — log-price momentum
149
+ - `drawdown_63` — drawdown from the trailing 63-day high
150
+ - `corr_21` — average pairwise correlation (when >= 2 assets)
151
+
152
+ The reference feature for ordering/sorting regimes is `rv_21`. States are
153
+ always sorted low → high volatility so labels are comparable across refits.
154
+
155
+ ## How to read the results
156
+
157
+ - **`share` / `avg_run_days`** — a regime that flips every few days is not a
158
+ regime. Real vol regimes persist for weeks to months.
159
+ - **`fwd_vol` / `fwd_ret`** — forward 21-day realized volatility and return by
160
+ regime. Good separation here is the main evidence the detector found
161
+ something.
162
+ - **Sharpe / MaxDD / turnover** — the toy allocator maps state 0 → 100%
163
+ equity, state 1 → 50%, state 2 → 0%. It ignores costs, cash yield and
164
+ slippage; treat it as a diagnostic, not a strategy.
165
+ - **ARI between detectors** — how much the models agree. Very high agreement
166
+ plus little economic difference means the HMM is not earning its complexity.
167
+
168
+ On the synthetic sample, ARI against the *latent* state is typically only
169
+ ~0.1–0.3 even when forward-vol separation is strong. That is expected, not a
170
+ bug: every feature is a trailing window, so detection necessarily lags each
171
+ switch, and ARI penalizes every lagged day. The informative diagnostics are
172
+ regime-conditional forward volatility/return and the economic scorecard.
173
+
174
+ ## Deliberate limitations
175
+
176
+ This is a baseline, not a production system:
177
+
178
+ - Single asset target; multi-asset regime work needs covariance/correlation
179
+ state modeling.
180
+ - No transaction costs, borrow costs or cash yield in the scorecard.
181
+ - No hyperparameter search. `n_states`, `train_days` and `refit_every` are
182
+ fixed by CLI flags; choosing them on the test period would be data snooping.
183
+ - HMM is full-covariance with light regularization. It can still find local
184
+ optima; `n_init` restarts mitigate but do not eliminate this.
185
+ - The synthetic generator is a sanity check, not evidence about real markets.
186
+
187
+ ## The trap this pipeline is built to avoid
188
+
189
+ An HMM fitted on the full sample and queried with `predict_proba` returns
190
+ **smoothed** state probabilities. At time `t` they incorporate observations
191
+ after `t`. Plots look excellent; live results do not.
192
+ `market_regime_classification.detectors` runs its own forward recursion and
193
+ only ever consumes data up to `t`. `tests/` includes a causality test that
194
+ verifies truncating future rows does not change past probabilities.
195
+
196
+ ## Publishing to PyPI
197
+
198
+ Build and validate locally:
199
+
200
+ ```bash
201
+ uv build
202
+ uvx twine check dist/*
203
+ ```
204
+
205
+ Publish with an API token:
206
+
207
+ ```bash
208
+ UV_PUBLISH_TOKEN=pypi-... uv publish
209
+ ```
210
+
211
+ Or use the included GitHub Actions workflow
212
+ (`.github/workflows/publish.yml`) with PyPI
213
+ [Trusted Publishing](https://docs.pypi.org/trusted-publishers/): configure the
214
+ PyPI project to trust this repository and the `publish` workflow, then publish
215
+ a GitHub release. The workflow builds, runs `twine check`, and uploads via OIDC
216
+ — no long-lived token in the repository.
217
+
218
+ ## License
219
+
220
+ MIT. See [LICENSE](LICENSE).
221
+
222
+ ## Layout
223
+
224
+ ```
225
+ pyproject.toml # metadata, deps, console script, pytest/uv config
226
+ uv.lock # pinned dependency resolution (commit this)
227
+ .python-version # interpreter uv should use
228
+ LICENSE # MIT
229
+ MANIFEST.in # files included in the sdist
230
+ .github/workflows/
231
+ └── publish.yml # build + PyPI trusted publishing
232
+ market_regime_classification/
233
+ ├── config.py # CLI/config defaults
234
+ ├── data.py # synthetic generator, yfinance loader, CSV loader
235
+ ├── features.py # feature engineering
236
+ ├── detectors.py # vol-threshold, GMM, causal Gaussian HMM
237
+ ├── walkforward.py # rolling refit / out-of-sample harness
238
+ ├── evaluate.py # regime stats + economic scorecard
239
+ ├── plotting.py # diagnostic figure
240
+ └── run.py # end-to-end CLI
241
+ tests/
242
+ ├── test_features.py
243
+ ├── test_detectors.py
244
+ └── test_walkforward.py
245
+ ```
@@ -0,0 +1,217 @@
1
+ # Market Regime Classification — Baseline Pipeline
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/market-regime-classification.svg)](https://pypi.org/project/market-regime-classification/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/market-regime-classification.svg)](https://pypi.org/project/market-regime-classification/)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ A deliberately simple, honest baseline for **detecting market regimes** with
8
+ statistical and machine-learning models, plus the evaluation discipline that
9
+ usually decides whether a regime model is real or an artifact.
10
+
11
+ The point of this scaffold is not to produce a trading system. It is to give
12
+ you a runnable reference for:
13
+
14
+ 1. **Filtered (causal) inference** — never forward-backward-smoothed
15
+ probabilities, which secretly use future data.
16
+ 2. **Walk-forward evaluation** — refit on a trailing window, predict the next
17
+ block out-of-sample.
18
+ 3. **Economic evaluation** — because "regime" has no ground truth, accuracy is
19
+ mostly meaningless. What matters is whether regime-conditional allocations
20
+ improve risk-adjusted return with acceptable turnover.
21
+
22
+ Distribution name: `market-regime-classification`.
23
+ Import package: `market_regime_classification`.
24
+ CLI command: `market-regime`.
25
+
26
+ ## Models included
27
+
28
+ | Name | Type | Notes |
29
+ |---|---|---|
30
+ | `vol_threshold` | Rule baseline | Trailing-window quantiles of 21-day realized vol. Hard labels, one-hot "probabilities". |
31
+ | `gmm` | Unsupervised ML | Gaussian mixture on standardized features; per-sample posterior, no temporal persistence. |
32
+ | `hmm` | Unsupervised ML | Full-covariance Gaussian HMM with EM (Baum-Welch), **forward-filtered only** at prediction time. States sorted by volatility. |
33
+
34
+ All three run through the same walk-forward harness and the same economic
35
+ scorecard. If the ML models cannot beat a simple vol quantile rule
36
+ out-of-sample, that is a finding, not a bug.
37
+
38
+ ## Install from PyPI
39
+
40
+ ```bash
41
+ pip install market-regime-classification
42
+
43
+ market-regime --help
44
+ market-regime --source synthetic --outdir outputs
45
+ ```
46
+
47
+ ## Development setup (uv)
48
+
49
+ This project is managed with [uv](https://docs.astral.sh/uv/). `pyproject.toml`
50
+ declares the dependencies and the `market-regime` console script; `uv.lock`
51
+ pins the full resolution.
52
+
53
+ ```bash
54
+ # Install uv if you don't have it
55
+ curl -LsSf https://astral.sh/uv/install.sh | sh
56
+
57
+ # Create .venv, install the project + dev dependencies from uv.lock
58
+ uv sync
59
+ ```
60
+
61
+ ## Quick start
62
+
63
+ ```bash
64
+ # No network needed: synthetic market with known latent regimes
65
+ # (~1–2 minutes for the default 5,000 days, mostly the HMM refits)
66
+ uv run market-regime --source synthetic --outdir outputs
67
+
68
+ # Real data (yfinance is a project dependency)
69
+ uv run market-regime --source yfinance --tickers SPY,TLT \
70
+ --start 2005-01-01 --outdir outputs
71
+
72
+ # Your own price CSV (date index, one or more price columns)
73
+ uv run market-regime --source csv --csv data/prices.csv --outdir outputs
74
+ ```
75
+
76
+ `uv run market-regime` invokes the console script declared in `pyproject.toml`:
77
+
78
+ ```toml
79
+ [project.scripts]
80
+ market-regime = "market_regime_classification.run:main"
81
+ ```
82
+
83
+ `uv run python -m market_regime_classification.run ...` is equivalent.
84
+
85
+ Run the tests:
86
+
87
+ ```bash
88
+ uv run pytest -q
89
+ ```
90
+
91
+ If you need a plain requirements file for a non-uv environment:
92
+
93
+ ```bash
94
+ uv export --format requirements-txt --no-hashes > requirements.txt
95
+ ```
96
+
97
+ ## What gets written
98
+
99
+ ```
100
+ outputs/
101
+ ├── features.csv
102
+ ├── vol_threshold_probabilities.csv
103
+ ├── vol_threshold_labels.csv
104
+ ├── vol_threshold_regime_stats.csv
105
+ ├── gmm_*.csv
106
+ ├── hmm_*.csv
107
+ ├── metrics.csv # economic scorecard, all detectors + buy & hold
108
+ ├── metrics.json
109
+ ├── agreement.csv # pairwise adjusted Rand index between detectors
110
+ ├── regimes.png # price shading, filtered probabilities, equity curves
111
+ └── true_states.csv # synthetic source only
112
+ ```
113
+
114
+ ## Features
115
+
116
+ Built from daily prices only (no look-ahead):
117
+
118
+ - `rv_5`, `rv_21`, `rv_63` — annualized realized volatility
119
+ - `vol_ratio` — `rv_5 / rv_63` (vol acceleration)
120
+ - `trend_21`, `trend_63` — log-price momentum
121
+ - `drawdown_63` — drawdown from the trailing 63-day high
122
+ - `corr_21` — average pairwise correlation (when >= 2 assets)
123
+
124
+ The reference feature for ordering/sorting regimes is `rv_21`. States are
125
+ always sorted low → high volatility so labels are comparable across refits.
126
+
127
+ ## How to read the results
128
+
129
+ - **`share` / `avg_run_days`** — a regime that flips every few days is not a
130
+ regime. Real vol regimes persist for weeks to months.
131
+ - **`fwd_vol` / `fwd_ret`** — forward 21-day realized volatility and return by
132
+ regime. Good separation here is the main evidence the detector found
133
+ something.
134
+ - **Sharpe / MaxDD / turnover** — the toy allocator maps state 0 → 100%
135
+ equity, state 1 → 50%, state 2 → 0%. It ignores costs, cash yield and
136
+ slippage; treat it as a diagnostic, not a strategy.
137
+ - **ARI between detectors** — how much the models agree. Very high agreement
138
+ plus little economic difference means the HMM is not earning its complexity.
139
+
140
+ On the synthetic sample, ARI against the *latent* state is typically only
141
+ ~0.1–0.3 even when forward-vol separation is strong. That is expected, not a
142
+ bug: every feature is a trailing window, so detection necessarily lags each
143
+ switch, and ARI penalizes every lagged day. The informative diagnostics are
144
+ regime-conditional forward volatility/return and the economic scorecard.
145
+
146
+ ## Deliberate limitations
147
+
148
+ This is a baseline, not a production system:
149
+
150
+ - Single asset target; multi-asset regime work needs covariance/correlation
151
+ state modeling.
152
+ - No transaction costs, borrow costs or cash yield in the scorecard.
153
+ - No hyperparameter search. `n_states`, `train_days` and `refit_every` are
154
+ fixed by CLI flags; choosing them on the test period would be data snooping.
155
+ - HMM is full-covariance with light regularization. It can still find local
156
+ optima; `n_init` restarts mitigate but do not eliminate this.
157
+ - The synthetic generator is a sanity check, not evidence about real markets.
158
+
159
+ ## The trap this pipeline is built to avoid
160
+
161
+ An HMM fitted on the full sample and queried with `predict_proba` returns
162
+ **smoothed** state probabilities. At time `t` they incorporate observations
163
+ after `t`. Plots look excellent; live results do not.
164
+ `market_regime_classification.detectors` runs its own forward recursion and
165
+ only ever consumes data up to `t`. `tests/` includes a causality test that
166
+ verifies truncating future rows does not change past probabilities.
167
+
168
+ ## Publishing to PyPI
169
+
170
+ Build and validate locally:
171
+
172
+ ```bash
173
+ uv build
174
+ uvx twine check dist/*
175
+ ```
176
+
177
+ Publish with an API token:
178
+
179
+ ```bash
180
+ UV_PUBLISH_TOKEN=pypi-... uv publish
181
+ ```
182
+
183
+ Or use the included GitHub Actions workflow
184
+ (`.github/workflows/publish.yml`) with PyPI
185
+ [Trusted Publishing](https://docs.pypi.org/trusted-publishers/): configure the
186
+ PyPI project to trust this repository and the `publish` workflow, then publish
187
+ a GitHub release. The workflow builds, runs `twine check`, and uploads via OIDC
188
+ — no long-lived token in the repository.
189
+
190
+ ## License
191
+
192
+ MIT. See [LICENSE](LICENSE).
193
+
194
+ ## Layout
195
+
196
+ ```
197
+ pyproject.toml # metadata, deps, console script, pytest/uv config
198
+ uv.lock # pinned dependency resolution (commit this)
199
+ .python-version # interpreter uv should use
200
+ LICENSE # MIT
201
+ MANIFEST.in # files included in the sdist
202
+ .github/workflows/
203
+ └── publish.yml # build + PyPI trusted publishing
204
+ market_regime_classification/
205
+ ├── config.py # CLI/config defaults
206
+ ├── data.py # synthetic generator, yfinance loader, CSV loader
207
+ ├── features.py # feature engineering
208
+ ├── detectors.py # vol-threshold, GMM, causal Gaussian HMM
209
+ ├── walkforward.py # rolling refit / out-of-sample harness
210
+ ├── evaluate.py # regime stats + economic scorecard
211
+ ├── plotting.py # diagnostic figure
212
+ └── run.py # end-to-end CLI
213
+ tests/
214
+ ├── test_features.py
215
+ ├── test_detectors.py
216
+ └── test_walkforward.py
217
+ ```
@@ -0,0 +1,8 @@
1
+ """Market regime detection baseline.
2
+
3
+ The package is intentionally dependency-light: the Gaussian HMM is implemented
4
+ directly in NumPy so filtered (causal) state probabilities are available
5
+ without relying on a library's smoothed posterior.
6
+ """
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,66 @@
1
+ """Shared defaults for the baseline pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ TRADING_DAYS = 252
8
+
9
+ # Feature order is stable so that `rv_21` has a known column index after
10
+ # subsetting. Detectors still look up the volatility column by name.
11
+ FEATURE_ORDER: tuple[str, ...] = (
12
+ "rv_5",
13
+ "rv_21",
14
+ "rv_63",
15
+ "vol_ratio",
16
+ "trend_21",
17
+ "trend_63",
18
+ "drawdown_63",
19
+ "corr_21",
20
+ )
21
+
22
+ DEFAULT_DETECTORS: tuple[str, ...] = ("vol_threshold", "gmm", "hmm")
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Config:
27
+ """Model / walk-forward configuration.
28
+
29
+ Attributes
30
+ ----------
31
+ n_states:
32
+ Number of regimes. States are sorted by mean realized vol, so state 0
33
+ is always the calmest.
34
+ train_days:
35
+ Length of the trailing training window in trading days.
36
+ refit_every:
37
+ Number of out-of-sample days between refits.
38
+ vol_col:
39
+ Feature used to sort states and (for the rule baseline) to threshold.
40
+ random_state:
41
+ Seed for KMeans / GaussianMixture initialization.
42
+ hmm_n_init, hmm_max_iter:
43
+ Restarts and EM iteration cap for the hand-rolled HMM.
44
+ gmm_n_init:
45
+ Restarts for sklearn's GaussianMixture.
46
+ """
47
+
48
+ n_states: int = 3
49
+ train_days: int = 756 # ~3 years
50
+ refit_every: int = 63 # ~quarterly
51
+ vol_col: str = "rv_21"
52
+ random_state: int = 42
53
+ hmm_n_init: int = 3
54
+ hmm_max_iter: int = 50
55
+ gmm_n_init: int = 3
56
+
57
+ def feature_columns(self, available: list[str] | tuple[str, ...]) -> list[str]:
58
+ """Return FEATURE_ORDER columns present in `available`, plus vol_col."""
59
+ cols = [c for c in FEATURE_ORDER if c in available]
60
+ if self.vol_col not in cols:
61
+ if self.vol_col not in available:
62
+ raise KeyError(
63
+ f"vol_col={self.vol_col!r} missing from features: {list(available)}"
64
+ )
65
+ cols.append(self.vol_col)
66
+ return cols