11 KiB
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 frominitialCapital(so first-period losses are never skipped). - Annualization factor (
A):252trading sessions/year for equity strategies (252 * 390only 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 same252/yr scale). - Volatility: Sample standard deviation (
N - 1degrees of freedom), annualized via\hat{\sigma}_{\text{ann}} = \hat{\sigma}_d \sqrt{252}. - Sharpe Ratio (
\widehat{SR}): Arithmetic excess return over risk-free rater_fper 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
Tobservations (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 to50.0across 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():
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 resetN = 1by inventing a new strategyfamilyname. - Multi-horizon / breakdown accounting: A single
analyze_signalcall evaluating 3 horizons (1d,5d,20d) records 3 rows intrial_ledger. - Effective independent trials (
\hat{N}, Bailey & López de Prado): GivenKtrials in the cluster with overlapping daily series correlation matrixP:
Sweeping\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)SMA(20)andSMA(21)(\rho \approx 0.97) adds\approx 0.03effective 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):
- Partition
TintoS = 16contiguous equal sub-periods (respectingpurgeat boundaries). - For all
\binom{16}{8} = 12,870splits into in-sampleJand out-of-sample\bar{J}: findn^* = \arg\max_n SR_n(J), compute the relative OOS rank\omega \in (0, 1)ofn^*within\{SR_n(\bar{J})\}, and set\lambda = \ln\!\frac{\omega}{1 - \omega}. \text{PBO} = \Pr(\lambda < 0)across all12,870splits.
Gate: Candidate → Validated requires PBO <= 0.20.
3. Purging, Embargo, Recency & the 6-Month Vault
- Purged Walk-Forward & CPCV: Every train/test boundary enforces:
purge_bars = prediction_horizon_bars + feature_warmup_bars(eliminatinglabelHorizonMs = 0overlap leakage).embargo_days = max(5, ceil(0.01 * total_trading_days))after each test fold before resuming training.
- 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. - 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/exportdisabled forsb-research.*tokens and campaign containers blocked from DB ports. - One-shot human burn: Triggered only on operator
Validated → Paperaction (<= 10evaluations/year enforced by an append-onlyvault_evaluationstable). Requires Vault post-cost Sharpe> 0.5and within1.5\sigmaof CPCV fold distribution.
- Set to
Vault Evaluations Schema (Append-Only)
Protected against UPDATE/DELETE/TRUNCATE by reject_research_evidence_mutation(). A BEFORE INSERT trigger requires READ COMMITTED transaction isolation (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:
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
- Multi-currency IBKR Margin accounting (
USD+CAD):- Rust
Ledgerholdscash: BTreeMap<Currency, Posting>(signedDecimal, scale 8). - Buying a
USDasset withoutUSDcash creates a negativeUSDbalance 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.00USD min fee,0.2bps) — neverIDEALPRO, unless a strategy explicitly opens a tracked FX alpha position.
- Rust
- Contract & Canadian board-lot rules:
- Every IB
Contractspecifiesconid,currency,exchange="SMART", andprimaryExchange(NYSE,NASDAQ,TSE,VENTURE, etc.). - Position sizing on
XTSE/XTSX(board_lot_policy = 'tsx_tiered') rounds target orders to Standard Trading Units (100shares if mark $\ge $1.00$ CAD;500shares if $$0.10\text{–}$0.995$;1,000shares if $< $0.10$) unless odd-lot execution + wider spread penalty is explicitly enabled. - Auction orders enforce hard venue cutoffs (
15:40 ETTSXMOC;15:50 ETNYSE/NasdaqMOC/LOC).
- Every IB
- 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
SMARTvolume/auction divergence before blaming execution.
- 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: