# Quantitative Analysis Features

> **Module Location**: `packages/be/src/quant/`
> **Shipped**: 2026-05-21
> **Status**: ✅ Fully wired to DSL + UI

Institutional-grade quantitative analysis primitives for the AI Algorithm Builder and trading systems.

---

## Overview

The `quant/` module provides 12 quantitative analysis capabilities, each with:
- Pure functions for core calculations
- DSL wrapper functions for use in the Algorithm Builder
- Caching with appropriate TTLs (1 hour to 24 hours depending on data volatility)
- Full integration with the primitives API (`/api/predict/v1/algorithms/primitives`)

---

## Feature Summary & Data Requirements

| Feature | Module | Data Source | Status | Impact |
|---------|--------|-------------|--------|--------|
| **Cointegration** | `cointegration.ts` | Existing price data | ✅ Complete | High (pairs trading) |
| **Fama-French 5-Factor** | `fama-french.ts` | Kenneth French data (free) | ✅ Complete | Medium (factor attribution) |
| **Options Greeks** | `options-greeks.ts` | Polygon options / Yahoo | ✅ Complete | High (derivatives) |
| **Order Book Imbalance** | `order-book.ts` | Binance L2 WebSocket | ✅ Complete | High (microstructure) |
| **Lead-Lag Analysis** | `lead-lag.ts` | Existing price data | ✅ Complete | Medium (predictive) |
| **Vol Forecasting** | `volatility.ts` | Existing OHLC data | ✅ Complete | High (risk mgmt) |
| **Momentum Decomposition** | `momentum.ts` | Existing price data | ✅ Complete | Medium (factor) |
| **TCA** | `tca.ts` | Trade execution logs | ✅ Complete | High (execution quality) |
| **TWAP/VWAP Execution** | `execution.ts` | ADV + volume profile | ✅ Complete | High (execution) |
| **Structural Breaks** | `structural-breaks.ts` | Existing price data | ✅ Complete | Medium (regime change) |
| **Correlation Breakdown** | `correlation.ts` | Existing price data | ✅ Complete | High (risk) |
| **Sector Momentum** | `sector-momentum.ts` | Sector ETF prices | ✅ Complete | High (rotation) |

---

## DSL Primitive Count

| Module | Purpose | DSL Primitives |
|--------|---------|----------------|
| `cointegration.ts` | Pairs trading signals | 4 |
| `fama-french.ts` | Factor model analysis | 3 |
| `options-greeks.ts` | Options pricing & Greeks | 5 |
| `order-book.ts` | L2 microstructure | 7 |
| `lead-lag.ts` | Cross-correlation analysis | 4 |
| `volatility.ts` | GARCH & vol forecasting | 6 |
| `momentum.ts` | TS vs XS momentum | 6 |
| `tca.ts` | Transaction cost analysis | 4 |
| `execution.ts` | TWAP/VWAP algorithms | 6 |
| `structural-breaks.ts` | Regime change detection | 5 |
| `correlation.ts` | Breakdown alerts | 6 |
| `sector-momentum.ts` | Sector cycle analysis | 7 |

**Total: 63 DSL primitives** (all wired to evaluator + algorithm builder)

---

## 1. Cointegration (`cointegration.ts`)

Engle-Granger cointegration testing for pairs trading.

### Core Functions

