T-175: tests
This commit is contained in:
parent
840597ad34
commit
c73e6b72aa
1 changed files with 430 additions and 0 deletions
430
libs/research/test/mcp-exchange-calendars-qa.test.ts
Normal file
430
libs/research/test/mcp-exchange-calendars-qa.test.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { type EventObservation, buildEventStudyInput } from '../src/event-panel';
|
||||
import type { BarRecord } from '../src/market-data-store';
|
||||
import {
|
||||
ExchangeCalendarResolverError,
|
||||
type ListingCalendarExecutor,
|
||||
type ListingCalendarRow,
|
||||
PostgresListingCalendarError,
|
||||
type SessionDatesQuery,
|
||||
createExchangeCalendarResolver,
|
||||
createPostgresListingCalendarPort,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
function utcMs(dateStr: string, hour: number, minute = 0): number {
|
||||
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
|
||||
return Date.UTC(y, m - 1, d, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
function isoDate(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function allDatesInclusive(from: string, to: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (let t = utcMs(from, 0); t <= utcMs(to, 0); t += MS_PER_DAY) {
|
||||
out.push(isoDate(t));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Independent oracle: local wall-clock date/time of `epochMs` in an IANA zone (ICU tzdata). */
|
||||
function makeZoneFormatter(timeZone: string): (epochMs: number) => string {
|
||||
const fmt = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hourCycle: 'h23',
|
||||
});
|
||||
return (epochMs) => {
|
||||
const parts = Object.fromEntries(fmt.formatToParts(new Date(epochMs)).map((p) => [p.type, p.value]));
|
||||
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
|
||||
};
|
||||
}
|
||||
|
||||
async function captureError(fn: () => unknown): Promise<unknown> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function countingPorts(
|
||||
rows: readonly ListingCalendarRow[] | (() => unknown),
|
||||
sessions: (q: SessionDatesQuery) => unknown
|
||||
) {
|
||||
const counts = { listing: 0, session: 0 };
|
||||
const sessionCalls: SessionDatesQuery[] = [];
|
||||
return {
|
||||
counts,
|
||||
sessionCalls,
|
||||
listingCalendars: {
|
||||
getListingCalendars: () => {
|
||||
counts.listing += 1;
|
||||
return (typeof rows === 'function' ? rows() : rows) as readonly ListingCalendarRow[];
|
||||
},
|
||||
},
|
||||
sessionDates: {
|
||||
listSessionDates: (q: SessionDatesQuery) => {
|
||||
counts.session += 1;
|
||||
sessionCalls.push(q);
|
||||
return sessions(q) as readonly string[];
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('QA: Eastern close timestamps vs ICU tzdata oracle', () => {
|
||||
test('every day 1976-01-01..=2030-12-31 closes at exactly 16:00 local in America/New_York and America/Toronto', async () => {
|
||||
const days = allDatesInclusive('1976-01-01', '2030-12-31');
|
||||
expect(days).toHaveLength(20_089);
|
||||
|
||||
const ports = countingPorts(
|
||||
[
|
||||
{ listingId: 1, calendarCode: 'XNYS' },
|
||||
{ listingId: 2, calendarCode: 'XTSE' },
|
||||
],
|
||||
() => days
|
||||
);
|
||||
const resolver = createExchangeCalendarResolver(ports);
|
||||
const result = await resolver({ listingIds: [1, 2], fromDate: days[0]!, toDate: days[days.length - 1]! });
|
||||
const calendars = result.calendars as Record<string, readonly { date: string; closeTs: number }[]>;
|
||||
|
||||
const ny = makeZoneFormatter('America/New_York');
|
||||
const to = makeZoneFormatter('America/Toronto');
|
||||
const mismatches: string[] = [];
|
||||
for (const code of ['XNYS', 'XTSE'] as const) {
|
||||
const sessions = calendars[code]!;
|
||||
expect(sessions).toHaveLength(days.length);
|
||||
for (let i = 0; i < days.length; i += 1) {
|
||||
const s = sessions[i]!;
|
||||
const expected = `${days[i]} 16:00`;
|
||||
if (s.date !== days[i] || ny(s.closeTs) !== expected || to(s.closeTs) !== expected) {
|
||||
mismatches.push(`${code} ${days[i]} -> ${new Date(s.closeTs).toISOString()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(mismatches).toEqual([]);
|
||||
expect(ports.counts).toEqual({ listing: 1, session: 2 });
|
||||
});
|
||||
|
||||
test('each supported year has exactly two offset flips, both on Sundays, and closes are only 20:00Z or 21:00Z', async () => {
|
||||
const days = allDatesInclusive('1976-01-01', '2030-12-31');
|
||||
const resolver = createExchangeCalendarResolver(
|
||||
countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => days)
|
||||
);
|
||||
const result = await resolver({ listingIds: [1], fromDate: days[0]!, toDate: days[days.length - 1]! });
|
||||
const sessions = (result.calendars as Record<string, readonly { date: string; closeTs: number }[]>).XNYS!;
|
||||
|
||||
const flipsByYear = new Map<number, string[]>();
|
||||
let prevHour = -1;
|
||||
for (const s of sessions) {
|
||||
const hour = (s.closeTs - utcMs(s.date, 0)) / 3_600_000;
|
||||
expect(hour === 20 || hour === 21).toBe(true);
|
||||
if (prevHour !== -1 && hour !== prevHour) {
|
||||
const year = Number(s.date.slice(0, 4));
|
||||
flipsByYear.set(year, [...(flipsByYear.get(year) ?? []), s.date]);
|
||||
expect(new Date(utcMs(s.date, 0)).getUTCDay()).toBe(0);
|
||||
}
|
||||
prevHour = hour;
|
||||
}
|
||||
// 1976 starts in EST, so every year (1976..=2030) has exactly spring + fall flips.
|
||||
expect(flipsByYear.size).toBe(55);
|
||||
for (const [, flips] of flipsByYear) {
|
||||
expect(flips).toHaveLength(2);
|
||||
}
|
||||
});
|
||||
|
||||
test('remaining session_close.rs known vectors (mid-season and 1986/2006 boundaries) match exactly', async () => {
|
||||
const vectors: ReadonlyArray<readonly [string, number]> = [
|
||||
['1980-01-15', 21],
|
||||
['1980-07-15', 20],
|
||||
['1986-04-26', 21],
|
||||
['1986-04-27', 20],
|
||||
['1999-01-15', 21],
|
||||
['1999-07-15', 20],
|
||||
['2006-04-01', 21],
|
||||
['2006-04-02', 20],
|
||||
['2006-10-28', 20],
|
||||
['2006-10-29', 21],
|
||||
['2024-01-15', 21],
|
||||
['2024-07-15', 20],
|
||||
];
|
||||
const resolver = createExchangeCalendarResolver(
|
||||
countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => vectors.map(([d]) => d))
|
||||
);
|
||||
const result = await resolver({ listingIds: [1], fromDate: '1980-01-15', toDate: '2024-07-15' });
|
||||
expect(result.calendars).toEqual({
|
||||
XNYS: vectors.map(([date, hour]) => ({ date, closeTs: utcMs(date, hour) })),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('QA: earlyCloses edge cases', () => {
|
||||
test('override applies in EDT and EST, 960 equals default, and minute 1 is 00:01 ET', async () => {
|
||||
const dates = ['2024-07-03', '2024-11-29', '2024-12-24', '2024-12-26'];
|
||||
const resolver = createExchangeCalendarResolver({
|
||||
...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => dates),
|
||||
earlyCloses: { XNYS: { '2024-07-03': 780, '2024-11-29': 960, '2024-12-24': 1 } },
|
||||
});
|
||||
const result = await resolver({ listingIds: [1], fromDate: '2024-07-01', toDate: '2024-12-31' });
|
||||
expect(result.calendars).toEqual({
|
||||
XNYS: [
|
||||
{ date: '2024-07-03', closeTs: utcMs('2024-07-03', 17) }, // 13:00 EDT
|
||||
{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }, // 16:00 EST (== default)
|
||||
{ date: '2024-12-24', closeTs: utcMs('2024-12-24', 5, 1) }, // 00:01 EST
|
||||
{ date: '2024-12-26', closeTs: utcMs('2024-12-26', 21) },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('overrides for unrequested calendars or non-session dates are ignored without error', async () => {
|
||||
const ports = countingPorts([{ listingId: 1, calendarCode: 'XTSE' }], () => ['2024-11-29']);
|
||||
const resolver = createExchangeCalendarResolver({
|
||||
...ports,
|
||||
earlyCloses: { XNYS: { '2024-11-29': 780 }, XTSE: { '2024-12-25': 780 } },
|
||||
});
|
||||
const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' });
|
||||
expect(result.calendars).toEqual({
|
||||
XTSE: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }],
|
||||
});
|
||||
});
|
||||
|
||||
test('calendar code matching for overrides is exact (case-sensitive)', async () => {
|
||||
const resolver = createExchangeCalendarResolver({
|
||||
...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-11-29']),
|
||||
earlyCloses: { xnys: { '2024-11-29': 780 } },
|
||||
});
|
||||
const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' });
|
||||
expect(result.calendars).toEqual({
|
||||
XNYS: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }],
|
||||
});
|
||||
});
|
||||
|
||||
test('earlyCloses parsed from JSON with a "__proto__" calendar key does not pollute Object.prototype', async () => {
|
||||
const earlyCloses = JSON.parse('{"__proto__": {"2024-11-29": 780}, "XNYS": {"2024-11-29": 780}}');
|
||||
const resolver = createExchangeCalendarResolver({
|
||||
...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-11-29']),
|
||||
earlyCloses,
|
||||
});
|
||||
const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' });
|
||||
expect(result.calendars).toEqual({
|
||||
XNYS: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 18) }],
|
||||
});
|
||||
expect(({} as Record<string, unknown>)['2024-11-29']).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('QA: query validation and port failures fail closed', () => {
|
||||
test('invalid queries throw INVALID_QUERY with zero port calls', async () => {
|
||||
const bad: unknown[] = [
|
||||
null,
|
||||
[],
|
||||
{ listingIds: 'x', fromDate: '2024-01-02', toDate: '2024-01-03' },
|
||||
{ listingIds: [1], fromDate: '2024-01-03', toDate: '2024-01-02' },
|
||||
{ listingIds: [1], fromDate: '2024-1-2', toDate: '2024-01-03' },
|
||||
{ listingIds: [1], fromDate: '2024-01-02', toDate: undefined },
|
||||
{ listingIds: [1.5], fromDate: '2024-01-02', toDate: '2024-01-03' },
|
||||
{ listingIds: ['1'], fromDate: '2024-01-02', toDate: '2024-01-03' },
|
||||
{ listingIds: [2_147_483_648], fromDate: '2024-01-02', toDate: '2024-01-03' },
|
||||
];
|
||||
for (const q of bad) {
|
||||
const ports = countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-01-02']);
|
||||
const err = await captureError(() => createExchangeCalendarResolver(ports)(q as never));
|
||||
expect(err, JSON.stringify(q)).toBeInstanceOf(ExchangeCalendarResolverError);
|
||||
expect((err as ExchangeCalendarResolverError).code, JSON.stringify(q)).toBe('INVALID_QUERY');
|
||||
expect(ports.counts, JSON.stringify(q)).toEqual({ listing: 0, session: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed listing port responses throw INVALID_LISTING_CALENDAR_ROW before any session call', async () => {
|
||||
const badResponses: unknown[] = [
|
||||
null,
|
||||
{ rows: [] },
|
||||
[null],
|
||||
[{ listingId: '1', calendarCode: 'XNYS' }],
|
||||
[{ listingId: 1, calendarCode: ' XNYS' }],
|
||||
[{ listingId: 1, calendarCode: '' }],
|
||||
[{ listingId: 1 }],
|
||||
];
|
||||
for (const resp of badResponses) {
|
||||
const ports = countingPorts(() => resp, () => ['2024-01-02']);
|
||||
const err = await captureError(() =>
|
||||
createExchangeCalendarResolver(ports)({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' })
|
||||
);
|
||||
expect(err, JSON.stringify(resp)).toBeInstanceOf(ExchangeCalendarResolverError);
|
||||
expect((err as ExchangeCalendarResolverError).code).toBe('INVALID_LISTING_CALENDAR_ROW');
|
||||
expect(ports.counts.session).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('port errors propagate unchanged and no partial result is returned', async () => {
|
||||
const listingBoom = new Error('pg down');
|
||||
const ports1 = countingPorts(() => {
|
||||
throw listingBoom;
|
||||
}, () => []);
|
||||
expect(
|
||||
await captureError(() =>
|
||||
createExchangeCalendarResolver(ports1)({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' })
|
||||
)
|
||||
).toBe(listingBoom);
|
||||
expect(ports1.counts.session).toBe(0);
|
||||
|
||||
const sessionBoom = new Error('sessions down');
|
||||
const ports2 = countingPorts(
|
||||
[
|
||||
{ listingId: 1, calendarCode: 'XNYS' },
|
||||
{ listingId: 2, calendarCode: 'XTSE' },
|
||||
],
|
||||
(q) => (q.calendarCode === 'XTSE' ? Promise.reject(sessionBoom) : ['2024-01-02'])
|
||||
);
|
||||
expect(
|
||||
await captureError(() =>
|
||||
createExchangeCalendarResolver(ports2)({ listingIds: [2, 1], fromDate: '2024-01-02', toDate: '2024-01-02' })
|
||||
)
|
||||
).toBe(sessionBoom);
|
||||
expect(ports2.sessionCalls.map((q) => q.calendarCode)).toEqual(['XNYS', 'XTSE']);
|
||||
});
|
||||
|
||||
test('session dates outside the supported DST range fail closed even when the window would allow them', async () => {
|
||||
// Query window is in range; port returns a pre-1976 date which is also outside the window.
|
||||
const ports = countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['1975-12-31']);
|
||||
const err = await captureError(() =>
|
||||
createExchangeCalendarResolver(ports)({ listingIds: [1], fromDate: '1976-01-01', toDate: '1976-01-05' })
|
||||
);
|
||||
expect(err).toBeInstanceOf(ExchangeCalendarResolverError);
|
||||
expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE');
|
||||
});
|
||||
|
||||
test('an empty session list for a calendar is returned as an empty array (not dropped)', async () => {
|
||||
const resolver = createExchangeCalendarResolver(
|
||||
countingPorts([{ listingId: 5, calendarCode: 'XTSE' }], () => [])
|
||||
);
|
||||
const result = await resolver({ listingIds: [5], fromDate: '2024-01-01', toDate: '2024-01-01' });
|
||||
expect(result).toEqual({ calendars: { XTSE: [] }, listingCalendarId: { 5: 'XTSE' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('QA: output safety and isolation', () => {
|
||||
test('a "__proto__" calendar code becomes an own property and does not pollute Object.prototype', async () => {
|
||||
const resolver = createExchangeCalendarResolver(
|
||||
countingPorts([{ listingId: 1, calendarCode: '__proto__' }], () => ['2024-01-02'])
|
||||
);
|
||||
const result = await resolver({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' });
|
||||
expect(Object.keys(result.calendars)).toEqual(['__proto__']);
|
||||
expect(Object.getPrototypeOf(result.calendars)).toBe(Object.prototype);
|
||||
expect(Object.hasOwn(result.calendars, '__proto__')).toBe(true);
|
||||
expect(({} as Record<string, unknown>).date).toBeUndefined();
|
||||
});
|
||||
|
||||
test('repeated calls return fresh objects; mutating one result does not affect the next', async () => {
|
||||
const resolver = createExchangeCalendarResolver(
|
||||
countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-01-02'])
|
||||
);
|
||||
const q = { listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' };
|
||||
const first = await resolver(q);
|
||||
(first.calendars as Record<string, { date: string; closeTs: number }[]>).XNYS!.push({
|
||||
date: '2024-01-03',
|
||||
closeTs: 0,
|
||||
});
|
||||
(first.listingCalendarId as Record<number, string>)[1] = 'XTSE';
|
||||
const second = await resolver(q);
|
||||
expect(second).toEqual({
|
||||
calendars: { XNYS: [{ date: '2024-01-02', closeTs: utcMs('2024-01-02', 21) }] },
|
||||
listingCalendarId: { 1: 'XNYS' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('QA: Postgres port → resolver → buildEventStudyInput (fake executor)', () => {
|
||||
test('rejects invalid listingIds with INVALID_ROW and zero queries; propagates executor rejection', async () => {
|
||||
let queries = 0;
|
||||
const executor: ListingCalendarExecutor = {
|
||||
async query() {
|
||||
queries += 1;
|
||||
return { rows: [] };
|
||||
},
|
||||
};
|
||||
const port = createPostgresListingCalendarPort({ executor, schema: 'public' });
|
||||
for (const bad of ['1' as unknown, [1.5], ['1'], [Number.NaN], [-2_147_483_649]]) {
|
||||
const err = await captureError(() => port.getListingCalendars(bad as never));
|
||||
expect(err).toBeInstanceOf(PostgresListingCalendarError);
|
||||
expect((err as PostgresListingCalendarError).code).toBe('INVALID_ROW');
|
||||
}
|
||||
expect(queries).toBe(0);
|
||||
|
||||
const boom = new Error('connection reset');
|
||||
const failing = createPostgresListingCalendarPort({
|
||||
executor: {
|
||||
async query() {
|
||||
throw boom;
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await captureError(() => failing.getListingCalendars([1]))).toBe(boom);
|
||||
});
|
||||
|
||||
test('padded VARCHAR calendar_code is trimmed and the composed result feeds buildEventStudyInput', async () => {
|
||||
const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = [];
|
||||
const executor: ListingCalendarExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
calls.push({ text, params });
|
||||
return {
|
||||
rows: [
|
||||
{ listing_id: 202, calendar_code: 'XTSE ' },
|
||||
{ listing_id: 101, calendar_code: 'XNYS' },
|
||||
] as unknown as readonly Row[],
|
||||
};
|
||||
},
|
||||
};
|
||||
const sessions: Record<string, readonly string[]> = {
|
||||
XNYS: ['2024-11-27', '2024-11-29', '2024-12-02'],
|
||||
XTSE: ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02'],
|
||||
};
|
||||
const resolver = createExchangeCalendarResolver({
|
||||
listingCalendars: createPostgresListingCalendarPort({ executor, schema: 'public' }),
|
||||
sessionDates: { listSessionDates: (q) => sessions[q.calendarCode] ?? [] },
|
||||
earlyCloses: { XNYS: { '2024-11-29': 780 } },
|
||||
});
|
||||
const cal = await resolver({ listingIds: [202, 101, 202], fromDate: '2024-11-27', toDate: '2024-12-02' });
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.params).toEqual([[101, 202]]);
|
||||
expect(calls[0]!.text).toContain('FROM "public".listing l');
|
||||
expect(cal.listingCalendarId).toEqual({ 101: 'XNYS', 202: 'XTSE' });
|
||||
|
||||
const bar = (listingId: number, date: string, close: number): BarRecord => {
|
||||
const ts = utcMs(date, 21);
|
||||
return { listingId, ts, open: close, high: close, low: close, close, volume: 1_000, knownAt: ts };
|
||||
};
|
||||
const bars: BarRecord[] = [
|
||||
...sessions.XNYS!.map((d, i) => bar(101, d, 100 + i)),
|
||||
...sessions.XTSE!.map((d, i) => bar(202, d, 50 + i)),
|
||||
];
|
||||
// 18:30Z on 2024-11-29: after XNYS 13:00 ET early close, before XTSE 16:00 ET close.
|
||||
const knownAt = utcMs('2024-11-29', 18, 30);
|
||||
const events: EventObservation[] = [
|
||||
{ listingId: 101, knownAt, kind: 'filing', subtype: '8-K' },
|
||||
{ listingId: 202, knownAt, kind: 'filing', subtype: '8-K' },
|
||||
];
|
||||
const panel = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate: '2024-12-03',
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: cal,
|
||||
});
|
||||
expect(panel.input.sessionDates).toEqual(['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02']);
|
||||
expect(panel.input.events).toEqual([
|
||||
{ entityId: 202, dayIndex: 2 },
|
||||
{ entityId: 101, dayIndex: 3 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue