diff --git a/libs/research/README.md b/libs/research/README.md index 771fe171..919c2b6d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -159,3 +159,40 @@ Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3 - **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`) + +## 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 a `MarketDataStore.events` `Table` into point-in-time `EventObservation[]` (`{ listingId, knownAt, kind, subtype }`), validating every row upfront (before applying optional exact-match `filter.kinds` / `filter.subtypes` allow-lists), normalizing `-0` to `0`, and rejecting missing columns, empty filter arrays, or malformed rows with `EventPanelError`. +- **`buildEventStudyInput({ bars, events, vaultCutoffDate, exchangeCalendars, benchmark? })`** — Transforms daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) and `EventObservation[]` rows into a Vault-safe `EventStudyInput` (`{ sessionDates, entityReturns, benchmarkReturns?, events }`) plus `EventPanelDiagnostics` ready for `runEventStudy` / `eventStudy`. Output is deterministic under any input permutation (entities inserted in ascending `listingId` order; 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, plus `listingId -> calendarId` mapping). Every pre-Vault listing in `bars` must be mapped to a calendar that covers all of its pre-Vault bar dates (coverage gaps or missing mappings throw `EventPanelError('invalid_option')`). Each listing's events are anchored against its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (`16:00 ET`), and the eligible session date is then mapped onto the shared `sessionDates` index. + - `benchmark?: 'equal_weight' | 'none'` (default `'none'` when omitted/`undefined`; `null` or any other value throws `EventPanelError('invalid_option')`): `'none'` omits `benchmarkReturns`; `'equal_weight'` sets `benchmarkReturns[d]` to the mean of finite `entityReturns` on session `d` (`NaN` when none). + +### UTC Session Calendar, PIT Anchoring, `NaN` Returns & 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`. +- **Consecutive-session returns & `NaN` contract (`eventStudy`):** For each listing, `entityReturns` is a `Float64Array` aligned to `sessionDates`. Simple close-to-close return `close[d] / close[d - 1] - 1` is computed strictly when the listing has bars on consecutive exchange-calendar sessions (`currCalIdx === prevCalIdx + 1`) and both closes are finite and `> 0` with a finite ratio. Session `0`, 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 in `diagnostics.nonPositiveCloseReturns`) are written as `NaN` (never `±Infinity`), matching `eventStudy`'s contract in `libs/calculations/src/analytics/event-study.ts` (which rejects `±Infinity` with `NON_FINITE_RETURN` and cleanly drops events with any `NaN` in `[-preDays, +postDays]`). +- **Duplicate-bar policy:** Exact pre-cutoff duplicate bars (`ts` and `close` identical, including `NaN === NaN`) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `EventPanelError('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) `knownAt` is 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 from `sessionDates` → `diagnostics.droppedMissingCalendarSession`; (5) lower-bound binary search over the listing's exchange close timestamps, matching `eventDayIndex` semantics 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`), preserving `events.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + droppedMissingCalendarSession + duplicateEvents`. +- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate` (post-cutoff dates are counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`. + +### `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,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`) diff --git a/libs/research/package.json b/libs/research/package.json index a3ad5417..89c29140 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -10,6 +10,7 @@ ".": "./src/index.ts", "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", + "./event-panel": "./src/event-panel.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", "./results": "./src/results.ts", diff --git a/libs/research/scripts/benchmark-event-panel.ts b/libs/research/scripts/benchmark-event-panel.ts new file mode 100644 index 00000000..de8e2c60 --- /dev/null +++ b/libs/research/scripts/benchmark-event-panel.ts @@ -0,0 +1,230 @@ +import { + type EventObservation, + type EventStudyExchangeCalendars, + buildEventStudyInput, +} from '../src/event-panel'; +import type { BarRecord } from '../src/market-data-store'; + +const SEED = 20261129; +const SESSIONS = 5_040; +const LISTINGS = 3_000; +const EVENT_STRIDE_SESSIONS = 63; // 5040 / 63 = 80 filings/listing -> 240,000 total events +const PRE_CUTOFF_SESSIONS = 5_020; + +function createMulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function generateBusinessCalendar(count: number, startYear: number): { + dates: string[]; + closeTs: Float64Array; + afterCloseTs: Float64Array; +} { + const dates: string[] = new Array(count); + const closeTs = new Float64Array(count); + const afterCloseTs = new Float64Array(count); + let year = startYear; + let month = 1; + let day = 1; + // 2006-01-01 was a Sunday (dow = 0) + let dow = 0; + let produced = 0; + + while (produced < count) { + if (dow !== 0 && dow !== 6) { + const yyyy = String(year).padStart(4, '0'); + const mm = String(month).padStart(2, '0'); + const dd = String(day).padStart(2, '0'); + dates[produced] = `${yyyy}-${mm}-${dd}`; + closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET + afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET + produced += 1; + } + + dow = (dow + 1) % 7; + day += 1; + const baseDays = DAYS_IN_MONTH[month] ?? 31; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day > maxDay) { + day = 1; + month += 1; + if (month > 12) { + month = 1; + year += 1; + } + } + } + + return { dates, closeTs, afterCloseTs }; +} + +function fnv1aByte(hash: number, byte: number): number { + return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0; +} + +function fnv1aUint32(hash: number, value: number): number { + const v = value >>> 0; + let h = fnv1aByte(hash, v & 0xff); + h = fnv1aByte(h, (v >>> 8) & 0xff); + h = fnv1aByte(h, (v >>> 16) & 0xff); + h = fnv1aByte(h, (v >>> 24) & 0xff); + return h; +} + +function fnv1aBytes(hash: number, bytes: Uint8Array): number { + let h = hash >>> 0; + for (let i = 0; i < bytes.length; i += 1) { + h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0; + } + return h; +} + +const rng = createMulberry32(SEED); +const calendar = generateBusinessCalendar(SESSIONS, 2006); +const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string; + +const totalBars = SESSIONS * LISTINGS; +const bars: BarRecord[] = new Array(totalBars); +const eventsPerListing = Math.ceil(SESSIONS / EVENT_STRIDE_SESSIONS); +const totalEvents = LISTINGS * eventsPerListing; +const events: EventObservation[] = new Array(totalEvents); + +let barIdx = 0; +let evIdx = 0; + +for (let l = 0; l < LISTINGS; l += 1) { + const listingId = l + 1; + const subtype = l % 2 === 0 ? '10-q' : 'interim_financial_statements'; + let price = 10 + (l % 200) * 0.5; + for (let t = 0; t < SESSIONS; t += 1) { + const ts = calendar.closeTs[t] as number; + price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02)); + bars[barIdx++] = { + listingId, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 10_000, + vwap: price, + knownAt: ts, + }; + if (t % EVENT_STRIDE_SESSIONS === 0) { + events[evIdx++] = { + listingId, + knownAt: calendar.afterCloseTs[t] as number, + kind: 'filing', + subtype, + }; + } + } +} + +const sessionCloses = calendar.dates.map((date, idx) => ({ + date, + closeTs: calendar.closeTs[idx] as number, +})); +const listingCalendarId = new Map(); +for (let l = 0; l < LISTINGS; l += 1) { + listingCalendarId.set(l + 1, l % 2 === 0 ? 'XNYS' : 'XTSE'); +} +const exchangeCalendars: EventStudyExchangeCalendars = { + calendars: new Map([ + ['XNYS', sessionCloses], + ['XTSE', sessionCloses], + ]), + listingCalendarId, +}; + +// Timed section: pure buildEventStudyInput execution (no fixture generation or checksum). +const started = performance.now(); +const result = buildEventStudyInput({ + bars, + events, + vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars, +}); +const elapsedMs = performance.now() - started; + +// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, returns, and events. +let checksum = 0x811c9dc5; +checksum = fnv1aUint32(checksum, result.input.sessionDates.length); +checksum = fnv1aUint32(checksum, result.input.entityReturns.size); +checksum = fnv1aUint32(checksum, result.input.events.length); +checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates); +checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedEvents); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedUnknownListing); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedAfterLastSession); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingCalendarSession); +checksum = fnv1aUint32(checksum, result.diagnostics.duplicateEvents); +checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars); +checksum = fnv1aUint32(checksum, result.diagnostics.nonPositiveCloseReturns); + +if (result.input.benchmarkReturns !== undefined) { + const bench = result.input.benchmarkReturns as Float64Array; + checksum = fnv1aBytes(checksum, new Uint8Array(bench.buffer, bench.byteOffset, bench.byteLength)); +} + +for (const [entityId, series] of result.input.entityReturns) { + checksum = fnv1aUint32(checksum, Number(entityId)); + const arr = series as Float64Array; + checksum = fnv1aBytes(checksum, new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength)); +} + +for (let i = 0; i < result.input.events.length; i += 1) { + const ev = result.input.events[i]; + if (ev === undefined) { + continue; + } + checksum = fnv1aUint32(checksum, ev.dayIndex); + checksum = fnv1aUint32(checksum, Number(ev.entityId)); +} + +const checksumHex = checksum.toString(16).padStart(8, '0'); + +const EXPECTED_CHECKSUM = '01b356d3'; +if (checksumHex !== EXPECTED_CHECKSUM) { + throw new Error( + `Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.` + ); +} + +const elapsedSec = elapsedMs / 1000; +const barsPerSec = Math.round(totalBars / elapsedSec); +const eventsPerSec = Math.round(totalEvents / elapsedSec); + +console.log( + JSON.stringify( + { + seed: SEED, + sessions: SESSIONS, + listings: LISTINGS, + vaultCutoffDate, + inputBars: totalBars, + inputEvents: totalEvents, + sessionDates: result.input.sessionDates.length, + anchoredEvents: result.input.events.length, + elapsedMs: Number(elapsedMs.toFixed(2)), + barsPerSec, + eventsPerSec, + diagnostics: result.diagnostics, + checksum: checksumHex, + }, + null, + 2 + ) +); diff --git a/libs/research/src/event-panel.ts b/libs/research/src/event-panel.ts new file mode 100644 index 00000000..53928a35 --- /dev/null +++ b/libs/research/src/event-panel.ts @@ -0,0 +1,1069 @@ +/** + * Pure, dependency-free event-study panel builder that transforms `MarketDataStore` + * daily bars and point-in-time `events` rows into Vault-safe `EventStudyInput` + * panels for `runEventStudy` / `eventStudy` (`design/MILESTONES.md` M1). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` + * access, and no database drivers. + * + * UTC session-calendar derivation: + * - Curated daily bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or + * `21:00 UTC`), so the UTC calendar date `Math.floor(bar.ts / 86_400_000)` + * matches the exchange session date without timezone drift. + * + * Return-series & `NaN` contract (matching `eventStudy` in + * `libs/calculations/src/analytics/event-study.ts`): + * - `entityReturns` maps each pre-cutoff `listingId` (inserted in ascending order) + * to a `Float64Array` aligned 1:1 with `sessionDates`. + * - Simple close-to-close return `close[d] / close[d - 1] - 1` is computed + * strictly across consecutive exchange-calendar sessions for that listing + * (`currCalIdx === prevCalIdx + 1`) where both closes are finite and `> 0` and + * the resulting return is finite. If an open exchange session is missing for a + * listing (or for all listings), the subsequent session's return is `NaN`. + * - `NaN` is written at session `0`, on any missing-bar session, on the first + * resumption session after a gap, and on any non-positive/non-finite close or + * overflowing ratio (`eventStudy` rejects `±Infinity` with `NON_FINITE_RETURN` + * and cleanly drops events whose `[-preDays, +postDays]` window contains `NaN`). + * + * Point-in-time (PIT) & Vault rules: + * - `sessionDates` holds only calendar dates strictly `< vaultCutoffDate`, and + * `bar.close` is never accessed for any bar on or after `vaultCutoffDate`. + * - Events with `knownAt >= vaultCutoffDate (00:00:00.000Z)` are excluded and + * counted in `diagnostics.vaultExcludedEvents`. + * - Caller-supplied `exchangeCalendars` is required and must cover every pre-Vault + * bar date of every mapped listing. Each listing's events are anchored against + * its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on + * NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (which + * is always stamped at `16:00 ET`), and the eligible session date is then mapped + * onto the shared `sessionDates` index. An after-close or post-half-day-close + * event always anchors to the next trading session, never the same day. + */ + +import { + type EventStudyEvent, + type EventStudyInput, + type NumericSeries, + eventDayIndex, +} from '@stock-bot/calculations'; +import type { BarRecord, EventKind, Table } from './market-data-store'; +import { EVENT_KINDS } from './market-data-store-duckdb'; +import { + type BarSortScratch, + MAX_DIRECT_DAY_SPAN, + MS_PER_DAY, + formatDayKeyUtc, + isPlainRecord, + isValidEpochMs, + isValidInt32, + normalizeZero, + parseCalendarDayKey, + sortBarSliceBySession, +} from './panel-shared'; + +const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); + +export type EventPanelErrorCode = + | 'invalid_input' + | 'invalid_date' + | 'invalid_bar' + | 'invalid_event' + | 'invalid_option' + | 'duplicate_bar'; + +export interface EventPanelErrorOptions { + readonly cause?: unknown; +} + +/** Typed validation and data-integrity error thrown by the event-panel builder helpers. */ +export class EventPanelError extends Error { + override readonly name = 'EventPanelError'; + readonly code: EventPanelErrorCode; + override readonly cause?: unknown; + + constructor(code: EventPanelErrorCode, message: string, options?: EventPanelErrorOptions) { + super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); + this.code = code; + if (options?.cause !== undefined) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Point-in-time event observation aligned to a listing ID and UTC epoch-ms `knownAt`. */ +export interface EventObservation { + readonly listingId: number; + readonly knownAt: number; + readonly kind: EventKind; + readonly subtype: string | null; +} + +/** Optional exact-match allow-list filter for {@link eventsTableToEventRows}. */ +export interface EventsTableFilter { + readonly kinds?: readonly EventKind[]; + readonly subtypes?: readonly string[]; +} + +/** Benchmark return construction mode for {@link buildEventStudyInput}. */ +export type EventStudyBenchmarkMode = 'equal_weight' | 'none'; + +/** Single exchange trading session close entry (`YYYY-MM-DD` date + actual close UTC epoch ms). */ +export interface ExchangeSessionClose { + readonly date: string; + readonly closeTs: number; +} + +/** + * Caller-supplied exchange close calendars for point-in-time event anchoring. + * + * Curated `bars_1d.ts` is stamped at `16:00 ET` even on exchange half-days (e.g. + * `13:00 ET` on NYSE Black Friday). Passing `exchangeCalendars` anchors each + * listing's events against its exchange's actual session close timestamps and + * maps the resulting eligible session date onto the shared `sessionDates` index. + */ +export interface EventStudyExchangeCalendars { + readonly calendars: + | ReadonlyMap + | Readonly>; + readonly listingCalendarId: + | ReadonlyMap + | Readonly>; +} + +/** Input contract for {@link buildEventStudyInput}. */ +export interface BuildEventStudyInputParams { + readonly bars: readonly BarRecord[]; + readonly events: readonly EventObservation[]; + readonly vaultCutoffDate: string; + readonly benchmark?: EventStudyBenchmarkMode; + readonly exchangeCalendars: EventStudyExchangeCalendars; +} + +/** Per-run diagnostic counters reported by {@link buildEventStudyInput}. */ +export interface EventPanelDiagnostics { + readonly vaultExcludedDates: number; + readonly vaultExcludedEvents: number; + readonly droppedUnknownListing: number; + readonly droppedAfterLastSession: number; + readonly droppedMissingCalendarSession: number; + readonly duplicateEvents: number; + readonly duplicateBars: number; + readonly nonPositiveCloseReturns: number; +} + +/** Output contract returned by {@link buildEventStudyInput}. */ +export interface BuildEventStudyInputResult { + readonly input: EventStudyInput; + readonly diagnostics: EventPanelDiagnostics; +} + +const STRICT_INT_KEY_RE = /^(?:0|-?[1-9]\d*)$/; + +interface ParsedExchangeCalendar { + readonly id: string; + readonly dayKeys: Int32Array; + readonly closeTs: Float64Array; + readonly minDayKey: number; + readonly maxDayKey: number; + readonly dayKeyToIdxArr: Int32Array | null; + readonly dayKeyToIdxMap: Map | null; +} + +function lookupCalendarDayIdx(cal: ParsedExchangeCalendar, dayKey: number): number { + if (cal.dayKeys.length === 0 || dayKey < cal.minDayKey || dayKey > cal.maxDayKey) { + return -1; + } + if (cal.dayKeyToIdxArr !== null) { + return cal.dayKeyToIdxArr[dayKey - cal.minDayKey] as number; + } + return (cal.dayKeyToIdxMap as Map).get(dayKey) ?? -1; +} + +function parseStrictCalendarDayKey(value: unknown, field: string): number { + return parseCalendarDayKey(value, field, (message, cause) => + new EventPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined) + ); +} + +function parseExchangeCalendars( + raw: unknown, + vaultCutoffDayKey: number +): Map { + if (!isPlainRecord(raw)) { + throw new EventPanelError( + 'invalid_option', + 'exchangeCalendars must be a non-null plain object.' + ); + } + + const rawCalendars = raw.calendars; + let calendarEntries: Array<[unknown, unknown]>; + if (rawCalendars instanceof Map) { + calendarEntries = Array.from(rawCalendars.entries()); + } else if (isPlainRecord(rawCalendars)) { + calendarEntries = Object.entries(rawCalendars); + } else { + throw new EventPanelError( + 'invalid_option', + 'exchangeCalendars.calendars must be a Map or plain object.' + ); + } + + const parsedByCalId = new Map(); + for (let c = 0; c < calendarEntries.length; c += 1) { + const [calId, rawSessions] = calendarEntries[c] as [unknown, unknown]; + if (typeof calId !== 'string' || calId.length === 0) { + throw new EventPanelError( + 'invalid_option', + `Invalid exchange calendar ID "${String(calId)}": expected a non-empty string.` + ); + } + if (!Array.isArray(rawSessions)) { + throw new EventPanelError( + 'invalid_option', + `exchangeCalendars.calendars["${calId}"] must be an array of { date, closeTs }.` + ); + } + + const n = rawSessions.length; + const allDayKeys = new Int32Array(n); + const allCloseTs = new Float64Array(n); + const order = new Int32Array(n); + for (let i = 0; i < n; i += 1) { + const entry: unknown = rawSessions[i]; + if (!isPlainRecord(entry)) { + throw new EventPanelError( + 'invalid_option', + `exchangeCalendars.calendars["${calId}"][${i}] must be a plain object.` + ); + } + const dk = parseStrictCalendarDayKey( + entry.date, + `exchangeCalendars.calendars["${calId}"][${i}].date` + ); + const closeTs = entry.closeTs; + if (!isValidEpochMs(closeTs)) { + throw new EventPanelError( + 'invalid_option', + `Invalid closeTs in exchangeCalendars.calendars["${calId}"][${i}]: ${String(closeTs)}.` + ); + } + allDayKeys[i] = dk; + allCloseTs[i] = normalizeZero(closeTs); + order[i] = i; + } + + if (n > 1) { + order.sort((a, b) => (allDayKeys[a] as number) - (allDayKeys[b] as number)); + } + + let preCount = 0; + for (let i = 0; i < n; i += 1) { + const currIdx = order[i] as number; + const dk = allDayKeys[currIdx] as number; + const ct = allCloseTs[currIdx] as number; + if (i > 0) { + const prevIdx = order[i - 1] as number; + const prevDk = allDayKeys[prevIdx] as number; + const prevCt = allCloseTs[prevIdx] as number; + if (dk === prevDk) { + throw new EventPanelError( + 'invalid_option', + `Duplicate session date "${formatDayKeyUtc(dk)}" in exchange calendar "${calId}".` + ); + } + if (ct <= prevCt) { + throw new EventPanelError( + 'invalid_option', + `Non-ascending closeTs in exchange calendar "${calId}" at session "${formatDayKeyUtc(dk)}".` + ); + } + } + if (dk < vaultCutoffDayKey) { + preCount += 1; + } + } + + const dayKeys = new Int32Array(preCount); + const closeTs = new Float64Array(preCount); + let outIdx = 0; + for (let i = 0; i < n; i += 1) { + const idx = order[i] as number; + const dk = allDayKeys[idx] as number; + if (dk < vaultCutoffDayKey) { + dayKeys[outIdx] = dk; + closeTs[outIdx] = allCloseTs[idx] as number; + outIdx += 1; + } + } + + let minDayKey = 0; + let maxDayKey = -1; + let dayKeyToIdxArr: Int32Array | null = null; + let dayKeyToIdxMap: Map | null = null; + if (preCount > 0) { + eventDayIndex(closeTs, closeTs[0] as number); + minDayKey = dayKeys[0] as number; + maxDayKey = dayKeys[preCount - 1] as number; + const calSpan = maxDayKey - minDayKey + 1; + if (calSpan <= MAX_DIRECT_DAY_SPAN) { + dayKeyToIdxArr = new Int32Array(calSpan); + dayKeyToIdxArr.fill(-1); + for (let i = 0; i < preCount; i += 1) { + dayKeyToIdxArr[(dayKeys[i] as number) - minDayKey] = i; + } + } else { + dayKeyToIdxMap = new Map(); + for (let i = 0; i < preCount; i += 1) { + dayKeyToIdxMap.set(dayKeys[i] as number, i); + } + } + } + + parsedByCalId.set(calId, { + id: calId, + dayKeys, + closeTs, + minDayKey, + maxDayKey, + dayKeyToIdxArr, + dayKeyToIdxMap, + }); + } + + const rawMapping = raw.listingCalendarId; + const listingCalendars = new Map(); + if (rawMapping instanceof Map) { + for (const [rawLid, calId] of rawMapping.entries()) { + if (!isValidInt32(rawLid)) { + throw new EventPanelError( + 'invalid_option', + `Invalid listingId in exchangeCalendars.listingCalendarId: ${String(rawLid)}.` + ); + } + if (typeof calId !== 'string' || !parsedByCalId.has(calId)) { + throw new EventPanelError( + 'invalid_option', + `Unknown exchange calendar "${String(calId)}" for listingId ${rawLid}.` + ); + } + listingCalendars.set(normalizeZero(rawLid), parsedByCalId.get(calId) as ParsedExchangeCalendar); + } + } else if (isPlainRecord(rawMapping)) { + for (const [key, calId] of Object.entries(rawMapping)) { + if (!STRICT_INT_KEY_RE.test(key)) { + throw new EventPanelError( + 'invalid_option', + `Invalid listingId key "${key}" in exchangeCalendars.listingCalendarId.` + ); + } + const lid = Number(key); + if (!isValidInt32(lid)) { + throw new EventPanelError( + 'invalid_option', + `Invalid INT32 listingId key "${key}" in exchangeCalendars.listingCalendarId.` + ); + } + if (typeof calId !== 'string' || !parsedByCalId.has(calId)) { + throw new EventPanelError( + 'invalid_option', + `Unknown exchange calendar "${String(calId)}" for listingId ${lid}.` + ); + } + listingCalendars.set(normalizeZero(lid), parsedByCalId.get(calId) as ParsedExchangeCalendar); + } + } else { + throw new EventPanelError( + 'invalid_option', + 'exchangeCalendars.listingCalendarId must be a Map or plain object.' + ); + } + + return listingCalendars; +} + +/** + * Maps a `MarketDataStore.events` `Table` into point-in-time {@link EventObservation} + * rows, validating every row upfront (before applying optional exact-match allow-lists) + * and rejecting malformed inputs with {@link EventPanelError}. + */ +export function eventsTableToEventRows( + table: Table, + filter?: EventsTableFilter +): EventObservation[] { + if (!isPlainRecord(table) || !Array.isArray(table.columns) || !Array.isArray(table.rows)) { + throw new EventPanelError( + 'invalid_input', + 'Expected a Table object with array columns and rows.' + ); + } + + let hasListingIdCol = false; + let hasKnownAtCol = false; + let hasKindCol = false; + let hasSubtypeCol = false; + for (let i = 0; i < table.columns.length; i += 1) { + const col: unknown = table.columns[i]; + if (col === 'listing_id') { + hasListingIdCol = true; + } else if (col === 'known_at') { + hasKnownAtCol = true; + } else if (col === 'kind') { + hasKindCol = true; + } else if (col === 'subtype') { + hasSubtypeCol = true; + } + } + if (!hasListingIdCol || !hasKnownAtCol || !hasKindCol || !hasSubtypeCol) { + throw new EventPanelError( + 'invalid_input', + 'Events table is missing required column(s): expected "listing_id", "known_at", "kind", and "subtype".' + ); + } + + let kindFilterSet: Set | null = null; + let subtypeFilterSet: Set | null = null; + if (filter !== undefined) { + if (!isPlainRecord(filter)) { + throw new EventPanelError('invalid_option', 'filter must be a non-null plain object.'); + } + if (filter.kinds !== undefined) { + if (!Array.isArray(filter.kinds) || filter.kinds.length === 0) { + throw new EventPanelError( + 'invalid_option', + 'filter.kinds must be a non-empty array of valid EventKind values.' + ); + } + kindFilterSet = new Set(); + for (let i = 0; i < filter.kinds.length; i += 1) { + const k: unknown = filter.kinds[i]; + if (typeof k !== 'string' || !EVENT_KIND_SET.has(k)) { + throw new EventPanelError( + 'invalid_option', + `Invalid filter.kinds[${i}] "${String(k)}": expected one of ${EVENT_KINDS.join(', ')}.` + ); + } + kindFilterSet.add(k); + } + } + if (filter.subtypes !== undefined) { + if (!Array.isArray(filter.subtypes) || filter.subtypes.length === 0) { + throw new EventPanelError( + 'invalid_option', + 'filter.subtypes must be a non-empty array of strings.' + ); + } + subtypeFilterSet = new Set(); + for (let i = 0; i < filter.subtypes.length; i += 1) { + const s: unknown = filter.subtypes[i]; + if (typeof s !== 'string') { + throw new EventPanelError( + 'invalid_option', + `Invalid filter.subtypes[${i}]: expected a string, got ${typeof s}.` + ); + } + subtypeFilterSet.add(s); + } + } + } + + const out: EventObservation[] = []; + const rows = table.rows; + for (let i = 0; i < rows.length; i += 1) { + const row: unknown = rows[i]; + if (!isPlainRecord(row)) { + throw new EventPanelError('invalid_event', `Events table row[${i}] must be a plain object.`); + } + if ( + !Object.prototype.hasOwnProperty.call(row, 'listing_id') || + !Object.prototype.hasOwnProperty.call(row, 'known_at') || + !Object.prototype.hasOwnProperty.call(row, 'kind') || + !Object.prototype.hasOwnProperty.call(row, 'subtype') + ) { + throw new EventPanelError( + 'invalid_event', + `Events table row[${i}] is missing required key "listing_id", "known_at", "kind", or "subtype".` + ); + } + + const listingId = row.listing_id; + if (!isValidInt32(listingId)) { + throw new EventPanelError( + 'invalid_event', + `Invalid listing_id in events table row[${i}]: ${String(listingId)}.` + ); + } + + const knownAt = row.known_at; + if (!isValidEpochMs(knownAt)) { + throw new EventPanelError( + 'invalid_event', + `Invalid known_at in events table row[${i}]: ${String(knownAt)}.` + ); + } + + const kind = row.kind; + if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) { + throw new EventPanelError( + 'invalid_event', + `Invalid kind in events table row[${i}]: "${String(kind)}".` + ); + } + + const subtype = row.subtype; + if (subtype !== null && typeof subtype !== 'string') { + throw new EventPanelError( + 'invalid_event', + `Invalid subtype in events table row[${i}]: expected string or null, got ${typeof subtype}.` + ); + } + + if (kindFilterSet !== null && !kindFilterSet.has(kind)) { + continue; + } + if (subtypeFilterSet !== null && (subtype === null || !subtypeFilterSet.has(subtype))) { + continue; + } + + out.push({ + listingId: normalizeZero(listingId), + knownAt: normalizeZero(knownAt), + kind: kind as EventKind, + subtype, + }); + } + + return out; +} + +/** + * Pure, synchronous event-study panel builder. + * + * Transforms daily bars (caller-supplied `'total'`-adjusted closes in any order) + * and point-in-time {@link EventObservation} rows into a Vault-safe + * `EventStudyInput` ready for `runEventStudy` / `eventStudy`, without mutating + * caller inputs or ever reading `bar.close` on or after `vaultCutoffDate`. + */ +export function buildEventStudyInput( + params: BuildEventStudyInputParams +): BuildEventStudyInputResult { + if (!isPlainRecord(params)) { + throw new EventPanelError('invalid_input', 'Input must be a non-null plain object.'); + } + + const vaultCutoffDayKey = parseStrictCalendarDayKey(params.vaultCutoffDate, 'vaultCutoffDate'); + const vaultCutoffMs = vaultCutoffDayKey * MS_PER_DAY; + + const rawBenchmark: unknown = params.benchmark; + const benchmark: EventStudyBenchmarkMode = + rawBenchmark === undefined ? 'none' : (rawBenchmark as EventStudyBenchmarkMode); + if (benchmark !== 'none' && benchmark !== 'equal_weight') { + throw new EventPanelError( + 'invalid_option', + `Invalid benchmark "${String(benchmark)}": expected "none" or "equal_weight".` + ); + } + + const listingCalendars = parseExchangeCalendars(params.exchangeCalendars, vaultCutoffDayKey); + + if (!Array.isArray(params.bars)) { + throw new EventPanelError('invalid_input', 'params.bars must be an array of BarRecord.'); + } + if (!Array.isArray(params.events)) { + throw new EventPanelError( + 'invalid_input', + 'params.events must be an array of EventObservation.' + ); + } + + const bars = params.bars; + const events = params.events; + + // Pass 1 over bars: validate structure, build pre-cutoff calendar, count bars per listing. + // Never access `bar.close` when the bar's UTC dayKey reaches or exceeds `vaultCutoffDayKey`. + const postCutoffDays = new Set(); + const preCutoffDays = new Set(); + const listingBarCounts = new Map(); + let preCutoffBarTotal = 0; + + for (let i = 0; i < bars.length; i += 1) { + const rawBar: unknown = bars[i]; + if (!isPlainRecord(rawBar)) { + throw new EventPanelError('invalid_bar', `bars[${i}] must be a non-null plain object.`); + } + + const listingId = rawBar.listingId; + if (!isValidInt32(listingId)) { + throw new EventPanelError( + 'invalid_bar', + `Invalid listingId at bars[${i}]: ${String(listingId)}.` + ); + } + + const ts = rawBar.ts; + if (!isValidEpochMs(ts)) { + throw new EventPanelError('invalid_bar', `Invalid ts at bars[${i}]: ${String(ts)}.`); + } + + const knownAt = rawBar.knownAt; + if (!isValidEpochMs(knownAt)) { + throw new EventPanelError( + 'invalid_bar', + `Invalid knownAt at bars[${i}]: ${String(knownAt)}.` + ); + } + + const dayKey = Math.floor(ts / MS_PER_DAY); + if (dayKey >= vaultCutoffDayKey) { + postCutoffDays.add(dayKey); + continue; + } + + const close = rawBar.close; + if (typeof close !== 'number') { + throw new EventPanelError('invalid_bar', `Invalid close at bars[${i}]: expected a number.`); + } + + preCutoffDays.add(dayKey); + + const normListingId = normalizeZero(listingId); + listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1); + preCutoffBarTotal += 1; + } + + // Validate all events upfront (even if bars is empty). + for (let i = 0; i < events.length; i += 1) { + const rawEv: unknown = events[i]; + if (!isPlainRecord(rawEv)) { + throw new EventPanelError('invalid_event', `events[${i}] must be a non-null plain object.`); + } + if (!isValidInt32(rawEv.listingId)) { + throw new EventPanelError( + 'invalid_event', + `Invalid listingId at events[${i}]: ${String(rawEv.listingId)}.` + ); + } + if (!isValidEpochMs(rawEv.knownAt)) { + throw new EventPanelError( + 'invalid_event', + `Invalid knownAt at events[${i}]: ${String(rawEv.knownAt)}.` + ); + } + if (typeof rawEv.kind !== 'string' || !EVENT_KIND_SET.has(rawEv.kind)) { + throw new EventPanelError( + 'invalid_event', + `Invalid kind at events[${i}]: "${String(rawEv.kind)}".` + ); + } + if (rawEv.subtype !== null && typeof rawEv.subtype !== 'string') { + throw new EventPanelError( + 'invalid_event', + `Invalid subtype at events[${i}]: expected string or null, got ${typeof rawEv.subtype}.` + ); + } + } + + const vaultExcludedDates = postCutoffDays.size; + + if (preCutoffBarTotal === 0) { + let vaultExcludedEvents = 0; + let droppedUnknownListing = 0; + for (let i = 0; i < events.length; i += 1) { + const ev = events[i] as EventObservation; + if (ev.knownAt >= vaultCutoffMs) { + vaultExcludedEvents += 1; + } else { + droppedUnknownListing += 1; + } + } + + const emptyInput: EventStudyInput = + benchmark === 'equal_weight' + ? { + sessionDates: [], + entityReturns: new Map(), + benchmarkReturns: new Float64Array(0), + events: [], + } + : { + sessionDates: [], + entityReturns: new Map(), + events: [], + }; + + return { + input: emptyInput, + diagnostics: { + vaultExcludedDates, + vaultExcludedEvents, + droppedUnknownListing, + droppedAfterLastSession: 0, + droppedMissingCalendarSession: 0, + duplicateEvents: 0, + duplicateBars: 0, + nonPositiveCloseReturns: 0, + }, + }; + } + + // Build strictly ascending pre-cutoff session calendar. + const preCount = preCutoffDays.size; + const preDayKeys = new Int32Array(preCount); + { + let idx = 0; + for (const dayKey of preCutoffDays) { + preDayKeys[idx] = dayKey; + idx += 1; + } + preDayKeys.sort(); + } + + const sessionDates: string[] = new Array(preCount); + for (let i = 0; i < preCount; i += 1) { + sessionDates[i] = formatDayKeyUtc(preDayKeys[i] as number); + } + + // Sort unique listingIds ascending for deterministic entityReturns Map insertion order. + const listingCount = listingBarCounts.size; + const sortedListingIds = new Int32Array(listingCount); + { + let idx = 0; + for (const lid of listingBarCounts.keys()) { + sortedListingIds[idx] = lid; + idx += 1; + } + sortedListingIds.sort(); + } + + const listingIdToIdx = new Map(); + const barOffsets = new Int32Array(listingCount + 1); + for (let l = 0; l < listingCount; l += 1) { + const lid = sortedListingIds[l] as number; + listingIdToIdx.set(lid, l); + barOffsets[l + 1] = (barOffsets[l] as number) + (listingBarCounts.get(lid) as number); + } + + // Build O(1) dayKey -> sessionIdx lookup (direct Int32Array when span <= 200_000, else Map). + const minDayKey = preDayKeys[0] as number; + const maxDayKey = preDayKeys[preCount - 1] as number; + const daySpan = maxDayKey - minDayKey + 1; + let dayKeyToIdxArr: Int32Array | null = null; + let dayKeyToIdxMap: Map | null = null; + if (daySpan <= MAX_DIRECT_DAY_SPAN) { + dayKeyToIdxArr = new Int32Array(daySpan); + dayKeyToIdxArr.fill(-1); + for (let i = 0; i < preCount; i += 1) { + dayKeyToIdxArr[(preDayKeys[i] as number) - minDayKey] = i; + } + } else { + dayKeyToIdxMap = new Map(); + for (let i = 0; i < preCount; i += 1) { + dayKeyToIdxMap.set(preDayKeys[i] as number, i); + } + } + + // Scatter pre-cutoff bars into CSR typed arrays grouped by listing index. + const barSessionIdx = new Int32Array(preCutoffBarTotal); + const barTs = new Float64Array(preCutoffBarTotal); + const barClose = new Float64Array(preCutoffBarTotal); + const barCursor = new Int32Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + barCursor[l] = barOffsets[l] as number; + } + + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i] as BarRecord; + const dayKey = Math.floor(bar.ts / MS_PER_DAY); + if (dayKey >= vaultCutoffDayKey) { + continue; + } + const l = listingIdToIdx.get(normalizeZero(bar.listingId)) as number; + const pos = barCursor[l] as number; + barCursor[l] = pos + 1; + + const sIdx = + dayKeyToIdxArr !== null + ? (dayKeyToIdxArr[dayKey - minDayKey] as number) + : ((dayKeyToIdxMap as Map).get(dayKey) as number); + barSessionIdx[pos] = sIdx; + barTs[pos] = normalizeZero(bar.ts); + barClose[pos] = bar.close; + } + + const barScratch: BarSortScratch = { + sessionIdx: new Int32Array(0), + ts: new Float64Array(0), + close: new Float64Array(0), + }; + + const entityReturns = new Map(); + const computeBench = benchmark === 'equal_weight'; + const benchSum = computeBench ? new Float64Array(preCount) : null; + const benchCount = computeBench ? new Int32Array(preCount) : null; + + let duplicateBars = 0; + let nonPositiveCloseReturns = 0; + + for (let l = 0; l < listingCount; l += 1) { + const listingId = sortedListingIds[l] as number; + const cal = listingCalendars.get(listingId); + if (cal === undefined) { + throw new EventPanelError( + 'invalid_option', + `Missing exchange calendar mapping for listingId ${listingId}.` + ); + } + + const bStart = barOffsets[l] as number; + const bEnd = barOffsets[l + 1] as number; + + sortBarSliceBySession(barSessionIdx, barTs, barClose, bStart, bEnd, barScratch); + + // Compact exact duplicates in place; reject conflicting duplicates on the same (listingId, date). + let write = bStart; + for (let i = bStart + 1; i < bEnd; i += 1) { + if (barSessionIdx[i] === barSessionIdx[write]) { + const prevTs = barTs[write] as number; + const currTs = barTs[i] as number; + const prevClose = barClose[write] as number; + const currClose = barClose[i] as number; + const sameClose = + prevClose === currClose || (Number.isNaN(prevClose) && Number.isNaN(currClose)); + if (currTs === prevTs && sameClose) { + duplicateBars += 1; + continue; + } + const conflictDate = sessionDates[barSessionIdx[i] as number] as string; + throw new EventPanelError( + 'duplicate_bar', + `Conflicting duplicate bars for listingId ${listingId} on session ${conflictDate}.` + ); + } + write += 1; + if (write !== i) { + barSessionIdx[write] = barSessionIdx[i] as number; + barTs[write] = barTs[i] as number; + barClose[write] = barClose[i] as number; + } + } + const uniqueEnd = write + 1; + + // Verify that the listing's mapped exchange calendar covers every pre-Vault bar date, + // and compute close-to-close returns strictly across consecutive exchange sessions. + const firstSIdx = barSessionIdx[bStart] as number; + let prevCalIdx = lookupCalendarDayIdx(cal, preDayKeys[firstSIdx] as number); + if (prevCalIdx < 0) { + throw new EventPanelError( + 'invalid_option', + `Exchange calendar "${cal.id}" for listingId ${listingId} does not cover pre-Vault bar session ${sessionDates[firstSIdx]}.` + ); + } + + const returns = new Float64Array(preCount); + returns.fill(Number.NaN); + + for (let i = bStart + 1; i < uniqueEnd; i += 1) { + const currSIdx = barSessionIdx[i] as number; + const currCalIdx = lookupCalendarDayIdx(cal, preDayKeys[currSIdx] as number); + if (currCalIdx < 0) { + throw new EventPanelError( + 'invalid_option', + `Exchange calendar "${cal.id}" for listingId ${listingId} does not cover pre-Vault bar session ${sessionDates[currSIdx]}.` + ); + } + const isConsecutiveSession = currCalIdx === prevCalIdx + 1; + prevCalIdx = currCalIdx; + if (!isConsecutiveSession) { + continue; + } + const prevClose = barClose[i - 1] as number; + const currClose = barClose[i] as number; + if (!Number.isFinite(prevClose) || prevClose <= 0 || !Number.isFinite(currClose) || currClose <= 0) { + nonPositiveCloseReturns += 1; + continue; + } + const ret = currClose / prevClose - 1; + if (!Number.isFinite(ret)) { + nonPositiveCloseReturns += 1; + continue; + } + const normRet = normalizeZero(ret); + returns[currSIdx] = normRet; + if (benchSum !== null && benchCount !== null) { + benchSum[currSIdx] = (benchSum[currSIdx] as number) + normRet; + benchCount[currSIdx] = (benchCount[currSIdx] as number) + 1; + } + } + + entityReturns.set(listingId, returns); + } + + let benchmarkReturns: Float64Array | undefined; + if (benchSum !== null && benchCount !== null) { + benchmarkReturns = new Float64Array(preCount); + benchmarkReturns.fill(Number.NaN); + for (let t = 0; t < preCount; t += 1) { + const count = benchCount[t] as number; + if (count > 0) { + const mean = (benchSum[t] as number) / count; + if (Number.isFinite(mean)) { + benchmarkReturns[t] = normalizeZero(mean); + } + } + } + } + + // Classify and anchor events in strict precedence order: + // (1) vaultExcludedEvents -> (2) droppedUnknownListing -> (3) droppedAfterLastSession + // -> (4) droppedMissingCalendarSession -> (5) anchor via the listing's exchange calendar. + const candDay = new Int32Array(events.length); + const candListing = new Int32Array(events.length); + let candCount = 0; + let vaultExcludedEvents = 0; + let droppedUnknownListing = 0; + let droppedAfterLastSession = 0; + let droppedMissingCalendarSession = 0; + + for (let i = 0; i < events.length; i += 1) { + const ev = events[i] as EventObservation; + const knownAt = normalizeZero(ev.knownAt); + if (knownAt >= vaultCutoffMs) { + vaultExcludedEvents += 1; + continue; + } + + const normListingId = normalizeZero(ev.listingId); + const l = listingIdToIdx.get(normListingId); + if (l === undefined) { + droppedUnknownListing += 1; + continue; + } + + const cal = listingCalendars.get(normListingId) as ParsedExchangeCalendar; + const calLen = cal.closeTs.length; + if (calLen === 0 || knownAt > (cal.closeTs[calLen - 1] as number)) { + droppedAfterLastSession += 1; + continue; + } + + // Lower-bound binary search over the listing's actual exchange close timestamps. + let lo = 0; + let hi = calLen - 1; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((cal.closeTs[mid] as number) < knownAt) { + lo = mid + 1; + } else { + hi = mid; + } + } + + const eligibleDayKey = cal.dayKeys[lo] as number; + if (eligibleDayKey > maxDayKey) { + droppedAfterLastSession += 1; + continue; + } + + const mappedIdx = + eligibleDayKey < minDayKey + ? -1 + : dayKeyToIdxArr !== null + ? (dayKeyToIdxArr[eligibleDayKey - minDayKey] as number) + : ((dayKeyToIdxMap as Map).get(eligibleDayKey) ?? -1); + if (mappedIdx < 0) { + droppedMissingCalendarSession += 1; + continue; + } + + candDay[candCount] = mappedIdx; + candListing[candCount] = l; + candCount += 1; + } + + // Canonical 2-pass counting sort into (dayIndex ASC, listingIdx ASC). + if (candCount > 1) { + const tmpDay = new Int32Array(candCount); + const tmpListing = new Int32Array(candCount); + + const listingCounts = new Int32Array(listingCount + 1); + for (let i = 0; i < candCount; i += 1) { + const idx = (candListing[i] as number) + 1; + listingCounts[idx] = (listingCounts[idx] as number) + 1; + } + for (let l = 1; l <= listingCount; l += 1) { + listingCounts[l] = (listingCounts[l] as number) + (listingCounts[l - 1] as number); + } + for (let i = 0; i < candCount; i += 1) { + const l = candListing[i] as number; + const pos = listingCounts[l] as number; + listingCounts[l] = pos + 1; + tmpDay[pos] = candDay[i] as number; + tmpListing[pos] = l; + } + + const dayCounts = new Int32Array(preCount + 1); + for (let i = 0; i < candCount; i += 1) { + const idx = (tmpDay[i] as number) + 1; + dayCounts[idx] = (dayCounts[idx] as number) + 1; + } + for (let d = 1; d <= preCount; d += 1) { + dayCounts[d] = (dayCounts[d] as number) + (dayCounts[d - 1] as number); + } + for (let i = 0; i < candCount; i += 1) { + const d = tmpDay[i] as number; + const pos = dayCounts[d] as number; + dayCounts[d] = pos + 1; + candDay[pos] = d; + candListing[pos] = tmpListing[i] as number; + } + } + + // Collapse exact duplicate (listingId, dayIndex) events (keep one). + const anchoredEvents: EventStudyEvent[] = []; + let duplicateEvents = 0; + let prevDay = -1; + let prevListing = -1; + + for (let i = 0; i < candCount; i += 1) { + const d = candDay[i] as number; + const l = candListing[i] as number; + if (d === prevDay && l === prevListing) { + duplicateEvents += 1; + continue; + } + prevDay = d; + prevListing = l; + anchoredEvents.push({ + entityId: sortedListingIds[l] as number, + dayIndex: d, + }); + } + + const input: EventStudyInput = + benchmarkReturns !== undefined + ? { + sessionDates, + entityReturns, + benchmarkReturns, + events: anchoredEvents, + } + : { + sessionDates, + entityReturns, + events: anchoredEvents, + }; + + return { + input, + diagnostics: { + vaultExcludedDates, + vaultExcludedEvents, + droppedUnknownListing, + droppedAfterLastSession, + droppedMissingCalendarSession, + duplicateEvents, + duplicateBars, + nonPositiveCloseReturns, + }, + }; +} diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 4f867394..3d57d822 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,5 +1,6 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; +export * from './event-panel'; export * from './market-data-store'; export * from './market-data-store-duckdb'; export * from './signal-panel'; diff --git a/libs/research/src/panel-shared.ts b/libs/research/src/panel-shared.ts new file mode 100644 index 00000000..8e540224 --- /dev/null +++ b/libs/research/src/panel-shared.ts @@ -0,0 +1,172 @@ +/** + * Internal, browser-safe helpers shared by `signal-panel.ts` and `event-panel.ts`. + * + * Pure, synchronous, and dependency-free: zero `node:*` imports and zero bare + * `process` access. Not exported from the package root. + */ + +import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store'; + +export const INT32_MIN = -2_147_483_648; +export const INT32_MAX = 2_147_483_647; +export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +export const MS_PER_DAY = 86_400_000; +export const MAX_DIRECT_DAY_SPAN = 200_000; +const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +export function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +export function normalizeZero(value: number): number { + return value === 0 ? 0 : value; +} + +export function isValidInt32(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isSafeInteger(value) && + value >= INT32_MIN && + value <= INT32_MAX + ); +} + +export function isValidEpochMs(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isSafeInteger(value) && + Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS + ); +} + +/** + * Parses a strict `YYYY-MM-DD` calendar date string into an integer UTC day key + * (`Math.floor(epochMs / MS_PER_DAY)`), delegating calendar validation to + * `applyVaultFence`. + */ +export function parseCalendarDayKey( + value: unknown, + field: string, + createError: (message: string, cause?: unknown) => Error +): number { + if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) { + throw createError( + `Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".` + ); + } + try { + const fenced = applyVaultFence( + { from: value, to: value, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + return fenced.fromMs / MS_PER_DAY; + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw createError(`Invalid "${field}": ${error.message}`, error); + } + throw error; + } +} + +export function formatDayKeyUtc(dayKey: number): string { + const date = new Date(dayKey * MS_PER_DAY); + const year = String(date.getUTCFullYear()).padStart(4, '0'); + const month = String(date.getUTCMonth() + 1).padStart(2, '0'); + const day = String(date.getUTCDate()).padStart(2, '0'); + return `${year}-${month}-${day}`; +} + +export interface BarSortScratch { + sessionIdx: Int32Array; + ts: Float64Array; + close: Float64Array; +} + +function ensureBarScratch(scratch: BarSortScratch, len: number): void { + if (scratch.sessionIdx.length < len) { + scratch.sessionIdx = new Int32Array(len); + scratch.ts = new Float64Array(len); + scratch.close = new Float64Array(len); + } +} + +/** + * Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered + * by `sessionIdx ASC`. Skips sorting when already non-decreasing. + */ +export function sortBarSliceBySession( + sessionIdx: Int32Array, + ts: Float64Array, + close: Float64Array, + start: number, + end: number, + scratch: BarSortScratch +): void { + const len = end - start; + if (len <= 1) { + return; + } + + let sorted = true; + for (let i = start + 1; i < end; i += 1) { + if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) { + sorted = false; + break; + } + } + if (sorted) { + return; + } + + ensureBarScratch(scratch, len); + const tmpSession = scratch.sessionIdx; + const tmpTs = scratch.ts; + const tmpClose = scratch.close; + + for (let width = 1; width < len; width *= 2) { + for (let left = 0; left < len; left += 2 * width) { + const mid = Math.min(left + width, len); + const right = Math.min(left + 2 * width, len); + let i = left; + let j = mid; + let k = left; + + while (i < mid && j < right) { + const si = sessionIdx[start + i] as number; + const sj = sessionIdx[start + j] as number; + if (si <= sj) { + tmpSession[k] = si; + tmpTs[k] = ts[start + i] as number; + tmpClose[k] = close[start + i] as number; + i += 1; + } else { + tmpSession[k] = sj; + tmpTs[k] = ts[start + j] as number; + tmpClose[k] = close[start + j] as number; + j += 1; + } + k += 1; + } + while (i < mid) { + tmpSession[k] = sessionIdx[start + i] as number; + tmpTs[k] = ts[start + i] as number; + tmpClose[k] = close[start + i] as number; + i += 1; + k += 1; + } + while (j < right) { + tmpSession[k] = sessionIdx[start + j] as number; + tmpTs[k] = ts[start + j] as number; + tmpClose[k] = close[start + j] as number; + j += 1; + k += 1; + } + } + + for (let k = 0; k < len; k += 1) { + sessionIdx[start + k] = tmpSession[k] as number; + ts[start + k] = tmpTs[k] as number; + close[start + k] = tmpClose[k] as number; + } + } +} diff --git a/libs/research/src/signal-panel.ts b/libs/research/src/signal-panel.ts index e293d462..60d5f82a 100644 --- a/libs/research/src/signal-panel.ts +++ b/libs/research/src/signal-panel.ts @@ -21,20 +21,19 @@ */ import type { SignalCrossSection } from '@stock-bot/calculations'; +import type { BarBatch, BarRecord, Table } from './market-data-store'; import { - type BarBatch, - type BarRecord, - MarketDataStoreValidationError, - type Table, - applyVaultFence, -} from './market-data-store'; - -const INT32_MIN = -2_147_483_648; -const INT32_MAX = 2_147_483_647; -const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -const MS_PER_DAY = 86_400_000; -const MAX_DIRECT_DAY_SPAN = 200_000; -const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + type BarSortScratch, + MAX_DIRECT_DAY_SPAN, + MS_PER_DAY, + formatDayKeyUtc, + isPlainRecord, + isValidEpochMs, + isValidInt32, + normalizeZero, + parseCalendarDayKey, + sortBarSliceBySession, +} from './panel-shared'; export type SignalPanelErrorCode = | 'invalid_input' @@ -103,60 +102,10 @@ export interface BuildForwardReturnPanelResult { readonly diagnostics: SignalPanelDiagnostics; } -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function normalizeZero(value: number): number { - return value === 0 ? 0 : value; -} - -function isValidInt32(value: unknown): value is number { - return ( - typeof value === 'number' && - Number.isSafeInteger(value) && - value >= INT32_MIN && - value <= INT32_MAX - ); -} - -function isValidEpochMs(value: unknown): value is number { - return ( - typeof value === 'number' && - Number.isSafeInteger(value) && - Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS - ); -} - function parseStrictCalendarDayKey(value: unknown, field: string): number { - if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) { - throw new SignalPanelError( - 'invalid_date', - `Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".` - ); - } - try { - const fenced = applyVaultFence( - { from: value, to: value, scope: 'vault_evaluation_only' }, - { vaultCutoffTs: 0, vaultOperatorAuthorized: true } - ); - return fenced.fromMs / MS_PER_DAY; - } catch (error) { - if (error instanceof MarketDataStoreValidationError) { - throw new SignalPanelError('invalid_date', `Invalid "${field}": ${error.message}`, { - cause: error, - }); - } - throw error; - } -} - -function formatDayKeyUtc(dayKey: number): string { - const date = new Date(dayKey * MS_PER_DAY); - const year = String(date.getUTCFullYear()).padStart(4, '0'); - const month = String(date.getUTCMonth() + 1).padStart(2, '0'); - const day = String(date.getUTCDate()).padStart(2, '0'); - return `${year}-${month}-${day}`; + return parseCalendarDayKey(value, field, (message, cause) => + new SignalPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined) + ); } /** @@ -291,25 +240,11 @@ export function shortsTableToSignalRows( return out; } -interface BarSortScratch { - sessionIdx: Int32Array; - ts: Float64Array; - close: Float64Array; -} - interface SignalSortScratch { knownAt: Float64Array; value: Float64Array; } -function ensureBarScratch(scratch: BarSortScratch, len: number): void { - if (scratch.sessionIdx.length < len) { - scratch.sessionIdx = new Int32Array(len); - scratch.ts = new Float64Array(len); - scratch.close = new Float64Array(len); - } -} - function ensureSignalScratch(scratch: SignalSortScratch, len: number): void { if (scratch.knownAt.length < len) { scratch.knownAt = new Float64Array(len); @@ -317,87 +252,6 @@ function ensureSignalScratch(scratch: SignalSortScratch, len: number): void { } } -/** - * Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered - * by `sessionIdx ASC`. Skips sorting when already non-decreasing. - */ -function sortBarSliceBySession( - sessionIdx: Int32Array, - ts: Float64Array, - close: Float64Array, - start: number, - end: number, - scratch: BarSortScratch -): void { - const len = end - start; - if (len <= 1) { - return; - } - - let sorted = true; - for (let i = start + 1; i < end; i += 1) { - if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) { - sorted = false; - break; - } - } - if (sorted) { - return; - } - - ensureBarScratch(scratch, len); - const tmpSession = scratch.sessionIdx; - const tmpTs = scratch.ts; - const tmpClose = scratch.close; - - for (let width = 1; width < len; width *= 2) { - for (let left = 0; left < len; left += 2 * width) { - const mid = Math.min(left + width, len); - const right = Math.min(left + 2 * width, len); - let i = left; - let j = mid; - let k = left; - - while (i < mid && j < right) { - const si = sessionIdx[start + i] as number; - const sj = sessionIdx[start + j] as number; - if (si <= sj) { - tmpSession[k] = si; - tmpTs[k] = ts[start + i] as number; - tmpClose[k] = close[start + i] as number; - i += 1; - } else { - tmpSession[k] = sj; - tmpTs[k] = ts[start + j] as number; - tmpClose[k] = close[start + j] as number; - j += 1; - } - k += 1; - } - while (i < mid) { - tmpSession[k] = sessionIdx[start + i] as number; - tmpTs[k] = ts[start + i] as number; - tmpClose[k] = close[start + i] as number; - i += 1; - k += 1; - } - while (j < right) { - tmpSession[k] = sessionIdx[start + j] as number; - tmpTs[k] = ts[start + j] as number; - tmpClose[k] = close[start + j] as number; - j += 1; - k += 1; - } - } - - for (let k = 0; k < len; k += 1) { - sessionIdx[start + k] = tmpSession[k] as number; - ts[start + k] = tmpTs[k] as number; - close[start + k] = tmpClose[k] as number; - } - } -} - /** * Iterative bottom-up mergesort for a listing's signal slice `[start, end)` * ordered by `(knownAt ASC, value ASC)` for deterministic tie-breaking. diff --git a/libs/research/test/event-panel-e2e.test.ts b/libs/research/test/event-panel-e2e.test.ts new file mode 100644 index 00000000..4ac07daa --- /dev/null +++ b/libs/research/test/event-panel-e2e.test.ts @@ -0,0 +1,729 @@ +import { describe, expect, it } from 'bun:test'; +import { + buildEventStudyInput, + collectBars, + createDuckDbMarketDataStore, + eventsTableToEventRows, + runEventStudy, + type DuckDbExecutor, + type DuckDbParam, + type EventStudyExchangeCalendars, + type TableRow, + type TrialLedgerExecutor, +} from '@stock-bot/research'; + +const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const IMMUTABLE_ADJ_PATH = `${CURATED_ROOT}/adj_factors/snapshots/qmfilings_e2e_fenced.parquet`; +const SEED = 20261129; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeUtcMs(date: string, hourUtc: number): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); +} + +interface StoredTrialRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +function createInMemoryTrialExecutor(): { + executor: TrialLedgerExecutor; + rows: StoredTrialRow[]; +} { + const rows: StoredTrialRow[] = []; + let nextTrialId = 1; + + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const trialId = nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored: StoredTrialRow = { + trial_id: String(trialId), + created_at: createdAt, + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: dailySeries, + }; + rows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + rowCount: 1, + }; + } + + if (trimmed.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = rows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = rows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + + return { rows: [], rowCount: 0 }; + }, + }; + + return { executor, rows }; +} + +interface AdjFactorRow { + readonly listing_id: number; + readonly ex_date: string; + readonly cum_split_factor: number; + readonly cum_total_factor: number; + readonly known_at: number; +} + +interface QmFilingsFixture { + readonly listingIds: number[]; + readonly usListingIds: ReadonlySet; + readonly caListingIds: ReadonlySet; + readonly allDates: string[]; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly barRows: TableRow[]; + readonly adjFactorRows: AdjFactorRow[]; + readonly eventRows: TableRow[]; + readonly exchangeCalendars: EventStudyExchangeCalendars; + readonly dividendCase: { + readonly listingId: number; + readonly exDate: string; + readonly exDayIdx: number; + readonly expectedTotalReturn: number; + readonly rawDropReturn: number; + }; + readonly halfDayCase: { + readonly usListingId: number; + readonly caListingId: number; + readonly halfDayDate: string; + readonly halfDayIdx: number; + readonly nextSessionDate: string; + readonly nextSessionIdx: number; + readonly usHalfDayReturn: number; + readonly usNextSessionReturn: number; + }; +} + +function makeFencedAdjKvRows(vaultCutoffTs: number, rowsWritten: number): TableRow[] { + return [ + { key: 'stock_bot.adj_factors.format_version', value: '1' }, + { key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' }, + { key: 'stock_bot.adj_factors.as_of_micros', value: 'none' }, + { key: 'stock_bot.adj_factors.vault_cutoff_micros', value: String(vaultCutoffTs * 1000) }, + { key: 'stock_bot.adj_factors.rows_written', value: String(rowsWritten) }, + { key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x024ec73a1afe7e6b' }, + ]; +} + +function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { + const rand = createSeededRng(SEED); + const listingCount = 24; // 12 US ('10-q') + 12 CA ('interim_financial_statements') + const preCutoffSessions = 160; // spans late 2022 through spring 2023 (pre-2023 & post-2023) + const postCutoffSessions = 10; + const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const listingIds = Array.from({ length: listingCount }, (_, i) => + i < 12 ? 10_001 + i : 50_001 + (i - 12) + ); + const usListingIds = new Set(listingIds.slice(0, 12)); + const caListingIds = new Set(listingIds.slice(12)); + const barRows: TableRow[] = []; + const adjFactorRows: AdjFactorRow[] = []; + const eventRows: TableRow[] = []; + + // Black Friday 2022-11-25: NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at + // 16:00 ET (21:00 UTC), even though curated bars_1d.ts stamps both at 16:00 ET (21:00 UTC). + const halfDayDate = '2022-11-25'; + const halfDayIdx = allDates.indexOf(halfDayDate); + if (halfDayIdx < 1 || halfDayIdx + 1 >= preCutoffSessions) { + throw new Error(`Expected half-day ${halfDayDate} inside pre-cutoff range.`); + } + const nextSessionIdx = halfDayIdx + 1; + const nextSessionDate = allDates[nextSessionIdx]!; + const halfDayUsIdx = 0; // listingId 10_001 (XNYS) + const halfDayCaIdx = 12; // listingId 50_001 (XTSE) + const halfDayUsListingId = listingIds[halfDayUsIdx]!; + const halfDayCaListingId = listingIds[halfDayCaIdx]!; + let usHalfDayReturn = 0; + let usNextSessionReturn = 0; + + const nyseCalendar = allDates.map(date => ({ + date, + closeTs: makeUtcMs(date, date === halfDayDate ? 18 : 21), // 13:00 ET on Black Friday, else 16:00 ET + })); + const tsxCalendar = allDates.map(date => ({ + date, + closeTs: makeUtcMs(date, 21), // 16:00 ET on all sessions including Black Friday + })); + const listingCalendarId = new Map(); + for (let l = 0; l < listingCount; l += 1) { + listingCalendarId.set(listingIds[l]!, l < 12 ? 'XNYS' : 'XTSE'); + } + const exchangeCalendars: EventStudyExchangeCalendars = { + calendars: new Map([ + ['XNYS', nyseCalendar], + ['XTSE', tsxCalendar], + ]), + listingCalendarId, + }; + + // Plant a 10% cash dividend inside a filing window for listing 0 (US, 10-q): + // On t = 12, listing l = ((12/4)*2 + 0) % 24 = 6 files after close; choose listing 6 + // and ex-date t = 15 (day +2 inside its [0..+5] filing window). + const divListingIdx = 6; + const divListingId = listingIds[divListingIdx]!; + const divExIdx = 15; + const divExDate = allDates[divExIdx]!; + const divYield = 0.1; // 10% cash dividend -> cum_total_factor = 1 / (1 - 0.1) = 10/9 + let divExpectedTotalReturn = 0; + let divRawDropReturn = 0; + + // Track active post-filing drift per listing: zero look-ahead because a filing stamped + // after close on session `t` (`22:00 UTC` / `17:00 ET`) only boosts returns starting on + // session `t + 1` (the event's anchored `dayIndex`) for 5 sessions. + const remainingBoostSessions = new Int32Array(listingCount); + const rawPrices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + rawPrices[l] = 15 + l * 1.25; + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET + const afterCloseTs = makeUtcMs(date, 22); // 17:00 ET + const isPostCutoff = date >= vaultCutoffDate; + + // Emit daily bars using ONLY boosts already active before today's close. + for (let l = 0; l < listingCount; l += 1) { + const boost = remainingBoostSessions[l]! > 0 ? 0.008 : 0; + if (remainingBoostSessions[l]! > 0) { + remainingBoostSessions[l] = remainingBoostSessions[l]! - 1; + } + const dailyRet = boost + (rand() * 2 - 1) * 0.006; + + if (l === divListingIdx && t === divExIdx) { + const prevRaw = rawPrices[l]!; + const exRawBase = prevRaw * (1 - divYield); + const nextRaw = exRawBase * (1 + dailyRet); + const cumTotalFactor = prevRaw / exRawBase; // 1 / (1 - divYield) + adjFactorRows.push({ + listing_id: divListingId, + ex_date: divExDate, + cum_split_factor: 1.0, + cum_total_factor: cumTotalFactor, + known_at: makeUtcMs(allDates[divExIdx - 1]!, 21), + }); + divExpectedTotalReturn = nextRaw / (prevRaw / cumTotalFactor) - 1; + divRawDropReturn = nextRaw / prevRaw - 1; + rawPrices[l] = nextRaw; + } else { + const prevRaw = rawPrices[l]!; + const nextRaw = Math.max(0.5, prevRaw * (1 + dailyRet)); + if (l === halfDayUsIdx && t === halfDayIdx) { + usHalfDayReturn = nextRaw / prevRaw - 1; + } else if (l === halfDayUsIdx && t === nextSessionIdx) { + usNextSessionReturn = nextRaw / prevRaw - 1; + } + rawPrices[l] = nextRaw; + } + + const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : rawPrices[l]!; + barRows.push({ + listing_id: listingIds[l]!, + session_date: date, + ts: closeTs, + open: closeVal, + high: closeVal, + low: closeVal, + close: closeVal, + volume: 75_000, + vwap: closeVal, + known_at: closeTs, + }); + } + + // Schedule staggered after-close filing events across pre-2023 and post-2023 sessions + // (plus post-cutoff filings to verify Vault isolation) using exact curator subtypes. + if (t >= 12 && (t - 12) % 4 === 0) { + for (let k = 0; k < 2; k += 1) { + const l = ((t / 4) * 2 + k) % listingCount; + const isUs = l < 12; + const subtype = isUs ? '10-q' : 'interim_financial_statements'; + eventRows.push({ + listing_id: listingIds[l]!, + ts: afterCloseTs, + known_at: afterCloseTs, + known_at_source: 'exact', + kind: 'filing', + subtype: poisonPostCutoff && isPostCutoff ? 'poison_filing' : subtype, + payload_json: JSON.stringify({ market: isUs ? 'US' : 'CA', form: subtype }), + }); + // Activate drift starting on session `t + 1`. + remainingBoostSessions[l] = 5; + } + + // Also emit a non-matching curated subtype filing on another listing to verify subtype filtering. + const otherL = (t + 7) % listingCount; + eventRows.push({ + listing_id: listingIds[otherL]!, + ts: afterCloseTs, + known_at: afterCloseTs, + known_at_source: 'exact', + kind: 'filing', + subtype: 'other', + payload_json: '{}', + }); + } + + // Emit half-day filings at 14:00 ET (19:00 UTC) on Black Friday 2022-11-25: + // - NYSE already closed at 13:00 ET (18:00 UTC) -> anchors to Monday 2022-11-28. + // - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2022-11-25. + if (t === halfDayIdx) { + const halfDay14EtTs = makeUtcMs(date, 19); + eventRows.push({ + listing_id: halfDayUsListingId, + ts: halfDay14EtTs, + known_at: halfDay14EtTs, + known_at_source: 'exact', + kind: 'filing', + subtype: '10-q', + payload_json: JSON.stringify({ market: 'US', form: '10-q', halfDay: true }), + }); + eventRows.push({ + listing_id: halfDayCaListingId, + ts: halfDay14EtTs, + known_at: halfDay14EtTs, + known_at_source: 'exact', + kind: 'filing', + subtype: 'interim_financial_statements', + payload_json: JSON.stringify({ + market: 'CA', + form: 'interim_financial_statements', + halfDay: true, + }), + }); + remainingBoostSessions[halfDayUsIdx] = 5; + remainingBoostSessions[halfDayCaIdx] = 5; + } + } + + return { + listingIds, + usListingIds, + caListingIds, + allDates, + vaultCutoffDate, + vaultCutoffTs, + barRows, + adjFactorRows, + eventRows, + exchangeCalendars, + dividendCase: { + listingId: divListingId, + exDate: divExDate, + exDayIdx: divExIdx, + expectedTotalReturn: divExpectedTotalReturn, + rawDropReturn: divRawDropReturn, + }, + halfDayCase: { + usListingId: halfDayUsListingId, + caListingId: halfDayCaListingId, + halfDayDate, + halfDayIdx, + nextSessionDate, + nextSessionIdx, + usHalfDayReturn, + usNextSessionReturn, + }, + }; +} + +interface RecordedQuery { + readonly sql: string; + readonly params: readonly DuckDbParam[]; +} + +function createFakeDuckDbExecutor(fixture: QmFilingsFixture): { + executor: DuckDbExecutor; + runStatements: string[]; + queries: RecordedQuery[]; +} { + const runStatements: string[] = []; + const queries: RecordedQuery[] = []; + + const executor: DuckDbExecutor = { + async run(sql: string) { + runStatements.push(sql); + }, + async query(sql: string, params: readonly DuckDbParam[]): Promise { + queries.push({ sql, params: [...params] }); + + if (sql.includes('parquet_kv_metadata')) { + return makeFencedAdjKvRows(fixture.vaultCutoffTs, fixture.adjFactorRows.length); + } + + if (sql.includes('bars_1d/year=*/part.parquet')) { + const nIds = fixture.listingIds.length; + const isAdjusted = sql.includes('ASOF LEFT JOIN'); + let idSet: Set; + let fromMs: number; + let toMs: number; + let asOfMs: number; + let adjAsOfMs: number | null = null; + + if (isAdjusted) { + // Bound params: [...listingIds, adjAsOfIso, ...listingIds, fromIso, toIso, asOfIso] + adjAsOfMs = Date.parse(params[nIds] as string); + idSet = new Set(params.slice(nIds + 1, 2 * nIds + 1) as number[]); + fromMs = Date.parse(params[2 * nIds + 1] as string); + toMs = Date.parse(params[2 * nIds + 2] as string); + asOfMs = Date.parse(params[2 * nIds + 3] as string); + } else { + // Bound params: [...listingIds, fromIso, toIso, asOfIso] + idSet = new Set(params.slice(0, nIds) as number[]); + fromMs = Date.parse(params[nIds] as string); + toMs = Date.parse(params[nIds + 1] as string); + asOfMs = Date.parse(params[nIds + 2] as string); + } + + const out: TableRow[] = []; + for (const row of fixture.barRows) { + const lid = row.listing_id as number; + const ts = row.ts as number; + const knownAt = row.known_at as number; + if (!idSet.has(lid) || ts < fromMs || ts > toMs || knownAt > asOfMs) { + continue; + } + + let priceDivisor = 1.0; + let splitFactor = 1.0; + if (isAdjusted && adjAsOfMs !== null) { + const sessionDate = row.session_date as string; + // ASOF LEFT JOIN: first adj_factors row with ex_date > session_date and known_at <= adjAsOfMs + let bestAdj: AdjFactorRow | null = null; + for (const adj of fixture.adjFactorRows) { + if ( + adj.listing_id === lid && + adj.known_at <= adjAsOfMs && + sessionDate < adj.ex_date && + (bestAdj === null || adj.ex_date < bestAdj.ex_date) + ) { + bestAdj = adj; + } + } + if (bestAdj !== null) { + priceDivisor = sql.includes('cum_total_factor') + ? bestAdj.cum_total_factor + : bestAdj.cum_split_factor; + splitFactor = bestAdj.cum_split_factor; + } + } + + out.push({ + listing_id: lid, + ts, + open: (row.open as number) / priceDivisor, + high: (row.high as number) / priceDivisor, + low: (row.low as number) / priceDivisor, + close: (row.close as number) / priceDivisor, + volume: (row.volume as number) * splitFactor, + vwap: (row.vwap as number) / priceDivisor, + known_at: knownAt, + }); + } + return out; + } + + if (sql.includes('events/year=*/part.parquet')) { + // Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso] + const nIds = fixture.listingIds.length; + const nKinds = params.length - nIds - 3; + const kindSet = new Set(params.slice(0, nKinds) as string[]); + const idSet = new Set(params.slice(nKinds, nKinds + nIds) as number[]); + const fromMs = Date.parse(params[nKinds + nIds] as string); + const toMs = Date.parse(params[nKinds + nIds + 1] as string); + const asOfMs = Date.parse(params[nKinds + nIds + 2] as string); + return fixture.eventRows.filter(row => { + const kind = row.kind as string; + const lid = row.listing_id as number; + const ts = row.ts as number; + const knownAt = row.known_at as number; + return ( + kindSet.has(kind) && + idSet.has(lid) && + ts >= fromMs && + ts <= toMs && + knownAt <= asOfMs + ); + }); + } + + throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`); + }, + }; + + return { executor, runStatements, queries }; +} + +describe('qmFilings end-to-end event study (headless, no database)', () => { + async function runQmFilingsStudy(poisonPostCutoff: boolean) { + const fixture = buildQmFilingsFixture(poisonPostCutoff); + const duck = createFakeDuckDbExecutor(fixture); + const ledger = createInMemoryTrialExecutor(); + + const store = createDuckDbMarketDataStore({ + executor: duck.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: fixture.vaultCutoffTs, + immutableAdjFactorsPath: IMMUTABLE_ADJ_PATH, + barBatchSize: 256, + }); + + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.allDates.length - 1]!; + + const bars = await collectBars( + store.bars({ + listingIds: fixture.listingIds, + timeframe: '1d', + from, + to, + adjustment: 'total', + }) + ); + const eventsTable = await store.events({ + kinds: ['filing'], + listingIds: fixture.listingIds, + from, + to, + }); + + const events = eventsTableToEventRows(eventsTable, { + kinds: ['filing'], + subtypes: ['10-q', 'interim_financial_statements'], + }); + const built = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: fixture.vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars: fixture.exchangeCalendars, + }); + + const studyResult = await runEventStudy(ledger.executor, { + principalId: 'operator', + universeMarket: 'US_CA_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'qmfilings_interim_10q_sedar_event_study', + params: { + kinds: ['filing'], + subtypes: ['10-q', 'interim_financial_statements'], + preDays: 5, + postDays: 5, + }, + universe: 'US_CA_EQ_FIXTURE', + horizon: '5d', + }, + input: built.input, + options: { preDays: 5, postDays: 5, minEvents: 10 }, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + + return { fixture, duck, ledger, events, built, studyResult }; + } + + it('flows DuckDbMarketDataStore (total-adjusted) -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => { + const clean = await runQmFilingsStudy(false); + + // DuckDB connection budget SET statements ran once; 3 queries ran (adj_factors kv metadata + bars + events). + expect(clean.duck.runStatements).toHaveLength(3); + expect(clean.duck.runStatements[0]).toContain('SET memory_limit'); + expect(clean.duck.runStatements[1]).toContain('SET threads'); + expect(clean.duck.runStatements[2]).toContain('SET temp_directory'); + expect(clean.duck.queries).toHaveLength(3); + expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata'); + expect(clean.duck.queries[1]!.sql).toContain('cum_total_factor'); + expect(clean.duck.queries[2]!.sql).toContain('events/year=*/part.parquet'); + + // Every bound timestamp parameter (`asOfIso`, `fromIso`, `toIso`) in every data query + // is strictly `< vaultCutoffTs`. + const isoRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/; + let checkedTimestamps = 0; + for (const q of clean.duck.queries) { + for (const param of q.params) { + if (typeof param === 'string' && isoRe.test(param)) { + const parsedMs = Date.parse(param); + expect(Number.isFinite(parsedMs)).toBe(true); + expect(parsedMs).toBeLessThan(clean.fixture.vaultCutoffTs); + checkedTimestamps += 1; + } + } + } + // bars_1d total-adjusted binds 4 timestamps (adjAsOfIso, fromIso, toIso, barsAsOfIso) + events binds 3. + expect(checkedTimestamps).toBe(7); + + // Both curated filing groups ('10-q' for US and 'interim_financial_statements' for CA) contribute events. + const usFilteredCount = clean.events.filter(e => e.subtype === '10-q').length; + const caFilteredCount = clean.events.filter( + e => e.subtype === 'interim_financial_statements' + ).length; + expect(usFilteredCount).toBeGreaterThan(0); + expect(caFilteredCount).toBeGreaterThan(0); + expect(usFilteredCount + caFilteredCount).toBe(clean.events.length); + + // Total-return adjustment eliminates the raw -10% dividend drop inside the filing window. + const divCase = clean.fixture.dividendCase; + expect(divCase.rawDropReturn).toBeLessThan(-0.08); + expect(divCase.expectedTotalReturn).toBeGreaterThan(-0.02); + const divSeries = clean.built.input.entityReturns.get(divCase.listingId)!; + expect(divSeries[divCase.exDayIdx]!).toBeCloseTo(divCase.expectedTotalReturn, 10); + + // Half-day anchoring: a US ('10-q') filing published at 14:00 ET on Black Friday 2022-11-25 + // (after NYSE's 13:00 ET close, even though curated bars_1d.ts stamps 16:00 ET) MUST anchor + // to Monday 2022-11-28 (not Friday), while the CA ('interim_financial_statements') filing at + // 14:00 ET anchors to Friday 2022-11-25 (before TSX's 16:00 ET close). + const halfDay = clean.fixture.halfDayCase; + expect( + clean.built.input.events.some( + e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.halfDayIdx + ) + ).toBe(false); + expect( + clean.built.input.events.some( + e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.nextSessionIdx + ) + ).toBe(true); + expect( + clean.built.input.events.some( + e => e.entityId === halfDay.caListingId && e.dayIndex === halfDay.halfDayIdx + ) + ).toBe(true); + const usHalfDaySeries = clean.built.input.entityReturns.get(halfDay.usListingId)!; + expect(clean.built.input.sessionDates[halfDay.nextSessionIdx]).toBe(halfDay.nextSessionDate); + expect(usHalfDaySeries[halfDay.nextSessionIdx]!).toBeCloseTo(halfDay.usNextSessionReturn, 12); + expect(halfDay.usNextSessionReturn).not.toBeCloseTo(halfDay.usHalfDayReturn, 6); + + // Event study succeeded and appended exactly one `event_study` row to trial_ledger. + expect(clean.studyResult.status).toBe('ok'); + if (clean.studyResult.status !== 'ok') { + return; + } + + // Both US ('10-q') and CA ('interim_financial_statements') listings contributed usable events to the study. + const usedIds = clean.studyResult.study.eventCars.entityIds; + const usUsedCount = usedIds.filter(id => clean.fixture.usListingIds.has(Number(id))).length; + const caUsedCount = usedIds.filter(id => clean.fixture.caListingIds.has(Number(id))).length; + expect(usUsedCount).toBeGreaterThan(0); + expect(caUsedCount).toBeGreaterThan(0); + + expect(clean.ledger.rows).toHaveLength(1); + const stored = clean.ledger.rows[0]!; + expect(stored.stage).toBe('event_study'); + expect(stored.universe_market).toBe('US_CA_EQ'); + expect(stored.horizon_bucket).toBe('swing_1_10d'); + expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true); + expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true); + + // Stored daily_series matches study.clustered.meanCars at float32 precision. + const expectedMeanCars = Array.from(clean.studyResult.study.clustered.meanCars, v => + Math.fround(v) + ); + expect(stored.daily_series).toEqual(expectedMeanCars); + + // Finite cluster-deflated Sharpe with effectiveTrials >= 1. + expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull(); + expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true); + expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1); + + // Planted positive post-filing abnormal return produces positive clustered CAR mean. + expect(clean.studyResult.study.clustered.carMean).toBeGreaterThan(0); + + // Poisoning post-cutoff bars & events leaves built input, study result, and ledger byte-identical. + const poisoned = await runQmFilingsStudy(true); + expect(poisoned.built.diagnostics).toEqual(clean.built.diagnostics); + expect(poisoned.built.input.sessionDates).toEqual(clean.built.input.sessionDates); + expect(poisoned.built.input.events).toEqual(clean.built.input.events); + expect(Array.from(poisoned.built.input.entityReturns.keys())).toEqual( + Array.from(clean.built.input.entityReturns.keys()) + ); + for (const [id, cleanSeries] of clean.built.input.entityReturns) { + const a = poisoned.built.input.entityReturns.get(id) as Float64Array; + const b = cleanSeries as Float64Array; + expect(new Uint8Array(a.buffer, a.byteOffset, a.byteLength)).toEqual( + new Uint8Array(b.buffer, b.byteOffset, b.byteLength) + ); + } + const cleanBench = clean.built.input.benchmarkReturns as Float64Array; + const poisonedBench = poisoned.built.input.benchmarkReturns as Float64Array; + expect( + new Uint8Array(poisonedBench.buffer, poisonedBench.byteOffset, poisonedBench.byteLength) + ).toEqual(new Uint8Array(cleanBench.buffer, cleanBench.byteOffset, cleanBench.byteLength)); + expect(poisoned.studyResult).toEqual(clean.studyResult); + expect(poisoned.ledger.rows).toEqual(clean.ledger.rows); + }); +}); diff --git a/libs/research/test/event-panel-qa.test.ts b/libs/research/test/event-panel-qa.test.ts new file mode 100644 index 00000000..23ef342a --- /dev/null +++ b/libs/research/test/event-panel-qa.test.ts @@ -0,0 +1,672 @@ +import { describe, expect, it } from 'bun:test'; +import { + type BarRecord, + type BuildEventStudyInputResult, + type EventObservation, + type EventStudyExchangeCalendars, + type ExchangeSessionClose, + type TrialLedgerExecutor, + buildEventStudyInput, + runEventStudy, +} from '@stock-bot/research'; + +// QA suite for T-123: compares `buildEventStudyInput` against a deliberately naive reference +// model on seeded random panels (two exchange calendars with different holidays and an NYSE +// half-day, EDT/EST close stamps, gaps, bad closes, exact duplicate bars, late-listing / +// early-delisting, events at/around exact close timestamps, weekends, pre-history and +// post-cutoff), plus truncation (prefix-stability) and an end-to-end half-day CAR probe. + +const MS_PER_DAY = 86_400_000; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0, ms = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms); +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = []; + const current = new Date(`${startDate}T00:00:00.000Z`); + while (out.length < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out.push(current.toISOString().slice(0, 10)); + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +// 16:00 ET in UTC: 20:00 during EDT (before 2022-11-06 / from 2023-03-12), 21:00 during EST. +function regularCloseHourUtc(date: string): number { + return date < '2022-11-06' || date >= '2023-03-12' ? 20 : 21; +} + +function makeBar(listingId: number, ts: number, close: number): BarRecord { + return { + listingId, + ts, + open: close, + high: close, + low: close, + close, + volume: 1_000, + vwap: close, + knownAt: ts, + }; +} + +function makeTrappedBar(listingId: number, ts: number): BarRecord { + const bar = { ...makeBar(listingId, ts, 1) } as Record; + Object.defineProperty(bar, 'close', { + enumerable: true, + get() { + throw new Error(`Vault breach: close read for listing ${listingId} at ${ts}`); + }, + }); + return bar as unknown as BarRecord; +} + +function shuffle(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rand = createSeededRng(seed); + for (let i = copy.length - 1; i > 0; i -= 1) { + const j = Math.floor(rand() * (i + 1)); + [copy[i], copy[j]] = [copy[j]!, copy[i]!]; + } + return copy; +} + +const US_HOLIDAYS = new Set(['2022-11-24', '2022-12-26', '2023-01-02', '2023-01-16', '2023-02-20']); +const CA_HOLIDAYS = new Set(['2022-10-10', '2022-12-26', '2022-12-27', '2023-01-02', '2023-02-20']); +const NYSE_HALF_DAYS = new Set(['2022-11-25']); + +function buildCalendars(dates: readonly string[]): { + xnys: ExchangeSessionClose[]; + xtse: ExchangeSessionClose[]; +} { + const xnys: ExchangeSessionClose[] = []; + const xtse: ExchangeSessionClose[] = []; + for (const date of dates) { + const regular = regularCloseHourUtc(date); + if (!US_HOLIDAYS.has(date)) { + xnys.push({ date, closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? regular - 3 : regular) }); + } + if (!CA_HOLIDAYS.has(date)) { + xtse.push({ date, closeTs: makeUtcMs(date, regular) }); + } + } + return { xnys, xtse }; +} + +interface RandomPanel { + readonly bars: BarRecord[]; + readonly events: EventObservation[]; + readonly calendars: EventStudyExchangeCalendars; + readonly calendarByListing: Map; + readonly dates: string[]; +} + +/** + * Builds a seeded random panel. Bars dated on/after `trapFromDate` get a throwing `close` + * getter so any Vault breach fails the test. + */ +function buildRandomPanel(seed: number, trapFromDate: string | null): RandomPanel { + const rand = createSeededRng(seed); + const dates = makeBusinessDates('2022-10-03', 110); + const { xnys, xtse } = buildCalendars(dates); + const listingCount = 12; + const listingIds = Array.from({ length: listingCount }, (_, i) => 100 + i * 7); + const calendarByListing = new Map(); + const listingCalendarId = new Map(); + const bars: BarRecord[] = []; + + for (let l = 0; l < listingCount; l += 1) { + const listingId = listingIds[l]!; + const isUs = l % 2 === 0; + const cal = isUs ? xnys : xtse; + calendarByListing.set(listingId, cal); + listingCalendarId.set(listingId, isUs ? 'XNYS' : 'XTSE'); + + const startIdx = l % 4 === 3 ? 20 + Math.floor(rand() * 20) : 0; + const endIdx = l % 5 === 4 ? cal.length - 30 - Math.floor(rand() * 10) : cal.length; + let price = 20 + l; + for (let s = startIdx; s < endIdx; s += 1) { + const session = cal[s]!; + if (rand() < 0.08) { + continue; // gap + } + price *= 1 + (rand() * 2 - 1) * 0.02; + const ts = makeUtcMs(session.date, regularCloseHourUtc(session.date)); // curated 16:00 ET + const trapped = trapFromDate !== null && session.date >= trapFromDate; + if (trapped) { + bars.push(makeTrappedBar(listingId, ts)); + continue; + } + const u = rand(); + const close = u < 0.01 ? 0 : u < 0.02 ? -1 : u < 0.025 ? Number.NaN : u < 0.03 ? Number.POSITIVE_INFINITY : price; + bars.push(makeBar(listingId, ts, close)); + if (rand() < 0.03) { + bars.push(makeBar(listingId, ts, close)); // exact duplicate + } + } + } + + const events: EventObservation[] = []; + const eventCount = 160; + for (let i = 0; i < eventCount; i += 1) { + const unknown = rand() < 0.05; + const listingId = unknown ? 9_999 : listingIds[Math.floor(rand() * listingCount)]!; + const cal = calendarByListing.get(listingId) ?? xnys; + const anchorSession = cal[Math.floor(rand() * cal.length)]!; + const mode = Math.floor(rand() * 7); + let knownAt: number; + if (mode === 0) { + knownAt = anchorSession.closeTs; // exactly at close -> same session + } else if (mode === 1) { + knownAt = anchorSession.closeTs + 1; // 1 ms after close -> next session + } else if (mode === 2) { + knownAt = anchorSession.closeTs - 1; + } else if (mode === 3) { + knownAt = makeUtcMs(anchorSession.date, 19); // 14:00/15:00 ET intraday (after half-day close) + } else if (mode === 4) { + knownAt = makeUtcMs(anchorSession.date, 22, 30); // after close + } else if (mode === 5) { + knownAt = makeUtcMs(anchorSession.date, 12) + 2 * MS_PER_DAY; // may land on weekend + } else { + knownAt = makeUtcMs('2022-09-15', 15) + Math.floor(rand() * 200) * MS_PER_DAY; // pre-history .. post-cutoff + } + events.push({ listingId, knownAt, kind: 'filing', subtype: rand() < 0.5 ? '10-q' : 'interim_financial_statements' }); + if (rand() < 0.05) { + events.push({ listingId, knownAt, kind: 'filing', subtype: 'other' }); // duplicate anchor + } + } + // Explicit NYSE half-day probe: 14:00 ET on Black Friday for a US and a CA listing. + events.push({ listingId: listingIds[0]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' }); + events.push({ listingId: listingIds[1]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: null }); + + return { + bars, + events, + calendars: { + calendars: new Map([ + ['XNYS', xnys], + ['XTSE', xtse], + ]), + listingCalendarId, + }, + calendarByListing, + dates, + }; +} + +interface ReferenceResult { + sessionDates: string[]; + entityIds: number[]; + returns: Map; + benchmark: number[]; + events: { entityId: number; dayIndex: number }[]; + diagnostics: Record; +} + +/** Naive O(n^2) reference model of the documented contract. */ +function referenceBuild(panel: RandomPanel, vaultCutoffDate: string): ReferenceResult { + const cutoffMs = makeUtcMs(vaultCutoffDate, 0); + const dateOf = (ts: number) => new Date(Math.floor(ts / MS_PER_DAY) * MS_PER_DAY).toISOString().slice(0, 10); + const postDates = new Set(); + const perListing = new Map>(); + let duplicateBars = 0; + for (const bar of panel.bars) { + const date = dateOf(bar.ts); + if (date >= vaultCutoffDate) { + postDates.add(date); + continue; + } + const m = perListing.get(bar.listingId) ?? new Map(); + perListing.set(bar.listingId, m); + if (m.has(date)) { + duplicateBars += 1; + continue; + } + m.set(date, bar.close); + } + const sessionDates = [...new Set([...perListing.values()].flatMap(m => [...m.keys()]))].sort(); + const entityIds = [...perListing.keys()].sort((a, b) => a - b); + const returns = new Map(); + const benchSum = new Array(sessionDates.length).fill(0); + const benchCount = new Array(sessionDates.length).fill(0); + let nonPositiveCloseReturns = 0; + for (const id of entityIds) { + const closes = perListing.get(id)!; + const calDates = panel.calendarByListing.get(id)!.map(s => s.date); + const series = sessionDates.map((date, d) => { + if (!closes.has(date)) { + return Number.NaN; + } + const c = calDates.indexOf(date); + if (c <= 0 || !closes.has(calDates[c - 1]!)) { + return Number.NaN; + } + const prev = closes.get(calDates[c - 1]!)!; + const curr = closes.get(date)!; + const ret = curr / prev - 1; + if (!(prev > 0 && curr > 0 && Number.isFinite(prev) && Number.isFinite(curr) && Number.isFinite(ret))) { + nonPositiveCloseReturns += 1; + return Number.NaN; + } + benchSum[d] += ret; + benchCount[d] += 1; + return ret; + }); + returns.set(id, series); + } + const benchmark = benchSum.map((s, d) => (benchCount[d]! > 0 ? s / benchCount[d]! : Number.NaN)); + + let vaultExcludedEvents = 0; + let droppedUnknownListing = 0; + let droppedAfterLastSession = 0; + let droppedMissingCalendarSession = 0; + const cands: { entityId: number; dayIndex: number }[] = []; + for (const ev of panel.events) { + if (ev.knownAt >= cutoffMs) { + vaultExcludedEvents += 1; + continue; + } + if (!perListing.has(ev.listingId)) { + droppedUnknownListing += 1; + continue; + } + const preCal = panel.calendarByListing.get(ev.listingId)!.filter(s => s.date < vaultCutoffDate); + const eligible = preCal.find(s => s.closeTs >= ev.knownAt); + if (eligible === undefined || eligible.date > sessionDates[sessionDates.length - 1]!) { + droppedAfterLastSession += 1; + continue; + } + const dayIndex = sessionDates.indexOf(eligible.date); + if (dayIndex < 0) { + droppedMissingCalendarSession += 1; + continue; + } + cands.push({ entityId: ev.listingId, dayIndex }); + } + cands.sort((a, b) => a.dayIndex - b.dayIndex || a.entityId - b.entityId); + const events = cands.filter( + (c, i) => i === 0 || c.dayIndex !== cands[i - 1]!.dayIndex || c.entityId !== cands[i - 1]!.entityId + ); + + return { + sessionDates, + entityIds, + returns, + benchmark, + events, + diagnostics: { + vaultExcludedDates: postDates.size, + vaultExcludedEvents, + droppedUnknownListing, + droppedAfterLastSession, + droppedMissingCalendarSession, + duplicateEvents: cands.length - events.length, + duplicateBars, + nonPositiveCloseReturns, + }, + }; +} + +function nanSafe(values: ArrayLike): (number | string)[] { + return Array.from(values, v => (Number.isNaN(v) ? 'NaN' : v)); +} + +function expectSameAsReference(actual: BuildEventStudyInputResult, ref: ReferenceResult): void { + expect(actual.input.sessionDates).toEqual(ref.sessionDates); + expect(Array.from(actual.input.entityReturns.keys())).toEqual(ref.entityIds); + for (const id of ref.entityIds) { + expect(nanSafe(actual.input.entityReturns.get(id)!)).toEqual(nanSafe(ref.returns.get(id)!)); + } + expect(nanSafe(actual.input.benchmarkReturns!)).toEqual(nanSafe(ref.benchmark)); + expect(actual.input.events.map(e => ({ entityId: e.entityId, dayIndex: e.dayIndex }))).toEqual(ref.events); + expect({ ...actual.diagnostics }).toEqual(ref.diagnostics); +} + +describe('buildEventStudyInput QA — seeded reference-model comparison', () => { + const VAULT_CUTOFF = '2023-02-01'; + + for (const seed of [20261129, 7, 424242, 99]) { + it(`matches the naive reference model exactly and never reads vaulted closes (seed ${seed})`, () => { + const panel = buildRandomPanel(seed, VAULT_CUTOFF); + const ref = referenceBuild(panel, VAULT_CUTOFF); + + const actual = buildEventStudyInput({ + bars: panel.bars, + events: panel.events, + vaultCutoffDate: VAULT_CUTOFF, + benchmark: 'equal_weight', + exchangeCalendars: panel.calendars, + }); + + expectSameAsReference(actual, ref); + // Conservation identity. + const d = actual.diagnostics; + expect( + actual.input.events.length + + d.vaultExcludedEvents + + d.droppedUnknownListing + + d.droppedAfterLastSession + + d.droppedMissingCalendarSession + + d.duplicateEvents + ).toBe(panel.events.length); + // No session date reaches the Vault and no event anchors onto a Vault session. + expect(actual.input.sessionDates.every(date => date < VAULT_CUTOFF)).toBe(true); + // Fixture actually exercises the interesting branches. + expect(d.vaultExcludedEvents).toBeGreaterThan(0); + expect(d.droppedUnknownListing).toBeGreaterThan(0); + expect(d.vaultExcludedDates).toBeGreaterThan(0); + expect(d.nonPositiveCloseReturns).toBeGreaterThan(0); + + // Shuffled inputs give the identical result. + const shuffled = buildEventStudyInput({ + bars: shuffle(panel.bars, seed + 1), + events: shuffle(panel.events, seed + 2), + vaultCutoffDate: VAULT_CUTOFF, + benchmark: 'equal_weight', + exchangeCalendars: panel.calendars, + }); + expectSameAsReference(shuffled, ref); + }); + } + + it('anchors the NYSE Black Friday 14:00 ET filing to Monday and the TSX one to Friday', () => { + const panel = buildRandomPanel(20261129, VAULT_CUTOFF); + const actual = buildEventStudyInput({ + bars: panel.bars, + events: panel.events, + vaultCutoffDate: VAULT_CUTOFF, + exchangeCalendars: panel.calendars, + }); + const usId = 100; + const caId = 107; + const dates = actual.input.sessionDates; + const usDates = actual.input.events.filter(e => e.entityId === usId).map(e => dates[e.dayIndex]); + const caDates = actual.input.events.filter(e => e.entityId === caId).map(e => dates[e.dayIndex]); + expect(usDates).toContain('2022-11-28'); + expect(caDates).toContain('2022-11-25'); + }); +}); + +describe('buildEventStudyInput QA — truncation (prefix stability) across Vault cutoffs', () => { + it('earlier-cutoff output is an exact prefix of later-cutoff output (no future-dependent values)', () => { + const panel = buildRandomPanel(31337, null); + const cutoffs = ['2022-11-25', '2022-12-27', '2023-01-17', '2023-02-21']; + const results = cutoffs.map(vaultCutoffDate => + buildEventStudyInput({ + bars: panel.bars, + events: panel.events, + vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars: panel.calendars, + }) + ); + + for (let i = 0; i + 1 < results.length; i += 1) { + const early = results[i]!.input; + const late = results[i + 1]!.input; + const n = early.sessionDates.length; + expect(n).toBeGreaterThan(0); + expect(late.sessionDates.slice(0, n)).toEqual([...early.sessionDates]); + for (const [id, series] of early.entityReturns) { + const lateSeries = late.entityReturns.get(id)!; + expect(nanSafe(Array.from(lateSeries).slice(0, n))).toEqual(nanSafe(series)); + } + expect(nanSafe(Array.from(late.benchmarkReturns!).slice(0, n))).toEqual( + nanSafe(early.benchmarkReturns!) + ); + const lateKeys = new Set(late.events.map(e => `${e.entityId}@${e.dayIndex}`)); + for (const ev of early.events) { + expect(lateKeys.has(`${ev.entityId}@${ev.dayIndex}`)).toBe(true); + } + } + }); + + it('a poisoned future (absurd closes, extra filings, calendar tail) leaves pre-cutoff output byte-identical', () => { + const cutoff = '2023-01-17'; + const panel = buildRandomPanel(555, null); + const base = buildEventStudyInput({ + bars: panel.bars, + events: panel.events, + vaultCutoffDate: cutoff, + benchmark: 'equal_weight', + exchangeCalendars: panel.calendars, + }); + + const cutoffMs = makeUtcMs(cutoff, 0); + const poisonedBars = panel.bars.map(b => + b.ts >= cutoffMs ? makeBar(b.listingId, b.ts, b.close * 1_000_000) : b + ); + const poisonedEvents: EventObservation[] = [ + ...panel.events, + ...[100, 107, 114].map(listingId => ({ + listingId, + knownAt: cutoffMs, + kind: 'filing' as const, + subtype: 'poison', + })), + ]; + const result = buildEventStudyInput({ + bars: poisonedBars, + events: poisonedEvents, + vaultCutoffDate: cutoff, + benchmark: 'equal_weight', + exchangeCalendars: panel.calendars, + }); + + expect(result.input.sessionDates).toEqual(base.input.sessionDates); + expect(result.input.events).toEqual(base.input.events); + for (const [id, series] of base.input.entityReturns) { + expect(nanSafe(result.input.entityReturns.get(id)!)).toEqual(nanSafe(series)); + } + expect(nanSafe(result.input.benchmarkReturns!)).toEqual(nanSafe(base.input.benchmarkReturns!)); + expect(result.diagnostics.vaultExcludedEvents).toBe(base.diagnostics.vaultExcludedEvents + 3); + }); +}); + +describe('buildEventStudyInput QA — calendar input forms and exact-close boundaries', () => { + it('treats plain-object calendars/mappings identically to Maps', () => { + const panel = buildRandomPanel(8080, null); + const cutoff = '2023-02-01'; + const cals = panel.calendars.calendars as ReadonlyMap; + const mapping = panel.calendars.listingCalendarId as ReadonlyMap; + const asMaps = buildEventStudyInput({ + bars: panel.bars, + events: panel.events, + vaultCutoffDate: cutoff, + benchmark: 'equal_weight', + exchangeCalendars: panel.calendars, + }); + const asRecords = buildEventStudyInput({ + bars: panel.bars, + events: panel.events, + vaultCutoffDate: cutoff, + benchmark: 'equal_weight', + exchangeCalendars: { + calendars: Object.fromEntries(cals), + listingCalendarId: Object.fromEntries(mapping), + }, + }); + expect(asRecords.input.events).toEqual(asMaps.input.events); + expect(asRecords.diagnostics).toEqual(asMaps.diagnostics); + for (const [id, series] of asMaps.input.entityReturns) { + expect(nanSafe(asRecords.input.entityReturns.get(id)!)).toEqual(nanSafe(series)); + } + }); + + it('anchors knownAt == close to that session and close + 1 ms to the next (half-day close included)', () => { + const dates = ['2022-11-22', '2022-11-23', '2022-11-25', '2022-11-28']; + const xnys = dates.map(date => ({ + date, + closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? 18 : 21), + })); + const bars = dates.map((date, i) => makeBar(1, makeUtcMs(date, 21), 10 + i)); + const halfClose = makeUtcMs('2022-11-25', 18); + const result = buildEventStudyInput({ + bars, + events: [ + { listingId: 1, knownAt: halfClose, kind: 'filing', subtype: '10-q' }, + { listingId: 1, knownAt: halfClose + 1, kind: 'filing', subtype: '10-q' }, + // Thanksgiving (NYSE closed) intraday -> Friday half-day session. + { listingId: 1, knownAt: makeUtcMs('2022-11-24', 15), kind: 'filing', subtype: '10-q' }, + ], + vaultCutoffDate: '2022-12-01', + exchangeCalendars: { calendars: { XNYS: xnys }, listingCalendarId: { 1: 'XNYS' } }, + }); + expect(result.input.events).toEqual([ + { entityId: 1, dayIndex: 2 }, + { entityId: 1, dayIndex: 3 }, + ]); + expect(result.diagnostics.duplicateEvents).toBe(1); + // Wed -> Fri is consecutive on the NYSE calendar (Thanksgiving closed), so Friday's return is valid. + expect(result.input.entityReturns.get(1)![2]).toBeCloseTo(12 / 11 - 1, 15); + }); +}); + +function createInMemoryTrialExecutor(): { executor: TrialLedgerExecutor; rows: Record[] } { + const rows: Record[] = []; + let nextTrialId = 1; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + const p = params ?? []; + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const trialId = String(nextTrialId++); + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, Number(trialId))); + const stored = { + trial_id: trialId, + created_at: createdAt, + principal_id: p[0], + campaign_id: p[1] ?? null, + stage: p[2], + universe_market: p[3], + horizon_bucket: p[4], + hypothesis_id: p[5] ?? null, + expression_hash: p[6], + sample_start: p[7], + sample_end: p[8], + n_obs: p[9], + sharpe_unann: p[10], + skewness: p[11], + kurtosis: p[12], + daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), + }; + rows.push(stored); + return { rows: [{ trial_id: trialId, created_at: createdAt } as unknown as Row], rowCount: 1 }; + } + if (trimmed.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const matched = rows.filter(r => r.trial_id === String(p[0])); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const matched = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + return { rows: [], rowCount: 0 }; + }, + }; + return { executor, rows }; +} + +describe('buildEventStudyInput QA — half-day filing reaches runEventStudy eventCars on Monday', () => { + it('keeps the NYSE Black Friday filing in study.eventCars dated Monday with the expected benchmark-adjusted CAR', async () => { + const rand = createSeededRng(20261129); + const dates = makeBusinessDates('2022-10-03', 90); + const { xnys, xtse } = buildCalendars(dates); + const vaultCutoffDate = dates[80]!; + const usIds = [11, 12, 13, 14]; + const caIds = [21, 22, 23, 24]; + const bars: BarRecord[] = []; + const listingCalendarId = new Map(); + for (const [ids, cal, calId] of [ + [usIds, xnys, 'XNYS'], + [caIds, xtse, 'XTSE'], + ] as const) { + for (const id of ids) { + listingCalendarId.set(id, calId); + let price = 30 + id; + for (const s of cal) { + price *= 1 + (rand() * 2 - 1) * 0.015; + bars.push(makeBar(id, makeUtcMs(s.date, regularCloseHourUtc(s.date)), price)); + } + } + } + + // Regular after-close filings every 5 sessions in windows that avoid cross-border holidays, + // plus the 14:00 ET Black Friday filing for listing 11 (after NYSE's 13:00 ET close). + const events: EventObservation[] = []; + for (let t = 3; t < 75; t += 5) { + const date = dates[t]!; + for (const id of [...usIds, ...caIds]) { + if ((t + id) % 3 === 0) { + events.push({ listingId: id, knownAt: makeUtcMs(date, 23), kind: 'filing', subtype: '10-q' }); + } + } + } + events.push({ listingId: 11, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' }); + + const built = buildEventStudyInput({ + bars, + events, + vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars: { calendars: { XNYS: xnys, XTSE: xtse }, listingCalendarId }, + }); + + const postDays = 3; + const ledger = createInMemoryTrialExecutor(); + const result = await runEventStudy(ledger.executor, { + principalId: 'operator', + universeMarket: 'US_CA_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'qa_half_day_filing_event_study', + params: { preDays: 0, postDays }, + universe: 'US_CA_EQ_QA', + horizon: '3d', + }, + input: built.input, + options: { preDays: 0, postDays, minEvents: 5 }, + vaultCutoffDate, + }); + + expect(result.status).toBe('ok'); + if (result.status !== 'ok') { + return; + } + expect(ledger.rows).toHaveLength(1); + + const cars = result.study.eventCars; + const usHalfDayIdx = cars.entityIds.findIndex((id, i) => id === 11 && cars.dates[i] === '2022-11-28'); + expect(usHalfDayIdx).toBeGreaterThanOrEqual(0); + expect(cars.entityIds.some((id, i) => id === 11 && cars.dates[i] === '2022-11-25')).toBe(false); + + const sessionDates = built.input.sessionDates; + const d = sessionDates.indexOf('2022-11-28'); + expect(cars.dayIndices[usHalfDayIdx]).toBe(d); + const r = built.input.entityReturns.get(11)!; + const b = built.input.benchmarkReturns!; + let expectedCar = 0; + for (let k = 0; k <= postDays; k += 1) { + expectedCar += (r[d + k] as number) - (b[d + k] as number); + } + expect(cars.cars[usHalfDayIdx]!).toBeCloseTo(expectedCar, 12); + expect(Number.isFinite(result.deflatedSharpe.dsr ?? Number.NaN)).toBe(true); + }); +}); diff --git a/libs/research/test/event-panel.test.ts b/libs/research/test/event-panel.test.ts new file mode 100644 index 00000000..a5979670 --- /dev/null +++ b/libs/research/test/event-panel.test.ts @@ -0,0 +1,1181 @@ +import { describe, expect, it } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { eventDayIndex, eventStudy } from '@stock-bot/calculations'; +import { + EventPanelError, + buildEventStudyInput, + eventsTableToEventRows, + type BarRecord, + type EventObservation, + type EventPanelErrorCode, + type EventStudyExchangeCalendars, + type Table, +} from '@stock-bot/research'; +import { + EventPanelError as SubpathEventPanelError, + buildEventStudyInput as subpathBuildEventStudyInput, + eventsTableToEventRows as subpathEventsTableToEventRows, +} from '@stock-bot/research/event-panel'; + +function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms); +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord { + const ts = makeUtcMs(date, hourUtc, 0, 0, 0); + return { + listingId, + ts, + open: close, + high: close, + low: close, + close, + volume: 1_000, + vwap: close, + knownAt: ts, + }; +} + +function makeExchangeCalendars( + listingIds: readonly number[], + dates: readonly string[], + hourUtc = 21 +): EventStudyExchangeCalendars { + const sessions = dates.map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) })); + const listingCalendarId = new Map(); + for (const id of listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { + calendars: new Map([['XNYS', sessions]]), + listingCalendarId, + }; +} + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function shuffle(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rand = createSeededRng(seed); + for (let i = copy.length - 1; i > 0; i -= 1) { + const j = Math.floor(rand() * (i + 1)); + const tmp = copy[i]!; + copy[i] = copy[j]!; + copy[j] = tmp; + } + return copy; +} + +function expectEventPanelError(fn: () => unknown, code: EventPanelErrorCode): EventPanelError { + try { + fn(); + } catch (err) { + expect(err).toBeInstanceOf(EventPanelError); + const typed = err as EventPanelError; + expect(typed.code).toBe(code); + return typed; + } + throw new Error(`Expected EventPanelError(${code}), but function did not throw.`); +} + +function expectBitIdenticalFloat64(actual: Float64Array, expected: Float64Array): void { + expect(actual.length).toBe(expected.length); + const aBytes = new Uint8Array(actual.buffer, actual.byteOffset, actual.byteLength); + const eBytes = new Uint8Array(expected.buffer, expected.byteOffset, expected.byteLength); + expect(aBytes).toEqual(eBytes); +} + +function expectBitIdenticalEventStudyInput( + actual: ReturnType['input'], + expected: ReturnType['input'] +): void { + expect(actual.sessionDates).toEqual(expected.sessionDates); + expect(actual.events).toEqual(expected.events); + expect(Array.from(actual.entityReturns.keys())).toEqual(Array.from(expected.entityReturns.keys())); + for (const [id, expectedSeries] of expected.entityReturns) { + const actualSeries = actual.entityReturns.get(id); + expect(actualSeries).toBeInstanceOf(Float64Array); + expectBitIdenticalFloat64(actualSeries as Float64Array, expectedSeries as Float64Array); + } + if (expected.benchmarkReturns === undefined) { + expect(actual.benchmarkReturns).toBeUndefined(); + } else { + expect(actual.benchmarkReturns).toBeInstanceOf(Float64Array); + expectBitIdenticalFloat64( + actual.benchmarkReturns as Float64Array, + expected.benchmarkReturns as Float64Array + ); + } +} + +describe('@stock-bot/research event-panel exports and browser safety', () => { + it('exposes identical symbols from root and ./event-panel subpath', () => { + expect(buildEventStudyInput).toBe(subpathBuildEventStudyInput); + expect(eventsTableToEventRows).toBe(subpathEventsTableToEventRows); + expect(EventPanelError).toBe(SubpathEventPanelError); + }); + + it('has zero node:* imports, zero bare process access, and unchanged package dependencies', () => { + for (const relPath of ['../src/event-panel.ts', '../src/panel-shared.ts']) { + const src = readFileSync(new URL(relPath, import.meta.url), 'utf8'); + expect(src).not.toMatch(/from\s+['"]node:/); + expect(src).not.toMatch(/require\s*\(\s*['"]node:/); + expect(src).not.toMatch(/\bprocess\./); + } + + const pkg = JSON.parse( + readFileSync(new URL('../package.json', import.meta.url), 'utf8') + ) as { dependencies?: Record; exports?: Record }; + expect(pkg.exports?.['./event-panel']).toBe('./src/event-panel.ts'); + expect(Object.keys(pkg.dependencies ?? {}).sort()).toEqual([ + '@stock-bot/calculations', + '@stock-bot/stock-config', + '@stock-bot/types', + 'zod', + ]); + }); +}); + +describe('eventsTableToEventRows', () => { + const baseColumns = [ + 'listing_id', + 'ts', + 'known_at', + 'known_at_source', + 'kind', + 'subtype', + 'payload_json', + ]; + + it('maps valid rows, normalizes -0, and preserves null/string subtypes', () => { + const table: Table = { + columns: baseColumns, + rows: [ + { + listing_id: -0, + ts: makeUtcMs('2024-01-05', 22), + known_at: -0, + known_at_source: 'exact', + kind: 'filing', + subtype: '10-Q', + payload_json: '{}', + }, + { + listing_id: 42, + ts: makeUtcMs('2024-01-08', 22), + known_at: makeUtcMs('2024-01-08', 22), + known_at_source: 'exact', + kind: 'earnings', + subtype: null, + payload_json: '{}', + }, + ], + }; + + const rows = eventsTableToEventRows(table); + expect(rows).toEqual([ + { listingId: 0, knownAt: 0, kind: 'filing', subtype: '10-Q' }, + { listingId: 42, knownAt: makeUtcMs('2024-01-08', 22), kind: 'earnings', subtype: null }, + ]); + expect(Object.is(rows[0]!.listingId, 0)).toBe(true); + expect(Object.is(rows[0]!.knownAt, 0)).toBe(true); + }); + + it('applies exact-match kinds and subtypes allow-lists', () => { + const table: Table = { + columns: ['listing_id', 'known_at', 'kind', 'subtype'], + rows: [ + { listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' }, + { listing_id: 2, known_at: 2000, kind: 'filing', subtype: '10-K' }, + { listing_id: 3, known_at: 3000, kind: 'filing', subtype: null }, + { listing_id: 4, known_at: 4000, kind: 'earnings', subtype: '10-Q' }, + ], + }; + + expect(eventsTableToEventRows(table, { kinds: ['filing'] })).toHaveLength(3); + expect(eventsTableToEventRows(table, { subtypes: ['10-Q'] })).toEqual([ + { listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' }, + { listingId: 4, knownAt: 4000, kind: 'earnings', subtype: '10-Q' }, + ]); + expect( + eventsTableToEventRows(table, { kinds: ['filing'], subtypes: ['10-Q', '10-K'] }) + ).toEqual([ + { listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' }, + { listingId: 2, knownAt: 2000, kind: 'filing', subtype: '10-K' }, + ]); + }); + + it('validates all rows upfront even when they would be filtered out', () => { + const table: Table = { + columns: ['listing_id', 'known_at', 'kind', 'subtype'], + rows: [ + { listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' }, + { listing_id: 2, known_at: Number.NaN, kind: 'earnings', subtype: 'Q1' }, + ], + }; + + expectEventPanelError( + () => eventsTableToEventRows(table, { kinds: ['filing'] }), + 'invalid_event' + ); + }); + + it('rejects malformed table, missing columns, invalid filter options, and malformed rows', () => { + expectEventPanelError( + () => eventsTableToEventRows(null as unknown as Table), + 'invalid_input' + ); + expectEventPanelError( + () => eventsTableToEventRows({ columns: ['listing_id', 'known_at', 'kind'], rows: [] }), + 'invalid_input' + ); + + const validEmptyTable: Table = { + columns: ['listing_id', 'known_at', 'kind', 'subtype'], + rows: [], + }; + expectEventPanelError( + () => eventsTableToEventRows(validEmptyTable, { kinds: [] }), + 'invalid_option' + ); + expectEventPanelError( + () => eventsTableToEventRows(validEmptyTable, { subtypes: [] }), + 'invalid_option' + ); + expectEventPanelError( + () => + eventsTableToEventRows(validEmptyTable, { + kinds: ['unknown_kind' as unknown as 'filing'], + }), + 'invalid_option' + ); + expectEventPanelError( + () => + eventsTableToEventRows(validEmptyTable, { + subtypes: [123 as unknown as string], + }), + 'invalid_option' + ); + expectEventPanelError( + () => eventsTableToEventRows(validEmptyTable, [] as unknown as Record), + 'invalid_option' + ); + + const badRows: unknown[] = [ + null, + { listing_id: 1, known_at: 1000, kind: 'filing' }, // missing subtype + { listing_id: 1.5, known_at: 1000, kind: 'filing', subtype: '10-Q' }, + { listing_id: 2_147_483_648, known_at: 1000, kind: 'filing', subtype: '10-Q' }, + { listing_id: 1, known_at: Number.POSITIVE_INFINITY, kind: 'filing', subtype: '10-Q' }, + { listing_id: 1, known_at: 1000, kind: 'bad_kind', subtype: '10-Q' }, + { listing_id: 1, known_at: 1000, kind: 'filing', subtype: 99 }, + ]; + for (const badRow of badRows) { + expectEventPanelError( + () => + eventsTableToEventRows({ + columns: ['listing_id', 'known_at', 'kind', 'subtype'], + rows: [badRow as Table['rows'][number]], + }), + 'invalid_event' + ); + } + }); +}); + +describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and invariants', () => { + it('computes consecutive-session simple returns, sets NaN on gaps/resumption, and handles equal_weight benchmark', () => { + const dates = makeBusinessDates('2024-01-02', 5); // 5 sessions: d0..d4 + const bars: BarRecord[] = [ + // Listing 10: present on all 5 sessions + makeBar(10, dates[0]!, 100), + makeBar(10, dates[1]!, 110), // +10% + makeBar(10, dates[2]!, 99), // -10% + makeBar(10, dates[3]!, 99), // 0% + makeBar(10, dates[4]!, 108.9), // +10% + // Listing 20: missing on d2 -> d2 is NaN AND d3 (resumption) is NaN; d4 is 120/100 - 1 = +20% + makeBar(20, dates[0]!, 50), + makeBar(20, dates[1]!, 60), // +20% + makeBar(20, dates[3]!, 100), + makeBar(20, dates[4]!, 120), // +20% + ]; + + const events: EventObservation[] = [ + { listingId: 10, knownAt: makeUtcMs(dates[1]!, 21), kind: 'filing', subtype: '10-Q' }, + ]; + + const exchangeCalendars = makeExchangeCalendars([10, 20], dates); + + const resNone = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: '2024-02-01', + exchangeCalendars, + }); + + expect(resNone.input.sessionDates).toEqual(dates); + expect('benchmarkReturns' in resNone.input).toBe(false); + expect(Array.from(resNone.input.entityReturns.keys())).toEqual([10, 20]); + + const r10 = resNone.input.entityReturns.get(10)!; + const r20 = resNone.input.entityReturns.get(20)!; + expect(Number.isNaN(r10[0]!)).toBe(true); + expect(r10[1]!).toBeCloseTo(0.1, 12); + expect(r10[2]!).toBeCloseTo(-0.1, 12); + expect(r10[3]!).toBe(0); + expect(r10[4]!).toBeCloseTo(0.1, 12); + + expect(Number.isNaN(r20[0]!)).toBe(true); + expect(r20[1]!).toBeCloseTo(0.2, 12); + expect(Number.isNaN(r20[2]!)).toBe(true); + expect(Number.isNaN(r20[3]!)).toBe(true); + expect(r20[4]!).toBeCloseTo(0.2, 12); + + const resEq = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: '2024-02-01', + benchmark: 'equal_weight', + exchangeCalendars, + }); + expect(resEq.input.benchmarkReturns).toBeInstanceOf(Float64Array); + const b = resEq.input.benchmarkReturns!; + expect(Number.isNaN(b[0]!)).toBe(true); + expect(b[1]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2 + expect(b[2]!).toBeCloseTo(-0.1, 12); // only listing 10 finite + expect(b[3]!).toBe(0); // only listing 10 finite + expect(b[4]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2 + }); + + it('writes NaN (never Infinity) for non-positive, non-finite, or overflowing closes and passes eventStudy', () => { + const dates = makeBusinessDates('2024-01-02', 6); + const bars: BarRecord[] = [ + makeBar(1, dates[0]!, 10), + makeBar(1, dates[1]!, 0), // non-positive + makeBar(1, dates[2]!, -5), // non-positive + makeBar(1, dates[3]!, Number.NaN), // non-finite + makeBar(1, dates[4]!, 1e-308), + makeBar(1, dates[5]!, 1e308), // close[5]/close[4] overflows to +Infinity + ]; + + const res = buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-02-01', + benchmark: 'equal_weight', + exchangeCalendars: makeExchangeCalendars([1], dates), + }); + + const series = res.input.entityReturns.get(1)!; + for (let t = 0; t < dates.length; t += 1) { + expect(Number.isNaN(series[t]!)).toBe(true); + expect(Number.isNaN(res.input.benchmarkReturns![t]!)).toBe(true); + } + expect(res.diagnostics.nonPositiveCloseReturns).toBe(5); + + // Must not throw NON_FINITE_RETURN in eventStudy. + const study = eventStudy(res.input, { preDays: 1, postDays: 1, minEvents: 1 }); + expect(study.status).toBe('insufficient_data'); + }); + + it('anchors after-close, weekend, and holiday events to the next session and matches eventDayIndex exactly', () => { + // Include a Friday -> Monday weekend and a Wednesday holiday (skip 2024-01-10). + const dates = ['2024-01-05', '2024-01-08', '2024-01-09', '2024-01-11', '2024-01-12']; + const bars: BarRecord[] = []; + for (const d of dates) { + bars.push(makeBar(1, d, 100, 21)); // 16:00 ET = 21:00 UTC + bars.push(makeBar(2, d, 50, 21)); + } + + const sessionMaxTs = Float64Array.from(dates.map(d => makeUtcMs(d, 21))); + const probeTimestamps: Array<{ listingId: number; knownAt: number; expectedIdx: number | null }> = [ + // Pre-market on first session -> day 0 + { listingId: 1, knownAt: makeUtcMs('2024-01-05', 13), expectedIdx: 0 }, + // Exact close on Friday -> day 0 + { listingId: 2, knownAt: makeUtcMs('2024-01-05', 21), expectedIdx: 0 }, + // After-close Friday 17:00 ET (22:00 UTC) -> Monday (day 1) + { listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), expectedIdx: 1 }, + // Saturday morning -> Monday (day 1) + { listingId: 2, knownAt: makeUtcMs('2024-01-06', 14), expectedIdx: 1 }, + // After-close Tuesday 21:00:00.001 UTC -> Thursday (day 3, skipping Wednesday holiday) + { listingId: 1, knownAt: makeUtcMs('2024-01-09', 21, 0, 0, 1), expectedIdx: 3 }, + // Holiday Wednesday -> Thursday (day 3) + { listingId: 2, knownAt: makeUtcMs('2024-01-10', 15), expectedIdx: 3 }, + // After-close Friday last session (22:00 UTC < Saturday cutoff 00:00Z) -> droppedAfterLastSession + { listingId: 1, knownAt: makeUtcMs('2024-01-12', 22), expectedIdx: null }, + ]; + + // Verify exact equivalence with eventDayIndex from @stock-bot/calculations. + for (const p of probeTimestamps) { + const ref = eventDayIndex(sessionMaxTs, p.knownAt); + if (p.expectedIdx === null) { + expect(ref).toEqual({ status: 'no_session', reason: 'after_last_session' }); + } else { + expect(ref).toEqual({ status: 'ok', dayIndex: p.expectedIdx }); + } + } + + const events: EventObservation[] = probeTimestamps.map(p => ({ + listingId: p.listingId, + knownAt: p.knownAt, + kind: 'filing', + subtype: '10-Q', + })); + + const res = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: '2024-01-13', + exchangeCalendars: makeExchangeCalendars([1, 2], dates), + }); + + expect(res.input.events).toEqual([ + { entityId: 1, dayIndex: 0 }, + { entityId: 2, dayIndex: 0 }, + { entityId: 1, dayIndex: 1 }, + { entityId: 2, dayIndex: 1 }, + { entityId: 1, dayIndex: 3 }, + { entityId: 2, dayIndex: 3 }, + ]); + expect(res.diagnostics.droppedAfterLastSession).toBe(1); + expect(res.diagnostics.vaultExcludedEvents).toBe(0); + expect(res.diagnostics.droppedUnknownListing).toBe(0); + expect(res.diagnostics.duplicateEvents).toBe(0); + }); + + it('deduplicates exact duplicate bars and rejects conflicting duplicates', () => { + const dates = makeBusinessDates('2024-01-02', 3); + const b0 = makeBar(1, dates[0]!, 10); + const b1 = makeBar(1, dates[1]!, 12); + const b2 = makeBar(1, dates[2]!, Number.NaN); + + const exchangeCalendars = makeExchangeCalendars([1], dates); + + const exactDup = buildEventStudyInput({ + bars: [b0, { ...b0 }, b1, b2, { ...b2 }], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars, + }); + expect(exactDup.diagnostics.duplicateBars).toBe(2); + expect(exactDup.input.entityReturns.get(1)![1]).toBeCloseTo(0.2, 12); + + // Conflicting close + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [b0, { ...b0, close: 10.01 }, b1], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars, + }), + 'duplicate_bar' + ); + + // Conflicting timestamp on same UTC date + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars, + }), + 'duplicate_bar' + ); + }); + + it('enforces Vault exclusion without ever reading post-cutoff bar.close and obeys event conservation', () => { + const dates = makeBusinessDates('2024-01-02', 6); // d0..d3 pre-cutoff, d4..d5 post-cutoff + const vaultCutoffDate = dates[4]!; + let postCutoffCloseReads = 0; + + const makeTrappedPostCutoffBar = (listingId: number, date: string): BarRecord => { + const ts = makeUtcMs(date, 21); + const bar = { + listingId, + ts, + open: 999, + high: 999, + low: 999, + volume: 100, + vwap: 999, + knownAt: ts, + }; + Object.defineProperty(bar, 'close', { + enumerable: true, + get() { + postCutoffCloseReads += 1; + throw new Error('Vault violation: post-cutoff bar.close was accessed!'); + }, + }); + return bar as unknown as BarRecord; + }; + + const preBars: BarRecord[] = []; + for (let t = 0; t < 4; t += 1) { + preBars.push(makeBar(10, dates[t]!, 100 + t * 5)); + } + const postBars: BarRecord[] = [ + makeTrappedPostCutoffBar(10, dates[4]!), + makeTrappedPostCutoffBar(10, dates[5]!), + makeTrappedPostCutoffBar(99, dates[4]!), // listing only exists post-cutoff + ]; + + const events: EventObservation[] = [ + // Valid event -> day 1 + { listingId: 10, knownAt: makeUtcMs(dates[0]!, 22), kind: 'filing', subtype: '10-Q' }, + // Duplicate event anchoring to day 1 (different timestamp on same pre-market morning) + { listingId: 10, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' }, + // Unknown listing (pre-cutoff) -> droppedUnknownListing + { listingId: 99, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' }, + // After last pre-cutoff session close, but still < vaultCutoffMs -> droppedAfterLastSession + { listingId: 10, knownAt: makeUtcMs(dates[3]!, 22), kind: 'filing', subtype: '10-Q' }, + // Exact vaultCutoffDate 00:00:00.000Z (even for unknown listing) -> vaultExcludedEvents + { listingId: 99, knownAt: makeUtcMs(vaultCutoffDate, 0), kind: 'filing', subtype: '10-Q' }, + // After vaultCutoffDate -> vaultExcludedEvents + { listingId: 10, knownAt: makeUtcMs(dates[5]!, 22), kind: 'filing', subtype: '10-Q' }, + ]; + + const exchangeCalendars = makeExchangeCalendars([10], dates); + + const trappedResult = buildEventStudyInput({ + bars: [...preBars, ...postBars], + events, + vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars, + }); + + expect(postCutoffCloseReads).toBe(0); + expect(trappedResult.input.sessionDates).toEqual(dates.slice(0, 4)); + expect(trappedResult.input.events).toEqual([{ entityId: 10, dayIndex: 1 }]); + expect(trappedResult.diagnostics).toEqual({ + vaultExcludedDates: 2, + vaultExcludedEvents: 2, + droppedUnknownListing: 1, + droppedAfterLastSession: 1, + droppedMissingCalendarSession: 0, + duplicateEvents: 1, + duplicateBars: 0, + nonPositiveCloseReturns: 0, + }); + + // Event conservation identity + const d = trappedResult.diagnostics; + expect( + trappedResult.input.events.length + + d.vaultExcludedEvents + + d.droppedUnknownListing + + d.droppedAfterLastSession + + d.droppedMissingCalendarSession + + d.duplicateEvents + ).toBe(events.length); + + // Poisoned post-cutoff bars/events leave pre-cutoff input byte-identical + const poisonedResult = buildEventStudyInput({ + bars: [ + ...preBars, + makeBar(10, dates[4]!, 999_999), + makeBar(10, dates[5]!, Number.NaN), + ], + events: [ + ...events.slice(0, 4), + { listingId: 10, knownAt: makeUtcMs(dates[4]!, 22), kind: 'filing', subtype: '10-K' }, + ], + vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars, + }); + expectBitIdenticalEventStudyInput(poisonedResult.input, trappedResult.input); + }); + + it('is bit-identical under arbitrary permutations and never mutates frozen inputs', () => { + const dates = makeBusinessDates('2024-01-02', 8); + const bars: BarRecord[] = []; + const events: EventObservation[] = []; + for (const lid of [30, 10, 20]) { + for (let t = 0; t < dates.length; t += 1) { + if (lid === 20 && t === 3) { + continue; // gap + } + bars.push(makeBar(lid, dates[t]!, 20 + lid + t * 0.75)); + } + events.push({ + listingId: lid, + knownAt: makeUtcMs(dates[1]!, 22), + kind: 'filing', + subtype: '10-Q', + }); + events.push({ + listingId: lid, + knownAt: makeUtcMs(dates[4]!, 15), + kind: 'filing', + subtype: '8-K', + }); + } + + const exchangeCalendars = makeExchangeCalendars([10, 20, 30], dates); + const frozenBars = Object.freeze(bars.map(b => Object.freeze({ ...b }))); + const frozenEvents = Object.freeze(events.map(e => Object.freeze({ ...e }))); + const frozenParams = Object.freeze({ + bars: frozenBars, + events: frozenEvents, + vaultCutoffDate: dates[6]!, + benchmark: 'equal_weight' as const, + exchangeCalendars, + }); + + const baseline = buildEventStudyInput(frozenParams); + for (const seed of [1, 42, 999, 20261129]) { + const permuted = buildEventStudyInput({ + bars: shuffle(bars, seed), + events: shuffle(events, seed + 17), + vaultCutoffDate: dates[6]!, + benchmark: 'equal_weight', + exchangeCalendars, + }); + expectBitIdenticalEventStudyInput(permuted.input, baseline.input); + expect(permuted.diagnostics).toEqual(baseline.diagnostics); + expect(Array.from(permuted.input.entityReturns.keys())).toEqual([10, 20, 30]); + } + }); + + it('handles empty and post-cutoff-only inputs cleanly', () => { + const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} }; + const emptyRes = buildEventStudyInput({ + bars: [], + events: [ + { listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), kind: 'filing', subtype: '10-Q' }, + { listingId: 1, knownAt: makeUtcMs('2024-02-01', 0), kind: 'filing', subtype: '10-Q' }, + ], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, + }); + expect(emptyRes.input.sessionDates).toEqual([]); + expect(emptyRes.input.entityReturns.size).toBe(0); + expect(emptyRes.input.events).toEqual([]); + expect('benchmarkReturns' in emptyRes.input).toBe(false); + expect(emptyRes.diagnostics).toEqual({ + vaultExcludedDates: 0, + vaultExcludedEvents: 1, + droppedUnknownListing: 1, + droppedAfterLastSession: 0, + droppedMissingCalendarSession: 0, + duplicateEvents: 0, + duplicateBars: 0, + nonPositiveCloseReturns: 0, + }); + + const postOnlyRes = buildEventStudyInput({ + bars: [makeBar(1, '2024-02-01', 100), makeBar(1, '2024-02-02', 105)], + events: [], + vaultCutoffDate: '2024-02-01', + benchmark: 'equal_weight', + exchangeCalendars: emptyCalendars, + }); + expect(postOnlyRes.input.sessionDates).toEqual([]); + expect(postOnlyRes.input.benchmarkReturns).toEqual(new Float64Array(0)); + expect(postOnlyRes.diagnostics.vaultExcludedDates).toBe(2); + }); + + it('throws typed EventPanelError for every remaining validation error code', () => { + const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} }; + expectEventPanelError( + () => buildEventStudyInput(null as unknown as Parameters[0]), + 'invalid_input' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars: 'not-array' as unknown as BarRecord[], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, + }), + 'invalid_input' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: 'not-array' as unknown as EventObservation[], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, + }), + 'invalid_input' + ); + + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024-02-30', + exchangeCalendars: emptyCalendars, + }), + 'invalid_date' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024/02/01', + exchangeCalendars: emptyCalendars, + }), + 'invalid_date' + ); + + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024-02-01', + benchmark: 'cap_weight' as unknown as 'none', + exchangeCalendars: emptyCalendars, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024-02-01', + benchmark: null as unknown as 'none', + exchangeCalendars: emptyCalendars, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: undefined as unknown as EventStudyExchangeCalendars, + }), + 'invalid_option' + ); + + const goodBar = makeBar(1, '2024-01-05', 10); + for (const badBar of [ + null, + { ...goodBar, listingId: 1.5 }, + { ...goodBar, ts: Number.NaN }, + { ...goodBar, knownAt: Number.POSITIVE_INFINITY }, + { ...goodBar, close: '10' }, + ]) { + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [badBar as BarRecord], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, + }), + 'invalid_bar' + ); + } + + const goodEv: EventObservation = { + listingId: 1, + knownAt: makeUtcMs('2024-01-05', 22), + kind: 'filing', + subtype: '10-Q', + }; + for (const badEv of [ + null, + { ...goodEv, listingId: 2_147_483_648 }, + { ...goodEv, knownAt: Number.NaN }, + { ...goodEv, kind: 'not_a_kind' }, + { ...goodEv, subtype: 42 }, + ]) { + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [badEv as EventObservation], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, + }), + 'invalid_event' + ); + } + }); + + it('uses caller-supplied exchangeCalendars for half-day US vs CA close times and cross-border holidays', () => { + // Black Friday 2024-11-29: curated bars_1d.ts stamps BOTH NYSE and TSX at 16:00 ET (21:00 UTC), + // even though NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at 16:00 ET (21:00 UTC). + // Also include US Thanksgiving 2024-11-28 (TSX open, NYSE closed). + const sharedDates = ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02', '2024-12-03']; + const nyseId = 10_001; + const tsxId = 50_001; + + const bars: BarRecord[] = [ + // NYSE bars (closed 2024-11-28; half-day 2024-11-29 still stamped 21:00 UTC by curator) + makeBar(nyseId, '2024-11-27', 100, 21), + makeBar(nyseId, '2024-11-29', 102, 21), + makeBar(nyseId, '2024-12-02', 105, 21), + makeBar(nyseId, '2024-12-03', 106, 21), + // TSX bars (open all 5 days, stamped 21:00 UTC) + makeBar(tsxId, '2024-11-27', 50, 21), + makeBar(tsxId, '2024-11-28', 50.5, 21), + makeBar(tsxId, '2024-11-29', 51, 21), + makeBar(tsxId, '2024-12-02', 52, 21), + makeBar(tsxId, '2024-12-03', 52.5, 21), + ]; + + const nyseCalendar = [ + { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET + { date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET early close + { date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET + { date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET + ]; + const tsxCalendar = [ + { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET + { date: '2024-11-28', closeTs: makeUtcMs('2024-11-28', 21) }, // 16:00 ET (US holiday) + { date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 21) }, // 16:00 ET (normal close) + { date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET + { date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET + ]; + + // Filing published at 14:00 ET (19:00 UTC) on Friday 2024-11-29: + // - NYSE already closed at 13:00 ET (18:00 UTC) -> MUST anchor to Monday 2024-12-02 (index 3). + // - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2024-11-29 (index 2). + // Filing published at 12:30 ET (17:30 UTC) on Friday 2024-11-29 for NYSE -> anchors to Friday 2024-11-29 (index 2). + // Filing published on US Thanksgiving 2024-11-28 at 10:00 ET (15:00 UTC): + // - NYSE closed -> anchors to Friday 2024-11-29 (index 2, collapses with 12:30 ET NYSE event). + // - TSX open -> anchors to Thursday 2024-11-28 (index 1). + const events: EventObservation[] = [ + { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' }, + { listingId: tsxId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: 'interim_financial_statements' }, + { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 17, 30), kind: 'filing', subtype: '10-q' }, + { listingId: nyseId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: '10-q' }, + { listingId: tsxId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: 'interim_financial_statements' }, + ]; + + const mapResult = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: '2024-12-04', + exchangeCalendars: { + calendars: new Map([ + ['XNYS', nyseCalendar], + ['XTSE', tsxCalendar], + ]), + listingCalendarId: new Map([ + [nyseId, 'XNYS'], + [tsxId, 'XTSE'], + ]), + }, + }); + + expect(mapResult.input.sessionDates).toEqual(sharedDates); + expect(mapResult.input.events).toEqual([ + { entityId: tsxId, dayIndex: 1 }, // 2024-11-28 + { entityId: nyseId, dayIndex: 2 }, // 2024-11-29 (12:30 ET & Thanksgiving deduped) + { entityId: tsxId, dayIndex: 2 }, // 2024-11-29 (14:00 ET still before TSX 16:00 ET close) + { entityId: nyseId, dayIndex: 3 }, // 2024-12-02 (14:00 ET after NYSE 13:00 ET close) + ]); + // Cross-border holiday: NYSE was closed on Thanksgiving 2024-11-28, so its Friday + // 2024-11-29 return (index 2) is a valid 1-session NYSE return (102 / 100 - 1 = 0.02). + const nyseRets = mapResult.input.entityReturns.get(nyseId)!; + expect(Number.isNaN(nyseRets[1]!)).toBe(true); + expect(nyseRets[2]!).toBeCloseTo(0.02, 12); + expect(nyseRets[3]!).toBeCloseTo(105 / 102 - 1, 12); + expect(mapResult.diagnostics.duplicateEvents).toBe(1); + expect(mapResult.diagnostics.droppedAfterLastSession).toBe(0); + expect(mapResult.diagnostics.droppedMissingCalendarSession).toBe(0); + + // Record-based calendars with shuffled sessions/bars/events produce bit-identical output. + const recordResult = buildEventStudyInput({ + bars: shuffle(bars, 7), + events: shuffle(events, 11), + vaultCutoffDate: '2024-12-04', + exchangeCalendars: { + calendars: { + XNYS: shuffle(nyseCalendar, 13), + XTSE: shuffle(tsxCalendar, 17), + }, + listingCalendarId: { + [nyseId]: 'XNYS', + [tsxId]: 'XTSE', + }, + }, + }); + expectBitIdenticalEventStudyInput(recordResult.input, mapResult.input); + expect(recordResult.diagnostics).toEqual(mapResult.diagnostics); + + // NYSE-only study: filing at 14:00 ET on 2024-11-29 anchors to Monday 2024-12-02 (index 2 in NYSE-only dates), + // even though curated bars_1d.ts for 2024-11-29 is stamped at 16:00 ET (21:00 UTC). + const nyseOnly = buildEventStudyInput({ + bars: bars.filter(b => b.listingId === nyseId), + events: [ + { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' }, + ], + vaultCutoffDate: '2024-12-04', + exchangeCalendars: { + calendars: { XNYS: nyseCalendar }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }); + expect(nyseOnly.input.sessionDates).toEqual(['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03']); + expect(nyseOnly.input.events).toEqual([{ entityId: nyseId, dayIndex: 2 }]); // 2024-12-02 + }); + + it('enforces Vault fencing, drop counters, and strict validation on exchangeCalendars', () => { + const nyseId = 10_001; + const bars = [ + makeBar(nyseId, '2024-11-27', 100, 21), + makeBar(nyseId, '2024-11-29', 102, 21), + ]; + const nyseCalendar = [ + { date: '2024-11-26', closeTs: makeUtcMs('2024-11-26', 21) }, // before first bar -> droppedMissingCalendarSession + { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, + { date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET half-day + { date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // post-cutoff (excluded from calendar) + ]; + + const res = buildEventStudyInput({ + bars, + events: [ + // Anchors to 2024-11-26 which has no bar in sessionDates -> droppedMissingCalendarSession + { listingId: nyseId, knownAt: makeUtcMs('2024-11-26', 15), kind: 'filing', subtype: '10-q' }, + // 14:00 ET on 2024-11-29 is after 13:00 ET close; 2024-12-02 is Vault-excluded -> droppedAfterLastSession + { listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' }, + ], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: { + calendars: { XNYS: nyseCalendar }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }); + + expect(res.input.events).toEqual([]); + expect(res.diagnostics.droppedMissingCalendarSession).toBe(1); + expect(res.diagnostics.droppedAfterLastSession).toBe(1); + expect(res.diagnostics.vaultExcludedEvents).toBe(0); + + // Invalid exchangeCalendars shapes and values + expectEventPanelError( + () => + buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: null as unknown as NonNullable< + Parameters[0]['exchangeCalendars'] + >, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: { + calendars: { + XNYS: [{ date: '2024-02-30', closeTs: makeUtcMs('2024-02-28', 21) }], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_date' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: { + calendars: { + XNYS: [ + { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, + { date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, + ], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: { + calendars: { + XNYS: [ + { date: '2024-11-27', closeTs: makeUtcMs('2024-11-29', 21) }, + { date: '2024-11-29', closeTs: makeUtcMs('2024-11-27', 21) }, + ], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: { + calendars: { XNYS: nyseCalendar }, + listingCalendarId: { [nyseId]: 'UNKNOWN_CAL' }, + }, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-12-02', + exchangeCalendars: { + calendars: { XNYS: nyseCalendar }, + listingCalendarId: {}, + }, + }), + 'invalid_option' + ); + }); + + it('rejects incomplete exchange calendar coverage when a calendar starts after or omits pre-Vault bar dates', () => { + const nyseId = 10_001; + const dec2023AndJan2024Bars: BarRecord[] = [ + makeBar(nyseId, '2023-12-28', 100, 21), + makeBar(nyseId, '2023-12-29', 101, 21), + makeBar(nyseId, '2024-01-02', 103, 21), + makeBar(nyseId, '2024-01-03', 104, 21), + ]; + + // Calendar starts on Jan 2, 2024 while bars include December 2023 -> must throw invalid_option. + expectEventPanelError( + () => + buildEventStudyInput({ + bars: dec2023AndJan2024Bars, + events: [ + { + listingId: nyseId, + knownAt: makeUtcMs('2023-12-29', 19), // 14:00 ET on Dec 29 + kind: 'filing', + subtype: '10-q', + }, + ], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: { + calendars: { + XNYS: [ + { date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) }, + { date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) }, + ], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_option' + ); + + // Calendar omits a mid-history bar session (2023-12-29) -> must throw invalid_option. + expectEventPanelError( + () => + buildEventStudyInput({ + bars: dec2023AndJan2024Bars, + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: { + calendars: { + XNYS: [ + { date: '2023-12-28', closeTs: makeUtcMs('2023-12-28', 21) }, + { date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) }, + { date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) }, + ], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_option' + ); + }); + + it('uses exchange-calendar adjacency so a missing open session for all listings yields NaN on the next bar', () => { + // Exchange is open Mon, Tue, Wed, Thu, but bars exist only on Mon, Wed, Thu (Tue missing for ALL listings). + const mon = '2024-01-08'; + const tue = '2024-01-09'; + const wed = '2024-01-10'; + const thu = '2024-01-11'; + const bars: BarRecord[] = [ + makeBar(10, mon, 100), + makeBar(10, wed, 110), + makeBar(10, thu, 121), + makeBar(20, mon, 50), + makeBar(20, wed, 55), + makeBar(20, thu, 60.5), + ]; + + const res = buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-02-01', + benchmark: 'equal_weight', + exchangeCalendars: makeExchangeCalendars([10, 20], [mon, tue, wed, thu]), + }); + + // sessionDates contains only observed bar dates [Mon, Wed, Thu]. + expect(res.input.sessionDates).toEqual([mon, wed, thu]); + + const r10 = res.input.entityReturns.get(10)!; + const r20 = res.input.entityReturns.get(20)!; + const bench = res.input.benchmarkReturns!; + + // Mon (index 0): NaN (first bar) + expect(Number.isNaN(r10[0]!)).toBe(true); + expect(Number.isNaN(r20[0]!)).toBe(true); + expect(Number.isNaN(bench[0]!)).toBe(true); + + // Wed (index 1): MUST be NaN because Tue was an open exchange session (not consecutive). + expect(Number.isNaN(r10[1]!)).toBe(true); + expect(Number.isNaN(r20[1]!)).toBe(true); + expect(Number.isNaN(bench[1]!)).toBe(true); + + // Thu (index 2): consecutive with Wed -> valid +10% return. + expect(r10[2]!).toBeCloseTo(0.1, 12); + expect(r20[2]!).toBeCloseTo(0.1, 12); + expect(bench[2]!).toBeCloseTo(0.1, 12); + }); +});