```typescript
// ADF test for stationarity
adfTest(series: number[]): { statistic: number; pValue: number; isStationary: boolean }

// Engle-Granger cointegration test
engleGrangerTest(seriesA: number[], seriesB: number[]): CointegrationResult

// Calculate spread z-score for mean-reversion trading
spreadZScore(seriesA: number[], seriesB: number[], hedgeRatio: number): number

// Calculate mean-reversion half-life (Ornstein-Uhlenbeck)
calculateHalfLife(spread: number[]): number
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `is_cointegrated(symbolA, symbolB)` | boolean | True if pair is cointegrated (p < 0.05) |
| `spread_zscore(symbolA, symbolB)` | number | Z-score of spread (-3 to +3 typical) |
| `half_life(symbolA, symbolB)` | number | Mean-reversion half-life in days |
| `hedge_ratio(symbolA, symbolB)` | number | Optimal hedge ratio for pair |

### Use Case

```
// Pairs trading strategy
entry: spread_zscore(symbol, "SPY") > 2 AND is_cointegrated(symbol, "SPY")
exit: spread_zscore(symbol, "SPY") < 0.5
```

---

## 2. Fama-French Factor Model (`fama-french.ts`)

Five-factor model for asset attribution and alpha generation.

### Factors

| Factor | Name | Description |
|--------|------|-------------|
| MKT | Market | Excess market return |
| SMB | Size | Small minus Big |
| HML | Value | High minus Low (book-to-market) |
| RMW | Profitability | Robust minus Weak |
| CMA | Investment | Conservative minus Aggressive |

### Core Functions

```typescript
// Calculate factor exposures (betas)
calculateFactorExposure(returns: number[], factorData: FactorData[]): FactorExposure

// Decompose returns into factor contributions
decomposeReturns(returns: number[], factorData: FactorData[]): ReturnDecomposition
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `ff_beta(symbol, factor)` | number | Factor beta (MKT/SMB/HML/RMW/CMA) |
| `factor_alpha(symbol)` | number | Annualized alpha after factor adjustment |
| `factor_r_squared(symbol)` | number | Factor model R² (0-1) |

### Use Case

```
// High alpha stock selection
entry: factor_alpha(symbol) > 0.05 AND factor_r_squared(symbol) > 0.7
```

---

## 3. Options Greeks (`options-greeks.ts`)

Black-Scholes pricing with full Greeks suite.

### Core Functions

```typescript
// Black-Scholes option price
blackScholesPrice(params: OptionParams): number

// All Greeks in one call
calculateGreeks(params: OptionParams): OptionGreeks

// Newton-Raphson implied volatility
impliedVolatility(marketPrice: number, params: Omit<OptionParams, 'sigma'>): number
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `option_delta(symbol, strike, expiry, type)` | number | Delta (-1 to 1) |
| `option_price(symbol, strike, expiry, type)` | number | Theoretical price |
| `iv_rank(symbol)` | number | IV rank vs 52-week range (0-100) |
| `iv_percentile(symbol)` | number | % of days with lower IV (0-100) |
| `put_call_skew(symbol)` | number | Put IV - Call IV |

### Use Case

```
// Volatility crush plays
entry: iv_rank(symbol) > 80 AND put_call_skew(symbol) > 0.05
direction: sell_premium
```

---

## 4. Order Book Analysis (`order-book.ts`)

Level 2 microstructure signals from Binance WebSocket.

### Core Functions

```typescript
// Calculate all order book metrics
calculateOrderBookMetrics(book: OrderBook, levels: number): OrderBookMetrics

// Volume-weighted mid price
microprice: number  // More accurate than simple mid

// Detect large orders (walls)
detectWalls(book: OrderBook, multiplier: number): { bidWalls; askWalls }
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `book_imbalance(symbol)` | number | -1 to 1 (negative = more asks) |
| `depth_pressure(symbol)` | number | Bid depth / Ask depth ratio |
| `spread_bps(symbol)` | number | Bid-ask spread in basis points |
| `microprice(symbol)` | number | Volume-weighted mid price |
| `imbalance_zscore(symbol)` | number | Imbalance vs recent history |
| `has_bid_wall(symbol)` | boolean | Large bid order detected |
| `has_ask_wall(symbol)` | boolean | Large ask order detected |

### Use Case

```
// Order flow momentum
entry: book_imbalance(symbol) > 0.4 AND imbalance_zscore(symbol) > 2
direction: long
```

---

## 5. Lead-Lag Analysis (`lead-lag.ts`)

