T-83: tests

This commit is contained in:
Studio 2026-11-28 02:28:42 -05:00
parent c4c99d6e8c
commit 6bbdb4049e

View file

@ -0,0 +1,446 @@
import { describe, expect, test } from 'bun:test';
import {
EventStudyError,
evaluateRecencyGate,
eventDayIndex,
eventStudy,
neweyWestMeanTest,
type EntityId,
type EventStudyErrorCode,
type EventStudyEvent,
type EventStudyPercentiles,
type EventStudyResult,
} from '@stock-bot/calculations';
// QA edge cases for T-83 that the programmer suite does not reach: the introselect
// percentile path under ties / adversarial orderings and at the 64/65 switch-over,
// end-to-end timestamp -> session mapping (no look-ahead), id ordering, input
// immutability, default Newey-West lag, and degenerate calendars.
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 tradingDates(count: number, startYear = 2022): string[] {
const out: string[] = [];
const dt = new Date(Date.UTC(startYear, 0, 3));
while (out.length < count) {
const dow = dt.getUTCDay();
if (dow !== 0 && dow !== 6) {
out.push(dt.toISOString().slice(0, 10));
}
dt.setUTCDate(dt.getUTCDate() + 1);
}
return out;
}
function refPercentiles(values: readonly number[]): EventStudyPercentiles {
const s = [...values].sort((a, b) => a - b);
const q = (p: number): number => {
const pos = p * (s.length - 1);
const lo = Math.floor(pos);
const hi = Math.ceil(pos);
return lo === hi ? s[lo]! : s[lo]! + (pos - lo) * (s[hi]! - s[lo]!);
};
return { p5: q(0.05), p25: q(0.25), p50: q(0.5), p75: q(0.75), p95: q(0.95) };
}
function expectCode(fn: () => unknown, code: EventStudyErrorCode): void {
let caught: unknown;
try {
fn();
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(EventStudyError);
expect((caught as EventStudyError).code).toBe(code);
}
function okOrThrow(res: EventStudyResult): Extract<EventStudyResult, { status: 'ok' }> {
if (res.status !== 'ok') {
throw new Error(`expected ok, got ${res.status}/${res.reason}`);
}
return res;
}
/**
* One event per entity, all on day 1 and day 2 alternately (2 dates), window 0..0, so each
* offset's CAR cross-section is exactly `cars` and the percentile fan must equal R-7 on it.
*/
function fanForCars(cars: readonly number[]): EventStudyPercentiles {
const sessionDates = tradingDates(4);
const entityReturns = new Map<EntityId, Float64Array>();
const events: EventStudyEvent[] = [];
for (let i = 0; i < cars.length; i++) {
const day = 1 + (i % 2);
const arr = new Float64Array(4);
arr[day] = cars[i]!;
entityReturns.set(i, arr);
events.push({ entityId: i, dayIndex: day });
}
const res = okOrThrow(
eventStudy({ sessionDates, entityReturns, events }, { preDays: 0, postDays: 0, minEvents: 1 })
);
expect(res.offsets[0]!.n).toBe(cars.length);
return res.offsets[0]!.carPercentiles;
}
function expectFanEqual(actual: EventStudyPercentiles, expected: EventStudyPercentiles): void {
for (const key of ['p5', 'p25', 'p50', 'p75', 'p95'] as const) {
expect(Math.abs(actual[key] - expected[key])).toBeLessThan(1e-15);
}
}
describe('event-study QA: percentile fan (introselect path)', () => {
test('matches sorted R-7 at sizes around the 64/65 insertion-sort / introselect switch', () => {
const rng = createMulberry32(830_001);
for (const n of [2, 3, 20, 63, 64, 65, 66, 67, 99, 100, 101, 257, 1_000, 4_097]) {
const cars = Array.from({ length: n }, () => (rng() - 0.5) * 0.2);
expectFanEqual(fanForCars(cars), refPercentiles(cars));
}
});
test('matches sorted R-7 under heavy ties (3-way partition) and all-equal values', () => {
const rng = createMulberry32(830_002);
for (const n of [65, 66, 200, 2_000]) {
// only 3 distinct values -> most order statistics land inside equal runs
const fewDistinct = Array.from({ length: n }, () => [-0.01, 0, 0.02][Math.floor(rng() * 3)]!);
expectFanEqual(fanForCars(fewDistinct), refPercentiles(fewDistinct));
// tie straddling an interpolation neighbour: all but one equal
const almostConst = Array.from({ length: n }, (_, i) => (i === n - 1 ? 0.5 : 0.01));
expectFanEqual(fanForCars(almostConst), refPercentiles(almostConst));
const allEqual = new Array<number>(n).fill(0.03);
expectFanEqual(fanForCars(allEqual), refPercentiles(allEqual));
}
});
test('matches sorted R-7 on adversarial orderings that stress median-of-3 / heapsort fallback', () => {
const n = 3_001;
const ascending = Array.from({ length: n }, (_, i) => i * 1e-4);
const descending = [...ascending].reverse();
const organPipe = Array.from({ length: n }, (_, i) => Math.min(i, n - 1 - i) * 1e-4);
const sawtooth = Array.from({ length: n }, (_, i) => (i % 17) * 1e-3);
// median-of-3 killer style: interleave small and large
const interleaved = Array.from({ length: n }, (_, i) => (i % 2 === 0 ? i : n * 2 - i) * 1e-5);
for (const cars of [ascending, descending, organPipe, sawtooth, interleaved]) {
expectFanEqual(fanForCars(cars), refPercentiles(cars));
}
});
});
describe('event-study QA: end-to-end information availability', () => {
test('an event known after session k close uses session k+1 as offset 0 (no look-ahead)', () => {
// closes at 16:00 on consecutive days (epoch ms); returns encode their own index
const T = 10;
const sessionDates = tradingDates(T);
const closes = sessionDates.map(d => Date.parse(`${d}T21:00:00Z`));
const series = Float64Array.from({ length: T }, (_, t) => (t + 1) / 100);
const entityReturns = new Map<EntityId, Float64Array>([['X', series]]);
const atClose = eventDayIndex(closes, closes[4]!);
const afterClose = eventDayIndex(closes, closes[4]! + 1);
const intraday = eventDayIndex(closes, closes[6]! - 3_600_000);
expect(atClose).toEqual({ status: 'ok', dayIndex: 4 });
expect(afterClose).toEqual({ status: 'ok', dayIndex: 5 });
expect(intraday).toEqual({ status: 'ok', dayIndex: 6 });
const res = okOrThrow(
eventStudy(
{
sessionDates,
entityReturns,
events: [
{ entityId: 'X', dayIndex: (afterClose as { dayIndex: number }).dayIndex },
{ entityId: 'X', dayIndex: (intraday as { dayIndex: number }).dayIndex },
],
},
{ preDays: 1, postDays: 1, minEvents: 2, neweyWestLag: 0 }
)
);
// offset 0 AR for event on day 5 is series[5] = 0.06, never series[4]
expect(Array.from(res.eventCars.dayIndices)).toEqual([5, 6]);
expect(Math.abs(res.eventCars.cars[0]! - (0.06 + 0.07))).toBeLessThan(1e-15);
expect(Math.abs(res.eventCars.cars[1]! - (0.07 + 0.08))).toBeLessThan(1e-15);
expect(res.eventCars.dates).toEqual([sessionDates[5], sessionDates[6]]);
});
test('eventDayIndex on a single-session calendar and with a huge sorted Float64Array', () => {
expect(eventDayIndex([100], 100)).toEqual({ status: 'ok', dayIndex: 0 });
expect(eventDayIndex([100], -1e15)).toEqual({ status: 'ok', dayIndex: 0 });
expect(eventDayIndex([100], 101)).toEqual({ status: 'no_session', reason: 'after_last_session' });
const big = Float64Array.from({ length: 100_000 }, (_, i) => i * 10);
for (const [ts, want] of [
[0, 0],
[1, 1],
[10, 1],
[11, 2],
[499_990, 49_999],
[999_990, 99_999],
] as const) {
expect(eventDayIndex(big, ts)).toEqual({ status: 'ok', dayIndex: want });
}
expectCode(() => eventDayIndex([1, 2, 3], Number.NEGATIVE_INFINITY), 'INVALID_TIMESTAMP');
expectCode(() => eventDayIndex([3, 2], 1), 'UNSORTED_TIMESTAMPS');
});
});
describe('event-study QA: ordering, immutability and defaults', () => {
test('numeric ids sort numerically (9 before 10) and before string ids in eventCars', () => {
const sessionDates = tradingDates(5);
const mk = (v: number) => Float64Array.from({ length: 5 }, () => v);
const entityReturns = new Map<EntityId, Float64Array>([
['b', mk(0.05)],
[10, mk(0.02)],
['a', mk(0.04)],
[9, mk(0.01)],
['10', mk(0.03)],
]);
const events: EventStudyEvent[] = ['b', 10, 'a', 9, '10'].map(id => ({
entityId: id,
dayIndex: 2,
}));
events.push({ entityId: 9, dayIndex: 3 });
const res = okOrThrow(
eventStudy({ sessionDates, entityReturns, events }, { preDays: 1, postDays: 0, minEvents: 2 })
);
expect(res.eventCars.entityIds).toEqual([9, 10, '10', 'a', 'b', 9]);
expect(Array.from(res.eventCars.cars)).toEqual([0.01, 0.02, 0.03, 0.04, 0.05, 0.01]);
});
test('does not mutate inputs and returns fresh buffers on repeated calls', () => {
const rng = createMulberry32(830_003);
const T = 40;
const sessionDates = tradingDates(T);
const bench = Float64Array.from({ length: T }, () => (rng() - 0.5) * 0.01);
const entityReturns = new Map<EntityId, Float64Array>();
for (let e = 0; e < 6; e++) {
entityReturns.set(e, Float64Array.from({ length: T }, () => (rng() - 0.5) * 0.04));
}
const events: EventStudyEvent[] = Array.from({ length: 30 }, () => ({
entityId: Math.floor(rng() * 6),
dayIndex: Math.floor(rng() * T),
}));
const snapshot = {
bench: Array.from(bench),
series: [...entityReturns].map(([id, s]) => [id, Array.from(s)]),
events: JSON.stringify(events),
dates: [...sessionDates],
};
const a = okOrThrow(
eventStudy({ sessionDates, entityReturns, benchmarkReturns: bench, events }, { preDays: 2, postDays: 3 })
);
const b = okOrThrow(
eventStudy({ sessionDates, entityReturns, benchmarkReturns: bench, events }, { preDays: 2, postDays: 3 })
);
expect(Array.from(bench)).toEqual(snapshot.bench);
expect([...entityReturns].map(([id, s]) => [id, Array.from(s)])).toEqual(snapshot.series);
expect(JSON.stringify(events)).toBe(snapshot.events);
expect(sessionDates).toEqual(snapshot.dates);
expect(a.eventCars.cars).not.toBe(b.eventCars.cars);
a.eventCars.cars.fill(99);
a.clustered.meanCars.fill(99);
expect(b.eventCars.cars[0]).not.toBe(99);
expect(b.clustered.meanCars[0]).not.toBe(99);
});
test('omitted neweyWestLag uses the T-82 default lag on the number of clustered dates', () => {
const rng = createMulberry32(830_004);
const T = 400;
const sessionDates = tradingDates(T, 2020);
const entityReturns = new Map<EntityId, Float64Array>();
for (let e = 0; e < 5; e++) {
entityReturns.set(e, Float64Array.from({ length: T }, () => (rng() - 0.48) * 0.03));
}
const events: EventStudyEvent[] = [];
for (let d = 5; d < T - 5; d += 2) {
events.push({ entityId: d % 5, dayIndex: d });
}
const res = okOrThrow(
eventStudy({ sessionDates, entityReturns, events }, { preDays: 1, postDays: 3 })
);
const expected = neweyWestMeanTest(res.clustered.meanCars);
expect(res.clustered.nDates).toBeGreaterThan(100);
expect(res.clustered.neweyWest).toEqual(expected);
expect(res.clustered.neweyWest.lag).toBeGreaterThan(0);
// positive-mean recency gate is exactly T-82's evaluateRecencyGate on the clustered series
const raw = evaluateRecencyGate(res.clustered.dates, res.clustered.meanCars);
expect(res.recency.pre).toEqual(raw.pre);
expect(res.recency.post).toEqual(raw.post);
if ((raw.pre.mean ?? 0) > 0) {
expect(res.recency.gate.pass).toBe(raw.gate.pass);
expect(res.recency.gate.ratio).toBe(raw.gate.ratio);
}
});
test('preDays = 0 makes caar equal caarFromZero and both fans identical at every offset', () => {
const rng = createMulberry32(830_005);
const T = 30;
const sessionDates = tradingDates(T);
const entityReturns = new Map<EntityId, Float64Array>();
for (let e = 0; e < 4; e++) {
entityReturns.set(e, Float64Array.from({ length: T }, () => (rng() - 0.5) * 0.04));
}
const events = Array.from({ length: 12 }, (_, i) => ({ entityId: i % 4, dayIndex: 2 + i * 2 }));
const res = okOrThrow(
eventStudy({ sessionDates, entityReturns, events }, { preDays: 0, postDays: 3, minEvents: 3 })
);
expect(res.offsets.map(o => o.offset)).toEqual([0, 1, 2, 3]);
for (const o of res.offsets) {
expect(o.caarFromZero).toBe(o.caar);
expect(o.postCarPercentiles).toEqual(o.carPercentiles);
}
});
test('compensated summation keeps AAR exact when large and small returns mix', () => {
const sessionDates = tradingDates(3);
const entityReturns = new Map<EntityId, number[]>();
const vals = [1e8, 1, -1e8, 1, 1e8, -1e8];
vals.forEach((v, i) => entityReturns.set(i, [0, v, 0]));
const events = vals.map((_, i) => ({ entityId: i, dayIndex: 1 }));
// one extra event on another date so nDates >= 2 (entity 0 day 2: return 0, window 0..0)
events.push({ entityId: 0, dayIndex: 2 });
const res = okOrThrow(
eventStudy({ sessionDates, entityReturns, events }, { preDays: 0, postDays: 0, minEvents: 2 })
);
expect(res.offsets[0]!.aar).toBe(2 / 7);
expect(res.clustered.meanCars[0]).toBe(2 / 6);
});
});
describe('event-study QA: degenerate inputs and validation gaps', () => {
test('empty calendar / empty events / empty entity map return insufficient_data with zeroed diagnostics', () => {
const empty = eventStudy({ sessionDates: [], entityReturns: new Map(), events: [] });
expect(empty.status).toBe('insufficient_data');
if (empty.status === 'insufficient_data') {
expect(empty.reason).toBe('below_min_events');
expect(empty.nDates).toBe(0);
expect(empty.diagnostics).toEqual({
eventsIn: 0,
eventsUsed: 0,
droppedUnknownEntity: 0,
droppedWindowOutOfRange: 0,
droppedMissingReturns: 0,
duplicateEventsCollapsed: 0,
});
}
const noEntities = eventStudy({
sessionDates: tradingDates(3),
entityReturns: new Map(),
events: [
{ entityId: 1, dayIndex: 1 },
{ entityId: 1, dayIndex: 1 },
],
});
expect(noEntities.diagnostics).toMatchObject({
eventsIn: 2,
droppedUnknownEntity: 1,
duplicateEventsCollapsed: 1,
});
});
test('huge dayIndex values are counted out of range, not wrapped through Int32 buffers', () => {
const sessionDates = tradingDates(10);
const entityReturns = new Map<EntityId, Float64Array>([[1, new Float64Array(10)]]);
const res = eventStudy(
{
sessionDates,
entityReturns,
events: [
{ entityId: 1, dayIndex: 2 ** 32 + 3 },
{ entityId: 1, dayIndex: 2 ** 31 },
{ entityId: 1, dayIndex: Number.MAX_SAFE_INTEGER },
{ entityId: 1, dayIndex: 3 },
{ entityId: 1, dayIndex: 4 },
],
},
{ preDays: 1, postDays: 1, minEvents: 2 }
);
expect(res.status).toBe('ok');
expect(res.diagnostics.droppedWindowOutOfRange).toBe(3);
expect(res.diagnostics.eventsUsed).toBe(2);
});
test('Infinity / holes anywhere in the benchmark or entity series throw, NaN entity key throws', () => {
const sessionDates = tradingDates(4);
const ok = new Float64Array(4);
const events = [{ entityId: 1, dayIndex: 1 }];
expectCode(
() =>
eventStudy({
sessionDates,
entityReturns: new Map([[1, ok]]),
benchmarkReturns: [0, 0, 0, Number.NEGATIVE_INFINITY],
events,
}),
'NON_FINITE_RETURN'
);
// sparse array hole -> undefined, must not be silently treated as a return
const holey: number[] = new Array(4);
holey[0] = 0;
holey[1] = 0;
holey[3] = 0;
expectCode(
() => eventStudy({ sessionDates, entityReturns: new Map([[1, holey]]), events }),
'NON_FINITE_RETURN'
);
expectCode(
() => eventStudy({ sessionDates, entityReturns: new Map([[Number.NaN, ok]]), events }),
'INVALID_EVENT'
);
expectCode(
() =>
eventStudy({
sessionDates,
entityReturns: new Map([[1, ok]]),
events: [{ entityId: 1, dayIndex: Number.NaN }],
}),
'INVALID_EVENT'
);
expectCode(
() => eventStudy({ sessionDates: ['2022-1-03'], entityReturns: new Map(), events: [] }),
'INVALID_DATE'
);
expectCode(
() => eventStudy({ sessionDates: [], entityReturns: new Map(), events: [] }, { postDays: 0.5 }),
'INVALID_OPTION'
);
expectCode(
() =>
eventStudy({ sessionDates: [], entityReturns: new Map(), events: [] }, { recencyMinRatio: -1 }),
'INVALID_OPTION'
);
});
test('negative effect strengthening post-split passes with ratio > 1 and keeps signed means', () => {
const pre = tradingDates(3, 2021);
const post = tradingDates(3, 2024);
const sessionDates = [...pre, ...post];
const series = new Float64Array([-0.02, -0.02, -0.02, -0.05, -0.05, -0.05]);
const res = okOrThrow(
eventStudy(
{
sessionDates,
entityReturns: new Map([[1, series]]),
events: sessionDates.map((_, i) => ({ entityId: 1, dayIndex: i })),
},
{ preDays: 0, postDays: 0, minEvents: 2 }
)
);
expect(res.recency.pre.mean).toBeCloseTo(-0.02, 15);
expect(res.recency.post.mean).toBeCloseTo(-0.05, 15);
expect(res.recency.gate).toEqual({ pass: true, reason: 'passed', ratio: res.recency.gate.ratio });
expect(res.recency.gate.ratio).toBeCloseTo(2.5, 12);
});
});