Lesson 12: Regime Detection

Goal: Enable the system to know "what market we're in now" so it can choose the right strategy.


A Typical Scenario (Illustrative)

Note: The following is a synthetic example to illustrate common phenomena; numbers are illustrative and don't correspond to any specific institution/product.

In early 2021, a quant fund simultaneously ran two strategies: trend following and mean reversion. Both strategies performed excellently in their respective favorable markets.

The problem was they used fixed weights - 50% each.

Result:

  • In trending markets, trend strategy gained 20%, mean reversion lost 15%, net gain 2.5%
  • In ranging markets, mean reversion gained 15%, trend strategy lost 20%, net loss 2.5%
  • For the whole year, the two canceled each other out, returns close to zero

Their competitor? Same two strategies, but added a Regime Detection module:

  • In trending markets, trend strategy weight 80%, mean reversion 20%
  • In ranging markets, reversed

Result: 18% annual return, Sharpe ratio 1.6.

What's the difference? Not the strategies themselves, but knowing when to use which strategy. This is the value of regime detection - it's the "router" of the multi-agent system.


12.1 What Is Market Regime

Three Basic States

The market is always in some "state" at any moment. While boundaries between states aren't clear, they can be roughly categorized:

StateCharacteristicsBest StrategyTypical Duration
TrendingPrice moves persistently in one direction, volatility risesMomentum/Trend followingWeeks to months
Mean-RevertingPrice oscillates within a range, mean reversion worksMean reversion/GridWeeks to months
CrisisViolent swings, correlations spike, liquidity dries upRisk control priority/Cash is kingDays to weeks

Why Is Regime Detection So Hard?

ChallengeExplanation
Rearview mirror problemStates are clear in hindsight, fuzzy in real-time
Fuzzy boundariesNo clear dividing line between trend and ranging
Nested statesDaily ranging, weekly trending, monthly ranging can coexist
Detection lagBy the time you confirm the state, it may be nearly over
Switching costsFrequent strategy switching is itself a cost

Paper Exercise: Identify Historical States

Look at this data and judge each period's market state:

Period20-Day Return20-Day VolatilityADXYour Judgment
A+12%18%35?
B-2%8%15?
C-25%45%28?
D+3%12%22?
Click to expand answer
PeriodJudgmentReasoning
ATrending (up)High return + moderate volatility + high ADX (>25 indicates strong trend)
BRangingLow return + low volatility + low ADX (<20 indicates no trend)
CCrisisLarge decline + extremely high volatility (>30% annualized is warning level)
DWeak trend/TransitionReturn and ADX both in middle zone, hard to judge

Key finding: Period D is hardest to judge - this is the most common real-world situation - most of the time the market is in "gray zones."


12.2 Four Methods for Regime Detection

Method Comparison

MethodPrincipleProsConsUse Case
Rules-basedUse indicator thresholdsSimple, interpretable, no lagHard to choose thresholds, hard boundariesQuick prototype, baseline
StatisticalUse statistical tests to identify structural changesMathematically rigorousNeeds historical data, has lagOffline analysis
Machine LearningUse ML models to classifyCan capture complex patternsNeeds labels, overfitting riskWhen sufficient labeled data exists
Hidden MarkovAssume states follow Markov chainCan estimate state probabilitiesAssumptions may not holdWhen number of states is known

Method 1: Rules-Based (Most Practical)

Use combinations of technical indicator thresholds to judge state:

Rules-Based Regime Detection

Paper Exercise: Design Your Rules

Given the following market data, use the rules above to judge state:

ScenarioADX20-Day Volatility20-Day ReturnAsset CorrelationState
13222%+8%0.4?
21812%-1%0.3?
32538%-15%0.85?
42318%+3%0.5?
Click to expand answer
ScenarioStateDecision Path
1TrendingVol=22% < 30% (not crisis) -> ADX=32 > 25 and Ret=8% > 5% (trending)
2RangingVol=12% < 30% (not crisis) -> ADX=18 < 20 and Vol=12% < 15% (ranging)
3CrisisVol=38% > 30% and Corr=0.85 > 0.8 (crisis takes priority)
4TransitionDoesn't satisfy any clear condition (ADX=23 is between 20-25)

Method 2: Hidden Markov Model (HMM)

HMM assumes the market switches between several hidden states - we can only observe prices, not the true state.

HMM State Transitions

HMM Core Outputs:

  • State probabilities: Probability of being in each state now (e.g., Trending 60%, Ranging 30%, Crisis 10%)
  • Transition probabilities: Probability of switching from one state to another

Paper Exercise: Understanding State Probabilities

HMM outputs current state probabilities as: Trending 55%, Ranging 35%, Crisis 10%