Cross-correlation and Granger causality for predictive signals.

### Core Functions

```typescript
// Cross-correlation at various lags
crossCorrelation(seriesA: number[], seriesB: number[], maxLag: number): Map<number, number>

// Granger causality test
grangerCausalityTest(seriesX: number[], seriesY: number[], lags: number): { fStat; pValue }

// Full lead-lag analysis
analyzeLeadLag(symbolA, symbolB, returnsA, returnsB, maxLag): LeadLagResult
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `leads(symbolA, symbolB)` | boolean | True if A leads B |
| `lag_correlation(symbolA, symbolB, lag)` | number | Correlation at specific lag |
| `optimal_lag(symbolA, symbolB)` | number | Lag with max correlation |
| `granger_causes(symbolA, symbolB)` | boolean | True if A Granger-causes B (p < 0.05) |

### Use Case

```
// Lead indicator strategy
entry: leads("BTC", symbol) AND ts_momentum("BTC", 5) > 0.02
```

---

## 6. Volatility Forecasting (`volatility.ts`)

GARCH, Yang-Zhang, and Parkinson volatility estimators.

### Core Functions

```typescript
// Realized volatility
calculateRealizedVol(returns: number[], window: number): number

// GARCH(1,1) forecast
garchForecast(returns: number[], params: GARCHParams, horizon: number): number

// Yang-Zhang (OHLC, most efficient)
yangZhangVolatility(opens, highs, lows, closes, window): number

// Parkinson (high-low range)
parkinsonVolatility(highs, lows, window): number

// Volatility cone (term structure percentiles)
calculateVolatilityCone(returns, horizons, percentiles): VolatilityCone
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `realized_vol(symbol, window)` | number | Annualized realized volatility |
| `vol_forecast(symbol)` | number | 1-day GARCH forecast |
| `vol_percentile(symbol)` | number | Current vol vs history (0-100) |
| `vol_regime(symbol)` | string | 'low'/'normal'/'high'/'extreme' |
| `is_vol_elevated(symbol)` | boolean | True if percentile ≥ 75 |
| `vol_of_vol(symbol)` | number | Volatility of volatility |

### Use Case

```
// Volatility regime filter
entry: vol_regime(symbol) == "normal" AND is_vol_elevated(symbol) == false
sizing: kelly_fraction * (1 / vol_forecast(symbol))
```

---

## 7. Momentum Decomposition (`momentum.ts`)

Time-series vs cross-sectional momentum analysis.

### Core Functions

```typescript
// Absolute momentum (vs own history)
calculateTimeSeriesMomentum(prices: number[], lookback: number): number

// Relative strength (vs peers)
calculateCrossSectionalRank(symbolMomentum: number, universeMomentums: number[]): number

// 12-1 momentum (classic factor)
calculate12Minus1Momentum(prices: number[]): number

// Risk-adjusted (Sharpe-like)
calculateRiskAdjustedMomentum(prices: number[], lookback: number): number
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `ts_momentum(symbol, days)` | number | Return over lookback period |
| `xs_momentum_rank(symbol, universe)` | number | Percentile rank (0-100) |
| `momentum_acceleration(symbol)` | number | Change in momentum |
| `momentum_12_1(symbol)` | number | 12-month ex last month |
| `risk_adjusted_momentum(symbol)` | number | Sharpe-like ratio |
| `is_momentum_positive(symbol, days)` | boolean | True if momentum > 0 |

### Use Case

```
// Dual momentum strategy
entry: ts_momentum(symbol, 252) > 0 AND xs_momentum_rank(symbol, "SP500") > 70
exit: ts_momentum(symbol, 21) < 0
```

---

## 8. Transaction Cost Analysis (`tca.ts`)

Execution quality measurement and impact estimation.

### Core Functions

```typescript
// Implementation shortfall (Perold, 1988)
calculateImplementationShortfall(trade: Trade, arrivalPrice: number): number

