stock-bot/design/VALIDATION-AND-RIGOR.md

133 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Stock Bot — Validation, Trial Ledger & Execution Rigor
Canonical mathematical and operational rules for `@stock-bot/calculations`, `@stock-bot/research`, the PostgreSQL `trial_ledger`, the 6-month Vault Holdout, and IBKR Margin / TSX execution.
---
## 1. Canonical Metric Conventions (`@stock-bot/calculations`)
No Python script, UI component, or legacy simulator may define its own Sharpe, Sortino, volatility, or drawdown formula. All layers read metrics computed by `@stock-bot/calculations`:
- **Return series:** Daily (or session-level) mark-to-market net portfolio total returns $r_t = \frac{E_t - E_{t-1}}{E_{t-1}}$ in the account's base currency, starting from `initialCapital` (so first-period losses are never skipped).
- **Annualization factor ($A$):** `252` trading sessions/year for equity strategies (`252 * 390` only when reporting un-aggregated 1m bar statistics; tearsheets always aggregate intraday equity to daily session closes before computing Sharpe/DSR/PBO so intraday and daily strategies compare on the same `252`/yr scale).
- **Volatility:** Sample standard deviation ($N - 1$ degrees of freedom), annualized via $\hat{\sigma}_{\text{ann}} = \hat{\sigma}_d \sqrt{252}$.
- **Sharpe Ratio ($\widehat{SR}$):** Arithmetic excess return over risk-free rate $r_f$ per period:
$$\widehat{SR}_{\text{ann}} = \frac{\bar{r}_d - r_{f,d}}{\hat{\sigma}_d}\sqrt{252}$$
- **Sortino Ratio:** Downside root-mean-square over **all** $T$ observations (`target = r_{f,d}`), never standard deviation of negative-only observations:
$$\widehat{\text{Sortino}}_{\text{ann}} = \frac{(\bar{r}_d - r_{f,d}) \cdot 252}{\sqrt{\frac{252}{T}\sum_{t=1}^{T} \min(0, r_t - r_{f,d})^2}}$$
- **RSI convention:** Wilder smoothing (`1/period`), with flat-price (`avg_gain == 0 && avg_loss == 0`) standardized to **`50.0`** across Rust, TypeScript, and batch feature jobs.
---
## 2. Trial Ledger & Multiple-Testing Math (`DSR` & `PBO`)
### A. PostgreSQL `trial_ledger` Schema (Append-Only)
Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`:
```sql
CREATE TABLE IF NOT EXISTS trial_ledger (
trial_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
principal_id TEXT NOT NULL, -- 'operator' | 'agent:<uuid>'
campaign_id UUID,
stage VARCHAR(16) NOT NULL, -- 'signal_ic' | 'event_study' | 'screen' | 'engine_backtest'
universe_market VARCHAR(12) NOT NULL, -- 'US_EQ' | 'CA_EQ' | 'US_CA_EQ' | 'FX'
horizon_bucket VARCHAR(32) NOT NULL, -- 'intraday' | 'swing_1_10d' | 'position_10d_plus'
hypothesis_id UUID,
expression_hash CHAR(64) NOT NULL, -- SHA-256 of canonical signal/strategy + params + universe + window
sample_start DATE NOT NULL,
sample_end DATE NOT NULL, -- must be < VAULT_CUTOFF_DATE
n_obs INTEGER NOT NULL,
sharpe_unann DOUBLE PRECISION NOT NULL,
skewness DOUBLE PRECISION NOT NULL,
kurtosis DOUBLE PRECISION NOT NULL, -- Pearson kurtosis (normal = 3.0)
daily_series REAL[] NOT NULL -- daily net return or daily cross-sectional IC vector (~5k floats = 20 KB)
);
```
### B. Relatedness Cluster & Effective Independent Trials ($\hat{N}$)
- **Deterministic cluster key:** `(universe_market, horizon_bucket)`. Agents cannot reset `N = 1` by inventing a new strategy `family` name.
- **Multi-horizon / breakdown accounting:** A single `analyze_signal` call evaluating 3 horizons (`1d`, `5d`, `20d`) records **3 rows** in `trial_ledger`.
- **Effective independent trials ($\hat{N}$, Bailey & López de Prado):** Given $K$ trials in the cluster with overlapping daily series correlation matrix $P$:
$$\bar{\rho} = \frac{2}{K(K - 1)}\sum_{1 \le i < j \le K} \rho_{ij}, \qquad \hat{N} = \max\!\big(1,\; 1 + (K - 1)(1 - \max(0, \bar{\rho}))\big)$$
Sweeping `SMA(20)` and `SMA(21)` ($\rho \approx 0.97$) adds $\approx 0.03$ effective trials; testing 100 orthogonal signals ($\bar{\rho} \approx 0$) yields $\hat{N} \approx 100$.
### C. Non-Normal Deflated Sharpe Ratio (`DSR`)
Using unannualized per-day $\widehat{SR}$ over $T$ daily observations, skewness $\hat{\gamma}_3$, Pearson kurtosis $\hat{\gamma}_4$, and cross-sectional variance $\hat{\sigma}_{\{SR\}}^2 = \text{Var}(\{\widehat{SR}_k\}_{k=1}^K)$ across the cluster:
$$SR_0 = \hat{\sigma}_{\{SR\}} \left[ (1 - \gamma)\Phi^{-1}\!\left(1 - \frac{1}{\hat{N}}\right) + \gamma\,\Phi^{-1}\!\left(1 - \frac{1}{\hat{N} e}\right) \right], \quad \gamma \approx 0.57721566$$
$$\widehat{\text{SE}}(\widehat{SR}) = \sqrt{\frac{1 - \hat{\gamma}_3 \widehat{SR} + \frac{\hat{\gamma}_4 - 1}{4}\widehat{SR}^2}{T - 1}}, \qquad \text{DSR} = \Phi\!\left(\frac{\widehat{SR} - SR_0}{\widehat{\text{SE}}(\widehat{SR})}\right)$$
**Gate:** Candidate → Validated requires **`DSR >= 0.95`**.
### D. Probability of Backtest Overfitting (`PBO` via CSCV)
Computed on any synchronous screen/experiment return matrix $M \in \mathbb{R}^{T \times N}$ ($N \ge 4$):
1. Partition $T$ into $S = 16$ contiguous equal sub-periods (respecting `purge` at boundaries).
2. For all $\binom{16}{8} = 12,870$ splits into in-sample $J$ and out-of-sample $\bar{J}$: find $n^* = \arg\max_n SR_n(J)$, compute the relative OOS rank $\omega \in (0, 1)$ of $n^*$ within $\{SR_n(\bar{J})\}$, and set $\lambda = \ln\!\frac{\omega}{1 - \omega}$.
3. $\text{PBO} = \Pr(\lambda < 0)$ across all $12,870$ splits.
**Gate:** Candidate → Validated requires **`PBO <= 0.20`**.
---
## 3. Purging, Embargo, Recency & the 6-Month Vault
1. **Purged Walk-Forward & CPCV:** Every train/test boundary enforces:
- `purge_bars = prediction_horizon_bars + feature_warmup_bars` (eliminating `labelHorizonMs = 0` overlap leakage).
- `embargo_days = max(5, ceil(0.01 * total_trading_days))` after each test fold before resuming training.
2. **Post-2023 Recency Gate:** Every candidate must report pre-2023 (`< 2023-01-01`) vs. post-2023 (`2023-01-01 .. VAULT_CUTOFF_DATE`) performance. Post-2023 rank-IC and post-cost Sharpe must both be **strictly positive** and **$\ge 50\%$** of pre-2023 levels.
3. **Rolling 6-Month Air-Gapped Vault (`VAULT_CUTOFF_DATE`):**
- Set to `max_curated_date - 6 calendar months` (~126 trading days).
- Physically fenced in `MarketDataStore` (`scope = 'vault_fenced'`), with `/export` disabled for `sb-research.*` tokens and campaign containers blocked from DB ports.
- **One-shot human burn:** Triggered only on operator `Validated → Paper` action (`<= 10` evaluations/year enforced by an append-only `vault_evaluations` table). Requires Vault post-cost Sharpe $> 0.5$ and within $1.5\sigma$ of CPCV fold distribution.
### Vault Evaluations Schema (Append-Only)
Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`. A `BEFORE INSERT` trigger requires `READ COMMITTED` or `READ UNCOMMITTED` transaction isolation (PostgreSQL treats `READ UNCOMMITTED` identically to `READ COMMITTED`, while rejecting `REPEATABLE READ` and `SERIALIZABLE` so a waiting writer cannot evaluate the cap against a stale snapshot), forces `evaluated_at := now()` under a schema-scoped transaction advisory lock, and rejects inserts once 10 evaluations exist in the rolling 1-year window (`evaluated_at > now() - interval '1 year'`) on the target table (`TG_RELID`), paired with a statement-level `AFTER INSERT` check so multi-row inserts cannot bypass the cap:
```sql
CREATE TABLE IF NOT EXISTS vault_evaluations (
evaluation_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
evaluated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
principal_id TEXT NOT NULL
CHECK (principal_id = 'operator'),
strategy_ref TEXT NOT NULL
CHECK (length(btrim(strategy_ref)) > 0),
expression_hash CHAR(64) NOT NULL
CHECK (expression_hash ~ '^[0-9a-f]{64}$'),
vault_cutoff_date DATE NOT NULL,
vault_start DATE NOT NULL,
vault_end DATE NOT NULL,
n_obs INTEGER NOT NULL
CHECK (n_obs >= 2),
sharpe_post_cost DOUBLE PRECISION NOT NULL
CHECK (sharpe_post_cost <> 'NaN'::double precision AND sharpe_post_cost > '-Infinity'::double precision AND sharpe_post_cost < 'Infinity'::double precision),
passed BOOLEAN NOT NULL,
notes TEXT,
CHECK (vault_start <= vault_end),
CHECK (vault_start >= vault_cutoff_date)
);
```
**Enforcement boundary:** The `<= 10`/year rolling cap (`vault_evaluations_cap`, `vault_evaluations_cap_after`) and append-only protections (`trial_ledger_retained`, `trial_ledger_no_truncate`, `vault_evaluations_retained`, `vault_evaluations_no_truncate`) are PostgreSQL triggers that block ordinary DML (`UPDATE`, `DELETE`, `TRUNCATE`, and cap-exceeding `INSERT`) from any role, but a table owner or superuser can bypass them via `ALTER TABLE ... DISABLE TRIGGER`. All services currently share a single owner role (while autonomous agents have no direct DB access); splitting an owner/migration role from a non-owner runtime role with only `SELECT, INSERT` on `trial_ledger` and `vault_evaluations` is deferred to pre-prod hardening.
---
## 4. IBKR Margin, USD/CAD, TSX Microstructure & Dual Drift Rules
1. **Multi-currency IBKR Margin accounting (`USD` + `CAD`):**
- Rust `Ledger` holds `cash: BTreeMap<Currency, Posting>` (signed `Decimal`, scale 8).
- Buying a `USD` asset without `USD` cash creates a negative `USD` balance accruing daily IBKR tier benchmark + spread interest (no implicit free FX conversion).
- Automated cash sweeps emit `secType="CASH"`, `symbol="USD"`, `currency="CAD"`, **`exchange="FXCONV"`** (`$2.00` USD min fee, `0.2` bps) — never `IDEALPRO`, unless a strategy explicitly opens a tracked FX alpha position.
2. **Contract & Canadian board-lot rules:**
- Every IB `Contract` specifies `conid`, `currency`, `exchange="SMART"`, and `primaryExchange` (`NYSE`, `NASDAQ`, `TSE`, `VENTURE`, etc.).
- Position sizing on `XTSE` / `XTSX` (`board_lot_policy = 'tsx_tiered'`) rounds target orders to **Standard Trading Units** (`100` shares if mark $\ge \$1.00$ CAD; `500` shares if $\$0.10\text{–}\$0.995$; `1,000` shares if $< \$0.10$) unless odd-lot execution + wider spread penalty is explicitly enabled.
- Auction orders enforce hard venue cutoffs (`15:40 ET` TSX `MOC`; `15:50 ET` NYSE/Nasdaq `MOC`/`LOC`).
3. **Dual Live Drift Monitor:**
- **Check 1 — Engine/Execution Drift:** Compare live IB fills & cash against a Rust replay run on the **exact recorded live IB bars & L1 quotes** (gate: $|\Delta\text{fill}| \le 15\text{ bps/trade}$, daily tracking error $\le 50\text{ bps}$ annualized).
- **Check 2 — Feed Basis Drift:** Next morning after EOD/QM ingestion, compare Rust replay on **recorded IB bars** vs. Rust replay on **curated EOD/QM bars** for the same session to detect SIP vs. IB `SMART` volume/auction divergence before blaming execution.