T-123: tests

This commit is contained in:
Studio 2026-11-29 16:52:30 -05:00
parent ee983cb349
commit abe114f415

View file

@ -0,0 +1,672 @@
import { describe, expect, it } from 'bun:test';
import {
type BarRecord,
type BuildEventStudyInputResult,
type EventObservation,
type EventStudyExchangeCalendars,
type ExchangeSessionClose,
type TrialLedgerExecutor,
buildEventStudyInput,
runEventStudy,
} from '@stock-bot/research';
// QA suite for T-123: compares `buildEventStudyInput` against a deliberately naive reference
// model on seeded random panels (two exchange calendars with different holidays and an NYSE
// half-day, EDT/EST close stamps, gaps, bad closes, exact duplicate bars, late-listing /
// early-delisting, events at/around exact close timestamps, weekends, pre-history and
// post-cutoff), plus truncation (prefix-stability) and an end-to-end half-day CAR probe.
const MS_PER_DAY = 86_400_000;
function createSeededRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0, ms = 0): number {
const [y, m, d] = date.split('-').map(Number);
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms);
}
function makeBusinessDates(startDate: string, count: number): string[] {
const out: string[] = [];
const current = new Date(`${startDate}T00:00:00.000Z`);
while (out.length < count) {
const day = current.getUTCDay();
if (day !== 0 && day !== 6) {
out.push(current.toISOString().slice(0, 10));
}
current.setUTCDate(current.getUTCDate() + 1);
}
return out;
}
// 16:00 ET in UTC: 20:00 during EDT (before 2022-11-06 / from 2023-03-12), 21:00 during EST.
function regularCloseHourUtc(date: string): number {
return date < '2022-11-06' || date >= '2023-03-12' ? 20 : 21;
}
function makeBar(listingId: number, ts: number, close: number): BarRecord {
return {
listingId,
ts,
open: close,
high: close,
low: close,
close,
volume: 1_000,
vwap: close,
knownAt: ts,
};
}
function makeTrappedBar(listingId: number, ts: number): BarRecord {
const bar = { ...makeBar(listingId, ts, 1) } as Record<string, unknown>;
Object.defineProperty(bar, 'close', {
enumerable: true,
get() {
throw new Error(`Vault breach: close read for listing ${listingId} at ${ts}`);
},
});
return bar as unknown as BarRecord;
}
function shuffle<T>(items: readonly T[], seed: number): T[] {
const copy = [...items];
const rand = createSeededRng(seed);
for (let i = copy.length - 1; i > 0; i -= 1) {
const j = Math.floor(rand() * (i + 1));
[copy[i], copy[j]] = [copy[j]!, copy[i]!];
}
return copy;
}
const US_HOLIDAYS = new Set(['2022-11-24', '2022-12-26', '2023-01-02', '2023-01-16', '2023-02-20']);
const CA_HOLIDAYS = new Set(['2022-10-10', '2022-12-26', '2022-12-27', '2023-01-02', '2023-02-20']);
const NYSE_HALF_DAYS = new Set(['2022-11-25']);
function buildCalendars(dates: readonly string[]): {
xnys: ExchangeSessionClose[];
xtse: ExchangeSessionClose[];
} {
const xnys: ExchangeSessionClose[] = [];
const xtse: ExchangeSessionClose[] = [];
for (const date of dates) {
const regular = regularCloseHourUtc(date);
if (!US_HOLIDAYS.has(date)) {
xnys.push({ date, closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? regular - 3 : regular) });
}
if (!CA_HOLIDAYS.has(date)) {
xtse.push({ date, closeTs: makeUtcMs(date, regular) });
}
}
return { xnys, xtse };
}
interface RandomPanel {
readonly bars: BarRecord[];
readonly events: EventObservation[];
readonly calendars: EventStudyExchangeCalendars;
readonly calendarByListing: Map<number, ExchangeSessionClose[]>;
readonly dates: string[];
}
/**
* Builds a seeded random panel. Bars dated on/after `trapFromDate` get a throwing `close`
* getter so any Vault breach fails the test.
*/
function buildRandomPanel(seed: number, trapFromDate: string | null): RandomPanel {
const rand = createSeededRng(seed);
const dates = makeBusinessDates('2022-10-03', 110);
const { xnys, xtse } = buildCalendars(dates);
const listingCount = 12;
const listingIds = Array.from({ length: listingCount }, (_, i) => 100 + i * 7);
const calendarByListing = new Map<number, ExchangeSessionClose[]>();
const listingCalendarId = new Map<number, string>();
const bars: BarRecord[] = [];
for (let l = 0; l < listingCount; l += 1) {
const listingId = listingIds[l]!;
const isUs = l % 2 === 0;
const cal = isUs ? xnys : xtse;
calendarByListing.set(listingId, cal);
listingCalendarId.set(listingId, isUs ? 'XNYS' : 'XTSE');
const startIdx = l % 4 === 3 ? 20 + Math.floor(rand() * 20) : 0;
const endIdx = l % 5 === 4 ? cal.length - 30 - Math.floor(rand() * 10) : cal.length;
let price = 20 + l;
for (let s = startIdx; s < endIdx; s += 1) {
const session = cal[s]!;
if (rand() < 0.08) {
continue; // gap
}
price *= 1 + (rand() * 2 - 1) * 0.02;
const ts = makeUtcMs(session.date, regularCloseHourUtc(session.date)); // curated 16:00 ET
const trapped = trapFromDate !== null && session.date >= trapFromDate;
if (trapped) {
bars.push(makeTrappedBar(listingId, ts));
continue;
}
const u = rand();
const close = u < 0.01 ? 0 : u < 0.02 ? -1 : u < 0.025 ? Number.NaN : u < 0.03 ? Number.POSITIVE_INFINITY : price;
bars.push(makeBar(listingId, ts, close));
if (rand() < 0.03) {
bars.push(makeBar(listingId, ts, close)); // exact duplicate
}
}
}
const events: EventObservation[] = [];
const eventCount = 160;
for (let i = 0; i < eventCount; i += 1) {
const unknown = rand() < 0.05;
const listingId = unknown ? 9_999 : listingIds[Math.floor(rand() * listingCount)]!;
const cal = calendarByListing.get(listingId) ?? xnys;
const anchorSession = cal[Math.floor(rand() * cal.length)]!;
const mode = Math.floor(rand() * 7);
let knownAt: number;
if (mode === 0) {
knownAt = anchorSession.closeTs; // exactly at close -> same session
} else if (mode === 1) {
knownAt = anchorSession.closeTs + 1; // 1 ms after close -> next session
} else if (mode === 2) {
knownAt = anchorSession.closeTs - 1;
} else if (mode === 3) {
knownAt = makeUtcMs(anchorSession.date, 19); // 14:00/15:00 ET intraday (after half-day close)
} else if (mode === 4) {
knownAt = makeUtcMs(anchorSession.date, 22, 30); // after close
} else if (mode === 5) {
knownAt = makeUtcMs(anchorSession.date, 12) + 2 * MS_PER_DAY; // may land on weekend
} else {
knownAt = makeUtcMs('2022-09-15', 15) + Math.floor(rand() * 200) * MS_PER_DAY; // pre-history .. post-cutoff
}
events.push({ listingId, knownAt, kind: 'filing', subtype: rand() < 0.5 ? '10-q' : 'interim_financial_statements' });
if (rand() < 0.05) {
events.push({ listingId, knownAt, kind: 'filing', subtype: 'other' }); // duplicate anchor
}
}
// Explicit NYSE half-day probe: 14:00 ET on Black Friday for a US and a CA listing.
events.push({ listingId: listingIds[0]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' });
events.push({ listingId: listingIds[1]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: null });
return {
bars,
events,
calendars: {
calendars: new Map([
['XNYS', xnys],
['XTSE', xtse],
]),
listingCalendarId,
},
calendarByListing,
dates,
};
}
interface ReferenceResult {
sessionDates: string[];
entityIds: number[];
returns: Map<number, number[]>;
benchmark: number[];
events: { entityId: number; dayIndex: number }[];
diagnostics: Record<string, number>;
}
/** Naive O(n^2) reference model of the documented contract. */
function referenceBuild(panel: RandomPanel, vaultCutoffDate: string): ReferenceResult {
const cutoffMs = makeUtcMs(vaultCutoffDate, 0);
const dateOf = (ts: number) => new Date(Math.floor(ts / MS_PER_DAY) * MS_PER_DAY).toISOString().slice(0, 10);
const postDates = new Set<string>();
const perListing = new Map<number, Map<string, number>>();
let duplicateBars = 0;
for (const bar of panel.bars) {
const date = dateOf(bar.ts);
if (date >= vaultCutoffDate) {
postDates.add(date);
continue;
}
const m = perListing.get(bar.listingId) ?? new Map<string, number>();
perListing.set(bar.listingId, m);
if (m.has(date)) {
duplicateBars += 1;
continue;
}
m.set(date, bar.close);
}
const sessionDates = [...new Set([...perListing.values()].flatMap(m => [...m.keys()]))].sort();
const entityIds = [...perListing.keys()].sort((a, b) => a - b);
const returns = new Map<number, number[]>();
const benchSum = new Array<number>(sessionDates.length).fill(0);
const benchCount = new Array<number>(sessionDates.length).fill(0);
let nonPositiveCloseReturns = 0;
for (const id of entityIds) {
const closes = perListing.get(id)!;
const calDates = panel.calendarByListing.get(id)!.map(s => s.date);
const series = sessionDates.map((date, d) => {
if (!closes.has(date)) {
return Number.NaN;
}
const c = calDates.indexOf(date);
if (c <= 0 || !closes.has(calDates[c - 1]!)) {
return Number.NaN;
}
const prev = closes.get(calDates[c - 1]!)!;
const curr = closes.get(date)!;
const ret = curr / prev - 1;
if (!(prev > 0 && curr > 0 && Number.isFinite(prev) && Number.isFinite(curr) && Number.isFinite(ret))) {
nonPositiveCloseReturns += 1;
return Number.NaN;
}
benchSum[d] += ret;
benchCount[d] += 1;
return ret;
});
returns.set(id, series);
}
const benchmark = benchSum.map((s, d) => (benchCount[d]! > 0 ? s / benchCount[d]! : Number.NaN));
let vaultExcludedEvents = 0;
let droppedUnknownListing = 0;
let droppedAfterLastSession = 0;
let droppedMissingCalendarSession = 0;
const cands: { entityId: number; dayIndex: number }[] = [];
for (const ev of panel.events) {
if (ev.knownAt >= cutoffMs) {
vaultExcludedEvents += 1;
continue;
}
if (!perListing.has(ev.listingId)) {
droppedUnknownListing += 1;
continue;
}
const preCal = panel.calendarByListing.get(ev.listingId)!.filter(s => s.date < vaultCutoffDate);
const eligible = preCal.find(s => s.closeTs >= ev.knownAt);
if (eligible === undefined || eligible.date > sessionDates[sessionDates.length - 1]!) {
droppedAfterLastSession += 1;
continue;
}
const dayIndex = sessionDates.indexOf(eligible.date);
if (dayIndex < 0) {
droppedMissingCalendarSession += 1;
continue;
}
cands.push({ entityId: ev.listingId, dayIndex });
}
cands.sort((a, b) => a.dayIndex - b.dayIndex || a.entityId - b.entityId);
const events = cands.filter(
(c, i) => i === 0 || c.dayIndex !== cands[i - 1]!.dayIndex || c.entityId !== cands[i - 1]!.entityId
);
return {
sessionDates,
entityIds,
returns,
benchmark,
events,
diagnostics: {
vaultExcludedDates: postDates.size,
vaultExcludedEvents,
droppedUnknownListing,
droppedAfterLastSession,
droppedMissingCalendarSession,
duplicateEvents: cands.length - events.length,
duplicateBars,
nonPositiveCloseReturns,
},
};
}
function nanSafe(values: ArrayLike<number>): (number | string)[] {
return Array.from(values, v => (Number.isNaN(v) ? 'NaN' : v));
}
function expectSameAsReference(actual: BuildEventStudyInputResult, ref: ReferenceResult): void {
expect(actual.input.sessionDates).toEqual(ref.sessionDates);
expect(Array.from(actual.input.entityReturns.keys())).toEqual(ref.entityIds);
for (const id of ref.entityIds) {
expect(nanSafe(actual.input.entityReturns.get(id)!)).toEqual(nanSafe(ref.returns.get(id)!));
}
expect(nanSafe(actual.input.benchmarkReturns!)).toEqual(nanSafe(ref.benchmark));
expect(actual.input.events.map(e => ({ entityId: e.entityId, dayIndex: e.dayIndex }))).toEqual(ref.events);
expect({ ...actual.diagnostics }).toEqual(ref.diagnostics);
}
describe('buildEventStudyInput QA — seeded reference-model comparison', () => {
const VAULT_CUTOFF = '2023-02-01';
for (const seed of [20261129, 7, 424242, 99]) {
it(`matches the naive reference model exactly and never reads vaulted closes (seed ${seed})`, () => {
const panel = buildRandomPanel(seed, VAULT_CUTOFF);
const ref = referenceBuild(panel, VAULT_CUTOFF);
const actual = buildEventStudyInput({
bars: panel.bars,
events: panel.events,
vaultCutoffDate: VAULT_CUTOFF,
benchmark: 'equal_weight',
exchangeCalendars: panel.calendars,
});
expectSameAsReference(actual, ref);
// Conservation identity.
const d = actual.diagnostics;
expect(
actual.input.events.length +
d.vaultExcludedEvents +
d.droppedUnknownListing +
d.droppedAfterLastSession +
d.droppedMissingCalendarSession +
d.duplicateEvents
).toBe(panel.events.length);
// No session date reaches the Vault and no event anchors onto a Vault session.
expect(actual.input.sessionDates.every(date => date < VAULT_CUTOFF)).toBe(true);
// Fixture actually exercises the interesting branches.
expect(d.vaultExcludedEvents).toBeGreaterThan(0);
expect(d.droppedUnknownListing).toBeGreaterThan(0);
expect(d.vaultExcludedDates).toBeGreaterThan(0);
expect(d.nonPositiveCloseReturns).toBeGreaterThan(0);
// Shuffled inputs give the identical result.
const shuffled = buildEventStudyInput({
bars: shuffle(panel.bars, seed + 1),
events: shuffle(panel.events, seed + 2),
vaultCutoffDate: VAULT_CUTOFF,
benchmark: 'equal_weight',
exchangeCalendars: panel.calendars,
});
expectSameAsReference(shuffled, ref);
});
}
it('anchors the NYSE Black Friday 14:00 ET filing to Monday and the TSX one to Friday', () => {
const panel = buildRandomPanel(20261129, VAULT_CUTOFF);
const actual = buildEventStudyInput({
bars: panel.bars,
events: panel.events,
vaultCutoffDate: VAULT_CUTOFF,
exchangeCalendars: panel.calendars,
});
const usId = 100;
const caId = 107;
const dates = actual.input.sessionDates;
const usDates = actual.input.events.filter(e => e.entityId === usId).map(e => dates[e.dayIndex]);
const caDates = actual.input.events.filter(e => e.entityId === caId).map(e => dates[e.dayIndex]);
expect(usDates).toContain('2022-11-28');
expect(caDates).toContain('2022-11-25');
});
});
describe('buildEventStudyInput QA — truncation (prefix stability) across Vault cutoffs', () => {
it('earlier-cutoff output is an exact prefix of later-cutoff output (no future-dependent values)', () => {
const panel = buildRandomPanel(31337, null);
const cutoffs = ['2022-11-25', '2022-12-27', '2023-01-17', '2023-02-21'];
const results = cutoffs.map(vaultCutoffDate =>
buildEventStudyInput({
bars: panel.bars,
events: panel.events,
vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars: panel.calendars,
})
);
for (let i = 0; i + 1 < results.length; i += 1) {
const early = results[i]!.input;
const late = results[i + 1]!.input;
const n = early.sessionDates.length;
expect(n).toBeGreaterThan(0);
expect(late.sessionDates.slice(0, n)).toEqual([...early.sessionDates]);
for (const [id, series] of early.entityReturns) {
const lateSeries = late.entityReturns.get(id)!;
expect(nanSafe(Array.from(lateSeries).slice(0, n))).toEqual(nanSafe(series));
}
expect(nanSafe(Array.from(late.benchmarkReturns!).slice(0, n))).toEqual(
nanSafe(early.benchmarkReturns!)
);
const lateKeys = new Set(late.events.map(e => `${e.entityId}@${e.dayIndex}`));
for (const ev of early.events) {
expect(lateKeys.has(`${ev.entityId}@${ev.dayIndex}`)).toBe(true);
}
}
});
it('a poisoned future (absurd closes, extra filings, calendar tail) leaves pre-cutoff output byte-identical', () => {
const cutoff = '2023-01-17';
const panel = buildRandomPanel(555, null);
const base = buildEventStudyInput({
bars: panel.bars,
events: panel.events,
vaultCutoffDate: cutoff,
benchmark: 'equal_weight',
exchangeCalendars: panel.calendars,
});
const cutoffMs = makeUtcMs(cutoff, 0);
const poisonedBars = panel.bars.map(b =>
b.ts >= cutoffMs ? makeBar(b.listingId, b.ts, b.close * 1_000_000) : b
);
const poisonedEvents: EventObservation[] = [
...panel.events,
...[100, 107, 114].map(listingId => ({
listingId,
knownAt: cutoffMs,
kind: 'filing' as const,
subtype: 'poison',
})),
];
const result = buildEventStudyInput({
bars: poisonedBars,
events: poisonedEvents,
vaultCutoffDate: cutoff,
benchmark: 'equal_weight',
exchangeCalendars: panel.calendars,
});
expect(result.input.sessionDates).toEqual(base.input.sessionDates);
expect(result.input.events).toEqual(base.input.events);
for (const [id, series] of base.input.entityReturns) {
expect(nanSafe(result.input.entityReturns.get(id)!)).toEqual(nanSafe(series));
}
expect(nanSafe(result.input.benchmarkReturns!)).toEqual(nanSafe(base.input.benchmarkReturns!));
expect(result.diagnostics.vaultExcludedEvents).toBe(base.diagnostics.vaultExcludedEvents + 3);
});
});
describe('buildEventStudyInput QA — calendar input forms and exact-close boundaries', () => {
it('treats plain-object calendars/mappings identically to Maps', () => {
const panel = buildRandomPanel(8080, null);
const cutoff = '2023-02-01';
const cals = panel.calendars.calendars as ReadonlyMap<string, readonly ExchangeSessionClose[]>;
const mapping = panel.calendars.listingCalendarId as ReadonlyMap<number, string>;
const asMaps = buildEventStudyInput({
bars: panel.bars,
events: panel.events,
vaultCutoffDate: cutoff,
benchmark: 'equal_weight',
exchangeCalendars: panel.calendars,
});
const asRecords = buildEventStudyInput({
bars: panel.bars,
events: panel.events,
vaultCutoffDate: cutoff,
benchmark: 'equal_weight',
exchangeCalendars: {
calendars: Object.fromEntries(cals),
listingCalendarId: Object.fromEntries(mapping),
},
});
expect(asRecords.input.events).toEqual(asMaps.input.events);
expect(asRecords.diagnostics).toEqual(asMaps.diagnostics);
for (const [id, series] of asMaps.input.entityReturns) {
expect(nanSafe(asRecords.input.entityReturns.get(id)!)).toEqual(nanSafe(series));
}
});
it('anchors knownAt == close to that session and close + 1 ms to the next (half-day close included)', () => {
const dates = ['2022-11-22', '2022-11-23', '2022-11-25', '2022-11-28'];
const xnys = dates.map(date => ({
date,
closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? 18 : 21),
}));
const bars = dates.map((date, i) => makeBar(1, makeUtcMs(date, 21), 10 + i));
const halfClose = makeUtcMs('2022-11-25', 18);
const result = buildEventStudyInput({
bars,
events: [
{ listingId: 1, knownAt: halfClose, kind: 'filing', subtype: '10-q' },
{ listingId: 1, knownAt: halfClose + 1, kind: 'filing', subtype: '10-q' },
// Thanksgiving (NYSE closed) intraday -> Friday half-day session.
{ listingId: 1, knownAt: makeUtcMs('2022-11-24', 15), kind: 'filing', subtype: '10-q' },
],
vaultCutoffDate: '2022-12-01',
exchangeCalendars: { calendars: { XNYS: xnys }, listingCalendarId: { 1: 'XNYS' } },
});
expect(result.input.events).toEqual([
{ entityId: 1, dayIndex: 2 },
{ entityId: 1, dayIndex: 3 },
]);
expect(result.diagnostics.duplicateEvents).toBe(1);
// Wed -> Fri is consecutive on the NYSE calendar (Thanksgiving closed), so Friday's return is valid.
expect(result.input.entityReturns.get(1)![2]).toBeCloseTo(12 / 11 - 1, 15);
});
});
function createInMemoryTrialExecutor(): { executor: TrialLedgerExecutor; rows: Record<string, unknown>[] } {
const rows: Record<string, unknown>[] = [];
let nextTrialId = 1;
const executor: TrialLedgerExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
const trimmed = text.trimStart();
const p = params ?? [];
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
const trialId = String(nextTrialId++);
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, Number(trialId)));
const stored = {
trial_id: trialId,
created_at: createdAt,
principal_id: p[0],
campaign_id: p[1] ?? null,
stage: p[2],
universe_market: p[3],
horizon_bucket: p[4],
hypothesis_id: p[5] ?? null,
expression_hash: p[6],
sample_start: p[7],
sample_end: p[8],
n_obs: p[9],
sharpe_unann: p[10],
skewness: p[11],
kurtosis: p[12],
daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)),
};
rows.push(stored);
return { rows: [{ trial_id: trialId, created_at: createdAt } as unknown as Row], rowCount: 1 };
}
if (trimmed.startsWith('SELECT')) {
if (text.includes('WHERE trial_id = $1::bigint')) {
const matched = rows.filter(r => r.trial_id === String(p[0]));
return { rows: matched as unknown as Row[], rowCount: matched.length };
}
if (text.includes('WHERE universe_market = $1')) {
const matched = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]);
return { rows: matched as unknown as Row[], rowCount: matched.length };
}
}
return { rows: [], rowCount: 0 };
},
};
return { executor, rows };
}
describe('buildEventStudyInput QA — half-day filing reaches runEventStudy eventCars on Monday', () => {
it('keeps the NYSE Black Friday filing in study.eventCars dated Monday with the expected benchmark-adjusted CAR', async () => {
const rand = createSeededRng(20261129);
const dates = makeBusinessDates('2022-10-03', 90);
const { xnys, xtse } = buildCalendars(dates);
const vaultCutoffDate = dates[80]!;
const usIds = [11, 12, 13, 14];
const caIds = [21, 22, 23, 24];
const bars: BarRecord[] = [];
const listingCalendarId = new Map<number, string>();
for (const [ids, cal, calId] of [
[usIds, xnys, 'XNYS'],
[caIds, xtse, 'XTSE'],
] as const) {
for (const id of ids) {
listingCalendarId.set(id, calId);
let price = 30 + id;
for (const s of cal) {
price *= 1 + (rand() * 2 - 1) * 0.015;
bars.push(makeBar(id, makeUtcMs(s.date, regularCloseHourUtc(s.date)), price));
}
}
}
// Regular after-close filings every 5 sessions in windows that avoid cross-border holidays,
// plus the 14:00 ET Black Friday filing for listing 11 (after NYSE's 13:00 ET close).
const events: EventObservation[] = [];
for (let t = 3; t < 75; t += 5) {
const date = dates[t]!;
for (const id of [...usIds, ...caIds]) {
if ((t + id) % 3 === 0) {
events.push({ listingId: id, knownAt: makeUtcMs(date, 23), kind: 'filing', subtype: '10-q' });
}
}
}
events.push({ listingId: 11, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' });
const built = buildEventStudyInput({
bars,
events,
vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars: { calendars: { XNYS: xnys, XTSE: xtse }, listingCalendarId },
});
const postDays = 3;
const ledger = createInMemoryTrialExecutor();
const result = await runEventStudy(ledger.executor, {
principalId: 'operator',
universeMarket: 'US_CA_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'qa_half_day_filing_event_study',
params: { preDays: 0, postDays },
universe: 'US_CA_EQ_QA',
horizon: '3d',
},
input: built.input,
options: { preDays: 0, postDays, minEvents: 5 },
vaultCutoffDate,
});
expect(result.status).toBe('ok');
if (result.status !== 'ok') {
return;
}
expect(ledger.rows).toHaveLength(1);
const cars = result.study.eventCars;
const usHalfDayIdx = cars.entityIds.findIndex((id, i) => id === 11 && cars.dates[i] === '2022-11-28');
expect(usHalfDayIdx).toBeGreaterThanOrEqual(0);
expect(cars.entityIds.some((id, i) => id === 11 && cars.dates[i] === '2022-11-25')).toBe(false);
const sessionDates = built.input.sessionDates;
const d = sessionDates.indexOf('2022-11-28');
expect(cars.dayIndices[usHalfDayIdx]).toBe(d);
const r = built.input.entityReturns.get(11)!;
const b = built.input.benchmarkReturns!;
let expectedCar = 0;
for (let k = 0; k <= postDays; k += 1) {
expectedCar += (r[d + k] as number) - (b[d + k] as number);
}
expect(cars.cars[usHalfDayIdx]!).toBeCloseTo(expectedCar, 12);
expect(Number.isFinite(result.deflatedSharpe.dsr ?? Number.NaN)).toBe(true);
});
});