r/algorithmictrading • • Jun 06 '26

Backtest Architecture Review: Multi-Asset Regime Switching Model (HMM + Conditional State Machine)

Hey everyone,

I am preparing to push a regime-switching policy to production and I am looking for some feedback on my architecture and a specific math anomaly.

My strategy is long-only, daily close execution, shifting capital between risk-on and risk-off instruments (holding exactly one asset at a time).

1. Regime Validation (HMM / MS-DR)
To ensure the mathematical validity of my HMM and prevent overfitting (too many states or features), I ran a regime inference using statsmodels Markov Switching Dynamic Regression (MS-DR).

The inferred hidden states show statistically significant variations in both average expected return and volatility.

2. Execution Layer and State Machine

To mitigate whipsaws during sudden liquidity panic and lag on violent, mean-reverting V-bottoms (HMMs are known to lag), I use uses a two-layer decision architecture.

The first layer generates discrete state probabilities via the HMM. The second layer feeds these probabilities into a conditional state machine. The latter synthesizes the HMM outputs alongside EOD market data (e.g., volatility or price distance to crucial moving averages) to make the final decision.

3. The vbt vs. QuantStats Sharpe Discrepancy

I backtested my model using vectorbt with cash_sharing=True over a multi-year cycle (~50 closed trades, Max DD ~22% from January 2022 till May 2026). Fill paths and drawdowns match identically across my analytical stacks, but I ran into a large divergence in annualized risk ratios:

  • vectorbt (group_by=True): Sharpe 1.31 | Sortino 1.95
  • QuantStats: Sharpe 0.91 | Sortino 1.34

My policy allocates 100% of capital in cash-equivalent instruments during defensive regimes. As far as I understand,vectorbt and QuantStats use different formula, but interestingly, the ratio of Sortino to Sharpe remains identical between both libraries (~1.48).

4. Validation and Robustness

Given the macro regime-switching nature of the system, the number of trades is intentionally low (~50 trades over the backtest horizon). To ensure statistical significance despite the low trade count:

  • MS-DR State Validation: As mentioned above, statsmodels confirms the latent regimes represent distinct market states.
  • OOS: Standard walk-forward optimization (hyper parameters optimization till 2021, and test from 2022)
  • Stress Testing: Trade shuffling (Montecarlo simulation) and fee/slippage degradation testing were applied to ensure the state machine thresholds don't collapse.
  • Risk-Free Rate: average of the FED Fund Rate (~4% in my study). While not 100% accurate, the quantstats Python package doesn't accept a time series of daily risk-free rates.

The equity curve chart below compares the performance of my strategy against that of QQQ during the January 2022 - May 2026 period:

  • Total return: 154% (vs 90% of QQQ)
  • Max DD: -23% (vs -35% of QQQ)
  • Longest DD days: 309 (vs 707 of QQQ)
  • CAGR: 23.7% (vs 15.8% of QQQ)

Montecarlo simulation results:

  • Bust probability (drawdown >= 50%): 0.0%
  • Goal probability: 100.0%
  • Maximum drawdown dict: {'min': np.float64(-0.4545879162289587), 'max': np.float64(-0.1371207593528134), 'mean': np.float64(-0.2491102335214213), 'median': np.float64(-0.24003417486462705), 'std': np.float64(0.05367118181123532), 'percentile_5': np.float64(-0.3549029751169525), 'percentile_95': np.float64(-0.17673633125820087)}
  • Sharpe range: 1.07 to 1.11
  • Drawdown range: -34.6% to -17.5%
  • CAGR range: 23.7% to 23.7%

Questions

  1. Has anyone integrated front-end vs. long-end credit duration spreads as features to lead equity volatility regimes, and did it provide independent alpha relative to generic high-yield spread velocity?
  2. How do you clean or handle zero-volatility "cash-parking" periods when building custom risk-reporting sheets for allocators who expect standard 252-day arithmetic accounting?
  3. Given the architecture and validation steps outlined above, what have I missed? Do you see any hidden structural blind spots, operational traps, or causes for concern before deploying to production?

Looking forward to your thoughts and critiques!

11 Upvotes

27 comments sorted by

View all comments

Show parent comment

