| .. | ||
| 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.planUniverseQuery(q, ctx)— Plans a'vault_fenced', survivorship-free query over<curatedRoot>/bars_1d/year=*/part.parquet(hive_partitioning = true) returningSELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASCfor supportedUNIVERSE_REFS('US_EQ','CA_EQ','US_CA_EQ') within[date - lookbackDays, date](defaultDEFAULT_UNIVERSE_LOOKBACK_DAYS = 7, configurable viactx.universeLookbackDays).createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, 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), pins a singleadj_factorsartifact version across bothparquet_kv_metadatafooter verification and theread_parquetfactor scan (viapinAdjFactorsArtifacthandle pinning or an explicit write-onceimmutableAdjFactorsPathdistinct from the mutable<curatedRoot>/adj_factors/part.parquet, failing closed withAdjFactorsSnapshotError('unpinned_mutable_path')if unpinned), validates per-column scalar types and nullability when mapping rows intoBarBatch/Table/ strictly ascending INT32universenumber[], and rejects out-of-slice methods (bars1m/5m/1h,fx1m,crossSection,fundamentalsAsOf,macroAsOf) 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. To prevent TOCTOU races whencurate-etlatomically replaces<curatedRoot>/adj_factors/part.parquetbetween footer verification and the factor scan,createDuckDbMarketDataStorerequires eitherpinAdjFactorsArtifact(binding a stable handle such as/proc/self/fd/<fd>,/dev/fd/<fd>, or a private hardlink/copy for both queries and releasing it infinally) or an explicit write-onceimmutableAdjFactorsPathdistinct from the mutable published path; unpinned mutable paths fail closed withAdjFactorsSnapshotError('unpinned_mutable_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).
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', matchingtrial_ledger.universe_market) filterbars_1d.currencyusing bound?parameters ('USD','CAD', orIN ('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 throwMarketDataStoreValidationError(field: 'ref') with zero executor calls. - Active-listing lookback window: A listing is active on
datewhen it has at least onebars_1drow withsession_datein[date - lookbackDays, date](calendar days; defaultDEFAULT_UNIVERSE_LOOKBACK_DAYS = 7, optional positive-integeruniverseLookbackDayson context/store options). No row afterdateis ever read, so delisted listings appear only while they traded. - Mandatory Vault & PIT fence:
dateis always routed throughapplyVaultFenceunder'vault_fenced'scope (date >= vaultCutoffTsthrowsVaultHoldoutFenceErrorwith zero executor calls, even whenvaultOperatorAuthorized: true), and every planned query binds bothb.ts <= ?andb.known_at <= ?strictly belowvaultCutoffTs.
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,000queries):elapsedMs = 225.79 ms,queriesPerSec = 531,470 queries/s(758,061bound params, pinned checksum8606c98c) universeplan + adapter mapping (200calls ×15,000listings):elapsedMs = 23.44 ms,callsPerSec = 8,534 calls/s,rowsPerSec = 128,011,137 rows/s(3,000,000mapped IDs, pinned checksumef5f1136)
- Mixed planners (
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 dailyBarRecord[](caller-supplied'total'-adjusted closes in any order) with point-in-timeSignalObservation[]({ listingId, knownAt, value }) into Vault-safeSignalCrossSection[]slices ready foranalyzeSignal. Returns{ panel, sessionDates, diagnostics }with strictly ascendingdates,ids: Int32Arraysorted ascending bylistingId, andsignal/forwardReturnasFloat64Array, deterministic under any input permutation and without mutating caller inputs.shortsTableToSignalRows(table, field)— Maps aMarketDataStore.shortsAsOfTableintoSignalObservation[]forfield: 'shares_short' | 'net_change' | 'pct_float', skippingnullcells, normalizing-0to0, and rejecting missing columns or malformed rows withSignalPanelError.collectBars(iterable)— DrainsAsyncIterable<BarBatch>(such asMarketDataStore.bars) into a flatBarRecord[]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 at16:00 ET(20:00or21:00 UTC), so the integer UTC day keyMath.floor(bar.ts / 86_400_000)maps 1:1 to the exchange session dateYYYY-MM-DD. - Strict point-in-time (
knownAt <= bar.ts): For each listing and sessiond, the active signal is the latest row withknownAt <= bar.ts(ties on identical(listingId, knownAt)break deterministically byvalue ASCso the highest value wins regardless of input order). A signal known after the close (e.g.17:00 ET) is never applied ondand first takes effect ond + 1. - Signal staleness (
maxSignalAgeSessions): When set (>= 0), age is measured in calendar sessions elapsed since the first actionable session wheresessionMaxTs[s] >= knownAt(so a17:00 ETafter-close signal has age0on the next trading day). Expired observations are dropped and counted indiagnostics.droppedStaleSignal. - Exact horizon alignment & close validation:
forwardReturn = close[d + h] / close[d] - 1uses the listing's own bar exactlyhorizonSessionscalendar sessions ahead; missing forward bars are dropped (diagnostics.droppedMissingForwardBar) and never shifted tod + h + 1. Non-positive or non-finite closes (<= 0,NaN,±Infinity) drop cleanly intodiagnostics.droppedNonPositiveClosewithout throwing. Exact pre-cutoff duplicate bars (tsandcloseidentical) are deduplicated intodiagnostics.duplicateBars; conflicting duplicates on the same(listingId, date)throwSignalPanelError('duplicate_bar'). - Vault holdout fence:
sessionDatescontains only dates strictly< vaultCutoffDate. No cross-section is emitted when eitherdor its forward sessiond + horizonSessionsreaches or exceedsvaultCutoffDate(counted indiagnostics.vaultExcludedDates), andbar.closeis never accessed for any bar on or aftervaultCutoffDate.
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,014emitted panel dates,15,042,000emitted observations,25Vault-excluded dates, pinned checksumf0f28bdf)
Event Study Panel Builder
Exported from both @stock-bot/research and @stock-bot/research/event-panel (libs/research/src/event-panel.ts). The module is pure, synchronous, dependency-free, and browser-safe (zero node:* imports, zero bare process access, no database drivers).
API
eventsTableToEventRows(table, filter?)— Maps aMarketDataStore.eventsTableinto point-in-timeEventObservation[]({ listingId, knownAt, kind, subtype }), validating every row upfront (before applying optional exact-matchfilter.kinds/filter.subtypesallow-lists), normalizing-0to0, and rejecting missing columns, empty filter arrays, or malformed rows withEventPanelError.buildEventStudyInput({ bars, events, vaultCutoffDate, exchangeCalendars, benchmark? })— Transforms dailyBarRecord[](caller-supplied'total'-adjusted closes in any order) andEventObservation[]rows into a Vault-safeEventStudyInput({ sessionDates, entityReturns, benchmarkReturns?, events }) plusEventPanelDiagnosticsready forrunEventStudy/eventStudy. Output is deterministic under any input permutation (entities inserted in ascendinglistingIdorder; events sorted by(dayIndex ASC, entityId ASC)) without mutating caller inputs.exchangeCalendars: { calendars, listingCalendarId }(required): caller-supplied exchange close calendars ({ date, closeTs }[]per calendar ID, pluslistingId -> calendarIdmapping). Every pre-Vault listing inbarsmust be mapped to a calendar that covers all of its pre-Vault bar dates (coverage gaps or missing mappings throwEventPanelError('invalid_option')). Each listing's events are anchored against its exchange's actual pre-Vault session close timestamps (e.g.13:00 ETon NYSE half-days vs16:00 ETon TSX) rather than curatedbars_1d.ts(16:00 ET), and the eligible session date is then mapped onto the sharedsessionDatesindex.benchmark?: 'equal_weight' | 'none'(default'none'when omitted/undefined;nullor any other value throwsEventPanelError('invalid_option')):'none'omitsbenchmarkReturns;'equal_weight'setsbenchmarkReturns[d]to the mean of finiteentityReturnson sessiond(NaNwhen none).
UTC Session Calendar, PIT Anchoring, NaN Returns & Vault Rules
- UTC session calendar: Daily curated bars (
bars_1d.ts) are stamped at16:00 ET(20:00or21:00 UTC), so the integer UTC day keyMath.floor(bar.ts / 86_400_000)maps 1:1 to the exchange session dateYYYY-MM-DD. - Consecutive-session returns &
NaNcontract (eventStudy): For each listing,entityReturnsis aFloat64Arrayaligned tosessionDates. Simple close-to-close returnclose[d] / close[d - 1] - 1is computed strictly when the listing has bars on consecutive exchange-calendar sessions (currCalIdx === prevCalIdx + 1) and both closes are finite and> 0with a finite ratio. Session0, missing-bar sessions (including an open exchange session missing for all listings), the first resumption session after a gap, and non-positive/non-finite/overflowing transitions (counted indiagnostics.nonPositiveCloseReturns) are written asNaN(never±Infinity), matchingeventStudy's contract inlibs/calculations/src/analytics/event-study.ts(which rejects±InfinitywithNON_FINITE_RETURNand cleanly drops events with anyNaNin[-preDays, +postDays]). - Duplicate-bar policy: Exact pre-cutoff duplicate bars (
tsandcloseidentical, includingNaN === NaN) are deduplicated intodiagnostics.duplicateBars; conflicting duplicates on the same(listingId, date)throwEventPanelError('duplicate_bar'). - Strict PIT event anchoring & drop precedence: Each event is classified in strict order: (1)
knownAt >= vaultCutoffDate (00:00:00.000Z)→diagnostics.vaultExcludedEvents; (2) listing has no pre-Vault bars →diagnostics.droppedUnknownListing; (3)knownAtis after the listing's last pre-Vault exchange close (or its eligible calendar date exceeds the last pre-Vault bar date) →diagnostics.droppedAfterLastSession; (4) eligible pre-Vault exchange session dates absent fromsessionDates→diagnostics.droppedMissingCalendarSession; (5) lower-bound binary search over the listing's exchange close timestamps, matchingeventDayIndexsemantics so after-close and post-half-day-close filings always anchor to the next trading session. Exact duplicate(listingId, dayIndex)events collapse to one (diagnostics.duplicateEvents), preservingevents.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + droppedMissingCalendarSession + duplicateEvents. - Vault holdout fence:
sessionDatescontains only dates strictly< vaultCutoffDate(post-cutoff dates are counted indiagnostics.vaultExcludedDates), andbar.closeis never accessed for any bar on or aftervaultCutoffDate.
EventPanelError Codes
| Code | Meaning |
|---|---|
'invalid_input' |
Non-object input envelope, non-array bars/events, malformed Table, or missing required columns (listing_id, known_at, kind, subtype) |
'invalid_date' |
vaultCutoffDate or an exchangeCalendars session date is not a valid strict calendar YYYY-MM-DD date |
'invalid_bar' |
Malformed bar record, invalid INT32 listingId, invalid epoch-ms ts/knownAt, or non-number pre-cutoff close |
'invalid_event' |
Malformed event or table row, invalid listingId/knownAt, kind outside EVENT_KINDS, or non-string/non-null subtype |
'invalid_option' |
Invalid benchmark mode, missing/malformed/incomplete exchangeCalendars (including pre-Vault bar coverage gaps), or invalid/empty eventsTableToEventRows filter (kinds/subtypes) |
'duplicate_bar' |
Two pre-cutoff bars for the same (listingId, date) disagree on ts or close |
Local In-Memory Benchmark (buildEventStudyInput)
Fixed-seed (20261129) local benchmark covering 5,040 business sessions × 3,000 listings (15,120,000 input bars, 240,000 after-close 17:00 ET filing events at stride 63, vaultCutoffDate = '2025-03-31', benchmark: 'equal_weight', XNYS/XTSE exchange calendars):
- Command:
bun run libs/research/scripts/benchmark-event-panel.ts - Observed (Bun 1.2.16):
elapsedMs = 731.06 ms,barsPerSec = 20,682,279 bars/s,eventsPerSec = 328,290 events/s(5,020pre-Vault sessions,240,000anchored events,20Vault-excluded dates, pinned checksum01b356d3)
MCP Copilot Core
Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported via the @stock-bot/research/mcp subpath (libs/research/src/mcp/index.ts). It is intentionally not re-exported from the browser-safe @stock-bot/research default entrypoint.
Registering Tools & Running Stdio Framing
defineMcpTool({ name, description, inputSchema, jsonSchema?, handler })— Registers a strict Zod-validated tool, convertsinputSchemainto a strict JSON Schema (additionalProperties: false, or uses an explicitjsonSchemaoverride), returnsisError: trueon invalid arguments without calling the handler, and sanitizes thrown handler errors so stack traces never leak.createMcpServer({ name, version, tools })— Transport-agnostic JSON-RPC 2.0 dispatcher implementinginitialize,notifications/initialized,ping,tools/list, andtools/callviahandleMessage(raw: string): Promise<string | null>. Rejects duplicate tool names at creation time.runStdioServer(server, { input?, output?, maxLineBytes? })— Newline-delimited JSON-RPC stdio transport over injectable streams (defaulting toprocess.stdin/process.stdout), with streaming UTF-8 decoding across arbitrary chunk boundaries, strict sequential dispatch in arrival order,maxLineBytesframe-size protection (default4 MiB), and zero non-protocol bytes onoutput.
query_data Tool (Vault-Fenced)
createQueryDataTool({ store, vaultContext })— Wraps an injectedMarketDataStorefor explicitlistingIds(maxQUERY_DATA_MAX_LISTING_IDS = 500) or a survivorship-freeuniverseref, with bounded output rows (QUERY_DATA_DEFAULT_LIMIT = 500, hard maxQUERY_DATA_MAX_LIMIT = 5_000).- Always enforces
scope: 'vault_fenced'viaapplyVaultFencebefore any store call, omitsscope/vault_evaluation_onlyfrom the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (ts >= vaultCutoffTsorknownAt >= vaultCutoffTs) as defense in depth, and mapsVaultHoldoutFenceError,VaultScopeNotAuthorizedError,MarketDataStoreValidationError,MarketDataStoreNotImplementedError, andAdjFactorsSnapshotErrortoisError: trueresponses naming the error class.
event_study Tool (Vault-Fenced)
createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })— Runs a Vault-fenced event study over daily bars and point-in-timeevents(filing,earnings,ceo_post,corporate_action, with optional exactsubtypesfilter capped atEVENT_STUDY_MAX_SUBTYPES = 100entries andEVENT_STUDY_MAX_SUBTYPE_LENGTH = 128chars each) for explicitlistingIds(maxEVENT_STUDY_MAX_LISTING_IDS = 500) or a survivorship-freeuniverseref matchinguniverseMarket, across[-preDays, +postDays](0–60sessions each;horizonBucketmust matchpostDays <= 10 ? 'swing_1_10d' : 'position_10d_plus').- Injected exchange calendars:
resolveExchangeCalendars({ listingIds, fromDate, toDate })supplies actual exchange session close timestamps (including half-days) forbuildEventStudyInputso events are anchored without synthesizing calendars from bars. - Returns, benchmark & Vault fence: Models daily close-to-close returns with no execution or transaction costs (
adjustmentdefaults to'raw';benchmarkdefaults to'equal_weight'using available eligible listing returns, or'none'for unbenchmarked returns). Enforcesscope: 'vault_fenced', clampsto/asOfstrictly belowvaultCutoffTs, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or withknown_at > asOf), and writes eligible trials exclusively to the injectedtrial_ledger(stage = 'event_study') under the server-injectedprincipalId.
file_finding Tool (Append-Only)
createFileFindingTool({ port, trialLookup, newId, now })— Files an append-only empiricalfindingordead_endrecord linked to 1–32 research-visibletrial_ledgerreferences (trialRefs, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (evidenceRefs, never dereferenced by the tool). Trims and enforces hard limits (title≤ 256,summary≤ 4,096,idempotencyKey≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message.- Review status & Vault safety: Server-controlled metadata (
id, UTC ISOcreatedAt, and initialstatus: 'pending_review') cannot be supplied by callers; director approval occurs out-of-band. Every uniquetrialRefis verified via the injected read-onlytrialLookup.hasResearchVisibleTrial(ref)before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only intitleandsummaryand keep Vault holdout observations out of filing text. - Idempotency & receipts:
FindingWritePortexposes onlyappendFinding(record, idempotencyKey?)with atomiccreated/replayed/conflictsemantics comparing normalizedkind,title,summary,trialRefs, andevidenceRefs. Retries with the same key and normalized payload return the original{ id, createdAt, created: false }without appending; key reuse with a different payload returns a fixedisError: trueconflict error with zero writes; unkeyed calls are independent. Filed records extendFindingRecordand can be read back by receipt ID viaread_knowledge.
Copilot Server
createResearchCopilotMcpServer(options)(exported from@stock-bot/research/mcpalongsideResearchCopilotMcpServerOptionsand the frozenRESEARCH_COPILOT_TOOL_NAMEStuple) composes all six research tools into one transport-agnosticMcpServerin the fixed registration ordersearch_symbols,query_data,analyze_signal,event_study,file_finding,read_knowledge. It acceptsnameandversion, shared authoritativestore,vaultContext,ledger, andprincipalId, plus the per-tool injected ports (searchSymbols,eventStudy.resolveExchangeCalendars,fileFinding,readKnowledge), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly withrunStdioServer(server, ...)for headless newline-delimited JSON-RPC sessions.
Remaining M2 MCP Items (Later Tasks)
- SSE/HTTP transport wrapper in
apps/stock/web-api. - Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters.
Versioned Feature Library
Exported from both @stock-bot/research and @stock-bot/research/feature-library (libs/research/src/feature-library.ts). The module is pure, dependency-free, and browser-safe (zero node:* imports, zero DuckDB driver dependency); SQL execution is injected via DuckDbExecutor ({ run(sql), query(sql, params) }).
API & Immutability
validateFeatureDefinition(def)— Fail-closed validator for declarativeduckdb_sqlfeature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a singleSELECTor non-recursiveWITH ... SELECTstatement projecting exactly(listing_id, ts, known_at, value)in contract order. RejectsWITH RECURSIVE, semicolons, comments, caller bind markers (?,$1,:name), prohibited DDL/DML/admin keywords (COPY,ATTACH,INSERT,CREATE,PRAGMA,SET, etc.), external readers (read_parquet,read_csv,glob, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared{{input:<dataset>}}placeholders (bars_1d,adj_factors,events,shorts,fx_1d,fundamentals_pit), in-scope non-recursive CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared.featureRef(def)/parseFeatureRef(ref)— Formats and parses canonical<name>@v<version>refs (^[a-z][a-z0-9_]{0,62}$and positive safe integer version; rejects non-canonical forms such asret_1d@v01).featureDefinitionHash(def)— Deterministic 64-char SHA-256 hex digest over{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals.familyanddescriptionare stored as metadata from the first registration.createFeatureRegistry()— In-memory registry exposingregisterSignal(def)(D11),get(ref), andlist(). Re-registering an identical hash is idempotent; re-registering<name>@v<version>with a different hash throwsFeatureLibraryError('FEATURE_VERSION_IMMUTABLE'). Defensive copies isolate stored definitions from caller mutation.planFeatureBatch(def, { curatedRoot, fromYear, toYear, vaultCutoffDate })— ValidatescuratedRoot, four-digit ordered years, and strict UTCYYYY-MM-DDvaultCutoffDateviaapplyVaultFence. Plans one yearly ZSTD Parquet write to<curatedRoot>/features/<name>/v<version>/year=YYYY/part.parquetthrough the last year with any pre-cutoff time (a January 1 cutoff excludes that calendar year; an entirely post-cutoff range throwsVAULT_RANGE_VIOLATION). Expands{{input:<dataset>}}scans with bound upper availability predicates (ts <= ? AND known_at <= ?,known_at <= ?, oreffective_known_at <= ?forfundamentals_pit) strictly< vaultCutoffDate(last included microsecond.999999Z) before authored SQL runs, preserving earlier history for SQL-owned warm-up.runFeatureBatch(def, opts, executor)— Validates and plans upfront (0 executor calls on invalid inputs), awaitsexecutor.query(sql, params)sequentially in year order, and returns{ ref, definitionHash, knownAtRule, warmupBars, inputs, writes }. On write failure, stops immediately and throwsFeatureLibraryError('BATCH_WRITE_FAILED')exposingcause,failedYear,completedYears, andcompletedWrites(earlier completed files may remain on disk for operator inspection before retry).RET_1D_V1— Built-inret_1d@v1example computing 1-day listing-partitioned raw-close return(close / LAG(close)) - 1.0withknown_at = tsandwarmupBars: 1(omitting rows without a positive prior close).
Operational & Research Governance Notes
- Executor & directory requirements: Callers running plans against DuckDB must configure the executor session timezone to UTC (
TZ=UTC) and ensure output parent directories (<curatedRoot>/features/<name>/v<version>/year=YYYY/) exist before executingCOPY. - Point-in-time &
adj_factorssnapshots: Feature definitions own per-observation availability (knownAtRuleand projectedknown_at). Becauseadj_factorsstores cumulative suffix products, features referencing{{input:adj_factors}}require a caller-verified, immutable point-in-time snapshot compatible withvaultCutoffDate. - Economic ownership & evidence: The Quant research role owns each feature's economic specification.
RET_1D_V1uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the featurerefanddefinitionHash, immutable dataset identifier, sample window,vaultCutoffDate, baseline, and execution assumptions.