diff --git a/libs/calculations/README.md b/libs/calculations/README.md index a26ced06..3005977d 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -57,8 +57,11 @@ const risk = returnStatistics(returns); and cross-sectional Signal Analysis (`analyzeSignalPanel`, `crossSectionIc`, `neweyWestMeanTest`, `defaultNeweyWestLag`, `summarizeIcSeries`, `evaluateRecencyGate`, `SignalAnalysisError`, `DEFAULT_MIN_CROSS_SECTION`, `DEFAULT_QUANTILE_COUNT`, - `RECENCY_SPLIT_DATE`, `RECENCY_MIN_RATIO`) are exported from both `./analytics` and - the root entry. + `RECENCY_SPLIT_DATE`, `RECENCY_MIN_RATIO`), plus pure Event-Study math (`eventDayIndex`, + `eventStudy`, `EventStudyError`, `DEFAULT_EVENT_PRE_DAYS`, `DEFAULT_EVENT_POST_DAYS`, + `DEFAULT_EVENT_MIN_EVENTS`) with date-clustered Newey-West significance, R-7 CAR + percentile fans, and a sign-preserving post-2023 recency gate, are exported from both + `./analytics` and the root entry. ## Benchmark @@ -85,6 +88,20 @@ Observed locally on Bun 1.2.16 (2 runs, seed `20260402`): `1,779.96 ms` `8,353,819 observations/s`), `meanRankIc = 0.057294`, `rankIcTStat = 218.5078`, `spreadMean = 0.003369`, `recencyGatePassed = true`. +Run the fixed-seed Event Study benchmark (`2,000` entities × `5,040` sessions, +`200,000` events, window `-10..+20`, covering full `eventStudy` with benchmark-adjusted +AAR/CAAR, R-7 CAR percentile fans, date-clustered Newey-West HAC, and recency gate): + +```sh +bun run test:calculations +``` + +Observed locally on Bun 1.2.16 (2026-11-28, seed `20260404`): + +```text +[event-study benchmark] events=200000 window=-10..+20 elapsedMs=608.09 events/s=328896 +``` + The root entry exports the supported returns, indicators and market-data helpers. Use subpaths to avoid loading unrelated math. Shared domain types remain owned by `@stock-bot/types`; HTTP/date/proxy helpers remain in `@stock-bot/utils`. diff --git a/libs/calculations/src/analytics/event-study.ts b/libs/calculations/src/analytics/event-study.ts new file mode 100644 index 00000000..4935c617 --- /dev/null +++ b/libs/calculations/src/analytics/event-study.ts @@ -0,0 +1,1056 @@ +/** + * Pure, zero-I/O event-study math per `design/PLATFORM-PLAN.md`, `design/MILESTONES.md` (M1), + * and `design/VALIDATION-AND-RIGOR.md`. + * + * Covers: + * - Zero-look-ahead event timestamp to session index mapping (`eventDayIndex`) + * - Cross-sectional abnormal returns (raw or benchmark-adjusted) across `[-preDays, +postDays]` + * - Average abnormal return (AAR), cross-sectional standard error, cumulative AAR (`caar` and `caarFromZero`) + * - Per-offset R-7 CAR percentile fans (`p5`, `p25`, `p50`, `p75`, `p95`) + * - Date-clustered post-event `CAR[0..postDays]` significance via Newey-West HAC (`neweyWestMeanTest`) + * - Sign-preserving pre/post-2023 recency split and gate reusing `evaluateRecencyGate` + * + * Pure stateless math: zero I/O, zero wall-clock or random calls, bit-identical determinism + * via canonical `(dayIndex ASC, entityId ASC)` 2-pass counting sort, and reused typed-array + * scratch buffers on the offset hot path. + */ + +import { + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + evaluateRecencyGate, + neweyWestMeanTest, + type EntityId, + type IcSummary, + type NeweyWestResult, + type NumericSeries, + type RecencyGateReason, +} from './signal-analysis'; + +/** Default number of trading sessions before the event session (`-10`). */ +export const DEFAULT_EVENT_PRE_DAYS = 10; + +/** Default number of trading sessions after the event session (`+20`). */ +export const DEFAULT_EVENT_POST_DAYS = 20; + +/** Default minimum usable events required to run an event study. */ +export const DEFAULT_EVENT_MIN_EVENTS = 5; + +/** Machine-readable error codes thrown by {@link EventStudyError}. */ +export type EventStudyErrorCode = + | 'INVALID_OPTION' + | 'INVALID_DATE' + | 'UNSORTED_DATES' + | 'DUPLICATE_DATE' + | 'INVALID_TIMESTAMP' + | 'UNSORTED_TIMESTAMPS' + | 'LENGTH_MISMATCH' + | 'INVALID_EVENT' + | 'NON_FINITE_RETURN'; + +/** Typed validation error thrown for malformed event-study inputs or options. */ +export class EventStudyError extends RangeError { + readonly code: EventStudyErrorCode; + + constructor(code: EventStudyErrorCode, message: string) { + super(message); + this.name = 'EventStudyError'; + this.code = code; + } +} + +/** Result of mapping an event timestamp to the first eligible session close (`>= knownAtTs`). */ +export type EventDayIndexResult = + | { + readonly status: 'ok'; + readonly dayIndex: number; + } + | { + readonly status: 'no_session'; + readonly reason: 'empty_calendar' | 'after_last_session'; + }; + +/** Single event anchored to an entity and a zero-based session calendar index. */ +export interface EventStudyEvent { + readonly entityId: EntityId; + readonly dayIndex: number; +} + +/** Input panel and event list for {@link eventStudy}. */ +export interface EventStudyInput { + readonly sessionDates: readonly string[]; + readonly entityReturns: ReadonlyMap; + readonly benchmarkReturns?: NumericSeries; + readonly events: readonly EventStudyEvent[]; +} + +/** Configuration options for {@link eventStudy}. */ +export interface EventStudyOptions { + readonly preDays?: number; + readonly postDays?: number; + readonly minEvents?: number; + readonly neweyWestLag?: number; + readonly recencySplitDate?: string; + readonly recencyMinRatio?: number; +} + +/** Cross-sectional R-7 linear-interpolation percentiles of per-event CARs at one offset. */ +export interface EventStudyPercentiles { + readonly p5: number; + readonly p25: number; + readonly p50: number; + readonly p75: number; + readonly p95: number; +} + +/** Abnormal-return and cumulative-abnormal-return summary for a single event offset. */ +export interface EventStudyOffsetStats { + readonly offset: number; + readonly n: number; + readonly aar: number; + readonly standardError: number; + readonly caar: number; + readonly caarFromZero: number | null; + readonly carPercentiles: EventStudyPercentiles; + readonly postCarPercentiles: EventStudyPercentiles | null; +} + +/** Columnar per-event `CAR[0..postDays]` ordered canonically by `(dayIndex ASC, entityId ASC)`. */ +export interface EventCarSeries { + readonly entityIds: readonly EntityId[]; + readonly dayIndices: Int32Array; + readonly dates: readonly string[]; + readonly cars: Float64Array; +} + +/** Date-clustered post-event `CAR[0..postDays]` summary and Newey-West HAC test. */ +export interface DateClusteredCarResult { + readonly nDates: number; + readonly dates: readonly string[]; + readonly eventCounts: Int32Array; + readonly meanCars: Float64Array; + readonly carMean: number; + readonly neweyWest: NeweyWestResult; +} + +/** Explicit reason describing why the sign-preserving event-study recency gate passed or failed. */ +export type EventStudyRecencyReason = + | 'passed' + | 'empty_pre_window' + | 'empty_post_window' + | 'zero_pre_mean' + | 'sign_flipped' + | 'post_below_ratio_threshold'; + +/** Pass/fail outcome of the sign-preserving post-2023 event-study recency gate. */ +export interface EventStudyRecencyGate { + readonly pass: boolean; + readonly reason: EventStudyRecencyReason; + readonly ratio: number | null; +} + +/** Pre/post recency split summaries and sign-preserving gate decision on date-clustered CARs. */ +export interface EventStudyRecencyResult { + readonly splitDate: string; + readonly minRatio: number; + readonly pre: IcSummary; + readonly post: IcSummary; + readonly gate: EventStudyRecencyGate; +} + +/** Exact event-filtering accounting (`eventsIn === eventsUsed + all dropped/collapsed`). */ +export interface EventStudyDiagnostics { + readonly eventsIn: number; + readonly eventsUsed: number; + readonly droppedUnknownEntity: number; + readonly droppedWindowOutOfRange: number; + readonly droppedMissingReturns: number; + readonly duplicateEventsCollapsed: number; +} + +/** Output of {@link eventStudy}. Returns an `insufficient_data` variant instead of `NaN`. */ +export type EventStudyResult = + | { + readonly status: 'ok'; + readonly preDays: number; + readonly postDays: number; + readonly hasBenchmark: boolean; + readonly offsets: readonly EventStudyOffsetStats[]; + readonly eventCars: EventCarSeries; + readonly clustered: DateClusteredCarResult; + readonly recency: EventStudyRecencyResult; + readonly diagnostics: EventStudyDiagnostics; + } + | { + readonly status: 'insufficient_data'; + readonly reason: 'below_min_events' | 'too_few_event_dates'; + readonly preDays: number; + readonly postDays: number; + readonly hasBenchmark: boolean; + readonly eventsUsed: number; + readonly nDates: number; + readonly diagnostics: EventStudyDiagnostics; + }; + +const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function assertIsoDate(value: string, label: string): void { + if (typeof value !== 'string' || !ISO_DATE_RE.test(value)) { + throw new EventStudyError('INVALID_DATE', `${label} must be a valid YYYY-MM-DD date`); + } + const year = Number(value.slice(0, 4)); + const month = Number(value.slice(5, 7)); + const day = Number(value.slice(8, 10)); + if (month < 1 || month > 12) { + throw new EventStudyError('INVALID_DATE', `${label} has invalid month: ${value}`); + } + const baseDays = DAYS_IN_MONTH[month] ?? 0; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day < 1 || day > maxDay) { + throw new EventStudyError('INVALID_DATE', `${label} is not a valid calendar date: ${value}`); + } +} + +function assertIntegerOption(value: number, min: number, label: string): void { + if (typeof value !== 'number' || !Number.isInteger(value) || value < min) { + throw new EventStudyError( + 'INVALID_OPTION', + `${label} must be an integer >= ${min}, received ${String(value)}` + ); + } +} + +function assertPositiveFiniteOption(value: number, label: string): void { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) { + throw new EventStudyError( + 'INVALID_OPTION', + `${label} must be a finite number > 0, received ${String(value)}` + ); + } +} + +function assertValidEntityId(id: EntityId, label: string): void { + if (typeof id === 'string') { + return; + } + if (typeof id === 'number' && !Number.isNaN(id)) { + return; + } + throw new EventStudyError('INVALID_EVENT', `${label} must be a string or non-NaN number`); +} + +function assertReturnSeriesValid(series: NumericSeries, expectedLength: number, label: string): void { + if (series.length !== expectedLength) { + throw new EventStudyError( + 'LENGTH_MISMATCH', + `${label} length (${series.length}) does not match sessionDates length (${expectedLength})` + ); + } + for (let i = 0; i < expectedLength; i++) { + const v = series[i]; + if ( + typeof v !== 'number' || + v === Number.POSITIVE_INFINITY || + v === Number.NEGATIVE_INFINITY + ) { + throw new EventStudyError( + 'NON_FINITE_RETURN', + `${label}[${i}] must be a finite number or NaN, received ${String(v)}` + ); + } + } +} + +function compareIds(a: EntityId, b: EntityId): number { + const typeA = typeof a; + const typeB = typeof b; + if (typeA === typeB) { + return a < b ? -1 : a > b ? 1 : 0; + } + return typeA === 'number' ? -1 : 1; +} + +function insertionSortRange(buf: Float64Array, left: number, right: number): void { + for (let i = left + 1; i <= right; i++) { + const val = buf[i] as number; + let j = i - 1; + while (j >= left && (buf[j] as number) > val) { + buf[j + 1] = buf[j] as number; + j--; + } + buf[j + 1] = val; + } +} + +function siftDown(buf: Float64Array, offset: number, start: number, count: number): void { + let root = start; + while (true) { + const leftChild = (root << 1) + 1; + if (leftChild >= count) { + return; + } + let swapIdx = root; + if ((buf[offset + swapIdx] as number) < (buf[offset + leftChild] as number)) { + swapIdx = leftChild; + } + const rightChild = leftChild + 1; + if ( + rightChild < count && + (buf[offset + swapIdx] as number) < (buf[offset + rightChild] as number) + ) { + swapIdx = rightChild; + } + if (swapIdx === root) { + return; + } + const tmp = buf[offset + root] as number; + buf[offset + root] = buf[offset + swapIdx] as number; + buf[offset + swapIdx] = tmp; + root = swapIdx; + } +} + +function heapSortRange(buf: Float64Array, left: number, right: number): void { + const count = right - left + 1; + for (let start = (count - 2) >> 1; start >= 0; start--) { + siftDown(buf, left, start, count); + } + for (let end = count - 1; end > 0; end--) { + const tmp = buf[left + end] as number; + buf[left + end] = buf[left] as number; + buf[left] = tmp; + siftDown(buf, left, 0, end); + } +} + +function medianOfThree(a: number, b: number, c: number): number { + if (a < b) { + if (b < c) { + return b; + } + return a < c ? c : a; + } + if (a < c) { + return a; + } + return b < c ? c : b; +} + +function introselect(buf: Float64Array, leftInit: number, rightInit: number, k: number): void { + let left = leftInit; + let right = rightInit; + const span = right - left + 1; + let depthLimit = span > 1 ? 2 * Math.floor(Math.log2(span)) + 2 : 0; + + while (right - left > 16) { + if (depthLimit === 0) { + heapSortRange(buf, left, right); + return; + } + depthLimit--; + + const mid = (left + right) >>> 1; + const pivot = medianOfThree(buf[left] as number, buf[mid] as number, buf[right] as number); + + // 3-way partition so equal-value runs collapse in O(n). + let lt = left; + let i = left; + let gt = right; + while (i <= gt) { + const v = buf[i] as number; + if (v < pivot) { + buf[i] = buf[lt] as number; + buf[lt] = v; + lt++; + i++; + } else if (v > pivot) { + buf[i] = buf[gt] as number; + buf[gt] = v; + gt--; + } else { + i++; + } + } + + if (k < lt) { + right = lt - 1; + } else if (k > gt) { + left = gt + 1; + } else { + return; + } + } + + if (right > left) { + insertionSortRange(buf, left, right); + } +} + +function minInRange(buf: Float64Array, start: number, endInclusive: number): number { + let best = buf[start] as number; + for (let i = start + 1; i <= endInclusive; i++) { + const v = buf[i] as number; + if (v < best) { + best = v; + } + } + return best; +} + +function computeR7Percentiles(buf: Float64Array, length: number): EventStudyPercentiles { + const last = length - 1; + if (length < 65) { + insertionSortRange(buf, 0, last); + const pick = (q: number): number => { + const pos = q * last; + const lo = Math.floor(pos); + const hi = Math.ceil(pos); + const loVal = buf[lo] as number; + if (lo === hi) { + return loVal; + } + return loVal + (pos - lo) * ((buf[hi] as number) - loVal); + }; + return { + p5: pick(0.05), + p25: pick(0.25), + p50: pick(0.5), + p75: pick(0.75), + p95: pick(0.95), + }; + } + + const pos5 = 0.05 * last; + const pos25 = 0.25 * last; + const pos50 = 0.5 * last; + const pos75 = 0.75 * last; + const pos95 = 0.95 * last; + + const lo5 = Math.floor(pos5); + const lo25 = Math.floor(pos25); + const lo50 = Math.floor(pos50); + const lo75 = Math.floor(pos75); + const lo95 = Math.floor(pos95); + + // For length >= 65, lo5 < lo25 < lo50 < lo75 < lo95 < last are strictly separated. + introselect(buf, 0, last, lo50); + introselect(buf, 0, lo50 - 1, lo25); + introselect(buf, 0, lo25 - 1, lo5); + introselect(buf, lo50 + 1, last, lo75); + introselect(buf, lo75 + 1, last, lo95); + + const v5 = buf[lo5] as number; + const f5 = pos5 - lo5; + const p5 = f5 === 0 ? v5 : v5 + f5 * (minInRange(buf, lo5 + 1, lo25 - 1) - v5); + + const v25 = buf[lo25] as number; + const f25 = pos25 - lo25; + const p25 = f25 === 0 ? v25 : v25 + f25 * (minInRange(buf, lo25 + 1, lo50 - 1) - v25); + + const v50 = buf[lo50] as number; + const f50 = pos50 - lo50; + const p50 = f50 === 0 ? v50 : v50 + f50 * (minInRange(buf, lo50 + 1, lo75 - 1) - v50); + + const v75 = buf[lo75] as number; + const f75 = pos75 - lo75; + const p75 = f75 === 0 ? v75 : v75 + f75 * (minInRange(buf, lo75 + 1, lo95 - 1) - v75); + + const v95 = buf[lo95] as number; + const f95 = pos95 - lo95; + const p95 = f95 === 0 ? v95 : v95 + f95 * (minInRange(buf, lo95 + 1, last) - v95); + + return { p5, p25, p50, p75, p95 }; +} + +function mapRecencyReason(reason: RecencyGateReason): EventStudyRecencyReason { + switch (reason) { + case 'non_positive_pre_mean': + return 'zero_pre_mean'; + case 'non_positive_post_mean': + return 'sign_flipped'; + default: + return reason; + } +} + +/** + * Maps an event's information-availability timestamp (`knownAtTs`) to the first trading + * session whose close timestamp is `>= knownAtTs`. + * + * Enforces zero look-ahead: an event known strictly after session `k`'s close maps to + * session `k + 1`. Validates every timestamp in `sessionCloseTs` for finiteness and + * strict ascending order before running the lower-bound binary search. + */ +export function eventDayIndex( + sessionCloseTs: NumericSeries, + knownAtTs: number +): EventDayIndexResult { + if (typeof knownAtTs !== 'number' || !Number.isFinite(knownAtTs)) { + throw new EventStudyError( + 'INVALID_TIMESTAMP', + `knownAtTs must be a finite number, received ${String(knownAtTs)}` + ); + } + + const n = sessionCloseTs.length; + for (let i = 0; i < n; i++) { + const ts = sessionCloseTs[i]; + if (typeof ts !== 'number' || !Number.isFinite(ts)) { + throw new EventStudyError( + 'INVALID_TIMESTAMP', + `sessionCloseTs[${i}] must be a finite number, received ${String(ts)}` + ); + } + if (i > 0 && ts <= (sessionCloseTs[i - 1] as number)) { + throw new EventStudyError( + 'UNSORTED_TIMESTAMPS', + `sessionCloseTs must be strictly ascending: ${String(sessionCloseTs[i - 1])} followed by ${String(ts)} at index ${i}` + ); + } + } + + if (n === 0) { + return { status: 'no_session', reason: 'empty_calendar' }; + } + + if (knownAtTs > (sessionCloseTs[n - 1] as number)) { + return { status: 'no_session', reason: 'after_last_session' }; + } + + let lo = 0; + let hi = n - 1; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sessionCloseTs[mid] as number) < knownAtTs) { + lo = mid + 1; + } else { + hi = mid; + } + } + + return { status: 'ok', dayIndex: lo }; +} + +/** + * Runs a pure, deterministic event study over an aligned daily-return panel: + * - computes raw or benchmark-adjusted abnormal returns across `[-preDays, +postDays]`, + * - produces per-offset AAR, cross-sectional standard error, CAAR (`-preDays..k` and `0..k`), + * and R-7 CAR percentile fans (`p5`, `p25`, `p50`, `p75`, `p95`), + * - clusters per-event `CAR[0..postDays]` by event session date and evaluates Newey-West HAC + * significance on the date-ordered clustered series, + * - evaluates the sign-preserving pre/post-2023 recency gate on the date-clustered series. + */ +export function eventStudy( + input: EventStudyInput, + options?: EventStudyOptions +): EventStudyResult { + const preDays = options?.preDays ?? DEFAULT_EVENT_PRE_DAYS; + const postDays = options?.postDays ?? DEFAULT_EVENT_POST_DAYS; + const minEvents = options?.minEvents ?? DEFAULT_EVENT_MIN_EVENTS; + const neweyWestLag = options?.neweyWestLag; + const recencySplitDate = options?.recencySplitDate ?? RECENCY_SPLIT_DATE; + const recencyMinRatio = options?.recencyMinRatio ?? RECENCY_MIN_RATIO; + + assertIntegerOption(preDays, 0, 'preDays'); + assertIntegerOption(postDays, 0, 'postDays'); + assertIntegerOption(minEvents, 1, 'minEvents'); + if (neweyWestLag !== undefined) { + assertIntegerOption(neweyWestLag, 0, 'neweyWestLag'); + } + assertIsoDate(recencySplitDate, 'recencySplitDate'); + assertPositiveFiniteOption(recencyMinRatio, 'recencyMinRatio'); + + const { sessionDates, entityReturns, benchmarkReturns, events } = input; + const T = sessionDates.length; + for (let t = 0; t < T; t++) { + const d = sessionDates[t] as string; + assertIsoDate(d, `sessionDates[${t}]`); + if (t > 0) { + const prev = sessionDates[t - 1] as string; + if (d === prev) { + throw new EventStudyError('DUPLICATE_DATE', `Duplicate session date at index ${t}: ${d}`); + } + if (d < prev) { + throw new EventStudyError( + 'UNSORTED_DATES', + `sessionDates must be strictly ascending: ${prev} followed by ${d} at index ${t}` + ); + } + } + } + + const hasBenchmark = benchmarkReturns !== undefined; + let benchPrefixNaN: Int32Array | null = null; + if (benchmarkReturns !== undefined) { + assertReturnSeriesValid(benchmarkReturns, T, 'benchmarkReturns'); + benchPrefixNaN = new Int32Array(T + 1); + let nanCount = 0; + for (let t = 0; t < T; t++) { + const v = benchmarkReturns[t] as number; + if (v !== v) { + nanCount++; + } + benchPrefixNaN[t + 1] = nanCount; + } + } + + const canonicalEntityIds: EntityId[] = []; + for (const [entityId, series] of entityReturns) { + assertValidEntityId(entityId, 'entityReturns key'); + assertReturnSeriesValid(series, T, `entityReturns[${String(entityId)}]`); + canonicalEntityIds.push(entityId); + } + canonicalEntityIds.sort(compareIds); + + const E = canonicalEntityIds.length; + const entityIndexMap = new Map(); + const entitySeriesArr: NumericSeries[] = new Array(E); + for (let e = 0; e < E; e++) { + const id = canonicalEntityIds[e] as EntityId; + entityIndexMap.set(id, e); + entitySeriesArr[e] = entityReturns.get(id) as NumericSeries; + } + + const eventsIn = events.length; + const candDay = new Int32Array(eventsIn); + const candEnt = new Int32Array(eventsIn); + let candCount = 0; + + let droppedUnknownEntity = 0; + let droppedWindowOutOfRange = 0; + let droppedMissingReturns = 0; + let duplicateEventsCollapsed = 0; + + let unknownSeen: Set | null = null; + let outOfRangeSeen: Set | null = null; + + for (let i = 0; i < eventsIn; i++) { + const ev = events[i] as EventStudyEvent; + assertValidEntityId(ev.entityId, `events[${i}].entityId`); + const dayIndex = ev.dayIndex; + if (typeof dayIndex !== 'number' || !Number.isInteger(dayIndex) || dayIndex < 0) { + throw new EventStudyError( + 'INVALID_EVENT', + `events[${i}].dayIndex must be a non-negative integer, received ${String(dayIndex)}` + ); + } + + const entIdx = entityIndexMap.get(ev.entityId); + if (entIdx === undefined) { + if (unknownSeen === null) { + unknownSeen = new Set(); + } + const key = `${typeof ev.entityId === 'number' ? 'n' : 's'}:${String(ev.entityId)}:${dayIndex}`; + if (unknownSeen.has(key)) { + duplicateEventsCollapsed++; + } else { + unknownSeen.add(key); + droppedUnknownEntity++; + } + continue; + } + + if (dayIndex - preDays < 0 || dayIndex + postDays >= T) { + if (outOfRangeSeen === null) { + outOfRangeSeen = new Set(); + } + const key = `${entIdx}:${dayIndex}`; + if (outOfRangeSeen.has(key)) { + duplicateEventsCollapsed++; + } else { + outOfRangeSeen.add(key); + droppedWindowOutOfRange++; + } + continue; + } + + candDay[candCount] = dayIndex; + candEnt[candCount] = entIdx; + candCount++; + } + + // Canonical 2-pass counting sort into (dayIndex ASC, entityOrder ASC). + if (candCount > 1) { + const tmpDay = new Int32Array(candCount); + const tmpEnt = new Int32Array(candCount); + + const entCounts = new Int32Array(E + 1); + for (let i = 0; i < candCount; i++) { + const idx = (candEnt[i] as number) + 1; + entCounts[idx] = (entCounts[idx] as number) + 1; + } + for (let e = 1; e <= E; e++) { + entCounts[e] = (entCounts[e] as number) + (entCounts[e - 1] as number); + } + for (let i = 0; i < candCount; i++) { + const e = candEnt[i] as number; + const pos = entCounts[e] as number; + entCounts[e] = pos + 1; + tmpDay[pos] = candDay[i] as number; + tmpEnt[pos] = e; + } + + const dayCounts = new Int32Array(T + 1); + for (let i = 0; i < candCount; i++) { + const idx = (tmpDay[i] as number) + 1; + dayCounts[idx] = (dayCounts[idx] as number) + 1; + } + for (let t = 1; t <= T; t++) { + dayCounts[t] = (dayCounts[t] as number) + (dayCounts[t - 1] as number); + } + for (let i = 0; i < candCount; i++) { + const d = tmpDay[i] as number; + const pos = dayCounts[d] as number; + dayCounts[d] = pos + 1; + candDay[pos] = d; + candEnt[pos] = tmpEnt[i] as number; + } + } + + const evDay = new Int32Array(candCount); + const evEnt = new Int32Array(candCount); + let eventsUsed = 0; + let prevDay = -1; + let prevEnt = -1; + + for (let i = 0; i < candCount; i++) { + const d = candDay[i] as number; + const e = candEnt[i] as number; + if (d === prevDay && e === prevEnt) { + duplicateEventsCollapsed++; + continue; + } + prevDay = d; + prevEnt = e; + + const start = d - preDays; + const end = d + postDays; + + if ( + benchPrefixNaN !== null && + (benchPrefixNaN[end + 1] as number) !== (benchPrefixNaN[start] as number) + ) { + droppedMissingReturns++; + continue; + } + + const series = entitySeriesArr[e] as NumericSeries; + let missing = false; + for (let t = start; t <= end; t++) { + const v = series[t] as number; + if (v !== v) { + missing = true; + break; + } + } + if (missing) { + droppedMissingReturns++; + continue; + } + + evDay[eventsUsed] = d; + evEnt[eventsUsed] = e; + eventsUsed++; + } + + let nDates = 0; + let lastDay = -1; + for (let i = 0; i < eventsUsed; i++) { + const d = evDay[i] as number; + if (d !== lastDay) { + nDates++; + lastDay = d; + } + } + + const diagnostics: EventStudyDiagnostics = { + eventsIn, + eventsUsed, + droppedUnknownEntity, + droppedWindowOutOfRange, + droppedMissingReturns, + duplicateEventsCollapsed, + }; + + if (eventsUsed < minEvents) { + return { + status: 'insufficient_data', + reason: 'below_min_events', + preDays, + postDays, + hasBenchmark, + eventsUsed, + nDates, + diagnostics, + }; + } + + if (nDates < 2) { + return { + status: 'insufficient_data', + reason: 'too_few_event_dates', + preDays, + postDays, + hasBenchmark, + eventsUsed, + nDates, + diagnostics, + }; + } + + const M = eventsUsed; + const windowLen = preDays + postDays + 1; + const arBuf = new Float64Array(M); + const runningCar = new Float64Array(M); + const runningPostCar = new Float64Array(M); + const sortBuf = new Float64Array(M); + + const offsets: EventStudyOffsetStats[] = new Array(windowLen); + const invSeDenom = 1 / (M * (M - 1)); + + let caarSum = 0; + let caarComp = 0; + let caarZeroSum = 0; + let caarZeroComp = 0; + + for (let w = 0; w < windowLen; w++) { + const k = w - preDays; + let aarSum = 0; + let aarComp = 0; + + if (benchmarkReturns !== undefined) { + if (k >= 0) { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = + ((entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number) - + (benchmarkReturns[t] as number); + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + runningPostCar[i] = (runningPostCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } else { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = + ((entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number) - + (benchmarkReturns[t] as number); + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } + } else if (k >= 0) { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = (entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number; + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + runningPostCar[i] = (runningPostCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } else { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = (entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number; + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } + + const aar = (aarSum + aarComp) / M; + + let sumSq = 0; + for (let i = 0; i < M; i++) { + const diff = (arBuf[i] as number) - aar; + sumSq += diff * diff; + } + const standardError = Math.sqrt(sumSq * invSeDenom); + + const nextCaar = caarSum + aar; + if (Math.abs(caarSum) >= Math.abs(aar)) { + caarComp += caarSum - nextCaar + aar; + } else { + caarComp += aar - nextCaar + caarSum; + } + caarSum = nextCaar; + const caar = caarSum + caarComp; + + let caarFromZero: number | null = null; + if (k >= 0) { + const nextZero = caarZeroSum + aar; + if (Math.abs(caarZeroSum) >= Math.abs(aar)) { + caarZeroComp += caarZeroSum - nextZero + aar; + } else { + caarZeroComp += aar - nextZero + caarZeroSum; + } + caarZeroSum = nextZero; + caarFromZero = caarZeroSum + caarZeroComp; + } + + sortBuf.set(runningCar); + const carPercentiles = computeR7Percentiles(sortBuf, M); + + let postCarPercentiles: EventStudyPercentiles | null = null; + if (k >= 0) { + sortBuf.set(runningPostCar); + postCarPercentiles = computeR7Percentiles(sortBuf, M); + } + + offsets[w] = { + offset: k, + n: M, + aar, + standardError, + caar, + caarFromZero, + carPercentiles, + postCarPercentiles, + }; + } + + // Columnar per-event CAR[0..postDays] in canonical (dayIndex ASC, entityId ASC) order. + const eventEntityIds: EntityId[] = new Array(M); + const eventDates: string[] = new Array(M); + const eventDayIndices = evDay.length === M ? evDay : evDay.slice(0, M); + for (let i = 0; i < M; i++) { + eventEntityIds[i] = canonicalEntityIds[evEnt[i] as number] as EntityId; + eventDates[i] = sessionDates[eventDayIndices[i] as number] as string; + } + + const eventCars: EventCarSeries = { + entityIds: eventEntityIds, + dayIndices: eventDayIndices, + dates: eventDates, + cars: runningPostCar, + }; + + // Cluster per-event CAR[0..postDays] by event session date. + const clusteredDates: string[] = new Array(nDates); + const clusteredCounts = new Int32Array(nDates); + const clusteredMeanCars = new Float64Array(nDates); + + let clusterIdx = 0; + let pos = 0; + let totalClusterSum = 0; + let totalClusterComp = 0; + while (pos < M) { + const d = eventDayIndices[pos] as number; + let sum = 0; + let comp = 0; + let count = 0; + while (pos < M && (eventDayIndices[pos] as number) === d) { + const v = runningPostCar[pos] as number; + const next = sum + v; + if (Math.abs(sum) >= Math.abs(v)) { + comp += sum - next + v; + } else { + comp += v - next + sum; + } + sum = next; + count++; + pos++; + } + const meanCar = (sum + comp) / count; + clusteredDates[clusterIdx] = sessionDates[d] as string; + clusteredCounts[clusterIdx] = count; + clusteredMeanCars[clusterIdx] = meanCar; + + const nextTotal = totalClusterSum + meanCar; + if (Math.abs(totalClusterSum) >= Math.abs(meanCar)) { + totalClusterComp += totalClusterSum - nextTotal + meanCar; + } else { + totalClusterComp += meanCar - nextTotal + totalClusterSum; + } + totalClusterSum = nextTotal; + clusterIdx++; + } + + const carMean = (totalClusterSum + totalClusterComp) / nDates; + const neweyWest = neweyWestMeanTest(clusteredMeanCars, neweyWestLag); + + const clustered: DateClusteredCarResult = { + nDates, + dates: clusteredDates, + eventCounts: clusteredCounts, + meanCars: clusteredMeanCars, + carMean, + neweyWest, + }; + + // Sign-preserving recency gate reusing T-82's evaluateRecencyGate. + const rawRecency = evaluateRecencyGate(clusteredDates, clusteredMeanCars, { + recencySplitDate, + recencyMinRatio, + lag: neweyWestLag, + }); + + let gateSource = rawRecency.gate; + if (rawRecency.pre.mean !== null && rawRecency.pre.mean < 0) { + const negated = new Float64Array(nDates); + for (let i = 0; i < nDates; i++) { + negated[i] = -(clusteredMeanCars[i] as number); + } + const flippedRecency = evaluateRecencyGate(clusteredDates, negated, { + recencySplitDate, + recencyMinRatio, + lag: neweyWestLag, + }); + gateSource = flippedRecency.gate; + } + + const recency: EventStudyRecencyResult = { + splitDate: rawRecency.splitDate, + minRatio: rawRecency.minRatio, + pre: rawRecency.pre, + post: rawRecency.post, + gate: { + pass: gateSource.pass, + reason: mapRecencyReason(gateSource.reason), + ratio: gateSource.ratio, + }, + }; + + return { + status: 'ok', + preDays, + postDays, + hasBenchmark, + offsets, + eventCars, + clustered, + recency, + diagnostics, + }; +} diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts index e9695557..39050ce3 100644 --- a/libs/calculations/src/analytics/index.ts +++ b/libs/calculations/src/analytics/index.ts @@ -54,3 +54,27 @@ export type { SignalPanelDiagnostics, TurnoverResult, } from './signal-analysis'; +export { + DEFAULT_EVENT_MIN_EVENTS, + DEFAULT_EVENT_POST_DAYS, + DEFAULT_EVENT_PRE_DAYS, + EventStudyError, + eventDayIndex, + eventStudy, +} from './event-study'; +export type { + DateClusteredCarResult, + EventCarSeries, + EventDayIndexResult, + EventStudyDiagnostics, + EventStudyErrorCode, + EventStudyEvent, + EventStudyInput, + EventStudyOffsetStats, + EventStudyOptions, + EventStudyPercentiles, + EventStudyRecencyGate, + EventStudyRecencyReason, + EventStudyRecencyResult, + EventStudyResult, +} from './event-study'; diff --git a/libs/calculations/src/index.ts b/libs/calculations/src/index.ts index c82f07d6..6b60c43a 100644 --- a/libs/calculations/src/index.ts +++ b/libs/calculations/src/index.ts @@ -56,10 +56,14 @@ export { groupBySymbol, } from './market-data'; export { + DEFAULT_EVENT_MIN_EVENTS, + DEFAULT_EVENT_POST_DAYS, + DEFAULT_EVENT_PRE_DAYS, DEFAULT_MIN_CROSS_SECTION, DEFAULT_QUANTILE_COUNT, DSR_VALIDATION_GATE, EULER_MASCHERONI, + EventStudyError, RECENCY_MIN_RATIO, RECENCY_SPLIT_DATE, SignalAnalysisError, @@ -69,6 +73,8 @@ export { deflatedSharpeRatio, effectiveIndependentTrials, evaluateRecencyGate, + eventDayIndex, + eventStudy, inverseNormalCdf, neweyWestMeanTest, normalCdf, @@ -79,11 +85,25 @@ export { export type { CrossSectionIcOptions, CrossSectionIcResult, + DateClusteredCarResult, DeflatedSharpeInput, DeflatedSharpeResult, EffectiveTrialsResult, EntityId, EntityIdSeries, + EventCarSeries, + EventDayIndexResult, + EventStudyDiagnostics, + EventStudyErrorCode, + EventStudyEvent, + EventStudyInput, + EventStudyOffsetStats, + EventStudyOptions, + EventStudyPercentiles, + EventStudyRecencyGate, + EventStudyRecencyReason, + EventStudyRecencyResult, + EventStudyResult, IcSummary, IcSummaryOptions, NeweyWestResult, diff --git a/libs/calculations/test/event-study.test.ts b/libs/calculations/test/event-study.test.ts new file mode 100644 index 00000000..284cef9e --- /dev/null +++ b/libs/calculations/test/event-study.test.ts @@ -0,0 +1,1279 @@ +import { describe, expect, test } from 'bun:test'; +import * as rootExports from '@stock-bot/calculations'; +import * as analyticsExports from '@stock-bot/calculations/analytics'; +import { + DEFAULT_EVENT_MIN_EVENTS, + DEFAULT_EVENT_POST_DAYS, + DEFAULT_EVENT_PRE_DAYS, + EventStudyError, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + eventDayIndex, + eventStudy, + neweyWestMeanTest, + type EntityId, + type EventStudyErrorCode, + type EventStudyEvent, + type EventStudyInput, + type EventStudyOptions, + type EventStudyPercentiles, + type EventStudyResult, +} from '@stock-bot/calculations'; + +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) / 4294967296; + }; +} + +function generateTradingDates(count: number, startYear = 2006): string[] { + const dates: string[] = new Array(count); + const dt = new Date(Date.UTC(startYear, 0, 2)); + let i = 0; + while (i < count) { + const dow = dt.getUTCDay(); + if (dow !== 0 && dow !== 6) { + const y = dt.getUTCFullYear(); + const m = String(dt.getUTCMonth() + 1).padStart(2, '0'); + const d = String(dt.getUTCDate()).padStart(2, '0'); + dates[i] = `${y}-${m}-${d}`; + i++; + } + dt.setUTCDate(dt.getUTCDate() + 1); + } + return dates; +} + +function assertNoNaNDeep(value: unknown): void { + if (typeof value === 'number') { + expect(Number.isFinite(value)).toBe(true); + return; + } + if (value instanceof Float64Array) { + for (let i = 0; i < value.length; i++) { + expect(Number.isFinite(value[i])).toBe(true); + } + return; + } + if (value instanceof Int32Array) { + return; + } + if (Array.isArray(value)) { + for (const item of value) { + assertNoNaNDeep(item); + } + return; + } + if (value !== null && typeof value === 'object') { + for (const entry of Object.values(value)) { + assertNoNaNDeep(entry); + } + } +} + +function expectEventStudyError(fn: () => unknown, code: EventStudyErrorCode): void { + try { + fn(); + throw new Error(`Expected EventStudyError(${code}) to be thrown`); + } catch (err) { + expect(err).toBeInstanceOf(EventStudyError); + expect(err).toBeInstanceOf(RangeError); + expect((err as EventStudyError).code).toBe(code); + } +} + +function assertAccountingIdentity(result: EventStudyResult): void { + const d = result.diagnostics; + expect(d.eventsIn).toBe( + d.eventsUsed + + d.droppedUnknownEntity + + d.droppedWindowOutOfRange + + d.droppedMissingReturns + + d.duplicateEventsCollapsed + ); +} + +function naiveR7Percentile(sorted: readonly number[], q: number): number { + const pos = q * (sorted.length - 1); + const lo = Math.floor(pos); + const hi = Math.ceil(pos); + if (lo === hi) { + return sorted[lo] as number; + } + const frac = pos - lo; + return (sorted[lo] as number) + frac * ((sorted[hi] as number) - (sorted[lo] as number)); +} + +function naivePercentiles(values: readonly number[]): EventStudyPercentiles { + const sorted = [...values].sort((a, b) => a - b); + return { + p5: naiveR7Percentile(sorted, 0.05), + p25: naiveR7Percentile(sorted, 0.25), + p50: naiveR7Percentile(sorted, 0.5), + p75: naiveR7Percentile(sorted, 0.75), + p95: naiveR7Percentile(sorted, 0.95), + }; +} + +interface NaiveReferenceResult { + readonly status: 'ok' | 'insufficient_data'; + readonly reason?: 'below_min_events' | 'too_few_event_dates'; + readonly diagnostics: { + readonly eventsIn: number; + readonly eventsUsed: number; + readonly droppedUnknownEntity: number; + readonly droppedWindowOutOfRange: number; + readonly droppedMissingReturns: number; + readonly duplicateEventsCollapsed: number; + }; + readonly offsets?: Array<{ + readonly offset: number; + readonly n: number; + readonly aar: number; + readonly standardError: number; + readonly caar: number; + readonly caarFromZero: number | null; + readonly carPercentiles: EventStudyPercentiles; + readonly postCarPercentiles: EventStudyPercentiles | null; + }>; + readonly eventCars?: readonly number[]; + readonly clusteredDates?: readonly string[]; + readonly clusteredCounts?: readonly number[]; + readonly clusteredMeanCars?: readonly number[]; + readonly carMean?: number; +} + +function naiveEventStudyReference( + input: EventStudyInput, + options?: EventStudyOptions +): NaiveReferenceResult { + const preDays = options?.preDays ?? DEFAULT_EVENT_PRE_DAYS; + const postDays = options?.postDays ?? DEFAULT_EVENT_POST_DAYS; + const minEvents = options?.minEvents ?? DEFAULT_EVENT_MIN_EVENTS; + const T = input.sessionDates.length; + + const seen = new Set(); + let droppedUnknownEntity = 0; + let droppedWindowOutOfRange = 0; + let droppedMissingReturns = 0; + let duplicateEventsCollapsed = 0; + + const usable: Array<{ entityId: EntityId; dayIndex: number }> = []; + + for (const ev of input.events) { + const key = `${typeof ev.entityId === 'number' ? 'n' : 's'}:${String(ev.entityId)}:${ev.dayIndex}`; + if (seen.has(key)) { + duplicateEventsCollapsed++; + continue; + } + seen.add(key); + + const series = input.entityReturns.get(ev.entityId); + if (!series) { + droppedUnknownEntity++; + continue; + } + if (ev.dayIndex - preDays < 0 || ev.dayIndex + postDays >= T) { + droppedWindowOutOfRange++; + continue; + } + let hasNaN = false; + for (let t = ev.dayIndex - preDays; t <= ev.dayIndex + postDays; t++) { + if (Number.isNaN(series[t])) { + hasNaN = true; + break; + } + if (input.benchmarkReturns && Number.isNaN(input.benchmarkReturns[t])) { + hasNaN = true; + break; + } + } + if (hasNaN) { + droppedMissingReturns++; + continue; + } + usable.push({ entityId: ev.entityId, dayIndex: ev.dayIndex }); + } + + usable.sort((a, b) => { + if (a.dayIndex !== b.dayIndex) { + return a.dayIndex - b.dayIndex; + } + const ta = typeof a.entityId; + const tb = typeof b.entityId; + if (ta !== tb) { + return ta === 'number' ? -1 : 1; + } + return a.entityId < b.entityId ? -1 : a.entityId > b.entityId ? 1 : 0; + }); + + const diagnostics = { + eventsIn: input.events.length, + eventsUsed: usable.length, + droppedUnknownEntity, + droppedWindowOutOfRange, + droppedMissingReturns, + duplicateEventsCollapsed, + }; + + const uniqueDates = new Set(usable.map(e => e.dayIndex)); + if (usable.length < minEvents) { + return { status: 'insufficient_data', reason: 'below_min_events', diagnostics }; + } + if (uniqueDates.size < 2) { + return { status: 'insufficient_data', reason: 'too_few_event_dates', diagnostics }; + } + + const M = usable.length; + const runningCar = new Array(M).fill(0); + const runningPostCar = new Array(M).fill(0); + let caar = 0; + let caarFromZero = 0; + const offsets: NonNullable = []; + + for (let k = preDays === 0 ? 0 : -preDays; k <= postDays; k++) { + const ars: number[] = []; + for (let i = 0; i < M; i++) { + const ev = usable[i]!; + const t = ev.dayIndex + k; + const ent = input.entityReturns.get(ev.entityId)![t]!; + const ar = input.benchmarkReturns ? ent - input.benchmarkReturns[t]! : ent; + ars.push(ar); + runningCar[i] = runningCar[i]! + ar; + if (k >= 0) { + runningPostCar[i] = runningPostCar[i]! + ar; + } + } + const aar = ars.reduce((s, v) => s + v, 0) / M; + const sumSq = ars.reduce((s, v) => s + (v - aar) * (v - aar), 0); + const standardError = Math.sqrt(sumSq / (M * (M - 1))); + caar += aar; + if (k >= 0) { + caarFromZero += aar; + } + offsets.push({ + offset: k, + n: M, + aar, + standardError, + caar, + caarFromZero: k >= 0 ? caarFromZero : null, + carPercentiles: naivePercentiles(runningCar), + postCarPercentiles: k >= 0 ? naivePercentiles(runningPostCar) : null, + }); + } + + const byDay = new Map(); + for (let i = 0; i < M; i++) { + const d = usable[i]!.dayIndex; + const arr = byDay.get(d); + if (arr) { + arr.push(runningPostCar[i]!); + } else { + byDay.set(d, [runningPostCar[i]!]); + } + } + const sortedDays = [...byDay.keys()].sort((a, b) => a - b); + const clusteredDates = sortedDays.map(d => input.sessionDates[d]!); + const clusteredCounts = sortedDays.map(d => byDay.get(d)!.length); + const clusteredMeanCars = sortedDays.map(d => { + const vals = byDay.get(d)!; + return vals.reduce((s, v) => s + v, 0) / vals.length; + }); + const carMean = + clusteredMeanCars.reduce((s, v) => s + v, 0) / clusteredMeanCars.length; + + return { + status: 'ok', + diagnostics, + offsets, + eventCars: runningPostCar, + clusteredDates, + clusteredCounts, + clusteredMeanCars, + carMean, + }; +} + +describe('event-study exports', () => { + test('both root and analytics entrypoints export the complete event-study surface', () => { + const names = [ + 'DEFAULT_EVENT_PRE_DAYS', + 'DEFAULT_EVENT_POST_DAYS', + 'DEFAULT_EVENT_MIN_EVENTS', + 'EventStudyError', + 'eventDayIndex', + 'eventStudy', + ] as const; + + for (const name of names) { + expect(rootExports[name]).toBeDefined(); + expect(analyticsExports[name]).toBe(rootExports[name]); + } + + expect(DEFAULT_EVENT_PRE_DAYS).toBe(10); + expect(DEFAULT_EVENT_POST_DAYS).toBe(20); + expect(DEFAULT_EVENT_MIN_EVENTS).toBe(5); + }); +}); + +describe('eventDayIndex', () => { + const closes = [1000, 2000, 3000, 4000, 5000]; + + test('maps before-first, exact-close, between-closes (zero look-ahead), after-last, and empty calendar', () => { + expect(eventDayIndex(closes, 500)).toEqual({ status: 'ok', dayIndex: 0 }); + expect(eventDayIndex(closes, 1000)).toEqual({ status: 'ok', dayIndex: 0 }); + expect(eventDayIndex(closes, 1001)).toEqual({ status: 'ok', dayIndex: 1 }); + expect(eventDayIndex(closes, 2000)).toEqual({ status: 'ok', dayIndex: 1 }); + expect(eventDayIndex(closes, 2500)).toEqual({ status: 'ok', dayIndex: 2 }); + expect(eventDayIndex(closes, 5000)).toEqual({ status: 'ok', dayIndex: 4 }); + expect(eventDayIndex(closes, 5001)).toEqual({ + status: 'no_session', + reason: 'after_last_session', + }); + expect(eventDayIndex([], 1000)).toEqual({ + status: 'no_session', + reason: 'empty_calendar', + }); + expect(eventDayIndex(new Float64Array(closes), 3000)).toEqual({ + status: 'ok', + dayIndex: 2, + }); + }); + + test('throws typed errors on unsorted, duplicate, off-probe-path inverted, or non-finite timestamps', () => { + expectEventStudyError(() => eventDayIndex(closes, Number.NaN), 'INVALID_TIMESTAMP'); + expectEventStudyError( + () => eventDayIndex(closes, Number.POSITIVE_INFINITY), + 'INVALID_TIMESTAMP' + ); + expectEventStudyError( + () => eventDayIndex([1000, Number.NaN, 3000], 1500), + 'INVALID_TIMESTAMP' + ); + expectEventStudyError( + () => eventDayIndex([1000, 2000, Number.NEGATIVE_INFINITY], 1500), + 'INVALID_TIMESTAMP' + ); + expectEventStudyError(() => eventDayIndex([1000, 2000, 2000, 3000], 1500), 'UNSORTED_TIMESTAMPS'); + // Off-probe-path inversion at the end while searching near index 0 + expectEventStudyError( + () => eventDayIndex([1000, 2000, 3000, 4000, 3500], 1000), + 'UNSORTED_TIMESTAMPS' + ); + }); +}); + +describe('eventStudy hand-computed golden fixture', () => { + // 3 entities, 12 sessions, 4 events, window -1..+2 + const sessionDates = [ + '2022-01-03', + '2022-01-04', + '2022-01-05', + '2022-01-06', + '2022-01-07', + '2022-01-10', + '2023-01-03', + '2023-01-04', + '2023-01-05', + '2023-01-06', + '2023-01-09', + '2023-01-10', + ]; + + // Simple exact decimal returns + const rA = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.02, 0.04, 0.06, 0.08, 0.01, 0.02]; + const rB = [0.0, 0.01, 0.02, 0.01, 0.03, 0.02, -0.01, 0.01, 0.03, 0.05, 0.02, 0.01]; + const rC = [0.02, -0.01, 0.01, 0.03, 0.02, 0.04, 0.03, 0.02, 0.01, 0.04, 0.05, 0.03]; + const bench = [0.005, 0.005, 0.01, 0.01, 0.01, 0.01, 0.005, 0.01, 0.01, 0.01, 0.005, 0.005]; + + // Events: + // E1: (A, 2) -> window [1..4], date 2022-01-05 + // E2: (B, 2) -> window [1..4], date 2022-01-05 + // E3: (C, 7) -> window [6..9], date 2023-01-04 + // E4: (A, 8) -> window [7..10], date 2023-01-05 + const entityReturns = new Map([ + ['A', rA], + ['B', rB], + ['C', rC], + ]); + const events: EventStudyEvent[] = [ + { entityId: 'A', dayIndex: 2 }, + { entityId: 'B', dayIndex: 2 }, + { entityId: 'C', dayIndex: 7 }, + { entityId: 'A', dayIndex: 8 }, + ]; + + test('matches hand-computed AAR, SE, CAAR, percentiles, CAR, and clustered stats without benchmark to 1e-12', () => { + const res = eventStudy( + { sessionDates, entityReturns, events }, + { preDays: 1, postDays: 2, minEvents: 4, neweyWestLag: 0 } + ); + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + if (res.status !== 'ok') { + return; + } + + expect(res.hasBenchmark).toBe(false); + expect(res.offsets.length).toBe(4); + + // Offset -1: A[1]=0.02, B[1]=0.01, C[6]=0.03, A[7]=0.04 -> mean = 0.025 + // sumSq = (-0.005)^2 + (-0.015)^2 + (0.005)^2 + (0.015)^2 = 0.0005 -> SE = sqrt(0.0005 / 12) + // Offset 0: A[2]=0.03, B[2]=0.02, C[7]=0.02, A[8]=0.06 -> mean = 0.0325 + // Offset +1: A[3]=0.04, B[3]=0.01, C[8]=0.01, A[9]=0.08 -> mean = 0.035 + // Offset +2: A[4]=0.05, B[4]=0.03, C[9]=0.04, A[10]=0.01 -> mean = 0.0325 + const expectedAar = [0.025, 0.0325, 0.035, 0.0325]; + const expectedSe = [ + Math.sqrt(0.0005 / 12), + Math.sqrt(0.001075 / 12), + Math.sqrt(0.0033 / 12), + Math.sqrt(0.000875 / 12), + ]; + const expectedCaar = [0.025, 0.0575, 0.0925, 0.125]; + const expectedCaarZero = [null, 0.0325, 0.0675, 0.1]; + + // Per-event running CAR[-1..k] at k = +2: + // E1 (A,2): 0.02+0.03+0.04+0.05 = 0.14 + // E2 (B,2): 0.01+0.02+0.01+0.03 = 0.07 + // E3 (C,7): 0.03+0.02+0.01+0.04 = 0.10 + // E4 (A,8): 0.04+0.06+0.08+0.01 = 0.19 + // Per-event CAR[0..+2]: + // E1: 0.03+0.04+0.05 = 0.12 + // E2: 0.02+0.01+0.03 = 0.06 + // E3: 0.02+0.01+0.04 = 0.07 + // E4: 0.06+0.08+0.01 = 0.15 + for (let w = 0; w < 4; w++) { + const off = res.offsets[w]!; + expect(off.offset).toBe(w - 1); + expect(off.n).toBe(4); + expect(Math.abs(off.aar - expectedAar[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.standardError - expectedSe[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.caar - expectedCaar[w]!)).toBeLessThan(1e-12); + if (expectedCaarZero[w] === null) { + expect(off.caarFromZero).toBeNull(); + expect(off.postCarPercentiles).toBeNull(); + } else { + expect(Math.abs((off.caarFromZero as number) - expectedCaarZero[w]!)).toBeLessThan(1e-12); + expect(off.postCarPercentiles).not.toBeNull(); + } + } + + // Check final offset percentiles on sorted full CARs [0.07, 0.10, 0.14, 0.19] + const lastFullP = res.offsets[3]!.carPercentiles; + expect(Math.abs(lastFullP.p5 - (0.07 + 0.15 * 0.03))).toBeLessThan(1e-12); + expect(Math.abs(lastFullP.p25 - (0.07 + 0.75 * 0.03))).toBeLessThan(1e-12); + expect(Math.abs(lastFullP.p50 - 0.12)).toBeLessThan(1e-12); + expect(Math.abs(lastFullP.p75 - (0.14 + 0.25 * 0.05))).toBeLessThan(1e-12); + expect(Math.abs(lastFullP.p95 - (0.14 + 0.85 * 0.05))).toBeLessThan(1e-12); + + // Per-event CAR[0..+2] in canonical (dayIndex ASC, entityId ASC) order + expect(res.eventCars.entityIds).toEqual(['A', 'B', 'C', 'A']); + expect(Array.from(res.eventCars.dayIndices)).toEqual([2, 2, 7, 8]); + const expectedCars = [0.12, 0.06, 0.07, 0.15]; + for (let i = 0; i < 4; i++) { + expect(Math.abs(res.eventCars.cars[i]! - expectedCars[i]!)).toBeLessThan(1e-12); + } + + // Clustered by date: + // 2022-01-05 (day 2): mean(0.12, 0.06) = 0.09 (count 2) + // 2023-01-04 (day 7): 0.07 (count 1) + // 2023-01-05 (day 8): 0.15 (count 1) + expect(res.clustered.nDates).toBe(3); + expect(res.clustered.dates).toEqual(['2022-01-05', '2023-01-04', '2023-01-05']); + expect(Array.from(res.clustered.eventCounts)).toEqual([2, 1, 1]); + const expectedClustered = [0.09, 0.07, 0.15]; + for (let i = 0; i < 3; i++) { + expect(Math.abs(res.clustered.meanCars[i]! - expectedClustered[i]!)).toBeLessThan(1e-12); + } + expect(Math.abs(res.clustered.carMean - 0.31 / 3)).toBeLessThan(1e-12); + const expectedNw = neweyWestMeanTest(expectedClustered, 0); + expect(res.clustered.neweyWest.status).toBe('ok'); + expect(expectedNw.status).toBe('ok'); + if (res.clustered.neweyWest.status === 'ok' && expectedNw.status === 'ok') { + expect(res.clustered.neweyWest.lag).toBe(expectedNw.lag); + expect( + Math.abs(res.clustered.neweyWest.longRunVariance - expectedNw.longRunVariance) + ).toBeLessThan(1e-12); + expect( + Math.abs(res.clustered.neweyWest.standardError - expectedNw.standardError) + ).toBeLessThan(1e-12); + expect(Math.abs(res.clustered.neweyWest.tStat - expectedNw.tStat)).toBeLessThan(1e-12); + } + assertNoNaNDeep(res); + }); + + test('matches hand-computed AAR, CAAR, and per-event CAR with benchmark to 1e-12', () => { + const res = eventStudy( + { sessionDates, entityReturns, benchmarkReturns: bench, events }, + { preDays: 1, postDays: 2, minEvents: 4, neweyWestLag: 0 } + ); + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + if (res.status !== 'ok') { + return; + } + + expect(res.hasBenchmark).toBe(true); + + // Benchmark values at each event's offsets: + // Offset -1: bench[1]=0.005, bench[1]=0.005, bench[6]=0.005, bench[7]=0.01 -> mean bench = 0.00625 + // Offset 0: bench[2]=0.01, bench[2]=0.01, bench[7]=0.01, bench[8]=0.01 -> mean bench = 0.01 + // Offset +1: bench[3]=0.01, bench[3]=0.01, bench[8]=0.01, bench[9]=0.01 -> mean bench = 0.01 + // Offset +2: bench[4]=0.01, bench[4]=0.01, bench[9]=0.01, bench[10]=0.005 -> mean bench = 0.00875 + const expectedAar = [0.025 - 0.00625, 0.0325 - 0.01, 0.035 - 0.01, 0.0325 - 0.00875]; + const expectedCaar = [ + expectedAar[0]!, + expectedAar[0]! + expectedAar[1]!, + expectedAar[0]! + expectedAar[1]! + expectedAar[2]!, + expectedAar[0]! + expectedAar[1]! + expectedAar[2]! + expectedAar[3]!, + ]; + const expectedCaarZero = [ + null, + expectedAar[1]!, + expectedAar[1]! + expectedAar[2]!, + expectedAar[1]! + expectedAar[2]! + expectedAar[3]!, + ]; + + for (let w = 0; w < 4; w++) { + const off = res.offsets[w]!; + expect(Math.abs(off.aar - expectedAar[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.caar - expectedCaar[w]!)).toBeLessThan(1e-12); + if (expectedCaarZero[w] === null) { + expect(off.caarFromZero).toBeNull(); + } else { + expect(Math.abs((off.caarFromZero as number) - expectedCaarZero[w]!)).toBeLessThan(1e-12); + } + } + + // Per-event benchmark-adjusted CAR[0..+2]: + // E1: 0.12 - (0.01+0.01+0.01) = 0.09 + // E2: 0.06 - (0.01+0.01+0.01) = 0.03 + // E3: 0.07 - (0.01+0.01+0.01) = 0.04 + // E4: 0.15 - (0.01+0.01+0.005) = 0.125 + const expectedCars = [0.09, 0.03, 0.04, 0.125]; + for (let i = 0; i < 4; i++) { + expect(Math.abs(res.eventCars.cars[i]! - expectedCars[i]!)).toBeLessThan(1e-12); + } + + // Clustered: day 2 -> mean(0.09, 0.03) = 0.06, day 7 -> 0.04, day 8 -> 0.125 + const expectedClustered = [0.06, 0.04, 0.125]; + for (let i = 0; i < 3; i++) { + expect(Math.abs(res.clustered.meanCars[i]! - expectedClustered[i]!)).toBeLessThan(1e-12); + } + assertNoNaNDeep(res); + }); +}); + +describe('eventStudy date clustering', () => { + test('10 events on one date + 1 event each on 5 other dates yields nDates = 6 and matches neweyWestMeanTest on 6 clustered means', () => { + const sessionDates = generateTradingDates(20, 2022); + const entityReturns = new Map(); + const events: EventStudyEvent[] = []; + + // 10 entities all having an event on dayIndex = 3 + for (let e = 0; e < 10; e++) { + const series = new Float64Array(20); + series[3] = 0.05 + e * 0.001; // CAR[0..0] = 0.05 + 0.001*e -> mean on day 3 = 0.0545 + entityReturns.set(`E${e}`, series); + events.push({ entityId: `E${e}`, dayIndex: 3 }); + } + + // 5 single-event dates on dayIndex = 5, 7, 9, 11, 13 + const otherDays = [5, 7, 9, 11, 13]; + const otherCars = [0.01, -0.02, 0.03, 0.04, -0.01]; + for (let i = 0; i < otherDays.length; i++) { + const id = `S${i}`; + const series = new Float64Array(20); + series[otherDays[i]!] = otherCars[i]!; + entityReturns.set(id, series); + events.push({ entityId: id, dayIndex: otherDays[i]! }); + } + + const res = eventStudy( + { sessionDates, entityReturns, events }, + { preDays: 1, postDays: 0, minEvents: 5 } + ); + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + + expect(res.diagnostics.eventsUsed).toBe(15); + expect(res.clustered.nDates).toBe(6); + expect(Array.from(res.clustered.eventCounts)).toEqual([10, 1, 1, 1, 1, 1]); + + const expectedClustered = [0.0545, 0.01, -0.02, 0.03, 0.04, -0.01]; + for (let i = 0; i < 6; i++) { + expect(Math.abs(res.clustered.meanCars[i]! - expectedClustered[i]!)).toBeLessThan(1e-12); + } + + const nwClustered = neweyWestMeanTest(expectedClustered); + const nwUnclustered = neweyWestMeanTest(res.eventCars.cars); + expect(res.clustered.neweyWest.status).toBe('ok'); + expect(nwClustered.status).toBe('ok'); + expect(nwUnclustered.status).toBe('ok'); + if ( + res.clustered.neweyWest.status === 'ok' && + nwClustered.status === 'ok' && + nwUnclustered.status === 'ok' + ) { + expect(res.clustered.neweyWest.lag).toBe(nwClustered.lag); + expect(Math.abs(res.clustered.neweyWest.tStat - nwClustered.tStat)).toBeLessThan(1e-12); + expect(Math.abs(res.clustered.neweyWest.standardError - nwClustered.standardError)).toBeLessThan( + 1e-12 + ); + // Confirm clustering materially differs from unclustered 15-observation test + expect(Math.abs(res.clustered.neweyWest.tStat - nwUnclustered.tStat)).toBeGreaterThan(0.5); + } + }); +}); + +describe('eventStudy diagnostics and NaN scoping', () => { + test('accounts for every drop bucket, collapses duplicates, and ignores out-of-window NaNs', () => { + const sessionDates = generateTradingDates(12, 2023); + const s1 = new Float64Array([ + Number.NaN, // index 0 (out of window for dayIndex=4 with pre=2, post=2) + 0.01, + 0.02, + 0.03, + 0.04, + 0.05, + 0.06, + 0.01, + 0.02, + 0.03, + Number.NaN, // index 10 (out of window for dayIndex=4) + 0.01, + ]); + const s2 = new Float64Array([ + 0.01, + 0.02, + 0.03, + 0.04, + Number.NaN, // index 4 -> drops event on dayIndex=5 (window 3..7) + 0.01, + 0.02, + 0.03, + 0.04, + 0.05, + 0.01, + 0.02, + ]); + const bench = new Float64Array([ + Number.NaN, // index 0 (out of window for dayIndex=4) + 0.001, + 0.001, + 0.001, + 0.001, + 0.001, + 0.001, + 0.001, + Number.NaN, // index 8 -> drops event on dayIndex=7 (window 5..9) + 0.001, + 0.001, + 0.001, + ]); + + const entityReturns = new Map([ + [1, s1], + [2, s2], + ]); + + const events: EventStudyEvent[] = [ + // Valid usable events (3 total across 3 dates) + { entityId: 1, dayIndex: 4 }, // window 2..6 (index 0 and 10 NaNs are outside window!) + { entityId: 1, dayIndex: 5 }, // window 3..7 + { entityId: 1, dayIndex: 3 }, // window 1..5 + // Duplicate valid event -> duplicateEventsCollapsed (1) + { entityId: 1, dayIndex: 4 }, + // Unknown entities (2 distinct: number 99 and string "99", plus 1 duplicate of number 99) + { entityId: 99, dayIndex: 4 }, + { entityId: '99', dayIndex: 4 }, + { entityId: 99, dayIndex: 4 }, // duplicateEventsCollapsed (2) + // Window out of range: off start, off end, dayIndex >= T, plus duplicate off-start + { entityId: 1, dayIndex: 1 }, // 1 - 2 < 0 + { entityId: 1, dayIndex: 10 }, // 10 + 2 >= 12 + { entityId: 1, dayIndex: 25 }, // dayIndex >= T + { entityId: 1, dayIndex: 1 }, // duplicateEventsCollapsed (3) + // Missing returns: entity NaN in window, benchmark NaN in window, plus duplicate missing + { entityId: 2, dayIndex: 5 }, // s2[4] is NaN + { entityId: 1, dayIndex: 7 }, // bench[8] is NaN + { entityId: 2, dayIndex: 5 }, // duplicateEventsCollapsed (4) + ]; + + const res = eventStudy( + { sessionDates, entityReturns, benchmarkReturns: bench, events }, + { preDays: 2, postDays: 2, minEvents: 3 } + ); + + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + expect(res.diagnostics).toEqual({ + eventsIn: 14, + eventsUsed: 3, + droppedUnknownEntity: 2, + droppedWindowOutOfRange: 3, + droppedMissingReturns: 2, + duplicateEventsCollapsed: 4, + }); + }); +}); + +describe('eventStudy recency gate', () => { + function runRecencyScenario(preCars: readonly number[], postCars: readonly number[]) { + const preDates = generateTradingDates(preCars.length, 2022); + const postDates = generateTradingDates(postCars.length, 2023); + const sessionDates = [...preDates, ...postDates]; + const series = new Float64Array(sessionDates.length); + const events: EventStudyEvent[] = []; + + for (let i = 0; i < preCars.length; i++) { + series[i] = preCars[i]!; + events.push({ entityId: 1, dayIndex: i }); + } + for (let i = 0; i < postCars.length; i++) { + const idx = preCars.length + i; + series[idx] = postCars[i]!; + events.push({ entityId: 1, dayIndex: idx }); + } + + const res = eventStudy( + { sessionDates, entityReturns: new Map([[1, series]]), events }, + { + preDays: 0, + postDays: 0, + minEvents: 2, + recencySplitDate: RECENCY_SPLIT_DATE, + recencyMinRatio: RECENCY_MIN_RATIO, + } + ); + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + throw new Error('Expected ok'); + } + return res.recency; + } + + test('passes positive and negative effects meeting recencyMinRatio and exact boundary', () => { + const posPass = runRecencyScenario([0.08, 0.12], [0.06, 0.08]); + expect(posPass.gate.pass).toBe(true); + expect(posPass.gate.reason).toBe('passed'); + expect(Math.abs((posPass.gate.ratio as number) - 0.7)).toBeLessThan(1e-12); + expect(Math.abs((posPass.pre.mean as number) - 0.1)).toBeLessThan(1e-12); + expect(Math.abs((posPass.post.mean as number) - 0.07)).toBeLessThan(1e-12); + + const posBoundary = runRecencyScenario([0.08], [0.04]); + expect(posBoundary.gate.pass).toBe(true); + expect(posBoundary.gate.reason).toBe('passed'); + expect(posBoundary.gate.ratio).toBe(0.5); + + // Negative event effect (e.g. dilutive offering / short spike): preserves negative sign + const negPass = runRecencyScenario([-0.08, -0.12], [-0.06, -0.08]); + expect(negPass.gate.pass).toBe(true); + expect(negPass.gate.reason).toBe('passed'); + expect(Math.abs((negPass.gate.ratio as number) - 0.7)).toBeLessThan(1e-12); + expect(Math.abs((negPass.pre.mean as number) - -0.1)).toBeLessThan(1e-12); + expect(Math.abs((negPass.post.mean as number) - -0.07)).toBeLessThan(1e-12); + + const negBoundary = runRecencyScenario([-0.08], [-0.04]); + expect(negBoundary.gate.pass).toBe(true); + expect(negBoundary.gate.reason).toBe('passed'); + expect(negBoundary.gate.ratio).toBe(0.5); + }); + + test('fails with explicit reasons for sign flip, decay below ratio, zero pre-mean, and empty windows', () => { + // Sign flips: pos -> neg, neg -> pos, pos -> 0, neg -> 0 + const posToNeg = runRecencyScenario([0.08], [-0.04]); + expect(posToNeg.gate.pass).toBe(false); + expect(posToNeg.gate.reason).toBe('sign_flipped'); + + const negToPos = runRecencyScenario([-0.08], [0.04]); + expect(negToPos.gate.pass).toBe(false); + expect(negToPos.gate.reason).toBe('sign_flipped'); + + const posToZero = runRecencyScenario([0.08], [0]); + expect(posToZero.gate.pass).toBe(false); + expect(posToZero.gate.reason).toBe('sign_flipped'); + + const negToZero = runRecencyScenario([-0.08], [0]); + expect(negToZero.gate.pass).toBe(false); + expect(negToZero.gate.reason).toBe('sign_flipped'); + + // Decay below ratio (both signs) + const posDecay = runRecencyScenario([0.08], [0.039]); + expect(posDecay.gate.pass).toBe(false); + expect(posDecay.gate.reason).toBe('post_below_ratio_threshold'); + + const negDecay = runRecencyScenario([-0.08], [-0.039]); + expect(negDecay.gate.pass).toBe(false); + expect(negDecay.gate.reason).toBe('post_below_ratio_threshold'); + + // Zero pre-mean (exact and float-cancelled) + const zeroPre = runRecencyScenario([0], [0.05]); + expect(zeroPre.gate.pass).toBe(false); + expect(zeroPre.gate.reason).toBe('zero_pre_mean'); + expect(zeroPre.gate.ratio).toBeNull(); + + const cancelledNegPre = runRecencyScenario([-0.1, -0.2, 0.3], [-0.05]); + expect(cancelledNegPre.gate.pass).toBe(false); + expect(cancelledNegPre.gate.reason).toBe('zero_pre_mean'); + expect(cancelledNegPre.gate.ratio).toBeNull(); + + // Empty pre / post windows + const emptyPre = runRecencyScenario([], [0.05, 0.06]); + expect(emptyPre.gate.pass).toBe(false); + expect(emptyPre.gate.reason).toBe('empty_pre_window'); + + const emptyPost = runRecencyScenario([0.05, 0.06], []); + expect(emptyPost.gate.pass).toBe(false); + expect(emptyPost.gate.reason).toBe('empty_post_window'); + }); +}); + +describe('eventStudy insufficient data, zero variance, and validation errors', () => { + const baseDates = ['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06']; + const baseMap = new Map([ + ['A', new Float64Array([0.01, 0.02, 0.03, 0.04])], + ['B', new Float64Array([0.01, 0.02, 0.03, 0.04])], + ]); + + test('returns insufficient_data for below_min_events and too_few_event_dates without throwing', () => { + const belowMin = eventStudy( + { + sessionDates: baseDates, + entityReturns: baseMap, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'B', dayIndex: 2 }, + ], + }, + { preDays: 0, postDays: 0, minEvents: 5 } + ); + expect(belowMin.status).toBe('insufficient_data'); + assertAccountingIdentity(belowMin); + if (belowMin.status === 'insufficient_data') { + expect(belowMin.reason).toBe('below_min_events'); + expect(belowMin.eventsUsed).toBe(2); + expect(belowMin.nDates).toBe(2); + } + + const oneDate = eventStudy( + { + sessionDates: baseDates, + entityReturns: baseMap, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'B', dayIndex: 1 }, + ], + }, + { preDays: 0, postDays: 0, minEvents: 2 } + ); + expect(oneDate.status).toBe('insufficient_data'); + assertAccountingIdentity(oneDate); + if (oneDate.status === 'insufficient_data') { + expect(oneDate.reason).toBe('too_few_event_dates'); + expect(oneDate.eventsUsed).toBe(2); + expect(oneDate.nDates).toBe(1); + } + }); + + test('zero-variance clustered CARs return status ok with insufficient neweyWest and zero NaNs', () => { + const constantReturns = new Map([ + ['A', new Float64Array([0.02, 0.02, 0.02, 0.02])], + ]); + const res = eventStudy( + { + sessionDates: baseDates, + entityReturns: constantReturns, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'A', dayIndex: 2 }, + ], + }, + { preDays: 0, postDays: 0, minEvents: 2 } + ); + expect(res.status).toBe('ok'); + if (res.status === 'ok') { + expect(res.clustered.neweyWest.status).toBe('insufficient_data'); + expect(res.offsets[0]!.standardError).toBe(0); + assertNoNaNDeep(res); + } + }); + + test('throws every EventStudyErrorCode on malformed inputs and options', () => { + const validInput: EventStudyInput = { + sessionDates: baseDates, + entityReturns: baseMap, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'B', dayIndex: 2 }, + ], + }; + + // INVALID_OPTION + expectEventStudyError(() => eventStudy(validInput, { preDays: -1 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { preDays: 1.5 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { postDays: -1 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { minEvents: 0 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { neweyWestLag: -1 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { recencyMinRatio: 0 }), 'INVALID_OPTION'); + expectEventStudyError( + () => eventStudy(validInput, { recencyMinRatio: Number.POSITIVE_INFINITY }), + 'INVALID_OPTION' + ); + + // INVALID_DATE + expectEventStudyError( + () => eventStudy(validInput, { recencySplitDate: '2023-02-29' }), + 'INVALID_DATE' + ); + expectEventStudyError( + () => eventStudy({ ...validInput, sessionDates: ['2023-02-29'] }), + 'INVALID_DATE' + ); + + // UNSORTED_DATES & DUPLICATE_DATE + expectEventStudyError( + () => eventStudy({ ...validInput, sessionDates: ['2022-01-04', '2022-01-03'] }), + 'UNSORTED_DATES' + ); + expectEventStudyError( + () => eventStudy({ ...validInput, sessionDates: ['2022-01-03', '2022-01-03'] }), + 'DUPLICATE_DATE' + ); + + // LENGTH_MISMATCH + expectEventStudyError( + () => + eventStudy({ + ...validInput, + entityReturns: new Map([['A', [0.01, 0.02]]]), + }), + 'LENGTH_MISMATCH' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + benchmarkReturns: [0.01, 0.02], + }), + 'LENGTH_MISMATCH' + ); + + // NON_FINITE_RETURN (even outside any event window) + expectEventStudyError( + () => + eventStudy({ + ...validInput, + entityReturns: new Map([ + ['A', [0.01, 0.02, 0.03, Number.POSITIVE_INFINITY]], + ]), + }), + 'NON_FINITE_RETURN' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + benchmarkReturns: [Number.NEGATIVE_INFINITY, 0.01, 0.02, 0.03], + }), + 'NON_FINITE_RETURN' + ); + + // INVALID_EVENT + expectEventStudyError( + () => + eventStudy({ + ...validInput, + events: [{ entityId: 'A', dayIndex: -1 }], + }), + 'INVALID_EVENT' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + events: [{ entityId: 'A', dayIndex: 1.25 }], + }), + 'INVALID_EVENT' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + events: [{ entityId: Number.NaN, dayIndex: 1 }], + }), + 'INVALID_EVENT' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + entityReturns: new Map([[Number.NaN, [0.01, 0.02, 0.03, 0.04]]]), + }), + 'INVALID_EVENT' + ); + }); +}); + +describe('eventStudy determinism and differential parity', () => { + test('produces bit-identical output under shuffled events and reversed entityReturns Map', () => { + const rng = createMulberry32(987654321); + const T = 60; + const E = 20; + const sessionDates = generateTradingDates(T, 2022); + const entries: Array<[EntityId, Float64Array]> = []; + for (let e = 0; e < E; e++) { + const id: EntityId = e % 2 === 0 ? e : `SYM_${e}`; + const arr = new Float64Array(T); + for (let t = 0; t < T; t++) { + arr[t] = (rng() - 0.49) * 0.04; + } + entries.push([id, arr]); + } + const bench = new Float64Array(T); + for (let t = 0; t < T; t++) { + bench[t] = (rng() - 0.5) * 0.01; + } + + const events: EventStudyEvent[] = []; + for (let i = 0; i < 120; i++) { + const id = entries[Math.floor(rng() * E)]![0]; + const dayIndex = 5 + Math.floor(rng() * (T - 12)); + events.push({ entityId: id, dayIndex }); + } + + const shuffledEvents = [...events]; + for (let i = shuffledEvents.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = shuffledEvents[i]!; + shuffledEvents[i] = shuffledEvents[j]!; + shuffledEvents[j] = tmp; + } + + const mapForward = new Map(entries); + const mapReverse = new Map([...entries].reverse()); + + const resA = eventStudy( + { sessionDates, entityReturns: mapForward, benchmarkReturns: bench, events }, + { preDays: 3, postDays: 5 } + ); + const resB = eventStudy( + { + sessionDates, + entityReturns: mapReverse, + benchmarkReturns: bench, + events: shuffledEvents, + }, + { preDays: 3, postDays: 5 } + ); + + expect(resA).toEqual(resB); + expect(resA.status).toBe('ok'); + expect(resB.status).toBe('ok'); + if (resA.status === 'ok' && resB.status === 'ok') { + for (let w = 0; w < resA.offsets.length; w++) { + const a = resA.offsets[w]!; + const b = resB.offsets[w]!; + expect(Object.is(a.aar, b.aar)).toBe(true); + expect(Object.is(a.standardError, b.standardError)).toBe(true); + expect(Object.is(a.caar, b.caar)).toBe(true); + expect(Object.is(a.caarFromZero, b.caarFromZero)).toBe(true); + expect(Object.is(a.carPercentiles.p5, b.carPercentiles.p5)).toBe(true); + expect(Object.is(a.carPercentiles.p50, b.carPercentiles.p50)).toBe(true); + expect(Object.is(a.carPercentiles.p95, b.carPercentiles.p95)).toBe(true); + } + for (let i = 0; i < resA.eventCars.cars.length; i++) { + expect(Object.is(resA.eventCars.cars[i], resB.eventCars.cars[i])).toBe(true); + } + for (let i = 0; i < resA.clustered.meanCars.length; i++) { + expect(Object.is(resA.clustered.meanCars[i], resB.clustered.meanCars[i])).toBe(true); + } + expect(Object.is(resA.clustered.carMean, resB.clustered.carMean)).toBe(true); + } + }); + + test('agrees with independent naive reference to 1e-12 across 200 seeded random panels', () => { + const rng = createMulberry32(20260403); + + for (let trial = 0; trial < 200; trial++) { + const T = 15 + Math.floor(rng() * 35); + const E = 3 + Math.floor(rng() * 12); + const preDays = Math.floor(rng() * 5); + const postDays = Math.floor(rng() * 6); + const minEvents = 2 + Math.floor(rng() * 4); + const useBench = rng() < 0.5; + const driftSign = rng() < 0.5 ? 1 : -1; + // Mix small (<65) and larger (>=65) event counts to exercise both percentile paths + const nEvents = trial % 5 === 0 ? 80 + Math.floor(rng() * 40) : 4 + Math.floor(rng() * 30); + + const sessionDates = generateTradingDates(T, 2022); + const entityReturns = new Map(); + const entityIds: EntityId[] = []; + + for (let e = 0; e < E; e++) { + const id: EntityId = e % 3 === 0 ? e : `E${e}`; + entityIds.push(id); + const arr = new Float64Array(T); + for (let t = 0; t < T; t++) { + arr[t] = rng() < 0.04 ? Number.NaN : driftSign * 0.002 + (rng() - 0.5) * 0.05; + } + entityReturns.set(id, arr); + } + + let benchmarkReturns: Float64Array | undefined; + if (useBench) { + benchmarkReturns = new Float64Array(T); + for (let t = 0; t < T; t++) { + benchmarkReturns[t] = rng() < 0.02 ? Number.NaN : (rng() - 0.5) * 0.02; + } + } + + const events: EventStudyEvent[] = []; + for (let i = 0; i < nEvents; i++) { + if (rng() < 0.05) { + events.push({ entityId: 'UNKNOWN', dayIndex: Math.floor(rng() * (T + 3)) }); + } else if (events.length > 0 && rng() < 0.1) { + events.push({ ...events[Math.floor(rng() * events.length)]! }); + } else { + const id = entityIds[Math.floor(rng() * E)]!; + const dayIndex = Math.floor(rng() * (T + 2)); + events.push({ entityId: id, dayIndex }); + } + } + + const input: EventStudyInput = { + sessionDates, + entityReturns, + benchmarkReturns, + events, + }; + const opts: EventStudyOptions = { preDays, postDays, minEvents }; + + const actual = eventStudy(input, opts); + const ref = naiveEventStudyReference(input, opts); + + assertAccountingIdentity(actual); + expect(actual.status).toBe(ref.status); + expect(actual.diagnostics).toEqual(ref.diagnostics); + + if (actual.status === 'insufficient_data') { + expect(actual.reason).toBe(ref.reason); + continue; + } + + assertNoNaNDeep(actual); + expect(actual.offsets.length).toBe(ref.offsets!.length); + for (let w = 0; w < actual.offsets.length; w++) { + const a = actual.offsets[w]!; + const r = ref.offsets![w]!; + expect(a.offset).toBe(r.offset); + expect(a.n).toBe(r.n); + expect(Math.abs(a.aar - r.aar)).toBeLessThan(1e-12); + expect(Math.abs(a.standardError - r.standardError)).toBeLessThan(1e-12); + expect(Math.abs(a.caar - r.caar)).toBeLessThan(1e-12); + if (r.caarFromZero === null) { + expect(a.caarFromZero).toBeNull(); + expect(a.postCarPercentiles).toBeNull(); + } else { + expect(Math.abs((a.caarFromZero as number) - r.caarFromZero)).toBeLessThan(1e-12); + for (const key of ['p5', 'p25', 'p50', 'p75', 'p95'] as const) { + expect( + Math.abs(a.postCarPercentiles![key] - r.postCarPercentiles![key]) + ).toBeLessThan(1e-12); + } + } + for (const key of ['p5', 'p25', 'p50', 'p75', 'p95'] as const) { + expect(Math.abs(a.carPercentiles[key] - r.carPercentiles[key])).toBeLessThan(1e-12); + } + } + + expect(actual.eventCars.cars.length).toBe(ref.eventCars!.length); + for (let i = 0; i < ref.eventCars!.length; i++) { + expect(Math.abs(actual.eventCars.cars[i]! - ref.eventCars![i]!)).toBeLessThan(1e-12); + } + + expect(actual.clustered.dates).toEqual(ref.clusteredDates!); + expect(Array.from(actual.clustered.eventCounts)).toEqual(ref.clusteredCounts!); + for (let i = 0; i < ref.clusteredMeanCars!.length; i++) { + expect( + Math.abs(actual.clustered.meanCars[i]! - ref.clusteredMeanCars![i]!) + ).toBeLessThan(1e-12); + } + expect(Math.abs(actual.clustered.carMean - ref.carMean!)).toBeLessThan(1e-12); + } + }); +}); + +describe('eventStudy benchmark', () => { + test( + '2,000 entities x 5,040 sessions, 200,000 events, window -10..+20 completes <= 5,000 ms', + () => { + const ENTITIES = 2_000; + const SESSIONS = 5_040; + const EVENTS = 200_000; + const PRE_DAYS = 10; + const POST_DAYS = 20; + + const rng = createMulberry32(20260404); + const sessionDates = generateTradingDates(SESSIONS, 2006); + const benchmarkReturns = new Float64Array(SESSIONS); + for (let t = 0; t < SESSIONS; t++) { + benchmarkReturns[t] = (rng() - 0.5) * 0.015; + } + + const entityReturns = new Map(); + for (let e = 0; e < ENTITIES; e++) { + const arr = new Float64Array(SESSIONS); + for (let t = 0; t < SESSIONS; t++) { + arr[t] = (rng() - 0.499) * 0.03; + } + entityReturns.set(e, arr); + } + + // Generate 200,000 distinct in-range (entityId, dayIndex) pairs deterministically: + // 100 distinct event days per entity across [PRE_DAYS, SESSIONS - POST_DAYS - 1]. + const minDay = PRE_DAYS; + const validSpan = SESSIONS - POST_DAYS - minDay; // 5010 + const eventsPerEntity = EVENTS / ENTITIES; // 100 + const stride = Math.floor(validSpan / eventsPerEntity); // 50 + const events: EventStudyEvent[] = new Array(EVENTS); + let idx = 0; + for (let e = 0; e < ENTITIES; e++) { + const offset = Math.floor(rng() * stride); + for (let k = 0; k < eventsPerEntity; k++) { + events[idx++] = { + entityId: e, + dayIndex: minDay + k * stride + offset, + }; + } + } + + const t0 = performance.now(); + const res = eventStudy( + { sessionDates, entityReturns, benchmarkReturns, events }, + { preDays: PRE_DAYS, postDays: POST_DAYS } + ); + const elapsedMs = performance.now() - t0; + const eventsPerSec = Math.round((EVENTS / elapsedMs) * 1000); + + process.stdout.write( + `[event-study benchmark] events=${EVENTS} window=-${PRE_DAYS}..+${POST_DAYS} elapsedMs=${elapsedMs.toFixed(2)} events/s=${eventsPerSec}\n` + ); + + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + if (res.status === 'ok') { + expect(res.diagnostics.eventsUsed).toBe(EVENTS); + expect(res.offsets.length).toBe(PRE_DAYS + POST_DAYS + 1); + } + expect(elapsedMs).toBeLessThanOrEqual(5_000); + }, + 15_000 + ); +});