npx claudepluginhub brainbytes-dev/everything-claude-tradingThis skill uses the workspace's default tool permissions.
name: regime-detection
Provides Ktor server patterns for routing DSL, plugins (auth, CORS, serialization), Koin DI, WebSockets, services, and testApplication testing.
Conducts multi-source web research with firecrawl and exa MCPs: searches, scrapes pages, synthesizes cited reports. For deep dives, competitive analysis, tech evaluations, or due diligence.
Provides demand forecasting, safety stock optimization, replenishment planning, and promotional lift estimation for multi-location retailers managing 300-800 SKUs.
name: regime-detection description: Market regime detection using HMM, Markov switching, and structural break methods. Use when identifying market environments.
Financial returns are not drawn from a single distribution. They exhibit:
Regime-aware strategies can adapt position sizes, hedge ratios, and factor exposures to current conditions.
Returns-based:
Volatility-based:
Correlation-based:
HMM assumes observed returns are generated by an unobserved (hidden) state variable that follows a Markov chain.
Model specification:
- K states (typically 2-3)
- Each state k has: mean mu_k, variance sigma_k^2
- Transition matrix A: A_ij = P(state_t = j | state_{t-1} = i)
- Initial state distribution pi
Estimation (Baum-Welch / EM algorithm):
Step 1: Initialize parameters (K-means on returns is a good start)
Step 2: E-step: Forward-backward algorithm computes state probabilities
Step 3: M-step: Update mu_k, sigma_k, A given state probabilities
Step 4: Iterate until log-likelihood converges
Step 5: Viterbi algorithm recovers most likely state sequence
Typical 2-state result for equities:
State 1 (Bull): mu = +0.08%/day, sigma = 0.7%/day, duration ~200 days
State 2 (Bear): mu = -0.05%/day, sigma = 1.5%/day, duration ~50 days
Practical considerations:
Extension of HMM that embeds regime switching within a regression framework:
y_t = mu_{s_t} + phi_{s_t} * y_{t-1} + sigma_{s_t} * epsilon_t
Where s_t in {1, 2, ..., K} follows a Markov chain
Advantages over simple HMM:
- Can include exogenous variables with regime-dependent coefficients
- Handles autoregressive dynamics within each regime
- Standard econometric framework with well-understood properties
Markov Switching GARCH: Allows both mean and variance to switch. Captures the empirical fact that volatility dynamics differ across regimes.
Unlike HMM (which assumes recurring regimes), structural break tests identify permanent changes.
Chow Test:
Bai-Perron (1998, 2003):
CUSUM / CUSUM-of-Squares:
Step 1: Choose observable(s) — returns, realized volatility, yield curve slope, credit spreads
Step 2: Estimate HMM with K=2 and K=3 states
Step 3: Compare BIC scores to select number of states
Step 4: Extract filtered (real-time) state probabilities
Step 5: Define regime threshold — e.g., P(bear) > 0.7 triggers defensive positioning
Step 6: Backtest regime-conditional strategy:
- Full allocation in bull regime
- Reduced allocation or hedged in bear regime
Step 7: Measure value-add vs static allocation
Step 8: Monitor for false signals (whipsaws during regime transitions)
| Strategy Component | Bull/Low-Vol Regime | Bear/High-Vol Regime |
|---|---|---|
| Equity allocation | 100% target | 50-70% target |
| Position sizing | Normal | Reduced (vol-scaled) |
| Stop-losses | Wider | Tighter |
| Factor tilts | Momentum, Growth | Quality, Low-Vol |
| Rebalancing freq | Monthly | Weekly |
| Hedge ratio | Minimal | Increased (tail hedges) |
A simpler alternative to full HMM — use realized volatility with thresholds:
Compute: RV_t = sqrt(252 * mean(r_{t-20:t}^2)) [20-day realized vol]
Regime classification:
Low vol: RV_t < 30th percentile of historical RV
Normal vol: 30th-70th percentile
High vol: RV_t > 70th percentile
Or use VIX term structure:
Contango (VIX < VIX futures): complacency, low-vol regime
Backwardation (VIX > VIX futures): fear, high-vol regime
HMM Regime Detection Report — [Asset/Portfolio]
Estimation Period: [Start] to [End]
Number of States: 2 (selected by BIC)
State Parameters:
State 1 (Bull): mu = +12.5% ann. | sigma = 11.2% ann. | duration = 210 days
State 2 (Bear): mu = -18.3% ann. | sigma = 26.8% ann. | duration = 45 days
Transition Matrix:
To State 1 To State 2
From State 1 0.9952 0.0048
From State 2 0.0222 0.9778
Current State: State 1 (Bull) with P = 0.94
Regime-Conditional Performance of Strategy X:
Bull regime: Sharpe = 1.45, Max DD = -8%
Bear regime: Sharpe = -0.30, Max DD = -28%
Full sample: Sharpe = 0.85, Max DD = -28%
With regime adaptation (50% allocation in bear):
Full sample: Sharpe = 1.10, Max DD = -16%
Value-add: +0.25 Sharpe, -12% max DD reduction
[ ] Number of states justified (BIC/AIC comparison for K=2,3,4)
[ ] Filtered (not smoothed) probabilities used for real-time signals
[ ] Regime durations are plausible (not too short for trading frequency)
[ ] No look-ahead bias — model estimated on expanding window
[ ] Whipsaw analysis: how many false regime transitions?
[ ] Transaction cost impact of regime switching measured
[ ] Robustness to parameter perturbation tested
[ ] Comparison vs simple rules (e.g., 200-day MA, VIX threshold)
[ ] Regime persistence is sufficient to be actionable
Before using regime detection in production: