/** * 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 calendar sessions (`currSessionIdx === prevSessionIdx + 1`) * where both closes are finite and `> 0` and the resulting return is finite. * - `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`. * - Remaining events for known listings anchor strictly to the first pre-Vault * session whose close timestamp `sessionMaxTs[d] >= knownAt` (matching * `eventDayIndex` semantics). An after-close event (e.g. `17:00 ET`) 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'; /** Input contract for {@link buildEventStudyInput}. */ export interface BuildEventStudyInputParams { readonly bars: readonly BarRecord[]; readonly events: readonly EventObservation[]; readonly vaultCutoffDate: string; readonly benchmark?: EventStudyBenchmarkMode; } /** Per-run diagnostic counters reported by {@link buildEventStudyInput}. */ export interface EventPanelDiagnostics { readonly vaultExcludedDates: number; readonly vaultExcludedEvents: number; readonly droppedUnknownListing: number; readonly droppedAfterLastSession: 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; } function parseStrictCalendarDayKey(value: unknown, field: string): number { return parseCalendarDayKey(value, field, (message, cause) => new EventPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined) ); } /** * 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 benchmark: EventStudyBenchmarkMode = params.benchmark ?? 'none'; if (benchmark !== 'none' && benchmark !== 'equal_weight') { throw new EventPanelError( 'invalid_option', `Invalid benchmark "${String(benchmark)}": expected "none" or "equal_weight".` ); } 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 preCutoffDayMaxTs = new Map(); 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.`); } const prevMaxTs = preCutoffDayMaxTs.get(dayKey); if (prevMaxTs === undefined || ts > prevMaxTs) { preCutoffDayMaxTs.set(dayKey, ts); } 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, duplicateEvents: 0, duplicateBars: 0, nonPositiveCloseReturns: 0, }, }; } // Build strictly ascending pre-cutoff session calendar. const preCount = preCutoffDayMaxTs.size; const preDayKeys = new Int32Array(preCount); { let idx = 0; for (const dayKey of preCutoffDayMaxTs.keys()) { preDayKeys[idx] = dayKey; idx += 1; } preDayKeys.sort(); } const sessionMaxTs = new Float64Array(preCount); const sessionDates: string[] = new Array(preCount); for (let i = 0; i < preCount; i += 1) { const dk = preDayKeys[i] as number; sessionMaxTs[i] = preCutoffDayMaxTs.get(dk) as number; sessionDates[i] = formatDayKeyUtc(dk); } // Validate sessionMaxTs once against eventDayIndex so the per-event O(log T) lower-bound // search matches eventDayIndex semantics without repeating its O(T) calendar scan. eventDayIndex(sessionMaxTs, sessionMaxTs[0] 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 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; const returns = new Float64Array(preCount); returns.fill(Number.NaN); for (let i = bStart + 1; i < uniqueEnd; i += 1) { const prevSIdx = barSessionIdx[i - 1] as number; const currSIdx = barSessionIdx[i] as number; if (currSIdx !== prevSIdx + 1) { 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) anchor. const lastSessionMaxTs = sessionMaxTs[preCount - 1] as number; const candDay = new Int32Array(events.length); const candListing = new Int32Array(events.length); let candCount = 0; let vaultExcludedEvents = 0; let droppedUnknownListing = 0; let droppedAfterLastSession = 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 l = listingIdToIdx.get(normalizeZero(ev.listingId)); if (l === undefined) { droppedUnknownListing += 1; continue; } if (knownAt > lastSessionMaxTs) { droppedAfterLastSession += 1; continue; } // Lower-bound binary search: first session index with sessionMaxTs[lo] >= knownAt. let lo = 0; let hi = preCount - 1; while (lo < hi) { const mid = (lo + hi) >>> 1; if ((sessionMaxTs[mid] as number) < knownAt) { lo = mid + 1; } else { hi = mid; } } candDay[candCount] = lo; 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, duplicateEvents, duplicateBars, nonPositiveCloseReturns, }, }; }