// Market impact (Almgren-Chriss)
estimateMarketImpact(quantity, adv, volatility, price): number

// Full TCA metrics
analyzeTrade(trade, benchmark, adv, volatility, spread): TCAMetrics
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `avg_slippage_bps(symbol, days)` | number | Average slippage in bps |
| `execution_score(symbol, days)` | number | Quality score (0-100) |
| `market_impact_estimate(qty, adv, vol)` | number | Expected impact in bps |
| `is_execution_poor(symbol, days)` | boolean | True if score < 40 |

### Use Case

```
// Avoid high-impact trading
sizing: if market_impact_estimate(position_size, adv, vol) > 10 then reduce_size(0.5)
```

---

## 9. Execution Algorithms (`execution.ts`)

TWAP, VWAP, POV, and Implementation Shortfall schedules.

### Algorithms

| Algorithm | Description | When to Use |
|-----------|-------------|-------------|
| TWAP | Even time splits | Simple, low urgency |
| VWAP | Volume-weighted splits | Match market VWAP |
| POV | Constant participation | Control market footprint |
| IS | Front-loaded decay | Minimize timing risk |

### Core Functions

```typescript
// Generate child order schedule
generateTWAPSchedule(order, intervalMinutes): ChildOrder[]
generateVWAPSchedule(order, volumeProfile): ChildOrder[]
generatePOVSchedule(order, participation, adv): ChildOrder[]
generateISSchedule(order, volatility, adv, riskAversion): ChildOrder[]

// Create execution plan with impact estimate
createExecutionPlan(order, adv, volatility): ExecutionPlan
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `twap_slices(qty, hours, interval)` | number | Number of child orders |
| `vwap_participation_rate(qty, adv, hours)` | number | Expected participation |
| `expected_impact_bps(qty, adv, vol)` | number | Estimated market impact |
| `optimal_duration_hours(qty, adv, vol, max_impact)` | number | Optimal execution duration |
| `should_use_vwap(qty, adv)` | boolean | True if order > 1% ADV |
| `is_execution_aggressive(participation)` | boolean | True if participation > 20% |

### Use Case

```
// Choose execution algorithm
algo: if should_use_vwap(position_size, adv) then "vwap" else "market"
duration: optimal_duration_hours(position_size, adv, vol, 10)
```

---

## 10. Structural Breaks (`structural-breaks.ts`)

Regime change detection using CUSUM, Chow, and Bai-Perron.

### Core Functions

```typescript
// Chow test at known breakpoint
chowTest(series, breakIndex): { fStat; pValue; isSignificant }

// CUSUM for unknown breakpoint
cusumTest(series, significance): CUSUMResult

// Multiple breakpoints (Bai-Perron style)
detectMultipleBreaks(series, maxBreaks, minSegment): BreakPoint[]

// Comprehensive analysis
analyzeStructuralBreaks(series, maxBreaks): StructuralBreakResult
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `has_recent_break(symbol, days)` | boolean | Break detected in window |
| `regime_count(symbol)` | number | Number of regimes in year |
| `stability_score(symbol)` | number | 0-100 (higher = more stable) |
| `is_regime_change(symbol)` | boolean | New regime in last 20 days |
| `cusum_break_detected(symbol)` | boolean | CUSUM test positive |

### Use Case

```
// Avoid regime instability
entry: stability_score(symbol) > 60 AND has_recent_break(symbol, 20) == false
```

---

## 11. Correlation Analysis (`correlation.ts`)

Correlation breakdown alerts and regime-dependent correlations.

### Core Functions