Strategy Weight ApproachTrend StrategyMean ReversionDefense StrategyIssue
Hard switch100%0%0%Ignores 35% ranging probability
Probability weighted55%35%10%More robust, but slow crisis response
Adjusted weighting50%30%20%Amplify crisis weight as insurance

Key insight: State probabilities shouldn't be used directly as strategy weights - they need adjustment based on risk preference.

Code Implementation (For Engineers)
# Note: This is illustrative code showing basic HMM usage
# Requires hmmlearn: pip install hmmlearn

import numpy as np
from hmmlearn import hmm

class RegimeDetector:
    """HMM-based market regime detector"""

    def __init__(self, n_states: int = 3):
        self.n_states = n_states
        self.model = hmm.GaussianHMM(
            n_components=n_states,
            covariance_type="full",
            n_iter=100
        )

    def fit(self, features: np.ndarray):
        """
        Train HMM model

        features: shape (n_samples, n_features)
                  typically includes: returns, volatility, ADX, etc.
        """
        self.model.fit(features)
        return self

    def predict_proba(self, features: np.ndarray) -> np.ndarray:
        """
        Predict current state probability

        Returns: shape (n_states,) probability distribution
        """
        # Get posterior probabilities
        posteriors = self.model.predict_proba(features)
        return posteriors[-1]  # Latest time point probability

    def get_regime(self, features: np.ndarray, threshold: float = 0.5) -> str:
        """
        Get current state (with confidence threshold)
        """
        probs = self.predict_proba(features)
        max_prob = np.max(probs)
        max_state = np.argmax(probs)

        if max_prob < threshold:
            return "uncertain"

        state_names = ["trending", "mean_reverting", "crisis"]
        return state_names[max_state]

Method 3: Volatility Clustering (Practical Variant)

A simplified but practical approach is to only look at volatility state:

Volatility RangeStateStrategy Recommendation
< 15%Low volatility (Ranging)Mean reversion, Sell options
15% - 25%Normal volatilityNormal operation
25% - 35%High volatility (Trending)Trend following, Reduce positions
> 35%Extreme volatility (Crisis)Risk control priority, Major position reduction

Why Is Volatility So Important?

  • Volatility is the market's "temperature," quickly reflects market health
  • Volatility has clustering effect (high volatility tends to follow high volatility)
  • Volatility is more predictable than returns

12.3 Evaluating Regime Detection

Regime detection isn't the goal - the goal is improving strategy returns. So the evaluation standard isn't "accuracy" but "did it help the strategy make more money."

Evaluation Framework

Regime Detection Evaluation Metrics

Paper Exercise: Calculate Regime Detection Value

Scenario: Your Regime Detection module's past year performance:

MetricValue
State switch count24 times
Average state duration15 days
Switching lag3 days
False switch rate20% (switched back within 5 days)

Strategy Performance Comparison:

ApproachAnnual ReturnMax DrawdownSharpe Ratio
No Regime (fixed 50/50)8%18%0.6
With Regime (dynamic switching)15%12%1.2
Switching cost (24 times x 0.5%)-12%--

Questions:

  1. What is the net value-add of Regime Detection?
  2. If false switch rate drops to 10%, how would expected return change?
  3. What to do if switching cost is too high?
Click to expand answer
  1. Net value-add calculation:

    • Gross return improvement = 15% - 8% = 7%
    • Switching cost = 24 x 0.5% = 12% (assuming each switch involves full position adjustment)
    • Net value-add = 7% - 12% = -5% (Actually lost money!)

    Problem: Switching too frequently, costs ate up the gains!

  2. If false switch rate drops to 10%:

    • False switches drop from 4.8 to 2.4
    • 2.4 fewer useless switches saves 2.4 x 0.5% = 1.2%
    • Net value-add = -5% + 1.2% = -3.8% (still negative)
  3. Solutions for high switching costs:

    • Gradual switching: Not 0->100%, but 50%->70%->90%
    • Confirmation delay: State must persist N days before switching
    • Soft switching: Use probability weighting instead of hard switches
    • Reduce frequency: Only switch when state is very certain

Key lesson: Regime Detection value = Detection accuracy x Strategy difference - Switching cost

The Cost of Switching Lag

Lag DaysImpact in Trending MarketImpact in Crisis Market
1 dayMiss about 5% of the moveSuffer about 3% more loss
3 daysMiss about 15% of the moveSuffer about 10% more loss
5 daysMiss about 25% of the moveMay miss stop-loss timing
10 daysTrend may be half overCrisis may have ended

Conclusion: Better to have some false positives than too much lag. Especially crisis detection must be fast.


12.4 Common Misconceptions

Misconception 1: Higher Regime Detection accuracy is always better

