# AI Regime Strategy Selector

> **AI Fund Manager Feature** — Automatically selects and switches trading strategies based on market regime.

## Overview

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.

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                    MARKET DATA FEEDS                            │
│         (Yahoo, Finnhub, CoinGecko, Polygon, etc.)              │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                   REGIME DETECTION LAYER                        │
│  ┌────────────────────────┐  ┌────────────────────────────┐    │
│  │  PINN Regime Predictor │  │  Markov HMM (252-bar)      │    │
│  │  • Physics-constrained │  │  • 4-state model           │    │
│  │  • Crisis probability  │  │  • Transition matrix       │    │
│  └────────────────────────┘  └────────────────────────────┘    │
│                              │                                  │
│              Outputs: regime, confidence, crisisWarning         │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                REGIME STRATEGY SELECTOR                         │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  1. Get current regime + confidence                       │  │
│  │  2. Evaluate fitness of all 6 strategies for regime      │  │
│  │  3. Check fund thresholds (configurable)                  │  │
│  │  4. Recommend best strategy with fitness score            │  │
│  │  5. Determine switch urgency (immediate/soon/optional)    │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                  FUND MANAGER ORCHESTRATOR                      │
│  Tick Loop (60s):                                               │
│  • Step 4.1: Check regime strategy switch                       │
│  • If auto-switch enabled + immediate urgency → execute switch  │
│  • Create new algorithm run with regime-appropriate strategy    │
│  • Update fund allocations                                      │
│  • Record to audit trail                                        │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    ALGORITHM EXECUTOR                           │
│  • Tick strategy DSL every 60s                                  │
│  • Evaluate entry/exit conditions                               │
│  • Execute trades via broker adapter                            │
└─────────────────────────────────────────────────────────────────┘
```

## Market Regimes

The system detects 5 market regimes:

| 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 |

## Regime-Specific Strategies

### 1. Bull Market Momentum
**Regimes:** Bull, Recovery
**Risk Level:** Medium
**Description:** Rides trends with wide stops, uses trailing stops to let winners run.

```yaml
entry:
  when: all(
    is_regime_bull(252),
    markov_regime_prob(252) > 0.60,
    is_trending(100, 0.55),
    rsi(14) > 50,
    rsi(14) < 75,
    close > sma(50),
    garch_volatility(100) < 25,
    factor_alpha(252) > 0
  )
  size: kelly_regime_aware(0.58, 2.5, max_position_usd)

exit:
  when: any(
    !is_regime_bull(252),
    !is_trending(100, 0.50),
    garch_volatility(100) > 35,
    position_pnl_pct() < -6,
    position_pnl_pct() > 20
  )

risk:
  max_position_usd: 40000
  max_drawdown_pct: 12
  stop_loss_pct: 6
  trailing_stop_pct: 4
```

### 2. Bull Factor Tilt
**Regimes:** Bull
**Risk Level:** High
**Description:** Tilts toward high-beta, small-cap (SMB) factors in bull markets.

### 3. Bear Defensive
**Regimes:** Bear, Crisis
**Risk Level:** Low
**Description:** Mean-reverting on oversold conditions, low beta preference, tight stops.

```yaml
entry:
  when: all(
    is_regime_bear(252),
    rsi(14) < 35,
    factor_beta(252) < 0.8,
    garch_volatility(100) < 40
  )

risk:
  max_position_usd: 15000
  stop_loss_pct: 2.5
  trailing_stop_pct: 1.5
```

### 4. Bear Pairs Trading
**Regimes:** Bear, Sideways
**Risk Level:** Medium
**Description:** Market-neutral pairs on cointegrated assets, z-score extremes.

### 5. Sideways Vol Selling
**Regimes:** Sideways
**Risk Level:** Medium
**Description:** Sells volatility premium when IV > RV in ranging markets.

### 6. Crisis Risk Parity
**Regimes:** Crisis
**Risk Level:** Low
**Description:** Maximum capital preservation with diversified defensive positions.

```yaml
risk:
  max_position_usd: 10000
  max_drawdown_pct: 5
  stop_loss_pct: 3
  max_daily_loss_pct: 1.5
```

## Configurable Thresholds

Each fund can have custom thresholds stored in `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

**Conservative:**
- Higher thresholds for more certainty before switching
- Lower crisis warning threshold for earlier defensive moves
- Longer wait between switches

```json
{
  "markovRegimeProbMin": 0.70,
  "crisisWarningThreshold": 0.20,
  "regimeSwitchConfidenceMin": 0.80,
  "minTicksBetweenSwitches": 20
}
```

**Moderate:** (Default)
```json
{
  "markovRegimeProbMin": 0.60,
  "crisisWarningThreshold": 0.30,
  "regimeSwitchConfidenceMin": 0.70,
  "minTicksBetweenSwitches": 10
}
```

**Aggressive:**
- Lower thresholds for faster regime response
- Higher crisis tolerance before switching
- Shorter intervals between switches

```json
{
  "markovRegimeProbMin": 0.50,
  "crisisWarningThreshold": 0.40,
  "regimeSwitchConfidenceMin": 0.60,
  "minTicksBetweenSwitches": 5
}
```

## Strategy Fitness Scoring

The selector evaluates each strategy's fitness for the current regime using weighted factors:

| 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 |

**Fitness Score Calculation:**
```typescript
fitness = (
  regimeMatch * 0.40 +
  riskAlignment * 0.25 +
  momentumFit * 0.20 +
  volatilityFit * 0.15
) * confidence;
```

## Switch Decision Logic

The selector determines switch urgency based on:

| 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 |

## API Endpoints

### GET /api/predict/v1/fund-manager/:id/regime

