stock-bot/libs/research
2026-11-29 15:57:31 -05:00
..
examples feat(strategies): publish type-only strategy authoring API (CL31) 2026-10-28 14:42:58 -04:00
scripts T-122: M1.3g — @stock-bot/research: Vault-fenced universe planner + adapter method (survivorship-free active listings on a date from curated bars_1d Parquet, US_EQ / CA_EQ / US_CA_EQ) with tests and local benchmark (no new dependencies) 2026-11-29 15:39:45 -05:00
src T-122: M1.3g — @stock-bot/research: Vault-fenced universe planner + adapter method (survivorship-free active listings on a date from curated bars_1d Parquet, US_EQ / CA_EQ / US_CA_EQ) with tests and local benchmark (no new dependencies) 2026-11-29 15:50:27 -05:00
test T-122: tests 2026-11-29 15:57:31 -05:00
package.json T-121: M1.3f — @stock-bot/research: pure signal-panel builder (MarketDataStore daily bars + as-of signal rows → Vault-safe forward-return SignalCrossSection[]) with an end-to-end ceoShorts signal study test (store → analyzeSignal → trial_ledger → DSR) and local benchmark (no new dependencies) 2026-11-29 08:45:16 -05:00
README.md T-122: M1.3g — @stock-bot/research: Vault-fenced universe planner + adapter method (survivorship-free active listings on a date from curated bars_1d Parquet, US_EQ / CA_EQ / US_CA_EQ) with tests and local benchmark (no new dependencies) 2026-11-29 15:39:45 -05:00
tsconfig.json refactor: share research domain and simplify application workflows 2026-10-26 15:29:43 -04:00