Not entirely true. The evaluation standard isn't "accuracy" but "did it help the strategy make more money." 80% accuracy but switching costs eating returns is worse than 60% accuracy with fewer switches.

Misconception 2: Trend/Ranging is a binary judgment

In reality, most of the time the market is in "gray zones." Forcing binary judgment leads to frequent false switches. Correct approach: use probability weighting (Trend 60%/Ranging 40%) or acknowledge "Transition period."

Misconception 3: Switch strategy immediately when state change is detected

Dangerous approach. Switching itself has costs (trading costs, slippage), frequent switching can lose all gains. Correct approach: confirmation delay (state persists N days) + gradual switching (50%->70%->90%).

Misconception 4: Crisis detection can "wait for confirmation"

Crisis detection must be fast. By the time you confirm, you may have lost 20%. Better to false positive on crisis (earn less) than miss it (lose big).


12.5 Handling Transition Periods

The hardest thing to handle in reality isn't clear trends or ranging, but transition periods - state is changing, but not yet certain.

Characteristics of Transition Periods

CharacteristicManifestation
Indicator contradictionADX says trending, volatility says ranging
Fuzzy probabilitiesHMM outputs 40%/35%/25%, no clear dominant state
Signal conflictTrend and mean reversion strategies give opposite signals

Transition Period Strategies

Transition Period Strategies

Recommendation: For most investors, Strategy 3 (Risk Priority) is the safest choice. Transition periods are often the highest risk periods.


12.5 Multi-Agent Perspective

In multi-agent architecture, Regime Detection is Meta Agent's core capability.

Architecture Design

Meta-Agent Regime Routing

Regime Agent Responsibilities

ResponsibilitySpecific ContentTrigger Condition
State detectionJudge current market stateDaily/Hourly
Signal routingDecide which expert Agent to dispatch tasks toWhen state changes
Weight allocationAllocate expert weights based on state probabilityContinuous
Switching controlPrevent over-switching, manage transitionsWhen state is fuzzy
Retrospective attributionRecord state judgments for post-analysisContinuous

Collaboration with Other Agents

CollaboratorCollaboration Method
Signal AgentReceives Regime signals, adjusts strategy parameters
Risk AgentIn crisis state, Risk Agent gets greater veto power
Execution AgentDuring state switches, Execution Agent handles smooth rebalancing
Evolution AgentProvides historical accuracy of regime detection for model evolution

Acceptance Criteria

After completing this lesson, use these standards to verify learning:

CheckpointStandardSelf-Test Method
Understand three statesCan describe characteristics and best strategies for trend/ranging/crisisExplain in your own words
Master rules-based methodCan design judgment rules using ADX/volatility/correlationComplete paper exercises
Understand HMM principleCan explain the meaning and use of state probabilitiesExplain why not to directly use probabilities as weights
Evaluate detection valueCan calculate net value-add = Return improvement - Switching costComplete evaluation exercise
Handle transition periodsCan name three transition strategies and their use casesGive your choice and reasoning

Comprehensive Exercise

Design Your Regime Detection System:

  1. Choose detection method (Rules-based/HMM/Other) and explain why
  2. Define input features and thresholds
  3. Design transition period handling strategy
  4. Set switching confirmation conditions (prevent over-switching)
  5. Define evaluation metrics

Lesson Deliverables

After completing this lesson, you will have:

  1. Regime Detection design framework - Complete thinking from method selection to evaluation metrics
  2. Practical rules-based template - Directly usable ADX/volatility/correlation judgment rules
  3. Method to evaluate Regime Detection value - Net value-add = Return improvement - Switching cost
  4. Transition period handling strategies - Three approaches and their use cases

Lesson Summary

  • Understand the concept of market regime and its impact on strategy selection
  • Master four Regime Detection methods: rules-based, statistical, ML, HMM
  • Understand Regime Detection evaluation isn't "accuracy" but "economic value"
  • Master transition period handling strategies

Further Reading


Next Lesson Preview

Lesson 13: Regime Misjudgment and Systemic Collapse

Regime Detection is the core of multi-agent systems, but it makes mistakes - misjudgment, lag, boundary oscillation. Next lesson we dive deep into five failure modes of Regime Detection, and how to design degradation strategies to prevent systemic collapse.

Cite this chapter
Zhang, Wayland (2026). Lesson 12: Regime Detection. In AI Quantitative Trading: From Zero to One. https://waylandz.com/quant-book-en/Lesson-12-Regime-Detection
@incollection{zhang2026quant_Lesson_12_Regime_Detection,
  author = {Zhang, Wayland},
  title = {Lesson 12: Regime Detection},
  booktitle = {AI Quantitative Trading: From Zero to One},
  year = {2026},
  url = {https://waylandz.com/quant-book-en/Lesson-12-Regime-Detection}
}