stock-bot/libs/research/README.md

3.6 KiB
Raw Blame History

@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 in expression is collapsed, undefined object keys are omitted, -0 is normalized to 0, and non-JSON values (NaN, ±Infinity, functions, symbols, BigInt, cycles) are rejected with TrialLedgerError.
  • buildTrialRow(input) — Pure validator and moment builder for a single trial_ledger row. Validates principal (operator or agent:<uuid>), optional UUIDs, schema enums (stage, universeMarket, horizonBucket), 64-hex expressionHash, strict YYYY-MM-DD dates, the exclusive Vault fence, and IEEE-754 REAL (float32) representability for every dailySeries element. Computes { nObs, sharpeUnann, skewness, kurtosis } via trialMoments from @stock-bot/calculations.
  • recordTrials(executor, rows) — Validates every row upfront (sending zero SQL on any invalid row or batch > MAX_TRIAL_BATCH_SIZE = 4681) and appends the batch atomically in one parameterised multi-row INSERT ... 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 by trial_id ASC (backed by idx_trial_ledger_cluster), optionally capped at created_at <= asOf.
  • clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate? }) — Loads the target trial and its relatedness cluster, aligns series without fabricating correlations across unalignable sample windows (shared sampleStart uses zero-copy left alignment; shared sampleEnd uses leading-NaN right alignment; unalignable windows are placed in disjoint NaN-padded blocks so effectiveIndependentTrials surfaces pairsSkipped and meanCorrelation: null), and computes { trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }.

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:

  • Command: bun test libs/research/test/trial-ledger.test.ts
  • Workload: 200 trials × 5,000 daily observations (seed 20260403)
  • Measured (Bun 1.2.16): elapsedMs = 732.35 ms, trialsPerSec = 273.1 trials/s (effectiveTrials = 171.85, dsr = 0.011891)