# AI Fund Manager

**Version:** 2.0
**Shipped:** 2026-05-12, Updated 2026-05-21
**Status:** Production Ready

## Overview

The AI Fund Manager is an autonomous multi-strategy trading system that:
- **Auto-adjusts strategies** based on market regime detection (BULL/BEAR/SIDEWAYS/CRISIS/RECOVERY)
- **Trades multiple asset classes** — Equities, Crypto, Forex, Futures, Options, CFDs
- **Supports simulation and live trading** — Mock, Paper, and Live modes with broker integration
- **Executes multiple trades** across a multi-symbol universe
- **Integrates multiple brokers** — Alpaca, Binance, IBKR, Pepperstone, Schwab
- Allocates capital across multiple AI trading strategies
- Integrates Stock Hunter recommendations for auto-trading
- Tracks NAV, performance, and provides real-time monitoring

## Key Capabilities

### 1. Automatic Strategy Adjustment (Regime Strategy Selector)

The fund automatically switches between 6 regime-specific strategies based on detected market conditions:

| Regime | Strategy | Description |
|--------|----------|-------------|
| **BULL** | Bull Market Momentum | Trend-following with wide stops, trailing stops |
| **BULL** | Bull Factor Tilt | High-beta, small-cap factor exposure |
| **BEAR** | Bear Defensive | Mean-reversion on oversold, tight stops |
| **BEAR/SIDEWAYS** | Bear Pairs Trading | Market-neutral statistical arbitrage |
| **SIDEWAYS** | Sideways Vol Premium | Volatility selling when IV > RV |
| **CRISIS** | Crisis Risk Parity | Maximum capital preservation |

**Regime Detection** uses:
- PINN (Physics-Informed Neural Network) with crisis probability
- Markov HMM (252-bar, 4-state model) with transition matrix
- Combined confidence scoring

**Configurable Thresholds** (UI-tunable):
- Markov regime probability minimum
- Hurst trending threshold
- GARCH volatility cap
- Crisis warning threshold
- Switch confidence minimum
- Minimum ticks between switches

### 2. Multiple Asset Classes

The fund supports trading across:

| Asset Class | Brokers | Examples |
|-------------|---------|----------|
| **Equities** | Alpaca, IBKR, Schwab | AAPL, MSFT, SPY, QQQ |
| **Crypto** | Alpaca, Binance | BTC, ETH, SOL |
| **Forex** | Pepperstone, IBKR | EUR/USD, GBP/USD |
| **Futures** | IBKR | ES, NQ, CL, GC |
| **Options** | IBKR, Schwab | SPY calls/puts |
| **CFDs** | Pepperstone | Indices, Commodities |

Each strategy's `universe` field defines which symbols to trade, supporting cross-asset allocation.

### 3. Simulation & Trading Modes

| Mode | Description | Risk |
|------|-------------|------|
| **Mock** | Simulated $100k, no broker connection | None |
| **Paper** | Realistic simulation with slippage modeling | None |
| **Live** | Real broker execution (MFA-gated) | Real capital |

**Paper trading features:**
- Almgren-Chriss market impact model
- Bid-ask spread simulation by asset class
- Realistic fill delays
- Slippage calculation

### 4. Multi-Trade / Multi-Symbol Execution

The multi-symbol executor processes each symbol in the strategy's universe:

- Per-symbol entry/exit decisions
- Shared cash pool across positions
- Portfolio-level risk management
- Correlation monitoring across strategies
- Position concentration limits

### 5. Multiple Broker Integration

| Broker | Auth | Asset Classes | Features |
|--------|------|---------------|----------|
| **Alpaca** | API Key | Stocks, ETFs, Crypto | Commission-free, $100k paper |
| **Binance** | API Key | Crypto spot + futures | Testnet for paper |
| **IBKR** | Session | All (stocks, options, futures, forex, bonds) | Gateway required |
| **Pepperstone** | OAuth 2.0 | Forex, CFDs, indices, commodities | 30-day token refresh |
| **Schwab** | OAuth 2.0 | US stocks, ETFs, options | 7-day re-auth required |

