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]: // k = -1: [0.02, 0.01, 0.03, 0.04] -> sorted [0.01, 0.02, 0.03, 0.04] // k = 0: [0.05, 0.03, 0.05, 0.10] -> sorted [0.03, 0.05, 0.05, 0.10] // k = +1: [0.09, 0.04, 0.06, 0.18] -> sorted [0.04, 0.06, 0.09, 0.18] // k = +2: [0.14, 0.07, 0.10, 0.19] -> sorted [0.07, 0.10, 0.14, 0.19] const expectedCarPercentiles = [ { p5: 0.0115, p25: 0.0175, p50: 0.025, p75: 0.0325, p95: 0.0385 }, { p5: 0.033, p25: 0.045, p50: 0.05, p75: 0.0625, p95: 0.0925 }, { p5: 0.043, p25: 0.055, p50: 0.075, p75: 0.1125, p95: 0.1665 }, { p5: 0.0745, p25: 0.0925, p50: 0.12, p75: 0.1525, p95: 0.1825 }, ]; // Per-event running post-event CAR[0..k]: // k = 0: [0.03, 0.02, 0.02, 0.06] -> sorted [0.02, 0.02, 0.03, 0.06] // k = +1: [0.07, 0.03, 0.03, 0.14] -> sorted [0.03, 0.03, 0.07, 0.14] // k = +2: [0.12, 0.06, 0.07, 0.15] -> sorted [0.06, 0.07, 0.12, 0.15] const expectedPostCarPercentiles = [ null, { p5: 0.02, p25: 0.02, p50: 0.025, p75: 0.0375, p95: 0.0555 }, { p5: 0.03, p25: 0.03, p50: 0.05, p75: 0.0875, p95: 0.1295 }, { p5: 0.0615, p25: 0.0675, p50: 0.095, p75: 0.1275, p95: 0.1455 }, ]; 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); const expCarP = expectedCarPercentiles[w]!; expect(Math.abs(off.carPercentiles.p5 - expCarP.p5)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p25 - expCarP.p25)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p50 - expCarP.p50)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p75 - expCarP.p75)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p95 - expCarP.p95)).toBeLessThan(1e-12); const expPostP = expectedPostCarPercentiles[w]!; if (expectedCaarZero[w] === null || expPostP === 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(); const postP = off.postCarPercentiles!; expect(Math.abs(postP.p5 - expPostP.p5)).toBeLessThan(1e-12); expect(Math.abs(postP.p25 - expPostP.p25)).toBeLessThan(1e-12); expect(Math.abs(postP.p50 - expPostP.p50)).toBeLessThan(1e-12); expect(Math.abs(postP.p75 - expPostP.p75)).toBeLessThan(1e-12); expect(Math.abs(postP.p95 - expPostP.p95)).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, SE, CAAR, percentiles, CAR, and clustered stats 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); expect(res.offsets.length).toBe(4); // Abnormal returns AR = r - bench at each offset: // Offset -1: [0.015, 0.005, 0.025, 0.030] -> mean = 0.01875, sumSq = 0.00036875 // Offset 0: [0.020, 0.010, 0.010, 0.050] -> mean = 0.0225, sumSq = 0.001075 // Offset +1: [0.030, 0.000, 0.000, 0.070] -> mean = 0.025, sumSq = 0.0033 // Offset +2: [0.040, 0.020, 0.030, 0.005] -> mean = 0.02375, sumSq = 0.00066875 const expectedAar = [0.01875, 0.0225, 0.025, 0.02375]; const expectedSe = [ Math.sqrt(0.00036875 / 12), Math.sqrt(0.001075 / 12), Math.sqrt(0.0033 / 12), Math.sqrt(0.00066875 / 12), ]; const expectedCaar = [0.01875, 0.04125, 0.06625, 0.09]; const expectedCaarZero = [null, 0.0225, 0.0475, 0.07125]; // Per-event running benchmark-adjusted CAR[-1..k]: // k = -1: [0.015, 0.005, 0.025, 0.030] -> sorted [0.005, 0.015, 0.025, 0.030] // k = 0: [0.035, 0.015, 0.035, 0.080] -> sorted [0.015, 0.035, 0.035, 0.080] // k = +1: [0.065, 0.015, 0.035, 0.150] -> sorted [0.015, 0.035, 0.065, 0.150] // k = +2: [0.105, 0.035, 0.065, 0.155] -> sorted [0.035, 0.065, 0.105, 0.155] const expectedCarPercentiles = [ { p5: 0.0065, p25: 0.0125, p50: 0.02, p75: 0.02625, p95: 0.02925 }, { p5: 0.018, p25: 0.03, p50: 0.035, p75: 0.04625, p95: 0.07325 }, { p5: 0.018, p25: 0.03, p50: 0.05, p75: 0.08625, p95: 0.13725 }, { p5: 0.0395, p25: 0.0575, p50: 0.085, p75: 0.1175, p95: 0.1475 }, ]; // Per-event running benchmark-adjusted post-event CAR[0..k]: // k = 0: [0.02, 0.01, 0.01, 0.05] -> sorted [0.01, 0.01, 0.02, 0.05] // k = +1: [0.05, 0.01, 0.01, 0.12] -> sorted [0.01, 0.01, 0.05, 0.12] // k = +2: [0.09, 0.03, 0.04, 0.125] -> sorted [0.03, 0.04, 0.09, 0.125] const expectedPostCarPercentiles = [ null, { p5: 0.01, p25: 0.01, p50: 0.015, p75: 0.0275, p95: 0.0455 }, { p5: 0.01, p25: 0.01, p50: 0.03, p75: 0.0675, p95: 0.1095 }, { p5: 0.0315, p25: 0.0375, p50: 0.065, p75: 0.09875, p95: 0.11975 }, ]; 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); const expCarP = expectedCarPercentiles[w]!; expect(Math.abs(off.carPercentiles.p5 - expCarP.p5)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p25 - expCarP.p25)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p50 - expCarP.p50)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p75 - expCarP.p75)).toBeLessThan(1e-12); expect(Math.abs(off.carPercentiles.p95 - expCarP.p95)).toBeLessThan(1e-12); const expPostP = expectedPostCarPercentiles[w]!; if (expectedCaarZero[w] === null || expPostP === 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(); const postP = off.postCarPercentiles!; expect(Math.abs(postP.p5 - expPostP.p5)).toBeLessThan(1e-12); expect(Math.abs(postP.p25 - expPostP.p25)).toBeLessThan(1e-12); expect(Math.abs(postP.p50 - expPostP.p50)).toBeLessThan(1e-12); expect(Math.abs(postP.p75 - expPostP.p75)).toBeLessThan(1e-12); expect(Math.abs(postP.p95 - expPostP.p95)).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 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.06, 0.04, 0.125]; 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.075)).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); }); }); 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'); }); test('assigns complete CAR[0..postDays] to its event-date cohort across the split boundary', () => { // Late-2022 event on 2022-12-30 has postDays=2 spanning 2023-01-03 and 2023-01-04. // Its full CAR[0..2] (0.01 + 0.02 + 0.03 = 0.06) is assigned to the pre-2023 cohort by event date. const sessionDates = [ '2022-12-29', '2022-12-30', '2023-01-03', '2023-01-04', '2023-01-05', '2023-01-06', ]; const series = new Float64Array([0.0, 0.01, 0.02, 0.03, 0.01, 0.0]); const res = eventStudy( { sessionDates, entityReturns: new Map([[1, series]]), events: [ { entityId: 1, dayIndex: 1 }, // 2022-12-30 (< 2023-01-01): CAR[0..2] = 0.01+0.02+0.03 = 0.06 { entityId: 1, dayIndex: 2 }, // 2023-01-03 (>= 2023-01-01): CAR[0..2] = 0.02+0.03+0.01 = 0.06 ], }, { preDays: 0, postDays: 2, minEvents: 2, recencySplitDate: RECENCY_SPLIT_DATE, recencyMinRatio: RECENCY_MIN_RATIO, } ); expect(res.status).toBe('ok'); if (res.status !== 'ok') { return; } expect(res.recency.pre.count).toBe(1); expect(res.recency.post.count).toBe(1); expect(Math.abs((res.recency.pre.mean as number) - 0.06)).toBeLessThan(1e-12); expect(Math.abs((res.recency.post.mean as number) - 0.06)).toBeLessThan(1e-12); expect(res.recency.gate.pass).toBe(true); expect(res.recency.gate.reason).toBe('passed'); expect(Math.abs((res.recency.gate.ratio as number) - 1.0)).toBeLessThan(1e-12); }); }); 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 ); });