@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 and non-zero variance at REAL storage precision for dailySeries. Computes { nObs, sharpeUnann, skewness, kurtosis } via trialMoments from @stock-bot/calculations.
  • recordTrials(executor, rows) — Validates every row upfront (re-verifying that pre-built rows' moments match their dailySeries, 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 while preserving PostgreSQL's 6-digit microsecond UTC precision across Z and explicit ±HH:MM offsets.
  • 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 (sessionDates covering the trial's full [sampleStart, sampleEnd] range where the series length matches the session count in [sampleStart, sampleEnd]) or explicit per-trial observationDatesByTrialId (for sparse signal_ic / event_study series); trials without proven alignment or pairs with constant overlap slices are counted in pairsSkipped without inventing correlations. Cross-window correlations are computed directly within and across alignment groups without materializing dense NaN padding.

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,900 overlapping pairs, zero NaN padding): staggeredElapsedMs = 508.77 ms, staggeredTrialsPerSec = 393.1 trials/s

Signal Study Runners

Exported from both @stock-bot/research and @stock-bot/research/signal-study (libs/research/src/signal-study.ts). Browser-safe and dependency-free; database access is injected via TrialLedgerExecutor.

API & Write-Before-Return Guarantee

  • analyzeSignal(executor, request) — Validates inputs upfront, runs analyzeSignalPanel under the exclusive vaultCutoffDate fence, appends one stage = 'signal_ic' row to trial_ledger, and computes clusterDeflatedSharpe for the newly recorded trial.
  • runEventStudy(executor, request) — Validates inputs upfront, fences out events whose event date or post-event window end (sessionDates[dayIndex + postDays]) falls on or after vaultCutoffDate, runs eventStudy, appends one stage = 'event_study' row to trial_ledger, and computes clusterDeflatedSharpe.
  • Write-before-return & partial-failure semantics:
    • If recordTrials (INSERT) fails, the error propagates directly and no analysis or study result is returned.
    • If recordTrials succeeds but clusterDeflatedSharpe (SELECT) fails, the runner throws SignalStudyError with code: 'dsr_read_failed', exposing the already-written trialId and original cause. The INSERT is never retried.
    • Validation errors and status: 'insufficient_data' paths (too few observations, below_min_events, too_few_event_dates, or zero-variance series at REAL precision) issue zero SQL queries.

Logged Series by Stage

Runner trial_ledger.stage Logged daily_series Observation Dates
analyzeSignal (default ledgerSeries: 'rank_ic') 'signal_ic' analysis.rankIcSeries analysis.dates
analyzeSignal (ledgerSeries: 'quantile_spread') 'signal_ic' analysis.quantiles.spreadSeries analysis.quantiles.dates
runEventStudy 'event_study' study.clustered.meanCars study.clustered.dates

Vault Holdout & Cluster DSR Behavior

  • analyzeSignal delegates to analyzeSignalPanel's exclusive vaultCutoffDate fence, excluding all cross-sections with date >= vaultCutoffDate (reported in analysis.diagnostics.vaultExcludedDates) so sampleEnd < vaultCutoffDate. Callers assembling pre-computed forward-return panels remain responsible for ensuring forward-return horizons do not consume post-cutoff prices.
  • runEventStudy validates return-array shapes against the original sessionDates calendar, drops every event where sessionDates[dayIndex] >= vaultCutoffDate or sessionDates[dayIndex + postDays] >= vaultCutoffDate (reported in vaultExcludedEvents), and passes only the pre-cutoff calendar and matching return prefixes to eventStudy without mutating caller inputs so held-out Vault-tail values (including non-finite returns) never leak into or fail pre-Vault studies.
  • Count-based DSR fallback: Because analyzeSignal and runEventStudy supply observationDatesByTrialId only for the newly written trial and no shared session grid for historical trials in the cluster, clusterDeflatedSharpe skips unaligned historical correlation pairs (pairsUsed === 0, pairsSkipped === clusterSize * (clusterSize - 1) / 2) and falls back conservatively to count-based effectiveTrials === clusterSize. Callers needing correlation-aware effectiveTrials across historical trials should invoke clusterDeflatedSharpe directly with a trusted sessionDates calendar or per-trial observationDatesByTrialId.

SignalStudyError Codes

Code Meaning
'invalid_request' Invalid executor, request envelope, expression, principal, UUID, market, or horizon bucket (0 SQL queries)
'empty_panel' Empty panel or empty input.sessionDates (0 SQL queries)
'invalid_date' Malformed or non-calendar YYYY-MM-DD date in vaultCutoffDate, panel, or sessionDates (0 SQL queries)
'unsorted_dates' Panel or sessionDates not strictly ascending (0 SQL queries)
'duplicate_date' Duplicate date in panel or sessionDates (0 SQL queries)
'invalid_panel' Malformed cross-section vectors/IDs, return arrays, or event descriptors (0 SQL queries)
'invalid_option' Invalid ledgerSeries, dsrGate, or analyzer/event-study options (0 SQL queries)
'dsr_read_failed' Trial row was inserted (error.trialId is set), but clusterDeflatedSharpe failed (error.cause holds the original error)

Local In-Memory Benchmark (analyzeSignal)

Fixed-seed (20260402) end-to-end analyzeSignal benchmark covering 5,040 business dates × 3,000 listings (15,120,000 observations) with an in-memory TrialLedgerExecutor:

  • Command: bun run libs/research/scripts/benchmark-signal-study.ts
  • Observed (Bun 1.2.16): elapsedMs = 1691.13 ms, rowsPerSec = 8,940,793 rows/s (2,980 dates/s, nObs = 5040, meanRankIc = 0.057294, recencyGatePassed = true)

DuckDB Curated Parquet Query Planner & MarketDataStore Adapter

Exported from both @stock-bot/research and @stock-bot/research/market-data-store-duckdb (libs/research/src/market-data-store-duckdb.ts). The module is dependency-free and browser-safe; DuckDB execution is injected via DuckDbExecutor ({ run(sql), query(sql, params) }) so parameter values are always bound separately from SQL text.

API

  • planBars1dQuery(q, ctx) — Plans a fenced query over <curatedRoot>/bars_1d/year=*/part.parquet (hive_partitioning = true) for timeframe: '1d' and adjustment: 'raw' | 'split' | 'total'. Rejects '1m' | '5m' | '1h' with MarketDataStoreNotImplementedError. For 'split' and 'total', requires a verified point_in_time_fenced ctx.adjFactorsSnapshot matching the query's effective asOf and Vault fence, and binds read_parquet(...) directly to ctx.adjFactorsSnapshot.path.
  • planAdjFactorsMetadataQuery(adjPath) / parseAdjFactorsSnapshotMetadata(adjPath, kvRows) — Plans the parquet_kv_metadata('<adjPath>') query for stock_bot.adj_factors.* footer keys and strictly parses/validates them (mirroring tools/curate-etl/src/curate_adj.rs).
  • planEventsQuery(q, ctx) — Plans a 'vault_fenced' query over <curatedRoot>/events/year=*/part.parquet (hive_partitioning = true) filtered by allow-listed kinds and optional listingIds, preserving the Parquet writer's total sort order (listing_id, ts, kind, subtype, payload_json, known_at, known_at_source).
  • planShortsAsOfQuery(q, ctx) — Plans a 'vault_fenced' query over <curatedRoot>/shorts/part.parquet, binding UTC YYYY-MM-DD report_date bounds and microsecond UTC ISO-8601 known_at <= ?.
  • planFx1dQuery(q, ctx) — Plans a 'vault_fenced' query (with default asOf = vaultCutoffTs * 1000 - 1 µs) over <curatedRoot>/fx_1d/part.parquet for timeframe: '1d', mapping 'USD.CAD' to the stored bound parameter 'USDCAD'. Rejects '1m' with MarketDataStoreNotImplementedError.
  • planUniverseQuery(q, ctx) — Plans a 'vault_fenced', survivorship-free query over <curatedRoot>/bars_1d/year=*/part.parquet (hive_partitioning = true) returning SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC for supported UNIVERSE_REFS ('US_EQ', 'CA_EQ', 'US_CA_EQ') within [date - lookbackDays, date] (default DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7, configurable via ctx.universeLookbackDays).
  • createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? }) — Returns a MarketDataStore adapter that eagerly validates options and resolveDuckDbConnectionBudget(env), lazily executes the three budget SET statements sequentially and at most once before the first executor.query(...) (including under concurrent first calls, with clean retry if initialization fails), pins a single adj_factors artifact version across both parquet_kv_metadata footer verification and the read_parquet factor scan (via pinAdjFactorsArtifact handle pinning or an explicit write-once immutableAdjFactorsPath distinct from the mutable <curatedRoot>/adj_factors/part.parquet, failing closed with AdjFactorsSnapshotError('unpinned_mutable_path') if unpinned), validates per-column scalar types and nullability when mapping rows into BarBatch / Table / strictly ascending INT32 universe number[], and rejects out-of-slice methods (bars 1m/5m/1h, fx 1m, crossSection, fundamentalsAsOf, macroAsOf) with MarketDataStoreNotImplementedError and zero executor calls.