```typescript
// Pearson correlation
pearsonCorrelation(seriesA, seriesB): number

// Rolling correlation
rollingCorrelation(seriesA, seriesB, window): number[]

// Detect breakdown (short vs long window)
detectCorrelationBreakdown(seriesA, seriesB, longWindow, shortWindow): CorrelationBreakdown

// Regime-dependent (up/down market)
regimeCorrelations(seriesA, seriesB, marketReturns): { upMarket; downMarket; asymmetry }
```

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `correlation(symbolA, symbolB, window)` | number | -1 to 1 |
| `correlation_change(symbolA, symbolB)` | number | Short vs long window delta |
| `is_correlation_breakdown(symbolA, symbolB)` | boolean | Significant z-score deviation |
| `downside_correlation(symbolA, symbolB)` | number | Correlation in down markets |
| `correlation_asymmetry(symbolA, symbolB)` | number | Down - up market correlation |
| `diversification_ratio(symbols[], weights[])` | number | > 1 means diversification benefit |

### Use Case

```
// Correlation regime awareness
entry: correlation_asymmetry(symbol, "SPY") < 0.2
risk: if is_correlation_breakdown(symbol, "SPY") then reduce_position(0.5)
```

---

## 12. Sector Momentum (`sector-momentum.ts`)

Business cycle positioning and sector relative strength.

**Note**: Full sector rotation system is at `packages/be/src/sector-rotation/`. This module provides simpler DSL-friendly primitives.

### Sector ETFs

| Sector | ETF |
|--------|-----|
| Technology | XLK |
| Healthcare | XLV |
| Financials | XLF |
| Consumer Discretionary | XLY |
| Consumer Staples | XLP |
| Energy | XLE |
| Materials | XLB |
| Industrials | XLI |
| Utilities | XLU |
| Real Estate | XLRE |
| Communications | XLC |

### Business Cycle Preferences

| Phase | Favored Sectors |
|-------|-----------------|
| Early Expansion | Financials, Industrials, Discretionary, Tech |
| Mid Expansion | Technology, Industrials, Materials, Energy |
| Late Expansion | Energy, Materials, Healthcare, Staples |
| Early Contraction | Staples, Healthcare, Utilities |
| Late Contraction | Utilities, Staples, Financials |

### DSL Primitives

| Primitive | Returns | Description |
|-----------|---------|-------------|
| `sector_rank(sector)` | number | 1 = best, 11 = worst |
| `sector_momentum(sector, months)` | number | Return over period |
| `sector_relative_strength(sector)` | number | Relative to SPY |
| `is_sector_leading(sector)` | boolean | True if top 3 |
| `sector_quadrant(sector)` | string | 'leading'/'weakening'/'lagging'/'improving' |
| `sector_breadth()` | number | % of sectors positive (0-100) |
| `inferred_cycle_phase()` | string | Business cycle phase |

### Use Case

```
// Sector rotation overlay
filter: is_sector_leading(sector(symbol)) OR sector_quadrant(sector(symbol)) == "improving"
```

---

## Integration with Algorithm Builder

All DSL primitives are designed for use in the Algorithm Builder. They:

1. **Accept dependency injection** — Pass `getReturns`, `getPrices`, etc. functions for testability
2. **Cache results** — 1-24 hour TTLs to minimize API calls
3. **Handle errors gracefully** — Return sensible defaults (0, false, 50) on failure
4. **Log warnings** — Use structured logging for debugging

### Example Algorithm

```
// Multi-factor quant strategy
universe: SP500
entry:
  ts_momentum(symbol, 126) > 0 AND
  xs_momentum_rank(symbol, "SP500") > 60 AND
  factor_alpha(symbol) > 0.03 AND
  is_cointegrated(symbol, "SPY") == false AND
  stability_score(symbol) > 50
exit:
  ts_momentum(symbol, 21) < -0.05 OR
  is_correlation_breakdown(symbol, "SPY")
sizing:
  kelly * (1 / realized_vol(symbol, 20)) *
  (1 - expected_impact_bps(position_size, adv, vol) / 100)
```

---

## Related Systems

- **Full Sector Rotation**: `packages/be/src/sector-rotation/` — Comprehensive phase classification with persistence
- **Insights Engine**: `packages/be/src/insights/` — Whale/bot detection, divergence scoring
- **Trading Signals**: `packages/be/src/trading/services/signal-generator.ts` — Adaptive ensemble
- **Backtest Engine**: `packages/be/src/algorithms/backtest/` — Uses these primitives for evaluation

---

## Mathematical Implementation Notes

> **Last Audit**: 2026-05-21
> **Auditor**: Expert mathematical review (PhD-level econometrics)

The following mathematical improvements were implemented to ensure institutional-grade accuracy:

### 1. Granger Causality — Proper OLS AR Estimation

**Module**: `lead-lag.ts`

**Issue Fixed**: The original implementation used a simple average `seriesY[t-i] / lags` as a predictor instead of proper OLS-fitted autoregressive coefficients.

**Correct Implementation**:
```typescript
// Granger causality test using proper F-test
// H₀: X does not Granger-cause Y
// Restricted:   Y_t = α + Σᵢ(aᵢ × Y_{t-i}) + ε
// Unrestricted: Y_t = α + Σᵢ(aᵢ × Y_{t-i}) + Σᵢ(bᵢ × X_{t-i}) + ε

function grangerCausalityTest(seriesX: number[], seriesY: number[], lags: number = 5): {
  fStat: number;
  pValue: number;
}
```

**Key Functions Added**:
- `olsRegression()` — Full OLS with design matrix, solves normal equations via Cholesky decomposition
- `solveCholesky()` — Numerically stable Cholesky decomposition for symmetric positive-definite matrices
- `fCDF()` — F-distribution CDF using regularized incomplete beta function
- `incompleteBeta()` — Lentz's continued fraction algorithm for Iₓ(a, b)
- `logGamma()` — Lanczos approximation for ln(Γ(x))

**F-statistic Formula**:
```
F = ((RSS_restricted - RSS_unrestricted) / k) / (RSS_unrestricted / (n - 2k - 1))

where:
  k = number of lags
  n = number of observations
  df₁ = k (numerator degrees of freedom)
  df₂ = n - 2k - 1 (denominator degrees of freedom)
```

---

### 2. ADF Test — MacKinnon P-Value Method

**Module**: `cointegration.ts`

**Issue Fixed**: Original had only 3 critical values (-3.43, -2.86, -2.57) with crude linear interpolation, producing inaccurate p-values for values outside the 1%/5%/10% range.

**Correct Implementation**: MacKinnon (1994, 2010) regression-based critical values with sample-size adjustment.

**MacKinnon Coefficients** (no constant, no trend case):
```typescript
const MACKINNON_COEFFS = {
  '0.001': { beta_inf: -3.4336, beta_1: -5.999,  beta_2: -29.25 },
  '0.01':  { beta_inf: -3.4336, beta_1: -5.999,  beta_2: -29.25 },
  '0.025': { beta_inf: -3.0989, beta_1: -4.083,  beta_2: -17.83 },
  '0.05':  { beta_inf: -2.8621, beta_1: -2.738,  beta_2: -8.36  },
  '0.10':  { beta_inf: -2.5671, beta_1: -1.438,  beta_2: -4.48  },
  '0.20':  { beta_inf: -2.2358, beta_1: -0.496,  beta_2: -1.44  },
  '0.50':  { beta_inf: -1.6167, beta_1:  0.481,  beta_2:  1.24  },
  '0.80':  { beta_inf: -0.9283, beta_1:  1.224,  beta_2:  2.91  },
  '0.90':  { beta_inf: -0.4769, beta_1:  1.536,  beta_2:  3.62  },
  '0.95':  { beta_inf: -0.0731, beta_1:  1.741,  beta_2:  4.04  },
  '0.99':  { beta_inf:  0.5489, beta_1:  2.019,  beta_2:  4.55  },
};
```