Each algorithm run specifies which broker to use for execution via the `broker_id` field.

## Architecture

```
┌─────────────────────────────────────────────────────────────────────┐
│                        AI FUND MANAGER                               │
├─────────────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                   FUND ORCHESTRATOR                          │   │
│  │  • NAV calculation (total equity / shares)                   │   │
│  │  • Capital allocation (Sharpe-weighted or equal-weight)      │   │
│  │  • Fund-level risk limits (max drawdown, exposure)           │   │
│  │  • Correlation monitoring across strategies                   │   │
│  │  • Automatic rebalancing between strategies                   │   │
│  └──────────────────────────┬──────────────────────────────────┘   │
│                              │                                       │
│      ┌───────────────────────┼───────────────────────────────┐      │
│      ▼                       ▼                       ▼        │      │
│  ┌────────────┐        ┌────────────┐        ┌────────────┐  │      │
│  │ Strategy 1 │        │ Strategy 2 │        │ Strategy 3 │  │      │
│  │ (Momentum) │        │ (Mean Rev) │        │ (AI Stock) │  │      │
│  │ DSL-based  │        │ DSL-based  │        │ Hunter     │  │      │
│  │ Algorithm  │        │ Algorithm  │        │            │  │      │
│  └─────┬──────┘        └─────┬──────┘        └─────┬──────┘  │      │
│        └─────────────────────┼─────────────────────┘          │      │
│                              ▼                                │      │
│  ┌─────────────────────────────────────────────────────────┐ │      │
│  │              EXISTING PAPER EXECUTOR                     │ │      │
│  │  • Price validation • Slippage • Guardrails • Telemetry │ │      │
│  └─────────────────────────────────────────────────────────┘ │      │
└─────────────────────────────────────────────────────────────────────┘
```

## Database Schema

**Migration:** `228_ai_fund_manager.sql`

### Tables

| Table | Purpose |
|-------|---------|
| `predict.funds` | Core fund entity with config, capital, NAV, risk limits |
| `predict.fund_strategies` | Algorithm/Stock Hunter allocations per fund |
| `predict.fund_positions` | Current holdings with P&L tracking |
| `predict.fund_trades` | All executed trades with source attribution |
| `predict.fund_nav_history` | Daily NAV snapshots for performance charts |
| `predict.fund_rebalancing_events` | Audit trail of rebalancing operations |
| `predict.fund_audit_log` | Complete audit trail of fund events |

### Key Fields

**funds table:**
- `initial_capital` / `current_capital` / `total_equity` - Capital tracking
- `shares_outstanding` / `nav_per_share` / `high_water_mark` - NAV tracking
- `risk_level` - conservative/moderate/aggressive presets
- `allocation_strategy` - equal_weight/sharpe_weighted/risk_parity
- `max_drawdown_pct` / `max_daily_loss_pct` / `max_position_pct` - Risk limits
- `stock_hunter_enabled` / `stock_hunter_min_confidence` - Stock Hunter config
- `auto_rebalance_enabled` / `rebalance_threshold_pct` - Rebalancing config

## API Endpoints

### Fund CRUD

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/predict/v1/fund-manager` | Create new fund |
| GET | `/api/predict/v1/fund-manager` | List user's funds |
| GET | `/api/predict/v1/fund-manager/:id` | Get fund details |
| PUT | `/api/predict/v1/fund-manager/:id` | Update fund config |
| DELETE | `/api/predict/v1/fund-manager/:id` | Delete fund |

### Fund Operations

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/predict/v1/fund-manager/:id/start` | Start/resume fund |
| POST | `/api/predict/v1/fund-manager/:id/pause` | Pause fund |
| POST | `/api/predict/v1/fund-manager/:id/stop` | Stop fund & close positions |
| POST | `/api/predict/v1/fund-manager/:id/deposit` | Deposit capital |
| POST | `/api/predict/v1/fund-manager/:id/withdraw` | Withdraw capital |