Mandatory Vault, PIT, Microsecond & Boundary Validation Rules

  • Every planner delegates unconditionally to applyVaultFence, binding ts/report_date bounds and known_at <= ? in UTC (TZ-invariant). Under 'vault_fenced', from >= vaultCutoffTs throws VaultHoldoutFenceError and to/asOf clamp strictly below vaultCutoffTs; 'vault_evaluation_only' requires vaultOperatorAuthorized === true (only on bars; events, shortsAsOf, and fx are always 'vault_fenced').
  • Microsecond upper-bound precision: Curated Parquet ts and known_at columns store UTC microseconds (curate_fx_1d stamps 23:59:59.999999Z). Date-only YYYY-MM-DD upper bounds (to, asOf) and default or clamped Vault upper bounds expand to the last included Parquet microsecond (.999999Z / vaultCutoffTs * 1000 - 1), while explicit time-of-day bounds preserve their caller-specified precision. Under 'vault_fenced', every planned upper bound remains strictly < vaultCutoffTs.
  • curatedRoot (and optional adjFactorsPath) are the only values embedded in SQL text and must be absolute POSIX paths free of control characters (<= 0x1f, 0x7f), ', ;, and glob metacharacters (*, ?, [, ]).
  • All caller values (listingIds as INT32 safe integers, allow-listed kinds, 'USD.CAD' -> 'USDCAD', and UTC date/timestamp bounds) are validated upfront and passed strictly as bound ? parameters.

bars 1d Adjustment Formulas & Verified Fenced adj_factors Requirement

