| .. | ||
| examples | ||
| scripts | ||
| src | ||
| test | ||
| package.json | ||
| README.md | ||
| tsconfig.json | ||
@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 (
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, runsanalyzeSignalPanelunder the exclusivevaultCutoffDatefence, appends onestage = 'signal_ic'row totrial_ledger, and computesclusterDeflatedSharpefor 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 aftervaultCutoffDate, runseventStudy, appends onestage = 'event_study'row totrial_ledger, and computesclusterDeflatedSharpe.- Write-before-return & partial-failure semantics:
- If
recordTrials(INSERT) fails, the error propagates directly and no analysis or study result is returned. - If
recordTrialssucceeds butclusterDeflatedSharpe(SELECT) fails, the runner throwsSignalStudyErrorwithcode: 'dsr_read_failed', exposing the already-writtentrialIdand originalcause. TheINSERTis never retried. - Validation errors and
status: 'insufficient_data'paths (too few observations,below_min_events,too_few_event_dates, or zero-variance series atREALprecision) issue zero SQL queries.
- If
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
analyzeSignaldelegates toanalyzeSignalPanel's exclusivevaultCutoffDatefence, excluding all cross-sections withdate >= vaultCutoffDate(reported inanalysis.diagnostics.vaultExcludedDates) sosampleEnd < vaultCutoffDate. Callers assembling pre-computed forward-return panels remain responsible for ensuring forward-return horizons do not consume post-cutoff prices.runEventStudyvalidates return-array shapes against the originalsessionDatescalendar, drops every event wheresessionDates[dayIndex] >= vaultCutoffDateorsessionDates[dayIndex + postDays] >= vaultCutoffDate(reported invaultExcludedEvents), and passes only the pre-cutoff calendar and matching return prefixes toeventStudywithout 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
analyzeSignalandrunEventStudysupplyobservationDatesByTrialIdonly for the newly written trial and no shared session grid for historical trials in the cluster,clusterDeflatedSharpeskips unaligned historical correlation pairs (pairsUsed === 0,pairsSkipped === clusterSize * (clusterSize - 1) / 2) and falls back conservatively to count-basedeffectiveTrials === clusterSize. Callers needing correlation-awareeffectiveTrialsacross historical trials should invokeclusterDeflatedSharpedirectly with a trustedsessionDatescalendar or per-trialobservationDatesByTrialId.
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) fortimeframe: '1d'andadjustment: 'raw' | 'split' | 'total'. Rejects'1m' | '5m' | '1h'withMarketDataStoreNotImplementedError. For'split'and'total', requires a verifiedpoint_in_time_fencedctx.adjFactorsSnapshotmatching the query's effectiveasOfand Vault fence, and bindsread_parquet(...)directly toctx.adjFactorsSnapshot.path.planAdjFactorsMetadataQuery(adjPath)/parseAdjFactorsSnapshotMetadata(adjPath, kvRows)— Plans theparquet_kv_metadata('<adjPath>')query forstock_bot.adj_factors.*footer keys and strictly parses/validates them (mirroringtools/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-listedkindsand optionallistingIds, 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 UTCYYYY-MM-DDreport_datebounds and microsecond UTC ISO-8601known_at <= ?.planFx1dQuery(q, ctx)— Plans a'vault_fenced'query (with defaultasOf = vaultCutoffTs * 1000 - 1µs) over<curatedRoot>/fx_1d/part.parquetfortimeframe: '1d', mapping'USD.CAD'to the stored bound parameter'USDCAD'. Rejects'1m'withMarketDataStoreNotImplementedError.createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, adjFactorsPath?, env?, barBatchSize? })— Returns aMarketDataStoreadapter that eagerly validates options andresolveDuckDbConnectionBudget(env), lazily executes the three budgetSETstatements sequentially and at most once before the firstexecutor.query(...)(including under concurrent first calls, with clean retry if initialization fails), verifiesparquet_kv_metadataon the exactadj_factorsfile before every'split'/'total'barsquery, validates per-column scalar types and nullability when mapping rows intoBarBatch/Table, and rejects out-of-slice methods (bars1m/5m/1h,fx1m,crossSection,fundamentalsAsOf,macroAsOf,universe) withMarketDataStoreNotImplementedErrorand zero executor calls.
Mandatory Vault, PIT, Microsecond & Boundary Validation Rules
- Every planner delegates unconditionally to
applyVaultFence, bindingts/report_datebounds andknown_at <= ?in UTC (TZ-invariant). Under'vault_fenced',from >= vaultCutoffTsthrowsVaultHoldoutFenceErrorandto/asOfclamp strictly belowvaultCutoffTs;'vault_evaluation_only'requiresvaultOperatorAuthorized === true(only onbars;events,shortsAsOf, andfxare always'vault_fenced'). - Microsecond upper-bound precision: Curated Parquet
tsandknown_atcolumns store UTC microseconds (curate_fx_1dstamps23:59:59.999999Z). Date-onlyYYYY-MM-DDupper 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 optionaladjFactorsPath) 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 (
listingIdsasINT32safe integers, allow-listedkinds,'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, andvolumeare returned unadjusted (adj_factorsis not read).'split'/'total': Require a verifiedpoint_in_time_fencedadj_factorsParquet artifact (published bycurate_and_write_adj_factors_as_ofwithstock_bot.adj_factors.*footer metadata) whose effective inclusive microsecond fence matches the query's effectiveasOfand Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected withAdjFactorsSnapshotErrorbefore anybarsquery runs, andread_parquet(...)is bound directly to the verified file path.- Against the verified
adj_factorsfile,bars_1dis joined viaASOF LEFT JOIN(filtered tolisting_id IN (...) AND known_at <= ?) onb.listing_id = a.listing_id AND b.session_date < a.ex_date(matching the firstadj_factorsrow withex_date > session_datepertools/curate-etl/README.md):'split':open,high,low,close, andvwapare divided byCOALESCE(a.cum_split_factor, 1.0);volumeis multiplied byCOALESCE(a.cum_split_factor, 1.0).'total':open,high,low,close, andvwapare divided byCOALESCE(a.cum_total_factor, 1.0);volumeis multiplied byCOALESCE(a.cum_split_factor, 1.0).
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 with no database dependency (full SQL text and ordered parameter values are verified against the pinned checksum outside the timed section):
- Command:
bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts - Observed (Bun 1.2.16):
elapsedMs = 218.55 ms,queriesPerSec = 549,073 queries/s(120,000queries,758,061bound params, pinned checksum8606c98c)