4.5 KiB
@stock-bot/research
Browser-safe research contracts, rolling 6-month Vault holdout fencing, and append-only trial_ledger accounting (design/DATA-CONTRACTS.md, design/VALIDATION-AND-RIGOR.md).
trial_ledger Writer & Cluster N-hat-Deflated Sharpe Reader
Exported from both @stock-bot/research and @stock-bot/research/trial-ledger (libs/research/src/trial-ledger.ts). The module is dependency-free and browser-safe; PostgreSQL access is injected via TrialLedgerExecutor ({ query(text, params) }).
API
canonicalExpressionHash(input)— Returns a 64-character lowercase SHA-256 hex digest over the recursively ASCII-key-sorted compact JSON of{ expression, params, universe, sampleStart, sampleEnd, horizon }. Leading/trailing/internal whitespace inexpressionis collapsed,undefinedobject keys are omitted,-0is normalized to0, and non-JSON values (NaN,±Infinity, functions, symbols,BigInt, cycles) are rejected withTrialLedgerError.buildTrialRow(input)— Pure validator and moment builder for a singletrial_ledgerrow. Validates principal (operatororagent:<uuid>), optional UUIDs, schema enums (stage,universeMarket,horizonBucket), 64-hexexpressionHash, strictYYYY-MM-DDdates, the exclusive Vault fence, and IEEE-754REAL(float32) representability and non-zero variance atREALstorage precision fordailySeries. Computes{ nObs, sharpeUnann, skewness, kurtosis }viatrialMomentsfrom@stock-bot/calculations.recordTrials(executor, rows)— Validates every row upfront (re-verifying that pre-built rows' moments match theirdailySeries, sending zero SQL on any invalid row or batch >MAX_TRIAL_BATCH_SIZE = 4681) and appends the batch atomically in one parameterised multi-rowINSERT ... RETURNING trial_id, created_at. Multi-horizon analyses (e.g.1d,5d,20d) record one row per horizon.loadClusterTrials(executor, { universeMarket, horizonBucket, asOf? })— Loads a(universe_market, horizon_bucket)relatedness cluster ordered bytrial_id ASC(backed byidx_trial_ledger_cluster), optionally capped atcreated_at <= asOfwhile preserving PostgreSQL's 6-digit microsecond UTC precision acrossZand explicit±HH:MMoffsets.clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate?, sessionDates?, observationDatesByTrialId? })— Loads the target trial and its relatedness cluster and computes{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }. Index alignment requires a proven shared session grid (sessionDatescovering the trial's full[sampleStart, sampleEnd]range where the series length matches the session count in[sampleStart, sampleEnd]) or explicit per-trialobservationDatesByTrialId(for sparsesignal_ic/event_studyseries); trials without proven alignment or pairs with constant overlap slices are counted inpairsSkippedwithout inventing correlations. Cross-window correlations are computed directly within and across alignment groups without materializing denseNaNpadding.
Vault Holdout Fence Rule
Every row built by buildTrialRow or persisted by recordTrials requires an explicit vaultCutoffDate (YYYY-MM-DD) and delegates calendar validation and holdout enforcement to applyVaultFence in libs/research/src/market-data-store.ts. Any trial with sampleEnd >= vaultCutoffDate (or sampleStart >= vaultCutoffDate) is rejected with TrialLedgerError('VAULT_FENCE_VIOLATION') before any SQL is executed.
Local In-Memory Benchmark
Fixed-seed (20260403) in-memory benchmark covering 200 trials × 5,000 daily observations (1,000,000 observations total, 19,900 pairwise correlations) through buildTrialRow + clusterDeflatedSharpe with no PostgreSQL dependency, for both shared-window and 200-distinct-window staggered rolling clusters:
- Command:
bun test libs/research/test/trial-ledger.test.ts - Workload: 200 trials × 5,000 daily observations (seed
20260403), shared 5,000-session grid and 200-window staggered rolling grid (shifted by 1 session per trial across 5,199 sessions) - Measured (Bun 1.2.16):
- Shared window (
buildTrialRow+clusterDeflatedSharpe):elapsedMs = 710.17 ms,trialsPerSec = 281.6 trials/s(effectiveTrials = 171.85,dsr = 0.011891) - Staggered rolling windows (
clusterDeflatedSharpe, 200 distinct windows,19,900overlapping pairs, zeroNaNpadding):staggeredElapsedMs = 508.77 ms,staggeredTrialsPerSec = 393.1 trials/s
- Shared window (