bars_1d stores raw OHLC, optional vwap, and split-unadjusted raw share volume. Because adj_factors stores right-to-left cumulative suffix products (cum_split_factor, cum_total_factor), slicing a retrospective adj_factors file with known_at <= asOf would still embed future or held-out Vault splits/dividends into earlier cumulative factors.

  • 'raw': OHLC, vwap, and volume are returned unadjusted (adj_factors is not read).
  • 'split' / 'total': Require a verified point_in_time_fenced adj_factors Parquet artifact (published by curate_and_write_adj_factors_as_of with stock_bot.adj_factors.* footer metadata) whose effective inclusive microsecond fence matches the query's effective asOf and Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected with AdjFactorsSnapshotError before any bars query runs. To prevent TOCTOU races when curate-etl atomically replaces <curatedRoot>/adj_factors/part.parquet between footer verification and the factor scan, createDuckDbMarketDataStore requires either pinAdjFactorsArtifact (binding a stable handle such as /proc/self/fd/<fd>, /dev/fd/<fd>, or a private hardlink/copy for both queries and releasing it in finally) or an explicit write-once immutableAdjFactorsPath distinct from the mutable published path; unpinned mutable paths fail closed with AdjFactorsSnapshotError('unpinned_mutable_path').
  • Against the verified adj_factors file, bars_1d is joined via ASOF LEFT JOIN (filtered to listing_id IN (...) AND known_at <= ?) on b.listing_id = a.listing_id AND b.session_date < a.ex_date (matching the first adj_factors row with ex_date > session_date per tools/curate-etl/README.md):
    • 'split': open, high, low, close, and vwap are divided by COALESCE(a.cum_split_factor, 1.0); volume is multiplied by COALESCE(a.cum_split_factor, 1.0).
    • 'total': open, high, low, close, and vwap are divided by COALESCE(a.cum_total_factor, 1.0); volume is multiplied by COALESCE(a.cum_split_factor, 1.0).

universe

planUniverseQuery and createDuckDbMarketDataStore().universe({ ref, date }) resolve the survivorship-free set of active INT32 listing_ids on a UTC calendar date (YYYY-MM-DD) directly from curated bars_1d Parquet (hive_partitioning = true):

  • Provisional M1 bar-currency membership rule: Supported UNIVERSE_REFS ('US_EQ', 'CA_EQ', 'US_CA_EQ', matching trial_ledger.universe_market) filter bars_1d.currency using bound ? parameters ('USD', 'CAD', or IN ('USD', 'CAD')). Because membership is provisionally determined by bar quote currency before security-master MIC joins are added, USD-quoted TSX listings land in 'US_EQ'. 'FX' and any other ref throw MarketDataStoreValidationError (field: 'ref') with zero executor calls.
  • Active-listing lookback window: A listing is active on date when it has at least one bars_1d row with session_date in [date - lookbackDays, date] (calendar days; default DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7, optional positive-integer universeLookbackDays on context/store options). No row after date is ever read, so delisted listings appear only while they traded.
  • Mandatory Vault & PIT fence: date is always routed through applyVaultFence under 'vault_fenced' scope (date >= vaultCutoffTs throws VaultHoldoutFenceError with zero executor calls, even when vaultOperatorAuthorized: true), and every planned query binds both b.ts <= ? and b.known_at <= ? strictly below vaultCutoffTs.

Local Query-Planner Benchmark

Fixed-seed (20261129) local benchmark planning 120,000 mixed queries across bars 1d (raw/split/total), events (with and without listingIds), shortsAsOf, and fx 1d, plus a fixed-seed (20261129) universe case exercising createDuckDbMarketDataStore().universe() (plan + adapter mapping) over 200 calls × 15,000 listing IDs (3,000,000 mapped IDs) via an in-memory executor (checksums verified outside the timed sections):

  • Command: bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts
  • Observed (Bun 1.2.16):
    • Mixed planners (120,000 queries): elapsedMs = 225.79 ms, queriesPerSec = 531,470 queries/s (758,061 bound params, pinned checksum 8606c98c)
    • universe plan + adapter mapping (200 calls × 15,000 listings): elapsedMs = 23.44 ms, callsPerSec = 8,534 calls/s, rowsPerSec = 128,011,137 rows/s (3,000,000 mapped IDs, pinned checksum ef5f1136)

Signal Panel Builder

Exported from both @stock-bot/research and @stock-bot/research/signal-panel (libs/research/src/signal-panel.ts). The module is pure, synchronous (except collectBars), dependency-free, and browser-safe (zero node:* imports, zero bare process access, no database drivers).