### Strategy Management

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/predict/v1/fund-manager/:id/strategies` | Add strategy |
| PUT | `/api/predict/v1/fund-manager/:id/strategies` | Update allocations |
| DELETE | `/api/predict/v1/fund-manager/:id/strategies/:sid` | Remove strategy |
| PATCH | `/api/predict/v1/fund-manager/:id/strategies/:sid` | Enable/disable |

### Performance & Monitoring

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/predict/v1/fund-manager/:id/performance` | Get performance metrics |
| GET | `/api/predict/v1/fund-manager/:id/nav-history` | Get NAV history |
| GET | `/api/predict/v1/fund-manager/:id/positions` | Get open positions |
| GET | `/api/predict/v1/fund-manager/:id/trades` | Get recent trades |
| GET | `/api/predict/v1/fund-manager/:id/audit` | Get audit log |

### Rebalancing

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/predict/v1/fund-manager/:id/rebalance` | Trigger manual rebalance |
| GET | `/api/predict/v1/fund-manager/:id/rebalance-history` | Get rebalance history |

## Key Features

### NAV Calculation

```typescript
function calculateNAV(fund, positions) {
  // 1. Sum position market values
  const positionsValue = positions.reduce((sum, p) => sum + p.market_value, 0);

  // 2. Add cash balance
  const totalEquity = positionsValue + fund.currentCapital;

  // 3. Calculate NAV per share
  const navPerShare = totalEquity / fund.sharesOutstanding;

  // 4. Calculate returns
  const dailyReturn = (navPerShare - previousNav) / previousNav;
  const cumulativeReturn = (navPerShare - initialNav) / initialNav;

  // 5. Calculate drawdown
  const drawdown = (peakEquity - totalEquity) / peakEquity;

  return { navPerShare, totalEquity, dailyReturn, cumulativeReturn, drawdown };
}
```

### Allocation Strategies

**Equal Weight:** Distributes capital evenly across all strategies.

**Sharpe Weighted:** Weights strategies by their Sharpe ratio (positive only):
```typescript
const sharpes = strategies.map(s => Math.max(0, s.sharpeRatio || 0));
const totalSharpe = sharpes.reduce((a, b) => a + b, 0);
allocations = sharpes.map(s => s / totalSharpe);
```

**Risk Parity:** Inverse volatility weighting:
```typescript
const invVols = strategies.map(s => 1 / Math.max(0.01, s.maxDrawdownPct || 10));
const totalInvVol = invVols.reduce((a, b) => a + b, 0);
allocations = invVols.map(v => v / totalInvVol);
```

### Stock Hunter Auto-Trading

When enabled, the fund automatically trades high-confidence Stock Hunter recommendations:

1. Fetches active recommendations above `stock_hunter_min_confidence`
2. Checks allocation limit (`stock_hunter_max_allocation_pct`)
3. Validates no duplicate positions exist
4. Executes trades with stop-loss and take-profit from recommendation
5. Records in fund_trades with `source_type='stock_hunter'`

### Risk Management

**Automatic Checks:**
- Max drawdown breach → Fund auto-pauses
- Daily loss limit breach → Fund auto-pauses
- Position concentration → Warning logged
- Strategy correlation → Haircut applied

**Risk Presets:**
| Level | Max DD | Daily Loss | Max Position |
|-------|--------|------------|--------------|
| Conservative | 10% | 2% | 15% |
| Moderate | 20% | 5% | 25% |
| Aggressive | 30% | 8% | 40% |

### Rebalancing

**Triggers:**
- **Scheduled:** Based on `rebalance_interval_days`
- **Drift:** When allocation drifts beyond `rebalance_threshold_pct`
- **Manual:** User-triggered via API
- **Risk:** After risk event

## Scheduler Jobs

| Job | Interval | Description |
|-----|----------|-------------|
| `fund-tick-active` | 60s | Tick all active funds |
| `fund-nav-snapshot` | Daily | Record daily NAV snapshots |
| `fund-rebalance-check` | 1 hour | Check funds for rebalancing |
| `fund-correlation-check` | 4 hours | Check strategy correlations |

## UI Components

### FundCard
Summary card for fund list view. Shows:
- Fund name and status badge
- Total equity and returns
- Strategy and position counts
- Quick action buttons (Start/Pause/Stop)

### FundCreator
5-step wizard for creating a new fund:
1. **Basics:** Name, description, initial capital
2. **Risk:** Risk level preset, drawdown/loss limits
3. **Allocation:** Strategy, auto-rebalance config
4. **Strategies:** Stock Hunter config, algorithm selection
5. **Review:** Summary before creation

### FundDashboard
Full dashboard for fund management:
- Key metrics cards (Equity, NAV, Sharpe, Drawdown)
- NAV history area chart
- Allocation pie chart
- Positions/Trades/Strategies tabs
- Fund control buttons

## Backend Files

| File | Purpose |
|------|---------|
| `packages/be/src/fund-manager/types.ts` | Type definitions |
| `packages/be/src/fund-manager/repository.ts` | Database operations |
| `packages/be/src/fund-manager/service.ts` | Business logic |
| `packages/be/src/fund-manager/orchestrator.ts` | Tick loop & coordination |
| `packages/be/src/fund-manager/scheduler.ts` | Scheduler jobs |
| `packages/be/src/fund-manager/index.ts` | Barrel exports |
| `packages/be/src/api/predict/v1/fund-manager/handlers.ts` | API handlers |

## Frontend Files

| File | Purpose |
|------|---------|
| `packages/fe/src/components/fund-manager/types.ts` | UI types |
| `packages/fe/src/components/fund-manager/FundCard.tsx` | Summary card |
| `packages/fe/src/components/fund-manager/FundCreator.tsx` | Creation wizard |
| `packages/fe/src/components/fund-manager/FundDashboard.tsx` | Main dashboard |
| `apps/web/src/app/fund-manager/page.tsx` | Fund list page |
| `apps/web/src/app/fund-manager/[id]/page.tsx` | Fund detail page |

## Usage Example

### Create a Fund

```bash
curl -X POST /api/predict/v1/fund-manager \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{
    "name": "My AI Fund",
    "initialCapital": 10000,
    "riskLevel": "moderate",
    "allocationStrategy": "sharpe_weighted",
    "stockHunterEnabled": true,
    "stockHunterMinConfidence": 0.7
  }'
```

### Add a Strategy

```bash
curl -X POST /api/predict/v1/fund-manager/:id/strategies \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{
    "strategyType": "algorithm",
    "algorithmId": "algo_123",
    "targetAllocationPct": 30
  }'
```

### Manual Rebalance

```bash
curl -X POST /api/predict/v1/fund-manager/:id/rebalance \
  -H "Authorization: Bearer <token>"
```

## Performance Metrics

The fund tracks these metrics:
- **Returns:** Total, daily, weekly, monthly, YTD
- **Risk:** Sharpe ratio, Sortino ratio, max drawdown, volatility
- **Trading:** Total trades, win rate, profit factor, avg win/loss

## Security Considerations

- All endpoints require authentication via `requireAuth()`
- User can only access their own funds (user_id check)
- Capital operations validate amounts
- Stop action requires confirmation in UI
- All events logged to audit table

## Integration Points

- **Algorithm Executor:** `tickRun()` for algorithm strategies
- **Stock Hunter:** `getRecommendations()` for auto-trading
- **Price Service:** `getCurrentPrice()` for position valuation
- **Slippage:** `calculateSlippage('paper')` for trade execution
- **Scheduler:** Job registration for autonomous operation
