stock-bot/libs/research/README.md

76 lines
9.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# `@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`)