Returns current regime status, thresholds, and recommendations.

**Response:**
```json
{
  "data": {
    "currentRegime": {
      "regime": "bull",
      "confidence": 0.78,
      "crisisWarning": 0.05,
      "transitionProbability": 0.12
    },
    "thresholds": {
      "markovRegimeProbMin": 0.60,
      "hurstTrendingThreshold": 0.55,
      "garchVolatilityCap": 25,
      "crisisWarningThreshold": 0.30,
      "regimeSwitchConfidenceMin": 0.70,
      "minTicksBetweenSwitches": 10
    },
    "autoSwitchEnabled": true,
    "lastSwitchAt": "2026-05-19T10:30:00Z",
    "recommendation": {
      "selectedStrategy": "Bull Market Momentum",
      "alternativeStrategies": ["Bull Factor Tilt", "Bear Pairs Trading"],
      "fitnessScore": 0.85,
      "reason": "Selected Bull Market Momentum for bull regime (fitness: 85%)"
    },
    "switchDecision": {
      "shouldSwitch": false,
      "urgency": "none",
      "recommendation": "Current strategy Bull Market Momentum remains optimal",
      "currentStrategyFitness": 0.85,
      "newStrategyFitness": null
    },
    "availableStrategies": [
      {
        "name": "Bull Market Momentum",
        "regimes": ["bull", "recovery"],
        "riskLevel": "medium",
        "description": "Rides trends with trailing stops",
        "suitableFor": ["growth", "momentum", "equity-focused"]
      }
    ],
    "presets": ["conservative", "moderate", "aggressive"],
    "defaultThresholds": { ... }
  }
}
```

### POST /api/predict/v1/fund-manager/:id/regime

Execute a regime-based strategy switch.

**Request:**
```json
{
  "forceRegime": "bear"  // Optional: override detected regime
}
```

**Response:**
```json
{
  "data": {
    "success": true,
    "newAlgorithmId": "algo_abc123",
    "newRunId": "run_xyz789",
    "strategy": "Bear Defensive",
    "regime": "bear",
    "fitnessScore": 0.92
  }
}
```

### PUT /api/predict/v1/fund-manager/:id/regime

Update thresholds and auto-switch settings.

**Request (preset):**
```json
{
  "preset": "conservative"
}
```

**Request (custom thresholds):**
```json
{
  "autoSwitchEnabled": true,
  "thresholds": {
    "markovRegimeProbMin": 0.65,
    "crisisWarningThreshold": 0.25
  }
}
```

## Database Schema

### Migration 265: Fund Regime Thresholds

```sql
ALTER TABLE predict.funds
ADD COLUMN regime_thresholds JSONB DEFAULT NULL,
ADD COLUMN last_regime_switch_at TIMESTAMPTZ DEFAULT NULL,
ADD COLUMN regime_auto_switch_enabled BOOLEAN DEFAULT FALSE;
```

## UI Components

### RegimeStrategyPanel

Located at `/packages/fe/src/components/fund-manager/RegimeStrategyPanel.tsx`

Displays:
- **Current Market Regime** with confidence indicator
- **Crisis Warning** (when elevated)
- **Recommended Strategy** with fitness score
- **Switch Decision** with urgency badge and action button
- **Auto-Switch Toggle** for autonomous operation
- **Threshold Settings** with sliders
- **Preset Buttons** (Conservative, Moderate, Aggressive)
- **Available Strategies** catalog

### Integration

Added to Fund Detail page (`/fund-manager/[id]`):

```tsx
<RegimeStrategyPanel
  fundId={fundId}
  onStrategySwitch={fetchFund}
/>
```

## Fund Manager Integration

The regime selector is integrated into the Fund Manager tick loop at Step 4.1:

```typescript
// Step 4.1: Check regime-based strategy switching (if enabled)
if (fund.regimeAutoSwitchEnabled) {
  const switchDecision = await checkRegimeSwitch(fundId, currentStrategyName);

  if (switchDecision.shouldSwitch && switchDecision.urgency === 'immediate') {
    const selection = await selectRegimeStrategy(fundId);
    await executeRegimeSwitch(fundId, fund.userId, selection.selectedStrategy);
  }
}
```

## Audit Trail

All regime decisions are logged to `predict.fund_audit_log`:

| Event Type | Data |
|------------|------|
| `regime_switch_recommended` | currentRegime, newRegime, urgency, recommendation |
| `regime_switch_executed` | newAlgorithmId, newRunId, regime, fitness |

## Files

| 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 |

## Related Documentation

- [AI Fund Manager](68-ai-fund-manager.md) — Multi-strategy fund management
- [Algorithm Builder](12-algorithm-builder.md) — DSL and strategy execution
- [PINN Predictor](77-pinn-predictor.md) — Physics-informed regime detection
- [Market Paradox Analysis](43-market-paradox-analysis.md) — Regime context
- [Pattern Detection](54-pattern-detection-system.md) — Supporting signals

## Usage Example

### Enable Automatic Strategy Switching

1. Navigate to Fund detail page (`/fund-manager/:id`)
2. Scroll to "AI Regime Strategy Selector" panel
3. Toggle "Automatic Strategy Switching" ON
4. (Optional) Adjust thresholds or apply a preset
5. The system will now automatically switch strategies when:
   - Crisis warning exceeds threshold
   - A significantly better strategy is available with high confidence

### Manual Strategy Switch

1. View the "Recommended Strategy" in the panel
2. If a switch is recommended, click "Switch to [Strategy Name]"
3. The system will:
   - Create a new algorithm from the strategy AST
   - Start a paper trading run
   - Update fund allocations
   - Log to audit trail