**Critical Value Formula**:
```
c(p, n) = β_∞ + β₁/n + β₂/n²

where:
  p = significance level
  n = sample size
```

**Key Functions Added**:
- `adfCriticalValue(p, n)` — MacKinnon critical value at significance p for sample size n
- `adfPValue(statistic, n)` — Bisection search over significance levels
- `solveLinearSystem()` — Gaussian elimination for ADF regression
- `invertMatrix()` — Full matrix inversion for covariance estimation

---

### 3. Fama-French — Multivariate OLS

**Module**: `fama-french.ts`

**Issue Fixed**: Original ran 5 separate univariate regressions (one per factor), which introduces omitted variable bias (OVB) because factors are correlated.

**Correct Implementation**: Single multivariate OLS regression with all 5 factors simultaneously:

```
R_i - R_f = α + β₁(MKT) + β₂(SMB) + β₃(HML) + β₄(RMW) + β₅(CMA) + ε
```

**Normal Equations**:
```
β = (X'X)⁻¹ X'Y

where:
  X = [1, MKT, SMB, HML, RMW, CMA] design matrix (n × 6)
  Y = excess returns vector (n × 1)
```

**Key Functions Added**:
- `multipleOLS()` — Full multivariate regression with:
  - Coefficient estimates (β̂)
  - Standard errors: SE(β̂ᵢ) = √(σ² × (X'X)⁻¹ᵢᵢ)
  - t-statistics: tᵢ = β̂ᵢ / SE(β̂ᵢ)
  - p-values via Student's t-distribution
  - R² and adjusted R²
- `invertSymmetricMatrix()` — Optimized for X'X (symmetric positive-definite)
- `tCDF()` — Student's t-distribution CDF using incomplete beta

**Statistical Output**:
```typescript
interface MultipleRegressionResult {
  coefficients: number[];      // [α, β₁, β₂, β₃, β₄, β₅]
  standardErrors: number[];    // SE for each coefficient
  tStatistics: number[];       // t-stats for significance tests
  pValues: number[];           // Two-tailed p-values
  rSquared: number;            // R² (0-1)
  adjustedRSquared: number;    // Adjusted for degrees of freedom
  residualVariance: number;    // σ² estimate
}
```

---

### Mathematical Accuracy Summary

| Module | Function | Method | Reference |
|--------|----------|--------|-----------|
| `cointegration.ts` | `adfPValue()` | MacKinnon critical values | MacKinnon (1994, 2010) |
| `lead-lag.ts` | `grangerCausalityTest()` | F-test with proper OLS AR | Granger (1969) |
| `lead-lag.ts` | `fCDF()` | Regularized incomplete beta | Press et al. (Numerical Recipes) |
| `fama-french.ts` | `multipleOLS()` | Normal equations | Fama & French (2015) |
| `fama-french.ts` | `tCDF()` | Incomplete beta transformation | Abramowitz & Stegun |

All implementations use:
- **Cholesky decomposition** for numerically stable linear system solving
- **Regularized incomplete beta** via Lentz's continued fraction algorithm
- **Lanczos approximation** for log-gamma function (15-digit precision)
- **Bisection search** for inverse CDF problems (p-value from statistic)

---

## File Reference

```
packages/be/src/quant/
├── index.ts              # Module exports
├── cointegration.ts      # Pairs trading (MacKinnon ADF p-values)
├── fama-french.ts        # Factor model (multivariate OLS)
├── options-greeks.ts     # Black-Scholes
├── order-book.ts         # L2 microstructure
├── lead-lag.ts           # Cross-correlation (proper Granger causality)
├── volatility.ts         # GARCH forecasting
├── momentum.ts           # TS/XS decomposition
├── tca.ts                # Transaction costs
├── execution.ts          # TWAP/VWAP
├── structural-breaks.ts  # CUSUM/Chow
├── correlation.ts        # Breakdown alerts
└── sector-momentum.ts    # Cycle positioning
```
