1181 lines
42 KiB
TypeScript
1181 lines
42 KiB
TypeScript
import { describe, expect, it } from 'bun:test';
|
|
import { readFileSync } from 'node:fs';
|
|
import { eventDayIndex, eventStudy } from '@stock-bot/calculations';
|
|
import {
|
|
EventPanelError,
|
|
buildEventStudyInput,
|
|
eventsTableToEventRows,
|
|
type BarRecord,
|
|
type EventObservation,
|
|
type EventPanelErrorCode,
|
|
type EventStudyExchangeCalendars,
|
|
type Table,
|
|
} from '@stock-bot/research';
|
|
import {
|
|
EventPanelError as SubpathEventPanelError,
|
|
buildEventStudyInput as subpathBuildEventStudyInput,
|
|
eventsTableToEventRows as subpathEventsTableToEventRows,
|
|
} from '@stock-bot/research/event-panel';
|
|
|
|
function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number {
|
|
const [y, m, d] = date.split('-').map(Number);
|
|
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms);
|
|
}
|
|
|
|
function makeBusinessDates(startDate: string, count: number): string[] {
|
|
const out: string[] = new Array(count);
|
|
const current = new Date(`${startDate}T00:00:00.000Z`);
|
|
let written = 0;
|
|
while (written < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out[written] = current.toISOString().slice(0, 10);
|
|
written += 1;
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord {
|
|
const ts = makeUtcMs(date, hourUtc, 0, 0, 0);
|
|
return {
|
|
listingId,
|
|
ts,
|
|
open: close,
|
|
high: close,
|
|
low: close,
|
|
close,
|
|
volume: 1_000,
|
|
vwap: close,
|
|
knownAt: ts,
|
|
};
|
|
}
|
|
|
|
function makeExchangeCalendars(
|
|
listingIds: readonly number[],
|
|
dates: readonly string[],
|
|
hourUtc = 21
|
|
): EventStudyExchangeCalendars {
|
|
const sessions = dates.map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) }));
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return {
|
|
calendars: new Map([['XNYS', sessions]]),
|
|
listingCalendarId,
|
|
};
|
|
}
|
|
|
|
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 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));
|
|
const tmp = copy[i]!;
|
|
copy[i] = copy[j]!;
|
|
copy[j] = tmp;
|
|
}
|
|
return copy;
|
|
}
|
|
|
|
function expectEventPanelError(fn: () => unknown, code: EventPanelErrorCode): EventPanelError {
|
|
try {
|
|
fn();
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(EventPanelError);
|
|
const typed = err as EventPanelError;
|
|
expect(typed.code).toBe(code);
|
|
return typed;
|
|
}
|
|
throw new Error(`Expected EventPanelError(${code}), but function did not throw.`);
|
|
}
|
|
|
|
function expectBitIdenticalFloat64(actual: Float64Array, expected: Float64Array): void {
|
|
expect(actual.length).toBe(expected.length);
|
|
const aBytes = new Uint8Array(actual.buffer, actual.byteOffset, actual.byteLength);
|
|
const eBytes = new Uint8Array(expected.buffer, expected.byteOffset, expected.byteLength);
|
|
expect(aBytes).toEqual(eBytes);
|
|
}
|
|
|
|
function expectBitIdenticalEventStudyInput(
|
|
actual: ReturnType<typeof buildEventStudyInput>['input'],
|
|
expected: ReturnType<typeof buildEventStudyInput>['input']
|
|
): void {
|
|
expect(actual.sessionDates).toEqual(expected.sessionDates);
|
|
expect(actual.events).toEqual(expected.events);
|
|
expect(Array.from(actual.entityReturns.keys())).toEqual(Array.from(expected.entityReturns.keys()));
|
|
for (const [id, expectedSeries] of expected.entityReturns) {
|
|
const actualSeries = actual.entityReturns.get(id);
|
|
expect(actualSeries).toBeInstanceOf(Float64Array);
|
|
expectBitIdenticalFloat64(actualSeries as Float64Array, expectedSeries as Float64Array);
|
|
}
|
|
if (expected.benchmarkReturns === undefined) {
|
|
expect(actual.benchmarkReturns).toBeUndefined();
|
|
} else {
|
|
expect(actual.benchmarkReturns).toBeInstanceOf(Float64Array);
|
|
expectBitIdenticalFloat64(
|
|
actual.benchmarkReturns as Float64Array,
|
|
expected.benchmarkReturns as Float64Array
|
|
);
|
|
}
|
|
}
|
|
|
|
describe('@stock-bot/research event-panel exports and browser safety', () => {
|
|
it('exposes identical symbols from root and ./event-panel subpath', () => {
|
|
expect(buildEventStudyInput).toBe(subpathBuildEventStudyInput);
|
|
expect(eventsTableToEventRows).toBe(subpathEventsTableToEventRows);
|
|
expect(EventPanelError).toBe(SubpathEventPanelError);
|
|
});
|
|
|
|
it('has zero node:* imports, zero bare process access, and unchanged package dependencies', () => {
|
|
for (const relPath of ['../src/event-panel.ts', '../src/panel-shared.ts']) {
|
|
const src = readFileSync(new URL(relPath, import.meta.url), 'utf8');
|
|
expect(src).not.toMatch(/from\s+['"]node:/);
|
|
expect(src).not.toMatch(/require\s*\(\s*['"]node:/);
|
|
expect(src).not.toMatch(/\bprocess\./);
|
|
}
|
|
|
|
const pkg = JSON.parse(
|
|
readFileSync(new URL('../package.json', import.meta.url), 'utf8')
|
|
) as { dependencies?: Record<string, string>; exports?: Record<string, string> };
|
|
expect(pkg.exports?.['./event-panel']).toBe('./src/event-panel.ts');
|
|
expect(Object.keys(pkg.dependencies ?? {}).sort()).toEqual([
|
|
'@stock-bot/calculations',
|
|
'@stock-bot/stock-config',
|
|
'@stock-bot/types',
|
|
'zod',
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('eventsTableToEventRows', () => {
|
|
const baseColumns = [
|
|
'listing_id',
|
|
'ts',
|
|
'known_at',
|
|
'known_at_source',
|
|
'kind',
|
|
'subtype',
|
|
'payload_json',
|
|
];
|
|
|
|
it('maps valid rows, normalizes -0, and preserves null/string subtypes', () => {
|
|
const table: Table = {
|
|
columns: baseColumns,
|
|
rows: [
|
|
{
|
|
listing_id: -0,
|
|
ts: makeUtcMs('2024-01-05', 22),
|
|
known_at: -0,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '10-Q',
|
|
payload_json: '{}',
|
|
},
|
|
{
|
|
listing_id: 42,
|
|
ts: makeUtcMs('2024-01-08', 22),
|
|
known_at: makeUtcMs('2024-01-08', 22),
|
|
known_at_source: 'exact',
|
|
kind: 'earnings',
|
|
subtype: null,
|
|
payload_json: '{}',
|
|
},
|
|
],
|
|
};
|
|
|
|
const rows = eventsTableToEventRows(table);
|
|
expect(rows).toEqual([
|
|
{ listingId: 0, knownAt: 0, kind: 'filing', subtype: '10-Q' },
|
|
{ listingId: 42, knownAt: makeUtcMs('2024-01-08', 22), kind: 'earnings', subtype: null },
|
|
]);
|
|
expect(Object.is(rows[0]!.listingId, 0)).toBe(true);
|
|
expect(Object.is(rows[0]!.knownAt, 0)).toBe(true);
|
|
});
|
|
|
|
it('applies exact-match kinds and subtypes allow-lists', () => {
|
|
const table: Table = {
|
|
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
|
|
rows: [
|
|
{ listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' },
|
|
{ listing_id: 2, known_at: 2000, kind: 'filing', subtype: '10-K' },
|
|
{ listing_id: 3, known_at: 3000, kind: 'filing', subtype: null },
|
|
{ listing_id: 4, known_at: 4000, kind: 'earnings', subtype: '10-Q' },
|
|
],
|
|
};
|
|
|
|
expect(eventsTableToEventRows(table, { kinds: ['filing'] })).toHaveLength(3);
|
|
expect(eventsTableToEventRows(table, { subtypes: ['10-Q'] })).toEqual([
|
|
{ listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' },
|
|
{ listingId: 4, knownAt: 4000, kind: 'earnings', subtype: '10-Q' },
|
|
]);
|
|
expect(
|
|
eventsTableToEventRows(table, { kinds: ['filing'], subtypes: ['10-Q', '10-K'] })
|
|
).toEqual([
|
|
{ listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' },
|
|
{ listingId: 2, knownAt: 2000, kind: 'filing', subtype: '10-K' },
|
|
]);
|
|
});
|
|
|
|
it('validates all rows upfront even when they would be filtered out', () => {
|
|
const table: Table = {
|
|
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
|
|
rows: [
|
|
{ listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' },
|
|
{ listing_id: 2, known_at: Number.NaN, kind: 'earnings', subtype: 'Q1' },
|
|
],
|
|
};
|
|
|
|
expectEventPanelError(
|
|
() => eventsTableToEventRows(table, { kinds: ['filing'] }),
|
|
'invalid_event'
|
|
);
|
|
});
|
|
|
|
it('rejects malformed table, missing columns, invalid filter options, and malformed rows', () => {
|
|
expectEventPanelError(
|
|
() => eventsTableToEventRows(null as unknown as Table),
|
|
'invalid_input'
|
|
);
|
|
expectEventPanelError(
|
|
() => eventsTableToEventRows({ columns: ['listing_id', 'known_at', 'kind'], rows: [] }),
|
|
'invalid_input'
|
|
);
|
|
|
|
const validEmptyTable: Table = {
|
|
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
|
|
rows: [],
|
|
};
|
|
expectEventPanelError(
|
|
() => eventsTableToEventRows(validEmptyTable, { kinds: [] }),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() => eventsTableToEventRows(validEmptyTable, { subtypes: [] }),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
eventsTableToEventRows(validEmptyTable, {
|
|
kinds: ['unknown_kind' as unknown as 'filing'],
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
eventsTableToEventRows(validEmptyTable, {
|
|
subtypes: [123 as unknown as string],
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() => eventsTableToEventRows(validEmptyTable, [] as unknown as Record<string, never>),
|
|
'invalid_option'
|
|
);
|
|
|
|
const badRows: unknown[] = [
|
|
null,
|
|
{ listing_id: 1, known_at: 1000, kind: 'filing' }, // missing subtype
|
|
{ listing_id: 1.5, known_at: 1000, kind: 'filing', subtype: '10-Q' },
|
|
{ listing_id: 2_147_483_648, known_at: 1000, kind: 'filing', subtype: '10-Q' },
|
|
{ listing_id: 1, known_at: Number.POSITIVE_INFINITY, kind: 'filing', subtype: '10-Q' },
|
|
{ listing_id: 1, known_at: 1000, kind: 'bad_kind', subtype: '10-Q' },
|
|
{ listing_id: 1, known_at: 1000, kind: 'filing', subtype: 99 },
|
|
];
|
|
for (const badRow of badRows) {
|
|
expectEventPanelError(
|
|
() =>
|
|
eventsTableToEventRows({
|
|
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
|
|
rows: [badRow as Table['rows'][number]],
|
|
}),
|
|
'invalid_event'
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and invariants', () => {
|
|
it('computes consecutive-session simple returns, sets NaN on gaps/resumption, and handles equal_weight benchmark', () => {
|
|
const dates = makeBusinessDates('2024-01-02', 5); // 5 sessions: d0..d4
|
|
const bars: BarRecord[] = [
|
|
// Listing 10: present on all 5 sessions
|
|
makeBar(10, dates[0]!, 100),
|
|
makeBar(10, dates[1]!, 110), // +10%
|
|
makeBar(10, dates[2]!, 99), // -10%
|
|
makeBar(10, dates[3]!, 99), // 0%
|
|
makeBar(10, dates[4]!, 108.9), // +10%
|
|
// Listing 20: missing on d2 -> d2 is NaN AND d3 (resumption) is NaN; d4 is 120/100 - 1 = +20%
|
|
makeBar(20, dates[0]!, 50),
|
|
makeBar(20, dates[1]!, 60), // +20%
|
|
makeBar(20, dates[3]!, 100),
|
|
makeBar(20, dates[4]!, 120), // +20%
|
|
];
|
|
|
|
const events: EventObservation[] = [
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[1]!, 21), kind: 'filing', subtype: '10-Q' },
|
|
];
|
|
|
|
const exchangeCalendars = makeExchangeCalendars([10, 20], dates);
|
|
|
|
const resNone = buildEventStudyInput({
|
|
bars,
|
|
events,
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars,
|
|
});
|
|
|
|
expect(resNone.input.sessionDates).toEqual(dates);
|
|
expect('benchmarkReturns' in resNone.input).toBe(false);
|
|
expect(Array.from(resNone.input.entityReturns.keys())).toEqual([10, 20]);
|
|
|
|
const r10 = resNone.input.entityReturns.get(10)!;
|
|
const r20 = resNone.input.entityReturns.get(20)!;
|
|
expect(Number.isNaN(r10[0]!)).toBe(true);
|
|
expect(r10[1]!).toBeCloseTo(0.1, 12);
|
|
expect(r10[2]!).toBeCloseTo(-0.1, 12);
|
|
expect(r10[3]!).toBe(0);
|
|
expect(r10[4]!).toBeCloseTo(0.1, 12);
|
|
|
|
expect(Number.isNaN(r20[0]!)).toBe(true);
|
|
expect(r20[1]!).toBeCloseTo(0.2, 12);
|
|
expect(Number.isNaN(r20[2]!)).toBe(true);
|
|
expect(Number.isNaN(r20[3]!)).toBe(true);
|
|
expect(r20[4]!).toBeCloseTo(0.2, 12);
|
|
|
|
const resEq = buildEventStudyInput({
|
|
bars,
|
|
events,
|
|
vaultCutoffDate: '2024-02-01',
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars,
|
|
});
|
|
expect(resEq.input.benchmarkReturns).toBeInstanceOf(Float64Array);
|
|
const b = resEq.input.benchmarkReturns!;
|
|
expect(Number.isNaN(b[0]!)).toBe(true);
|
|
expect(b[1]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2
|
|
expect(b[2]!).toBeCloseTo(-0.1, 12); // only listing 10 finite
|
|
expect(b[3]!).toBe(0); // only listing 10 finite
|
|
expect(b[4]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2
|
|
});
|
|
|
|
it('writes NaN (never Infinity) for non-positive, non-finite, or overflowing closes and passes eventStudy', () => {
|
|
const dates = makeBusinessDates('2024-01-02', 6);
|
|
const bars: BarRecord[] = [
|
|
makeBar(1, dates[0]!, 10),
|
|
makeBar(1, dates[1]!, 0), // non-positive
|
|
makeBar(1, dates[2]!, -5), // non-positive
|
|
makeBar(1, dates[3]!, Number.NaN), // non-finite
|
|
makeBar(1, dates[4]!, 1e-308),
|
|
makeBar(1, dates[5]!, 1e308), // close[5]/close[4] overflows to +Infinity
|
|
];
|
|
|
|
const res = buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: makeExchangeCalendars([1], dates),
|
|
});
|
|
|
|
const series = res.input.entityReturns.get(1)!;
|
|
for (let t = 0; t < dates.length; t += 1) {
|
|
expect(Number.isNaN(series[t]!)).toBe(true);
|
|
expect(Number.isNaN(res.input.benchmarkReturns![t]!)).toBe(true);
|
|
}
|
|
expect(res.diagnostics.nonPositiveCloseReturns).toBe(5);
|
|
|
|
// Must not throw NON_FINITE_RETURN in eventStudy.
|
|
const study = eventStudy(res.input, { preDays: 1, postDays: 1, minEvents: 1 });
|
|
expect(study.status).toBe('insufficient_data');
|
|
});
|
|
|
|
it('anchors after-close, weekend, and holiday events to the next session and matches eventDayIndex exactly', () => {
|
|
// Include a Friday -> Monday weekend and a Wednesday holiday (skip 2024-01-10).
|
|
const dates = ['2024-01-05', '2024-01-08', '2024-01-09', '2024-01-11', '2024-01-12'];
|
|
const bars: BarRecord[] = [];
|
|
for (const d of dates) {
|
|
bars.push(makeBar(1, d, 100, 21)); // 16:00 ET = 21:00 UTC
|
|
bars.push(makeBar(2, d, 50, 21));
|
|
}
|
|
|
|
const sessionMaxTs = Float64Array.from(dates.map(d => makeUtcMs(d, 21)));
|
|
const probeTimestamps: Array<{ listingId: number; knownAt: number; expectedIdx: number | null }> = [
|
|
// Pre-market on first session -> day 0
|
|
{ listingId: 1, knownAt: makeUtcMs('2024-01-05', 13), expectedIdx: 0 },
|
|
// Exact close on Friday -> day 0
|
|
{ listingId: 2, knownAt: makeUtcMs('2024-01-05', 21), expectedIdx: 0 },
|
|
// After-close Friday 17:00 ET (22:00 UTC) -> Monday (day 1)
|
|
{ listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), expectedIdx: 1 },
|
|
// Saturday morning -> Monday (day 1)
|
|
{ listingId: 2, knownAt: makeUtcMs('2024-01-06', 14), expectedIdx: 1 },
|
|
// After-close Tuesday 21:00:00.001 UTC -> Thursday (day 3, skipping Wednesday holiday)
|
|
{ listingId: 1, knownAt: makeUtcMs('2024-01-09', 21, 0, 0, 1), expectedIdx: 3 },
|
|
// Holiday Wednesday -> Thursday (day 3)
|
|
{ listingId: 2, knownAt: makeUtcMs('2024-01-10', 15), expectedIdx: 3 },
|
|
// After-close Friday last session (22:00 UTC < Saturday cutoff 00:00Z) -> droppedAfterLastSession
|
|
{ listingId: 1, knownAt: makeUtcMs('2024-01-12', 22), expectedIdx: null },
|
|
];
|
|
|
|
// Verify exact equivalence with eventDayIndex from @stock-bot/calculations.
|
|
for (const p of probeTimestamps) {
|
|
const ref = eventDayIndex(sessionMaxTs, p.knownAt);
|
|
if (p.expectedIdx === null) {
|
|
expect(ref).toEqual({ status: 'no_session', reason: 'after_last_session' });
|
|
} else {
|
|
expect(ref).toEqual({ status: 'ok', dayIndex: p.expectedIdx });
|
|
}
|
|
}
|
|
|
|
const events: EventObservation[] = probeTimestamps.map(p => ({
|
|
listingId: p.listingId,
|
|
knownAt: p.knownAt,
|
|
kind: 'filing',
|
|
subtype: '10-Q',
|
|
}));
|
|
|
|
const res = buildEventStudyInput({
|
|
bars,
|
|
events,
|
|
vaultCutoffDate: '2024-01-13',
|
|
exchangeCalendars: makeExchangeCalendars([1, 2], dates),
|
|
});
|
|
|
|
expect(res.input.events).toEqual([
|
|
{ entityId: 1, dayIndex: 0 },
|
|
{ entityId: 2, dayIndex: 0 },
|
|
{ entityId: 1, dayIndex: 1 },
|
|
{ entityId: 2, dayIndex: 1 },
|
|
{ entityId: 1, dayIndex: 3 },
|
|
{ entityId: 2, dayIndex: 3 },
|
|
]);
|
|
expect(res.diagnostics.droppedAfterLastSession).toBe(1);
|
|
expect(res.diagnostics.vaultExcludedEvents).toBe(0);
|
|
expect(res.diagnostics.droppedUnknownListing).toBe(0);
|
|
expect(res.diagnostics.duplicateEvents).toBe(0);
|
|
});
|
|
|
|
it('deduplicates exact duplicate bars and rejects conflicting duplicates', () => {
|
|
const dates = makeBusinessDates('2024-01-02', 3);
|
|
const b0 = makeBar(1, dates[0]!, 10);
|
|
const b1 = makeBar(1, dates[1]!, 12);
|
|
const b2 = makeBar(1, dates[2]!, Number.NaN);
|
|
|
|
const exchangeCalendars = makeExchangeCalendars([1], dates);
|
|
|
|
const exactDup = buildEventStudyInput({
|
|
bars: [b0, { ...b0 }, b1, b2, { ...b2 }],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars,
|
|
});
|
|
expect(exactDup.diagnostics.duplicateBars).toBe(2);
|
|
expect(exactDup.input.entityReturns.get(1)![1]).toBeCloseTo(0.2, 12);
|
|
|
|
// Conflicting close
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [b0, { ...b0, close: 10.01 }, b1],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars,
|
|
}),
|
|
'duplicate_bar'
|
|
);
|
|
|
|
// Conflicting timestamp on same UTC date
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars,
|
|
}),
|
|
'duplicate_bar'
|
|
);
|
|
});
|
|
|
|
it('enforces Vault exclusion without ever reading post-cutoff bar.close and obeys event conservation', () => {
|
|
const dates = makeBusinessDates('2024-01-02', 6); // d0..d3 pre-cutoff, d4..d5 post-cutoff
|
|
const vaultCutoffDate = dates[4]!;
|
|
let postCutoffCloseReads = 0;
|
|
|
|
const makeTrappedPostCutoffBar = (listingId: number, date: string): BarRecord => {
|
|
const ts = makeUtcMs(date, 21);
|
|
const bar = {
|
|
listingId,
|
|
ts,
|
|
open: 999,
|
|
high: 999,
|
|
low: 999,
|
|
volume: 100,
|
|
vwap: 999,
|
|
knownAt: ts,
|
|
};
|
|
Object.defineProperty(bar, 'close', {
|
|
enumerable: true,
|
|
get() {
|
|
postCutoffCloseReads += 1;
|
|
throw new Error('Vault violation: post-cutoff bar.close was accessed!');
|
|
},
|
|
});
|
|
return bar as unknown as BarRecord;
|
|
};
|
|
|
|
const preBars: BarRecord[] = [];
|
|
for (let t = 0; t < 4; t += 1) {
|
|
preBars.push(makeBar(10, dates[t]!, 100 + t * 5));
|
|
}
|
|
const postBars: BarRecord[] = [
|
|
makeTrappedPostCutoffBar(10, dates[4]!),
|
|
makeTrappedPostCutoffBar(10, dates[5]!),
|
|
makeTrappedPostCutoffBar(99, dates[4]!), // listing only exists post-cutoff
|
|
];
|
|
|
|
const events: EventObservation[] = [
|
|
// Valid event -> day 1
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[0]!, 22), kind: 'filing', subtype: '10-Q' },
|
|
// Duplicate event anchoring to day 1 (different timestamp on same pre-market morning)
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' },
|
|
// Unknown listing (pre-cutoff) -> droppedUnknownListing
|
|
{ listingId: 99, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' },
|
|
// After last pre-cutoff session close, but still < vaultCutoffMs -> droppedAfterLastSession
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[3]!, 22), kind: 'filing', subtype: '10-Q' },
|
|
// Exact vaultCutoffDate 00:00:00.000Z (even for unknown listing) -> vaultExcludedEvents
|
|
{ listingId: 99, knownAt: makeUtcMs(vaultCutoffDate, 0), kind: 'filing', subtype: '10-Q' },
|
|
// After vaultCutoffDate -> vaultExcludedEvents
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[5]!, 22), kind: 'filing', subtype: '10-Q' },
|
|
];
|
|
|
|
const exchangeCalendars = makeExchangeCalendars([10], dates);
|
|
|
|
const trappedResult = buildEventStudyInput({
|
|
bars: [...preBars, ...postBars],
|
|
events,
|
|
vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars,
|
|
});
|
|
|
|
expect(postCutoffCloseReads).toBe(0);
|
|
expect(trappedResult.input.sessionDates).toEqual(dates.slice(0, 4));
|
|
expect(trappedResult.input.events).toEqual([{ entityId: 10, dayIndex: 1 }]);
|
|
expect(trappedResult.diagnostics).toEqual({
|
|
vaultExcludedDates: 2,
|
|
vaultExcludedEvents: 2,
|
|
droppedUnknownListing: 1,
|
|
droppedAfterLastSession: 1,
|
|
droppedMissingCalendarSession: 0,
|
|
duplicateEvents: 1,
|
|
duplicateBars: 0,
|
|
nonPositiveCloseReturns: 0,
|
|
});
|
|
|
|
// Event conservation identity
|
|
const d = trappedResult.diagnostics;
|
|
expect(
|
|
trappedResult.input.events.length +
|
|
d.vaultExcludedEvents +
|
|
d.droppedUnknownListing +
|
|
d.droppedAfterLastSession +
|
|
d.droppedMissingCalendarSession +
|
|
d.duplicateEvents
|
|
).toBe(events.length);
|
|
|
|
// Poisoned post-cutoff bars/events leave pre-cutoff input byte-identical
|
|
const poisonedResult = buildEventStudyInput({
|
|
bars: [
|
|
...preBars,
|
|
makeBar(10, dates[4]!, 999_999),
|
|
makeBar(10, dates[5]!, Number.NaN),
|
|
],
|
|
events: [
|
|
...events.slice(0, 4),
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[4]!, 22), kind: 'filing', subtype: '10-K' },
|
|
],
|
|
vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars,
|
|
});
|
|
expectBitIdenticalEventStudyInput(poisonedResult.input, trappedResult.input);
|
|
});
|
|
|
|
it('is bit-identical under arbitrary permutations and never mutates frozen inputs', () => {
|
|
const dates = makeBusinessDates('2024-01-02', 8);
|
|
const bars: BarRecord[] = [];
|
|
const events: EventObservation[] = [];
|
|
for (const lid of [30, 10, 20]) {
|
|
for (let t = 0; t < dates.length; t += 1) {
|
|
if (lid === 20 && t === 3) {
|
|
continue; // gap
|
|
}
|
|
bars.push(makeBar(lid, dates[t]!, 20 + lid + t * 0.75));
|
|
}
|
|
events.push({
|
|
listingId: lid,
|
|
knownAt: makeUtcMs(dates[1]!, 22),
|
|
kind: 'filing',
|
|
subtype: '10-Q',
|
|
});
|
|
events.push({
|
|
listingId: lid,
|
|
knownAt: makeUtcMs(dates[4]!, 15),
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
});
|
|
}
|
|
|
|
const exchangeCalendars = makeExchangeCalendars([10, 20, 30], dates);
|
|
const frozenBars = Object.freeze(bars.map(b => Object.freeze({ ...b })));
|
|
const frozenEvents = Object.freeze(events.map(e => Object.freeze({ ...e })));
|
|
const frozenParams = Object.freeze({
|
|
bars: frozenBars,
|
|
events: frozenEvents,
|
|
vaultCutoffDate: dates[6]!,
|
|
benchmark: 'equal_weight' as const,
|
|
exchangeCalendars,
|
|
});
|
|
|
|
const baseline = buildEventStudyInput(frozenParams);
|
|
for (const seed of [1, 42, 999, 20261129]) {
|
|
const permuted = buildEventStudyInput({
|
|
bars: shuffle(bars, seed),
|
|
events: shuffle(events, seed + 17),
|
|
vaultCutoffDate: dates[6]!,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars,
|
|
});
|
|
expectBitIdenticalEventStudyInput(permuted.input, baseline.input);
|
|
expect(permuted.diagnostics).toEqual(baseline.diagnostics);
|
|
expect(Array.from(permuted.input.entityReturns.keys())).toEqual([10, 20, 30]);
|
|
}
|
|
});
|
|
|
|
it('handles empty and post-cutoff-only inputs cleanly', () => {
|
|
const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} };
|
|
const emptyRes = buildEventStudyInput({
|
|
bars: [],
|
|
events: [
|
|
{ listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), kind: 'filing', subtype: '10-Q' },
|
|
{ listingId: 1, knownAt: makeUtcMs('2024-02-01', 0), kind: 'filing', subtype: '10-Q' },
|
|
],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: emptyCalendars,
|
|
});
|
|
expect(emptyRes.input.sessionDates).toEqual([]);
|
|
expect(emptyRes.input.entityReturns.size).toBe(0);
|
|
expect(emptyRes.input.events).toEqual([]);
|
|
expect('benchmarkReturns' in emptyRes.input).toBe(false);
|
|
expect(emptyRes.diagnostics).toEqual({
|
|
vaultExcludedDates: 0,
|
|
vaultExcludedEvents: 1,
|
|
droppedUnknownListing: 1,
|
|
droppedAfterLastSession: 0,
|
|
droppedMissingCalendarSession: 0,
|
|
duplicateEvents: 0,
|
|
duplicateBars: 0,
|
|
nonPositiveCloseReturns: 0,
|
|
});
|
|
|
|
const postOnlyRes = buildEventStudyInput({
|
|
bars: [makeBar(1, '2024-02-01', 100), makeBar(1, '2024-02-02', 105)],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: emptyCalendars,
|
|
});
|
|
expect(postOnlyRes.input.sessionDates).toEqual([]);
|
|
expect(postOnlyRes.input.benchmarkReturns).toEqual(new Float64Array(0));
|
|
expect(postOnlyRes.diagnostics.vaultExcludedDates).toBe(2);
|
|
});
|
|
|
|
it('throws typed EventPanelError for every remaining validation error code', () => {
|
|
const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} };
|
|
expectEventPanelError(
|
|
() => buildEventStudyInput(null as unknown as Parameters<typeof buildEventStudyInput>[0]),
|
|
'invalid_input'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: 'not-array' as unknown as BarRecord[],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_input'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: 'not-array' as unknown as EventObservation[],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_input'
|
|
);
|
|
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-30',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_date'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: [],
|
|
vaultCutoffDate: '2024/02/01',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_date'
|
|
);
|
|
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
benchmark: 'cap_weight' as unknown as 'none',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
benchmark: null as unknown as 'none',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: undefined as unknown as EventStudyExchangeCalendars,
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
|
|
const goodBar = makeBar(1, '2024-01-05', 10);
|
|
for (const badBar of [
|
|
null,
|
|
{ ...goodBar, listingId: 1.5 },
|
|
{ ...goodBar, ts: Number.NaN },
|
|
{ ...goodBar, knownAt: Number.POSITIVE_INFINITY },
|
|
{ ...goodBar, close: '10' },
|
|
]) {
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [badBar as BarRecord],
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_bar'
|
|
);
|
|
}
|
|
|
|
const goodEv: EventObservation = {
|
|
listingId: 1,
|
|
knownAt: makeUtcMs('2024-01-05', 22),
|
|
kind: 'filing',
|
|
subtype: '10-Q',
|
|
};
|
|
for (const badEv of [
|
|
null,
|
|
{ ...goodEv, listingId: 2_147_483_648 },
|
|
{ ...goodEv, knownAt: Number.NaN },
|
|
{ ...goodEv, kind: 'not_a_kind' },
|
|
{ ...goodEv, subtype: 42 },
|
|
]) {
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: [],
|
|
events: [badEv as EventObservation],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: emptyCalendars,
|
|
}),
|
|
'invalid_event'
|
|
);
|
|
}
|
|
});
|
|
|
|
it('uses caller-supplied exchangeCalendars for half-day US vs CA close times and cross-border holidays', () => {
|
|
// Black Friday 2024-11-29: curated bars_1d.ts stamps BOTH NYSE and TSX at 16:00 ET (21:00 UTC),
|
|
// even though NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at 16:00 ET (21:00 UTC).
|
|
// Also include US Thanksgiving 2024-11-28 (TSX open, NYSE closed).
|
|
const sharedDates = ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02', '2024-12-03'];
|
|
const nyseId = 10_001;
|
|
const tsxId = 50_001;
|
|
|
|
const bars: BarRecord[] = [
|
|
// NYSE bars (closed 2024-11-28; half-day 2024-11-29 still stamped 21:00 UTC by curator)
|
|
makeBar(nyseId, '2024-11-27', 100, 21),
|
|
makeBar(nyseId, '2024-11-29', 102, 21),
|
|
makeBar(nyseId, '2024-12-02', 105, 21),
|
|
makeBar(nyseId, '2024-12-03', 106, 21),
|
|
// TSX bars (open all 5 days, stamped 21:00 UTC)
|
|
makeBar(tsxId, '2024-11-27', 50, 21),
|
|
makeBar(tsxId, '2024-11-28', 50.5, 21),
|
|
makeBar(tsxId, '2024-11-29', 51, 21),
|
|
makeBar(tsxId, '2024-12-02', 52, 21),
|
|
makeBar(tsxId, '2024-12-03', 52.5, 21),
|
|
];
|
|
|
|
const nyseCalendar = [
|
|
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET
|
|
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET early close
|
|
{ date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET
|
|
{ date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET
|
|
];
|
|
const tsxCalendar = [
|
|
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET
|
|
{ date: '2024-11-28', closeTs: makeUtcMs('2024-11-28', 21) }, // 16:00 ET (US holiday)
|
|
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 21) }, // 16:00 ET (normal close)
|
|
{ date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET
|
|
{ date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET
|
|
];
|
|
|
|
// Filing published at 14:00 ET (19:00 UTC) on Friday 2024-11-29:
|
|
// - NYSE already closed at 13:00 ET (18:00 UTC) -> MUST anchor to Monday 2024-12-02 (index 3).
|
|
// - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2024-11-29 (index 2).
|
|
// Filing published at 12:30 ET (17:30 UTC) on Friday 2024-11-29 for NYSE -> anchors to Friday 2024-11-29 (index 2).
|
|
// Filing published on US Thanksgiving 2024-11-28 at 10:00 ET (15:00 UTC):
|
|
// - NYSE closed -> anchors to Friday 2024-11-29 (index 2, collapses with 12:30 ET NYSE event).
|
|
// - TSX open -> anchors to Thursday 2024-11-28 (index 1).
|
|
const events: EventObservation[] = [
|
|
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' },
|
|
{ listingId: tsxId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: 'interim_financial_statements' },
|
|
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 17, 30), kind: 'filing', subtype: '10-q' },
|
|
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: '10-q' },
|
|
{ listingId: tsxId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: 'interim_financial_statements' },
|
|
];
|
|
|
|
const mapResult = buildEventStudyInput({
|
|
bars,
|
|
events,
|
|
vaultCutoffDate: '2024-12-04',
|
|
exchangeCalendars: {
|
|
calendars: new Map([
|
|
['XNYS', nyseCalendar],
|
|
['XTSE', tsxCalendar],
|
|
]),
|
|
listingCalendarId: new Map([
|
|
[nyseId, 'XNYS'],
|
|
[tsxId, 'XTSE'],
|
|
]),
|
|
},
|
|
});
|
|
|
|
expect(mapResult.input.sessionDates).toEqual(sharedDates);
|
|
expect(mapResult.input.events).toEqual([
|
|
{ entityId: tsxId, dayIndex: 1 }, // 2024-11-28
|
|
{ entityId: nyseId, dayIndex: 2 }, // 2024-11-29 (12:30 ET & Thanksgiving deduped)
|
|
{ entityId: tsxId, dayIndex: 2 }, // 2024-11-29 (14:00 ET still before TSX 16:00 ET close)
|
|
{ entityId: nyseId, dayIndex: 3 }, // 2024-12-02 (14:00 ET after NYSE 13:00 ET close)
|
|
]);
|
|
// Cross-border holiday: NYSE was closed on Thanksgiving 2024-11-28, so its Friday
|
|
// 2024-11-29 return (index 2) is a valid 1-session NYSE return (102 / 100 - 1 = 0.02).
|
|
const nyseRets = mapResult.input.entityReturns.get(nyseId)!;
|
|
expect(Number.isNaN(nyseRets[1]!)).toBe(true);
|
|
expect(nyseRets[2]!).toBeCloseTo(0.02, 12);
|
|
expect(nyseRets[3]!).toBeCloseTo(105 / 102 - 1, 12);
|
|
expect(mapResult.diagnostics.duplicateEvents).toBe(1);
|
|
expect(mapResult.diagnostics.droppedAfterLastSession).toBe(0);
|
|
expect(mapResult.diagnostics.droppedMissingCalendarSession).toBe(0);
|
|
|
|
// Record-based calendars with shuffled sessions/bars/events produce bit-identical output.
|
|
const recordResult = buildEventStudyInput({
|
|
bars: shuffle(bars, 7),
|
|
events: shuffle(events, 11),
|
|
vaultCutoffDate: '2024-12-04',
|
|
exchangeCalendars: {
|
|
calendars: {
|
|
XNYS: shuffle(nyseCalendar, 13),
|
|
XTSE: shuffle(tsxCalendar, 17),
|
|
},
|
|
listingCalendarId: {
|
|
[nyseId]: 'XNYS',
|
|
[tsxId]: 'XTSE',
|
|
},
|
|
},
|
|
});
|
|
expectBitIdenticalEventStudyInput(recordResult.input, mapResult.input);
|
|
expect(recordResult.diagnostics).toEqual(mapResult.diagnostics);
|
|
|
|
// NYSE-only study: filing at 14:00 ET on 2024-11-29 anchors to Monday 2024-12-02 (index 2 in NYSE-only dates),
|
|
// even though curated bars_1d.ts for 2024-11-29 is stamped at 16:00 ET (21:00 UTC).
|
|
const nyseOnly = buildEventStudyInput({
|
|
bars: bars.filter(b => b.listingId === nyseId),
|
|
events: [
|
|
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' },
|
|
],
|
|
vaultCutoffDate: '2024-12-04',
|
|
exchangeCalendars: {
|
|
calendars: { XNYS: nyseCalendar },
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
});
|
|
expect(nyseOnly.input.sessionDates).toEqual(['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03']);
|
|
expect(nyseOnly.input.events).toEqual([{ entityId: nyseId, dayIndex: 2 }]); // 2024-12-02
|
|
});
|
|
|
|
it('enforces Vault fencing, drop counters, and strict validation on exchangeCalendars', () => {
|
|
const nyseId = 10_001;
|
|
const bars = [
|
|
makeBar(nyseId, '2024-11-27', 100, 21),
|
|
makeBar(nyseId, '2024-11-29', 102, 21),
|
|
];
|
|
const nyseCalendar = [
|
|
{ date: '2024-11-26', closeTs: makeUtcMs('2024-11-26', 21) }, // before first bar -> droppedMissingCalendarSession
|
|
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) },
|
|
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET half-day
|
|
{ date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // post-cutoff (excluded from calendar)
|
|
];
|
|
|
|
const res = buildEventStudyInput({
|
|
bars,
|
|
events: [
|
|
// Anchors to 2024-11-26 which has no bar in sessionDates -> droppedMissingCalendarSession
|
|
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-26', 15), kind: 'filing', subtype: '10-q' },
|
|
// 14:00 ET on 2024-11-29 is after 13:00 ET close; 2024-12-02 is Vault-excluded -> droppedAfterLastSession
|
|
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' },
|
|
],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: {
|
|
calendars: { XNYS: nyseCalendar },
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
});
|
|
|
|
expect(res.input.events).toEqual([]);
|
|
expect(res.diagnostics.droppedMissingCalendarSession).toBe(1);
|
|
expect(res.diagnostics.droppedAfterLastSession).toBe(1);
|
|
expect(res.diagnostics.vaultExcludedEvents).toBe(0);
|
|
|
|
// Invalid exchangeCalendars shapes and values
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: null as unknown as NonNullable<
|
|
Parameters<typeof buildEventStudyInput>[0]['exchangeCalendars']
|
|
>,
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: {
|
|
calendars: {
|
|
XNYS: [{ date: '2024-02-30', closeTs: makeUtcMs('2024-02-28', 21) }],
|
|
},
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
}),
|
|
'invalid_date'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: {
|
|
calendars: {
|
|
XNYS: [
|
|
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) },
|
|
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) },
|
|
],
|
|
},
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: {
|
|
calendars: {
|
|
XNYS: [
|
|
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-29', 21) },
|
|
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-27', 21) },
|
|
],
|
|
},
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: {
|
|
calendars: { XNYS: nyseCalendar },
|
|
listingCalendarId: { [nyseId]: 'UNKNOWN_CAL' },
|
|
},
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-12-02',
|
|
exchangeCalendars: {
|
|
calendars: { XNYS: nyseCalendar },
|
|
listingCalendarId: {},
|
|
},
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
});
|
|
|
|
it('rejects incomplete exchange calendar coverage when a calendar starts after or omits pre-Vault bar dates', () => {
|
|
const nyseId = 10_001;
|
|
const dec2023AndJan2024Bars: BarRecord[] = [
|
|
makeBar(nyseId, '2023-12-28', 100, 21),
|
|
makeBar(nyseId, '2023-12-29', 101, 21),
|
|
makeBar(nyseId, '2024-01-02', 103, 21),
|
|
makeBar(nyseId, '2024-01-03', 104, 21),
|
|
];
|
|
|
|
// Calendar starts on Jan 2, 2024 while bars include December 2023 -> must throw invalid_option.
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: dec2023AndJan2024Bars,
|
|
events: [
|
|
{
|
|
listingId: nyseId,
|
|
knownAt: makeUtcMs('2023-12-29', 19), // 14:00 ET on Dec 29
|
|
kind: 'filing',
|
|
subtype: '10-q',
|
|
},
|
|
],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: {
|
|
calendars: {
|
|
XNYS: [
|
|
{ date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) },
|
|
{ date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) },
|
|
],
|
|
},
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
|
|
// Calendar omits a mid-history bar session (2023-12-29) -> must throw invalid_option.
|
|
expectEventPanelError(
|
|
() =>
|
|
buildEventStudyInput({
|
|
bars: dec2023AndJan2024Bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
exchangeCalendars: {
|
|
calendars: {
|
|
XNYS: [
|
|
{ date: '2023-12-28', closeTs: makeUtcMs('2023-12-28', 21) },
|
|
{ date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) },
|
|
{ date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) },
|
|
],
|
|
},
|
|
listingCalendarId: { [nyseId]: 'XNYS' },
|
|
},
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
});
|
|
|
|
it('uses exchange-calendar adjacency so a missing open session for all listings yields NaN on the next bar', () => {
|
|
// Exchange is open Mon, Tue, Wed, Thu, but bars exist only on Mon, Wed, Thu (Tue missing for ALL listings).
|
|
const mon = '2024-01-08';
|
|
const tue = '2024-01-09';
|
|
const wed = '2024-01-10';
|
|
const thu = '2024-01-11';
|
|
const bars: BarRecord[] = [
|
|
makeBar(10, mon, 100),
|
|
makeBar(10, wed, 110),
|
|
makeBar(10, thu, 121),
|
|
makeBar(20, mon, 50),
|
|
makeBar(20, wed, 55),
|
|
makeBar(20, thu, 60.5),
|
|
];
|
|
|
|
const res = buildEventStudyInput({
|
|
bars,
|
|
events: [],
|
|
vaultCutoffDate: '2024-02-01',
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: makeExchangeCalendars([10, 20], [mon, tue, wed, thu]),
|
|
});
|
|
|
|
// sessionDates contains only observed bar dates [Mon, Wed, Thu].
|
|
expect(res.input.sessionDates).toEqual([mon, wed, thu]);
|
|
|
|
const r10 = res.input.entityReturns.get(10)!;
|
|
const r20 = res.input.entityReturns.get(20)!;
|
|
const bench = res.input.benchmarkReturns!;
|
|
|
|
// Mon (index 0): NaN (first bar)
|
|
expect(Number.isNaN(r10[0]!)).toBe(true);
|
|
expect(Number.isNaN(r20[0]!)).toBe(true);
|
|
expect(Number.isNaN(bench[0]!)).toBe(true);
|
|
|
|
// Wed (index 1): MUST be NaN because Tue was an open exchange session (not consecutive).
|
|
expect(Number.isNaN(r10[1]!)).toBe(true);
|
|
expect(Number.isNaN(r20[1]!)).toBe(true);
|
|
expect(Number.isNaN(bench[1]!)).toBe(true);
|
|
|
|
// Thu (index 2): consecutive with Wed -> valid +10% return.
|
|
expect(r10[2]!).toBeCloseTo(0.1, 12);
|
|
expect(r20[2]!).toBeCloseTo(0.1, 12);
|
|
expect(bench[2]!).toBeCloseTo(0.1, 12);
|
|
});
|
|
});
|