1

u/Slight_Boat1910 Jun 12 '26

Thanks for your quick feedback, u/Zestyclose-Eagle1809 . Indeed, I take the worst 5% paths of my strategy and then check how QQQ did.

I then looked at autocorrelation and i think i found the problem:

==================================================

MOMENTUM AND WHIPSAW DIAGNOSTIC           

==================================================

Real QQQ OOS Autocorr (Lag 1):         -0.0280

Real Strategy OOS Autocorr (Lag 1):    -0.0408

==================================================

  QQQ MARKET DAILY RETURN ACF PROFILE (Lags 1-10)

==================================================

Lag 1 Autocorrelation: -0.0280

Lag 2 Autocorrelation: 0.0064

Lag 3 Autocorrelation: -0.0664

Lag 4 Autocorrelation: -0.0223

Lag 5 Autocorrelation: 0.0144

Lag 6 Autocorrelation: -0.0042

Lag 7 Autocorrelation: 0.0038

Lag 8 Autocorrelation: -0.0138

Lag 9 Autocorrelation: 0.0552

Lag 10 Autocorrelation: -0.0101

--------------------------------------------------

10-Day Return Autocorrelation (Lag 10): -0.0214

==================================================

==================================================

  STRATEGY V7 DAILY RETURN ACF PROFILE (Lags 1-10)

==================================================

Lag 1 Autocorrelation: -0.0409

Lag 2 Autocorrelation: 0.0303

Lag 3 Autocorrelation: -0.0522

Lag 4 Autocorrelation: 0.0033

Lag 5 Autocorrelation: -0.0059

Lag 6 Autocorrelation: -0.0097

Lag 7 Autocorrelation: -0.0009

Lag 8 Autocorrelation: 0.0114

Lag 9 Autocorrelation: 0.0379

Lag 10 Autocorrelation: -0.0246

--------------------------------------------------

10-Day Return Autocorrelation (Lag 10): -0.0931

==================================================

Note: when running via MCMC, everything is 0.

The 10 day autocorrelation of my strategy in the OSS is negative (its performance is mean reverting). However we know it does less than 50 trades in 4.5 years (less than one trade per month, on average), I suspect that is due to one of the safe assets I use (I have verified it returns are mean reverting).

1

u/Zestyclose-Eagle1809 Jun 13 '26

That result kills the momentum critique. You were worried MCMC is unfair because it has short memory and washes out trend. For that to be true your real path needs positive autocorrelation that MCMC destroys, and it doesn't have any. Real lag 1 is -0.028 for QQQ and -0.041 for your strategy, the 10 day read is -0.093 for the strategy. That is near zero leaning negative, not positive. No momentum in your return stream for MCMC to clean, so MCMC is fair and the tail underperformance we flagged is real, not made up..

One note tho.. is worth being precise about direction. Your returns are slightly mean reverting, MCMC produces exactly zero by construction. If anything that makes MCMC harsh on drawdown, not generous, because your real path gets a small bounce back that MCMC paths never see. The effect is tiny at these magnitudes but it points the opposite way from your worry. The critique is backwards.

Here is the bigger thing the test surfaced, and you already half caught it. You do under 50 trades in 4.5 years, less than one a month. That means your daily return series is mostly the safe asset you are parked in, not your edge. You confirmed that safe asset is mean reverting, so the -0.093 at 10 days is measuring your parking spot, not your strategy. Daily autocorrelation is the wrong resolution for a system that trades monthly. makes sense??

Drop to the per trade level, that is where your real sample lives and it is small. 50 trades. Remove the top 5 winners by fixed count, then the top 10, and see what is left of the edge. If the convexity all comes from 3 or 4 prints you have a tail harvester that has to be sized as a satellite. With N under 50 that test matters more than any autocorrelation number... so put your eyeballs there mate

And the question from last time is still open, it is the one that decides the fix. Are your worst 5% paths the same calendar paths as QQQ's worst 5%, or different ones? Same paths means you bleed exactly when QQQ bleeds and the conditional tail (-55% DD vs -49%, 933 days underwater vs 798) is a no diversification problem you fix with sizing. Different paths means it is a timing problem with a completely different fix. Which is it?