API

  • buildForwardReturnPanel({ bars, signals, horizonSessions, vaultCutoffDate, maxSignalAgeSessions? }) — Joins daily BarRecord[] (caller-supplied 'total'-adjusted closes in any order) with point-in-time SignalObservation[] ({ listingId, knownAt, value }) into Vault-safe SignalCrossSection[] slices ready for analyzeSignal. Returns { panel, sessionDates, diagnostics } with strictly ascending dates, ids: Int32Array sorted ascending by listingId, and signal / forwardReturn as Float64Array, deterministic under any input permutation and without mutating caller inputs.
  • shortsTableToSignalRows(table, field) — Maps a MarketDataStore.shortsAsOf Table into SignalObservation[] for field: 'shares_short' | 'net_change' | 'pct_float', skipping null cells, normalizing -0 to 0, and rejecting missing columns or malformed rows with SignalPanelError.
  • collectBars(iterable) — Drains AsyncIterable<BarBatch> (such as MarketDataStore.bars) into a flat BarRecord[] using indexed loops without mutating yielded batches.

UTC Session Calendar, PIT Alignment & Vault Rules

  • UTC session calendar: Daily curated bars (bars_1d.ts) are stamped at 16:00 ET (20:00 or 21:00 UTC), so the integer UTC day key Math.floor(bar.ts / 86_400_000) maps 1:1 to the exchange session date YYYY-MM-DD.
  • Strict point-in-time (knownAt <= bar.ts): For each listing and session d, the active signal is the latest row with knownAt <= bar.ts (ties on identical (listingId, knownAt) break deterministically by value ASC so the highest value wins regardless of input order). A signal known after the close (e.g. 17:00 ET) is never applied on d and first takes effect on d + 1.
  • Signal staleness (maxSignalAgeSessions): When set (>= 0), age is measured in calendar sessions elapsed since the first actionable session where sessionMaxTs[s] >= knownAt (so a 17:00 ET after-close signal has age 0 on the next trading day). Expired observations are dropped and counted in diagnostics.droppedStaleSignal.
  • Exact horizon alignment & close validation: forwardReturn = close[d + h] / close[d] - 1 uses the listing's own bar exactly horizonSessions calendar sessions ahead; missing forward bars are dropped (diagnostics.droppedMissingForwardBar) and never shifted to d + h + 1. Non-positive or non-finite closes (<= 0, NaN, ±Infinity) drop cleanly into diagnostics.droppedNonPositiveClose without throwing. Exact pre-cutoff duplicate bars (ts and close identical) are deduplicated into diagnostics.duplicateBars; conflicting duplicates on the same (listingId, date) throw SignalPanelError('duplicate_bar').
  • Vault holdout fence: sessionDates contains only dates strictly < vaultCutoffDate. No cross-section is emitted when either d or its forward session d + horizonSessions reaches or exceeds vaultCutoffDate (counted in diagnostics.vaultExcludedDates), and bar.close is never accessed for any bar on or after vaultCutoffDate.

SignalPanelError Codes

Code Meaning
'invalid_input' Non-object input envelope, non-array bars/signals, invalid AsyncIterable, invalid shorts field, or missing required table columns
'invalid_horizon' horizonSessions is not a safe integer >= 1
'invalid_option' maxSignalAgeSessions is defined and not a safe integer >= 0
'invalid_date' vaultCutoffDate is not a valid strict calendar YYYY-MM-DD date
'invalid_bar' Malformed bar record, invalid INT32 listingId, invalid epoch-ms ts/knownAt, non-number pre-cutoff close, or malformed BarBatch
'invalid_signal' Malformed signal or shorts table row, invalid listingId/knownAt, or non-finite non-null signal value
'duplicate_bar' Two pre-cutoff bars for the same (listingId, date) disagree on ts or close

Local In-Memory Benchmark (buildForwardReturnPanel)

Fixed-seed (20261129) local benchmark covering 5,040 business sessions × 3,000 listings (15,120,000 input bars, 720,000 monthly-ish 17:00 ET signal rows, horizonSessions = 5, vaultCutoffDate = '2025-03-31'):

  • Command: bun run libs/research/scripts/benchmark-signal-panel.ts
  • Observed (Bun 1.2.16): elapsedMs = 817.24 ms, rowsPerSec = 18,501,301 rows/s (5,014 emitted panel dates, 15,042,000 emitted observations, 25 Vault-excluded dates, pinned checksum f0f28bdf)