This commit is contained in:
Boki 2026-11-26 22:23:07 -05:00
parent c353ddbe01
commit ce9e2df67c
310 changed files with 2550 additions and 36861 deletions

View file

@ -0,0 +1,103 @@
# 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(16) 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.
---
## 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.