Quick Navigation
Overview
6
Configurable Thresholds
The Regime Strategy Selector is the orchestration layer that bridges regime detection (PINN, Markov HMM) with strategy execution. It automatically evaluates market conditions and selects the optimal trading strategy for the current regime.
System Architecture
Complete flow from market data ingestion through regime detection to automated strategy switching.
flowchart TB
subgraph DATA["Market Data Feeds"]
Yahoo["Yahoo Finance"]
Finnhub["Finnhub"]
CoinGecko["CoinGecko"]
Polygon["Polygon.io"]
end
subgraph REGIME["Regime Detection Layer"]
PINN["PINN Regime Predictor Physics-constrained Crisis probability"]
HMM["Markov HMM (252-bar) 4-state model Transition matrix"]
OUTPUTS["Outputs: regime, confidence, crisisWarning"]
end
subgraph SELECTOR["Regime Strategy Selector"]
GET_REGIME["1. Get current regime + confidence"]
EVAL_FITNESS["2. Evaluate fitness of all 6 strategies"]
CHECK_THRESH["3. Check fund thresholds"]
RECOMMEND["4. Recommend best strategy"]
URGENCY["5. Determine switch urgency"]
end
subgraph ORCHESTRATOR["Fund Manager Orchestrator"]
TICK["Tick Loop (60s)"]
STEP41["Step 4.1: Check regime switch"]
AUTO_CHECK["If auto-switch enabled + immediate urgency"]
EXECUTE["Execute switch"]
ALLOCATE["Update allocations"]
AUDIT["Record to audit trail"]
end
subgraph EXECUTOR["Algorithm Executor"]
TICK_DSL["Tick strategy DSL every 60s"]
EVAL_COND["Evaluate entry/exit conditions"]
TRADE["Execute trades via broker"]
end
DATA --> REGIME
Yahoo --> PINN
Finnhub --> PINN
CoinGecko --> HMM
Polygon --> HMM
PINN --> OUTPUTS
HMM --> OUTPUTS
OUTPUTS --> SELECTOR
GET_REGIME --> EVAL_FITNESS
EVAL_FITNESS --> CHECK_THRESH
CHECK_THRESH --> RECOMMEND
RECOMMEND --> URGENCY
SELECTOR --> ORCHESTRATOR
TICK --> STEP41
STEP41 --> AUTO_CHECK
AUTO_CHECK -->|Yes| EXECUTE
EXECUTE --> ALLOCATE
ALLOCATE --> AUDIT
ORCHESTRATOR --> EXECUTOR
TICK_DSL --> EVAL_COND
EVAL_COND --> TRADE
style PINN fill:#1a4d1a,stroke:#3fb950
style HMM fill:#1a3d4d,stroke:#58a6ff
style SELECTOR fill:#2d1a4d,stroke:#a371f7
style ORCHESTRATOR fill:#4d3d1a,stroke:#f0883e
Market Regimes
The system detects 5 distinct market regimes, each requiring a different trading approach.
stateDiagram-v2
[*] --> Bull
Bull --> Bear: Negative drift High volatility
Bull --> Sideways: Low momentum Moderate vol
Bull --> Crisis: VIX spike Correlation breakdown
Bear --> Bull: Positive drift Low volatility
Bear --> Recovery: Stabilization
Bear --> Crisis: Extreme volatility
Sideways --> Bull: Breakout up
Sideways --> Bear: Breakout down
Crisis --> Recovery: Volatility subsides
Crisis --> Bear: Continued decline
Recovery --> Bull: Full confidence
Recovery --> Sideways: Stall
note right of Bull: Positive drift Low vol, Hurst > 0.55
note right of Bear: Negative drift High vol, Hurst < 0.45
note right of Sideways: No drift Moderate vol, ranging
note right of Crisis: Extreme vol Correlations spike
note right of Recovery: Transition phase Rebuilding
Regime
Characteristics
Strategy Approach
BULL
Positive drift, low vol, Hurst > 0.55
Momentum, trend-following, let winners run
BEAR
Negative drift, high vol, Hurst < 0.45
Defensive, quick profits, tight stops
SIDEWAYS
No drift, moderate vol, ranging
Mean-reversion, vol selling, range trading
CRISIS
Extreme vol, correlations spike, tail risk
Capital preservation, hedging, risk parity
RECOVERY
Transition from crisis/bear to bull
Cautious momentum, rebuilding positions
6 Regime-Specific Strategies
Pre-built strategy ASTs optimized for each market regime.
Bull Market Momentum
Regimes: Bull, Recovery
Risk: Medium
Rides trends with wide stops, uses trailing stops to let winners run. Entry requires regime confirmation, trending market (Hurst > 0.55), RSI 50-75, price above SMA50.
Bull Factor Tilt
Regimes: Bull
Risk: High
Tilts toward high-beta, small-cap (SMB) factors in bull markets. Maximizes upside capture during strong trends.
Bear Defensive
Regimes: Bear, Crisis
Risk: Low
Mean-reverting on oversold conditions, low beta preference, tight stops (2.5%). Max position $15k.
Bear Pairs Trading
Regimes: Bear, Sideways
Risk: Medium
Market-neutral pairs on cointegrated assets. Enters on z-score extremes for statistical arbitrage.
Sideways Vol Selling
Regimes: Sideways
Risk: Medium
Sells volatility premium when IV > RV in ranging markets. Captures theta decay in low-momentum environments.
Crisis Risk Parity
Regimes: Crisis
Risk: Low
Maximum capital preservation with diversified defensive positions. Max position $10k, max drawdown 5%, max daily loss 1.5%.
Strategy Fitness Scoring
The selector evaluates each strategy's fitness for the current regime using weighted factors.
flowchart LR
subgraph INPUTS["Scoring Inputs"]
RM["Regime Match 40% weight"]
RA["Risk Alignment 25% weight"]
MF["Momentum Fit 20% weight"]
VF["Volatility Fit 15% weight"]
end
subgraph CALC["Calculation"]
FORMULA["fitness = ( regimeMatch * 0.40 + riskAlignment * 0.25 + momentumFit * 0.20 + volatilityFit * 0.15 ) * confidence"]
end
subgraph OUTPUT["Output"]
SCORE["Fitness Score 0.0 - 1.0"]
SELECTED["Selected Strategy"]
ALTS["Alternative Strategies"]
end
RM --> FORMULA
RA --> FORMULA
MF --> FORMULA
VF --> FORMULA
FORMULA --> SCORE
SCORE --> SELECTED
SCORE --> ALTS
style FORMULA fill:#2d1a4d,stroke:#a371f7
style SCORE fill:#1a4d1a,stroke:#3fb950
Factor
Weight
Description
Regime Match
40%
Does the strategy support this regime?
Risk Alignment
25%
Does risk level match regime needs?
Momentum Fit
20%
Momentum strategies for bull, defensive for crisis
Volatility Fit
15%
Low-vol strategies for crisis
Switch Decision Logic
The selector determines switch urgency based on crisis warnings and fitness differentials.
flowchart TD
START["Check Switch Decision"] --> CRISIS{"Crisis Warning > threshold?"}
CRISIS -->|Yes| IMMEDIATE["IMMEDIATE Auto-execute if enabled"]
CRISIS -->|No| FITNESS{"Fitness diff > 30%?"}
FITNESS -->|Yes| CONFIDENCE{"Confidence >= threshold?"}
FITNESS -->|No| DIFF15{"Fitness diff > 15%?"}
CONFIDENCE -->|Yes| SOON["SOON Recommend in UI"]
CONFIDENCE -->|No| OPTIONAL["OPTIONAL Show as suggestion"]
DIFF15 -->|Yes| OPTIONAL
DIFF15 -->|No| NONE["NONE Current strategy optimal"]
IMMEDIATE --> EXECUTE["Execute Switch"]
SOON --> UI_BADGE["Show urgency badge"]
OPTIONAL --> SUGGESTION["Display suggestion"]
NONE --> NO_ACTION["No action needed"]
style IMMEDIATE fill:#4d1a1a,stroke:#f85149
style SOON fill:#4d3d1a,stroke:#f0883e
style OPTIONAL fill:#1a3d4d,stroke:#58a6ff
style NONE fill:#1a4d1a,stroke:#3fb950
Urgency
Trigger
Action
Immediate
Crisis warning > threshold
Auto-execute if enabled
Soon
Fitness diff > 30% AND confidence >= threshold
Recommend in UI
Optional
Fitness diff > 15%
Show as suggestion
None
Current strategy optimal
No action
Configurable Thresholds
Each fund can have custom thresholds stored in the regime_thresholds JSONB column.
Threshold
Default
Range
Description
markovRegimeProbMin
0.60
0.30 - 0.90
Minimum Markov regime probability to confirm regime
hurstTrendingThreshold
0.55
0.45 - 0.70
Hurst exponent threshold for trending confirmation
garchVolatilityCap
25
15 - 50
GARCH volatility cap (%) for normal trading
crisisWarningThreshold
0.30
0.10 - 0.60
Crisis warning level to trigger defensive switch
regimeSwitchConfidenceMin
0.70
0.50 - 0.95
Confidence required to trigger automatic switch
minTicksBetweenSwitches
10
1 - 60
Minimum ticks (minutes) before allowing another switch
Threshold Presets
Three pre-configured threshold profiles for different risk tolerances.
flowchart LR
subgraph CONSERVATIVE["Conservative"]
C1["markovRegimeProbMin: 0.70"]
C2["crisisWarningThreshold: 0.20"]
C3["regimeSwitchConfidenceMin: 0.80"]
C4["minTicksBetweenSwitches: 20"]
end
subgraph MODERATE["Moderate (Default)"]
M1["markovRegimeProbMin: 0.60"]
M2["crisisWarningThreshold: 0.30"]
M3["regimeSwitchConfidenceMin: 0.70"]
M4["minTicksBetweenSwitches: 10"]
end
subgraph AGGRESSIVE["Aggressive"]
A1["markovRegimeProbMin: 0.50"]
A2["crisisWarningThreshold: 0.40"]
A3["regimeSwitchConfidenceMin: 0.60"]
A4["minTicksBetweenSwitches: 5"]
end
style CONSERVATIVE fill:#1a4d1a,stroke:#3fb950
style MODERATE fill:#1a3d4d,stroke:#58a6ff
style AGGRESSIVE fill:#4d1a1a,stroke:#f85149
Conservative
Higher thresholds for more certainty before switching. Lower crisis warning threshold for earlier defensive moves. Longer wait between switches.
Moderate (Default)
Balanced approach with reasonable confirmation requirements. Suitable for most funds.
Aggressive
Lower thresholds for faster regime response. Higher crisis tolerance before switching. Shorter intervals between switches.
API Reference
GET /api/predict/v1/fund-manager/:id/regime
Returns current regime status, thresholds, and recommendations.
POST /api/predict/v1/fund-manager/:id/regime
Execute a regime-based strategy switch.
PUT /api/predict/v1/fund-manager/:id/regime
Update thresholds and auto-switch settings.
sequenceDiagram
participant UI as RegimeStrategyPanel
participant API as /fund-manager/:id/regime
participant Selector as RegimeStrategySelector
participant Repo as FundRepository
UI->>API: GET (fetch current state)
API->>Selector: getCurrentRegimeWithConfidence()
API->>Selector: getFundThresholds(fundId)
API->>Selector: selectRegimeStrategy(fundId)
API->>Selector: checkRegimeSwitch(fundId, currentStrategy)
Selector-->>API: regime, thresholds, recommendation, switchDecision
API-->>UI: { currentRegime, thresholds, recommendation, switchDecision }
UI->>API: POST (execute switch)
API->>Selector: selectRegimeStrategy(fundId, { forceRegime })
API->>Selector: executeRegimeSwitch(fundId, userId, strategy)
Selector->>Repo: Update fund, create algorithm run
Selector-->>API: { success, newAlgorithmId, newRunId }
API-->>UI: Switch result
UI->>API: PUT (update settings)
API->>Repo: Update regime_auto_switch_enabled
API->>Selector: applyThresholdPreset(fundId, preset) or updateFundThresholds()
Selector-->>API: Updated thresholds
API-->>UI: { success, thresholds }
Fund Manager Integration
The regime selector is integrated into the Fund Manager tick loop at Step 4.1.
flowchart TB
subgraph TICK_LOOP["Fund Manager Tick Loop (60s)"]
STEP1["Step 1: Update prices & NAV"]
STEP2["Step 2: Update positions P&L"]
STEP3["Step 3: Check risk limits"]
STEP4["Step 4: Tick algorithm strategies"]
STEP41["Step 4.1: Check regime switch"]
STEP5["Step 5: Process Stock Hunter"]
STEP6["Step 6: Log telemetry"]
end
STEP1 --> STEP2 --> STEP3 --> STEP4
STEP4 --> STEP41
STEP41 --> STEP5 --> STEP6
subgraph REGIME_CHECK["Step 4.1 Detail"]
CHECK_ENABLED{"regimeAutoSwitchEnabled?"}
GET_DECISION["checkRegimeSwitch(fundId, currentStrategy)"]
IS_IMMEDIATE{"urgency === 'immediate'?"}
SELECT["selectRegimeStrategy(fundId)"]
EXECUTE_SWITCH["executeRegimeSwitch(fundId, userId, strategy)"]
LOG["Log to audit trail"]
end
STEP41 --> CHECK_ENABLED
CHECK_ENABLED -->|Yes| GET_DECISION
CHECK_ENABLED -->|No| STEP5
GET_DECISION --> IS_IMMEDIATE
IS_IMMEDIATE -->|Yes| SELECT
IS_IMMEDIATE -->|No| STEP5
SELECT --> EXECUTE_SWITCH
EXECUTE_SWITCH --> LOG
LOG --> STEP5
style STEP41 fill:#4d3d1a,stroke:#f0883e
style EXECUTE_SWITCH fill:#1a4d1a,stroke:#3fb950
UI Components
The RegimeStrategyPanel displays on the Fund Detail page (/fund-manager/:id).
Current Market Regime
Shows detected regime with confidence indicator and crisis warning level.
Recommended Strategy
Displays best strategy with fitness score and alternative options.
Switch Decision
Shows urgency badge and action button when switch is recommended.
Auto-Switch Toggle
Enable/disable autonomous strategy switching.
Threshold Sliders
Adjust individual thresholds with real-time preview.
Preset Buttons
One-click application of Conservative, Moderate, or Aggressive presets.
Audit Trail
All regime decisions are logged to predict.fund_audit_log.
Event Type
Data Logged
regime_switch_recommended
currentRegime, newRegime, urgency, recommendation, fitnessScores
regime_switch_executed
newAlgorithmId, newRunId, regime, fitness, previousStrategy
threshold_updated
previousThresholds, newThresholds, preset (if applied)
auto_switch_toggled
enabled, triggeredBy
Files Reference
File
Description
packages/be/src/fund-manager/regime-strategy-selector.ts
Core selector logic
packages/be/src/fund-manager/orchestrator.ts
Tick loop integration
packages/be/src/fund-manager/types.ts
Fund type with regime fields
packages/be/src/fund-manager/repository.ts
Database mapping
packages/be/src/algorithms/strategies/regime-specific-strategies.ts
6 strategy ASTs
apps/web/src/app/api/predict/v1/fund-manager/[id]/regime/route.ts
API routes
packages/fe/src/components/fund-manager/RegimeStrategyPanel.tsx
UI component
db/migrations/265_fund_regime_thresholds.sql
Schema migration