789 lines
28 KiB
TypeScript
789 lines
28 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { type EventObservation, buildEventStudyInput } from '../src/event-panel';
|
|
import type { BarRecord } from '../src/market-data-store';
|
|
import {
|
|
EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET,
|
|
EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE,
|
|
EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE,
|
|
ExchangeCalendarResolverError,
|
|
type ListingCalendarExecutor,
|
|
type ListingCalendarPort,
|
|
type ListingCalendarRow,
|
|
PostgresListingCalendarError,
|
|
type SessionDatesPort,
|
|
type SessionDatesQuery,
|
|
createExchangeCalendarResolver,
|
|
createPostgresListingCalendarPort,
|
|
} from '../src/mcp/index';
|
|
|
|
function utcMs(
|
|
year: number,
|
|
month: number,
|
|
day: number,
|
|
hour = 0,
|
|
minute = 0,
|
|
second = 0
|
|
): number {
|
|
return Date.UTC(year, month - 1, day, hour, minute, second, 0);
|
|
}
|
|
|
|
function makeBar(listingId: number, dateStr: string, close: number, closeHourUtc = 21): BarRecord {
|
|
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
|
|
const ts = utcMs(y, m, d, closeHourUtc, 0, 0);
|
|
return {
|
|
listingId,
|
|
ts,
|
|
open: close,
|
|
high: close,
|
|
low: close,
|
|
close,
|
|
volume: 100_000,
|
|
knownAt: ts,
|
|
};
|
|
}
|
|
|
|
describe('createExchangeCalendarResolver — Eastern DST schedule & date bounds', () => {
|
|
test('computes exact UTC ms for EDT (2024-07-01 -> 20:00Z) and EST (2024-12-02 -> 21:00Z)', async () => {
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => [{ listingId: 1, calendarCode: 'XNYS' }],
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: () => ['2024-07-01', '2024-12-02'],
|
|
},
|
|
});
|
|
|
|
const result = await resolver({
|
|
listingIds: [1],
|
|
fromDate: '2024-07-01',
|
|
toDate: '2024-12-02',
|
|
});
|
|
|
|
expect(result.calendars).toEqual({
|
|
XNYS: [
|
|
{ date: '2024-07-01', closeTs: utcMs(2024, 7, 1, 20, 0, 0) },
|
|
{ date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) },
|
|
],
|
|
});
|
|
expect(result.listingCalendarId).toEqual({ 1: 'XNYS' });
|
|
});
|
|
|
|
test('matches session_close.rs DST transition vectors across all three eras (1976, 1987, 2007)', async () => {
|
|
const vectors: readonly {
|
|
readonly date: string;
|
|
readonly expectedUtcHour: number;
|
|
}[] = [
|
|
// Era 1 (1976..=1986): last Sunday of April -> last Sunday of October
|
|
{ date: '1976-04-24', expectedUtcHour: 21 }, // Sat before spring-forward (EST)
|
|
{ date: '1976-04-25', expectedUtcHour: 20 }, // Last Sun of April (EDT)
|
|
{ date: '1976-10-30', expectedUtcHour: 20 }, // Sat before fall-back (EDT)
|
|
{ date: '1976-10-31', expectedUtcHour: 21 }, // Last Sun of October (EST)
|
|
// Era 2 (1987..=2006): first Sunday of April -> last Sunday of October
|
|
{ date: '1987-04-04', expectedUtcHour: 21 }, // Sat before spring-forward (EST)
|
|
{ date: '1987-04-05', expectedUtcHour: 20 }, // First Sun of April (EDT)
|
|
{ date: '1987-10-24', expectedUtcHour: 20 }, // Sat before fall-back (EDT)
|
|
{ date: '1987-10-25', expectedUtcHour: 21 }, // Last Sun of October (EST)
|
|
// Era 3 (2007..=2030): second Sunday of March -> first Sunday of November
|
|
{ date: '2007-03-10', expectedUtcHour: 21 }, // Sat before spring-forward (EST)
|
|
{ date: '2007-03-11', expectedUtcHour: 20 }, // Second Sun of March (EDT)
|
|
{ date: '2007-11-03', expectedUtcHour: 20 }, // Sat before fall-back (EDT)
|
|
{ date: '2007-11-04', expectedUtcHour: 21 }, // First Sun of November (EST)
|
|
];
|
|
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => [{ listingId: 10, calendarCode: 'XNYS' }],
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: () => vectors.map((v) => v.date),
|
|
},
|
|
});
|
|
|
|
const result = await resolver({
|
|
listingIds: [10],
|
|
fromDate: '1976-04-24',
|
|
toDate: '2007-11-04',
|
|
});
|
|
|
|
const sessions = (result.calendars as Record<string, readonly { date: string; closeTs: number }[]>)
|
|
.XNYS;
|
|
expect(sessions).toHaveLength(vectors.length);
|
|
|
|
for (let i = 0; i < vectors.length; i += 1) {
|
|
const vec = vectors[i] as { date: string; expectedUtcHour: number };
|
|
const [y, m, d] = vec.date.split('-').map(Number) as [number, number, number];
|
|
expect(sessions?.[i]).toEqual({
|
|
date: vec.date,
|
|
closeTs: utcMs(y, m, d, vec.expectedUtcHour, 0, 0),
|
|
});
|
|
}
|
|
});
|
|
|
|
test('supports inclusive endpoints 1976-01-01 and 2030-12-31 and fails closed outside range', async () => {
|
|
let listingCalls = 0;
|
|
let sessionCalls = 0;
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => {
|
|
listingCalls += 1;
|
|
return [{ listingId: 1, calendarCode: 'XNYS' }];
|
|
},
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: () => {
|
|
sessionCalls += 1;
|
|
return [EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE];
|
|
},
|
|
},
|
|
});
|
|
|
|
const ok = await resolver({
|
|
listingIds: [1],
|
|
fromDate: '1976-01-01',
|
|
toDate: '2030-12-31',
|
|
});
|
|
expect(ok.calendars).toEqual({
|
|
XNYS: [
|
|
{ date: '1976-01-01', closeTs: utcMs(1976, 1, 1, 21, 0, 0) },
|
|
{ date: '2030-12-31', closeTs: utcMs(2030, 12, 31, 21, 0, 0) },
|
|
],
|
|
});
|
|
expect(listingCalls).toBe(1);
|
|
expect(sessionCalls).toBe(1);
|
|
|
|
await expect(
|
|
resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' })
|
|
).rejects.toThrow(ExchangeCalendarResolverError);
|
|
try {
|
|
await resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' });
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(ExchangeCalendarResolverError);
|
|
expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE');
|
|
}
|
|
|
|
try {
|
|
await resolver({ listingIds: [1], fromDate: '2030-12-30', toDate: '2031-01-01' });
|
|
expect.unreachable('expected UNSUPPORTED_DATE for 2031-01-01');
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(ExchangeCalendarResolverError);
|
|
expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE');
|
|
}
|
|
|
|
// Out-of-range query bounds fail before calling either port.
|
|
expect(listingCalls).toBe(1);
|
|
expect(sessionCalls).toBe(1);
|
|
});
|
|
});
|
|
|
|
describe('createPostgresListingCalendarPort', () => {
|
|
test('issues one parameterized SELECT joining listing.mic to exchange.mic with no ID literals or writes', 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 });
|
|
const rows = [
|
|
{ listing_id: 101, calendar_code: 'XNYS' },
|
|
{ listing_id: 202, calendar_code: 'XTSE' },
|
|
];
|
|
return { rows: rows as unknown as readonly Row[] };
|
|
},
|
|
};
|
|
|
|
const port = createPostgresListingCalendarPort({ executor });
|
|
const rows = await port.getListingCalendars([101, 202]);
|
|
|
|
expect(rows).toEqual([
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
{ listingId: 202, calendarCode: 'XTSE' },
|
|
]);
|
|
expect(calls).toHaveLength(1);
|
|
|
|
const call = calls[0] as { text: string; params: readonly unknown[] | undefined };
|
|
expect(call.text).toContain('SELECT');
|
|
expect(call.text).toContain('FROM listing l');
|
|
expect(call.text).toContain('INNER JOIN exchange e ON e.mic = l.mic');
|
|
expect(call.text).toContain('WHERE l.listing_id = ANY($1::integer[])');
|
|
expect(call.text).not.toContain('101');
|
|
expect(call.text).not.toContain('202');
|
|
expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
|
|
expect(call.params).toEqual([[101, 202]]);
|
|
});
|
|
|
|
test('supports optional validated schema qualification and short-circuits empty listingIds', 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: 7, calendar_code: 'XNYS' }] as unknown as readonly Row[] };
|
|
},
|
|
};
|
|
|
|
const port = createPostgresListingCalendarPort({ executor, schema: 'sec_master_v1' });
|
|
expect(await port.getListingCalendars([])).toEqual([]);
|
|
expect(calls).toHaveLength(0);
|
|
|
|
const rows = await port.getListingCalendars([7]);
|
|
expect(rows).toEqual([{ listingId: 7, calendarCode: 'XNYS' }]);
|
|
expect(calls).toHaveLength(1);
|
|
expect(calls[0]?.text).toContain('FROM "sec_master_v1".listing l');
|
|
expect(calls[0]?.text).toContain('INNER JOIN "sec_master_v1".exchange e ON e.mic = l.mic');
|
|
});
|
|
|
|
test('throws typed INVALID_EXECUTOR, INVALID_SCHEMA, and INVALID_ROW errors', async () => {
|
|
const badExecutors: unknown[] = [null, undefined, {}, { executor: null }, { executor: {} }];
|
|
for (const bad of badExecutors) {
|
|
let caught: unknown;
|
|
try {
|
|
createPostgresListingCalendarPort(bad as never);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect(caught).toBeInstanceOf(PostgresListingCalendarError);
|
|
expect((caught as PostgresListingCalendarError).code).toBe('INVALID_EXECUTOR');
|
|
}
|
|
|
|
const okExecutor: ListingCalendarExecutor = {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
};
|
|
for (const badSchema of ['', 'Public', '1bad', 'bad-schema', 'a; DROP TABLE listing;']) {
|
|
let caught: unknown;
|
|
try {
|
|
createPostgresListingCalendarPort({ executor: okExecutor, schema: badSchema });
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect(caught).toBeInstanceOf(PostgresListingCalendarError);
|
|
expect((caught as PostgresListingCalendarError).code).toBe('INVALID_SCHEMA');
|
|
}
|
|
|
|
const badResponses: unknown[] = [
|
|
null,
|
|
{ rows: 'not-an-array' },
|
|
{ rows: [null] },
|
|
{ rows: [{ listing_id: '101', calendar_code: 'XNYS' }] },
|
|
{ rows: [{ listing_id: 2_147_483_648, calendar_code: 'XNYS' }] },
|
|
{ rows: [{ listing_id: 101, calendar_code: '' }] },
|
|
{ rows: [{ listing_id: 101, calendar_code: ' ' }] },
|
|
{ rows: [{ listing_id: 101, calendar_code: null }] },
|
|
];
|
|
for (const badResp of badResponses) {
|
|
const port = createPostgresListingCalendarPort({
|
|
executor: {
|
|
async query() {
|
|
return badResp as never;
|
|
},
|
|
},
|
|
});
|
|
let caught: unknown;
|
|
try {
|
|
await port.getListingCalendars([101]);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect(caught).toBeInstanceOf(PostgresListingCalendarError);
|
|
expect((caught as PostgresListingCalendarError).code).toBe('INVALID_ROW');
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('createExchangeCalendarResolver — multi-calendar, earlyCloses, and buildEventStudyInput integration', () => {
|
|
const createMultiCalendarFixture = () => {
|
|
const xnysDates = ['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03'] as const;
|
|
const xtseDates = [
|
|
'2024-11-27',
|
|
'2024-11-28',
|
|
'2024-11-29',
|
|
'2024-12-02',
|
|
'2024-12-03',
|
|
] as const;
|
|
|
|
const bars: BarRecord[] = [
|
|
// Listing 101 (XNYS) — closed on US Thanksgiving 2024-11-28
|
|
makeBar(101, '2024-11-27', 100),
|
|
makeBar(101, '2024-11-29', 110),
|
|
makeBar(101, '2024-12-02', 121),
|
|
makeBar(101, '2024-12-03', 121),
|
|
makeBar(101, '2024-12-04', 999), // post-Vault bar (must be excluded)
|
|
// Listing 102 (XNYS)
|
|
makeBar(102, '2024-11-27', 50),
|
|
makeBar(102, '2024-11-29', 55),
|
|
makeBar(102, '2024-12-02', 60.5),
|
|
makeBar(102, '2024-12-03', 60.5),
|
|
// Listing 201 (XTSE) — open on 2024-11-28
|
|
makeBar(201, '2024-11-27', 200),
|
|
makeBar(201, '2024-11-28', 210),
|
|
makeBar(201, '2024-11-29', 220.5),
|
|
makeBar(201, '2024-12-02', 242.55),
|
|
makeBar(201, '2024-12-03', 242.55),
|
|
];
|
|
|
|
// Event at 19:00:00Z on 2024-11-29 (14:00 EST):
|
|
// - After XNYS 13:00 EST early close (18:00Z), so with override it anchors to 2024-12-02.
|
|
// - Before XTSE 16:00 EST close (21:00Z), so it stays on 2024-11-29.
|
|
const eventTs = utcMs(2024, 11, 29, 19, 0, 0);
|
|
const events: EventObservation[] = [
|
|
{ listingId: 101, knownAt: eventTs, kind: 'filing', subtype: '8-K' },
|
|
{ listingId: 201, knownAt: eventTs, kind: 'filing', subtype: '8-K' },
|
|
];
|
|
|
|
return {
|
|
xnysDates,
|
|
xtseDates,
|
|
bars,
|
|
events,
|
|
fromDate: '2024-11-27',
|
|
toDate: '2024-12-03',
|
|
vaultCutoffDate: '2024-12-04',
|
|
};
|
|
};
|
|
|
|
test('calls listSessionDates once per distinct calendar, anchors early-close vs 16:00 ET in buildEventStudyInput, and respects Vault cutoff', async () => {
|
|
const fixture = createMultiCalendarFixture();
|
|
|
|
const makePorts = () => {
|
|
const sessionCalls: SessionDatesQuery[] = [];
|
|
const listingPort: ListingCalendarPort = {
|
|
async getListingCalendars() {
|
|
return [
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
{ listingId: 102, calendarCode: 'XNYS' },
|
|
{ listingId: 201, calendarCode: 'XTSE' },
|
|
];
|
|
},
|
|
};
|
|
const sessionPort: SessionDatesPort = {
|
|
async listSessionDates(q) {
|
|
sessionCalls.push(q);
|
|
return q.calendarCode === 'XNYS' ? fixture.xnysDates : fixture.xtseDates;
|
|
},
|
|
};
|
|
return { listingPort, sessionPort, sessionCalls };
|
|
};
|
|
|
|
// 1) Baseline: no earlyCloses (all sessions close at 16:00 ET = 21:00Z in EST)
|
|
const baselinePorts = makePorts();
|
|
const baselineResolver = createExchangeCalendarResolver({
|
|
listingCalendars: baselinePorts.listingPort,
|
|
sessionDates: baselinePorts.sessionPort,
|
|
});
|
|
const baselineCal = await baselineResolver({
|
|
listingIds: [101, 102, 201],
|
|
fromDate: fixture.fromDate,
|
|
toDate: fixture.toDate,
|
|
});
|
|
|
|
expect(baselinePorts.sessionCalls).toEqual([
|
|
{ calendarCode: 'XNYS', fromDate: fixture.fromDate, toDate: fixture.toDate },
|
|
{ calendarCode: 'XTSE', fromDate: fixture.fromDate, toDate: fixture.toDate },
|
|
]);
|
|
expect(baselineCal.listingCalendarId).toEqual({
|
|
101: 'XNYS',
|
|
102: 'XNYS',
|
|
201: 'XTSE',
|
|
});
|
|
|
|
const baselinePanel = buildEventStudyInput({
|
|
bars: fixture.bars,
|
|
events: fixture.events,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: baselineCal,
|
|
});
|
|
|
|
expect(baselinePanel.diagnostics.vaultExcludedDates).toBe(1);
|
|
expect(baselinePanel.input.sessionDates).toEqual([
|
|
'2024-11-27',
|
|
'2024-11-28',
|
|
'2024-11-29',
|
|
'2024-12-02',
|
|
'2024-12-03',
|
|
]);
|
|
// Under 16:00 ET baseline, both listings anchor to 2024-11-29 (index 2).
|
|
expect(baselinePanel.input.events).toEqual([
|
|
{ entityId: 101, dayIndex: 2 },
|
|
{ entityId: 201, dayIndex: 2 },
|
|
]);
|
|
|
|
// Consecutive-session returns: listing 101 has no 2024-11-28 session on XNYS,
|
|
// so 2024-11-27 -> 2024-11-29 is consecutive on XNYS (+10%), and 2024-11-28 is NaN.
|
|
const returns101 = baselinePanel.input.entityReturns.get(101) as Float64Array;
|
|
expect(Number.isNaN(returns101[0] as number)).toBe(true);
|
|
expect(Number.isNaN(returns101[1] as number)).toBe(true);
|
|
expect(returns101[2]).toBeCloseTo(0.1, 12);
|
|
expect(returns101[3]).toBeCloseTo(0.1, 12);
|
|
expect(returns101[4]).toBeCloseTo(0.0, 12);
|
|
|
|
// 2) With XNYS-only early close override (780 = 13:00 ET -> 18:00Z on 2024-11-29)
|
|
const overridePorts = makePorts();
|
|
const overrideConfig = { XNYS: { '2024-11-29': 780 } };
|
|
const overrideResolver = createExchangeCalendarResolver({
|
|
listingCalendars: overridePorts.listingPort,
|
|
sessionDates: overridePorts.sessionPort,
|
|
earlyCloses: overrideConfig,
|
|
});
|
|
// Mutating caller's override object after construction must not affect resolver.
|
|
overrideConfig.XNYS['2024-11-29'] = EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET;
|
|
|
|
const overrideCal = await overrideResolver({
|
|
listingIds: [101, 102, 201],
|
|
fromDate: fixture.fromDate,
|
|
toDate: fixture.toDate,
|
|
});
|
|
|
|
const xnysSessions = (
|
|
overrideCal.calendars as Record<string, readonly { date: string; closeTs: number }[]>
|
|
).XNYS;
|
|
const xtseSessions = (
|
|
overrideCal.calendars as Record<string, readonly { date: string; closeTs: number }[]>
|
|
).XTSE;
|
|
|
|
expect(xnysSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe(
|
|
utcMs(2024, 11, 29, 18, 0, 0)
|
|
);
|
|
expect(xnysSessions?.find((s) => s.date === '2024-12-02')?.closeTs).toBe(
|
|
utcMs(2024, 12, 2, 21, 0, 0)
|
|
);
|
|
expect(xtseSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe(
|
|
utcMs(2024, 11, 29, 21, 0, 0)
|
|
);
|
|
|
|
const overridePanel = buildEventStudyInput({
|
|
bars: fixture.bars,
|
|
events: fixture.events,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: overrideCal,
|
|
});
|
|
|
|
// Listing 201 (XTSE) stays on 2024-11-29 (index 2); listing 101 (XNYS) shifts to 2024-12-02 (index 3).
|
|
expect(overridePanel.input.events).toEqual([
|
|
{ entityId: 201, dayIndex: 2 },
|
|
{ entityId: 101, dayIndex: 3 },
|
|
]);
|
|
});
|
|
|
|
test('is deterministic under permuted listingIds and reversed listing rows without mutating caller inputs', async () => {
|
|
const fixture = createMultiCalendarFixture();
|
|
|
|
const runWithOrder = async (
|
|
listingIds: number[],
|
|
rows: readonly ListingCalendarRow[],
|
|
asyncSessionPort: boolean
|
|
) => {
|
|
const snapshot = [...listingIds];
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => rows,
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: (q) => {
|
|
const dates = q.calendarCode === 'XNYS' ? fixture.xnysDates : fixture.xtseDates;
|
|
return asyncSessionPort ? Promise.resolve(dates) : dates;
|
|
},
|
|
},
|
|
earlyCloses: { XNYS: { '2024-11-29': 780 } },
|
|
});
|
|
|
|
const resolved = await resolver({
|
|
listingIds,
|
|
fromDate: fixture.fromDate,
|
|
toDate: fixture.toDate,
|
|
});
|
|
expect(listingIds).toEqual(snapshot);
|
|
return resolved;
|
|
};
|
|
|
|
const forward = await runWithOrder(
|
|
[101, 102, 201],
|
|
[
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
{ listingId: 102, calendarCode: 'XNYS' },
|
|
{ listingId: 201, calendarCode: 'XTSE' },
|
|
],
|
|
false
|
|
);
|
|
|
|
// Permuted listingIds (including duplicate) + reversed listing rows (including identical duplicate)
|
|
const permuted = await runWithOrder(
|
|
[201, 102, 101, 102],
|
|
[
|
|
{ listingId: 201, calendarCode: 'XTSE' },
|
|
{ listingId: 102, calendarCode: 'XNYS' },
|
|
{ listingId: 102, calendarCode: 'XNYS' },
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
],
|
|
true
|
|
);
|
|
|
|
expect(permuted).toEqual(forward);
|
|
expect(Object.keys(permuted.calendars)).toEqual(Object.keys(forward.calendars));
|
|
expect(Object.keys(permuted.listingCalendarId)).toEqual(
|
|
Object.keys(forward.listingCalendarId)
|
|
);
|
|
|
|
// Replay both resolved calendars through buildEventStudyInput on the same pinned bars,
|
|
// events, and Vault cutoff, and assert identical anchors, return series, and diagnostics.
|
|
const forwardPanel = buildEventStudyInput({
|
|
bars: fixture.bars,
|
|
events: fixture.events,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: forward,
|
|
});
|
|
const permutedPanel = buildEventStudyInput({
|
|
bars: fixture.bars,
|
|
events: fixture.events,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: permuted,
|
|
});
|
|
|
|
expect(permutedPanel.input.sessionDates).toEqual(forwardPanel.input.sessionDates);
|
|
expect(permutedPanel.input.events).toEqual(forwardPanel.input.events);
|
|
expect(permutedPanel.input.events).toEqual([
|
|
{ entityId: 201, dayIndex: 2 },
|
|
{ entityId: 101, dayIndex: 3 },
|
|
]);
|
|
expect(Array.from(permutedPanel.input.entityReturns.keys())).toEqual(
|
|
Array.from(forwardPanel.input.entityReturns.keys())
|
|
);
|
|
for (const [entityId, forwardSeries] of forwardPanel.input.entityReturns.entries()) {
|
|
const permutedSeries = permutedPanel.input.entityReturns.get(entityId);
|
|
expect(permutedSeries).toBeDefined();
|
|
expect(Array.from(permutedSeries as Float64Array)).toEqual(Array.from(forwardSeries));
|
|
}
|
|
expect(Array.from(permutedPanel.input.benchmarkReturns)).toEqual(
|
|
Array.from(forwardPanel.input.benchmarkReturns)
|
|
);
|
|
expect(permutedPanel.diagnostics).toEqual(forwardPanel.diagnostics);
|
|
expect(permutedPanel.diagnostics.vaultExcludedDates).toBe(1);
|
|
});
|
|
});
|
|
|
|
describe('createExchangeCalendarResolver — fail-closed validation & edge cases', () => {
|
|
test('empty listingIds returns empty records with zero port calls', async () => {
|
|
let listingCalls = 0;
|
|
let sessionCalls = 0;
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => {
|
|
listingCalls += 1;
|
|
return [];
|
|
},
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: () => {
|
|
sessionCalls += 1;
|
|
return [];
|
|
},
|
|
},
|
|
});
|
|
|
|
const result = await resolver({
|
|
listingIds: [],
|
|
fromDate: '2024-01-01',
|
|
toDate: '2024-12-31',
|
|
});
|
|
|
|
expect(result).toEqual({ calendars: {}, listingCalendarId: {} });
|
|
expect(listingCalls).toBe(0);
|
|
expect(sessionCalls).toBe(0);
|
|
});
|
|
|
|
test('fails closed with zero sessionDates calls on missing, unrequested, or conflicting listing rows', async () => {
|
|
const cases: readonly {
|
|
readonly name: string;
|
|
readonly rows: readonly ListingCalendarRow[];
|
|
readonly expectedCode: string;
|
|
}[] = [
|
|
{
|
|
name: 'missing requested listing',
|
|
rows: [{ listingId: 101, calendarCode: 'XNYS' }],
|
|
expectedCode: 'MISSING_LISTING_CALENDAR',
|
|
},
|
|
{
|
|
name: 'unrequested listing returned',
|
|
rows: [
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
{ listingId: 102, calendarCode: 'XNYS' },
|
|
{ listingId: 999, calendarCode: 'XTSE' },
|
|
],
|
|
expectedCode: 'UNEXPECTED_LISTING_CALENDAR',
|
|
},
|
|
{
|
|
name: 'conflicting duplicate listing rows',
|
|
rows: [
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
{ listingId: 101, calendarCode: 'XTSE' },
|
|
{ listingId: 102, calendarCode: 'XNYS' },
|
|
],
|
|
expectedCode: 'CONFLICTING_LISTING_CALENDAR',
|
|
},
|
|
];
|
|
|
|
for (const tc of cases) {
|
|
let sessionCalls = 0;
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: { getListingCalendars: () => tc.rows },
|
|
sessionDates: {
|
|
listSessionDates: () => {
|
|
sessionCalls += 1;
|
|
return ['2024-12-02'];
|
|
},
|
|
},
|
|
});
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await resolver({
|
|
listingIds: [101, 102],
|
|
fromDate: '2024-12-02',
|
|
toDate: '2024-12-02',
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError);
|
|
expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe(tc.expectedCode);
|
|
expect(sessionCalls, tc.name).toBe(0);
|
|
}
|
|
});
|
|
|
|
test('fails closed with no partial result on unsorted, duplicate, malformed, or out-of-range session dates', async () => {
|
|
const badSessionLists: readonly { readonly name: string; readonly dates: unknown }[] = [
|
|
{ name: 'non-array response', dates: '2024-12-02' },
|
|
{ name: 'unsorted dates', dates: ['2024-12-03', '2024-12-02'] },
|
|
{ name: 'duplicate dates', dates: ['2024-12-02', '2024-12-02'] },
|
|
{ name: 'malformed date string', dates: ['2024-02-30'] },
|
|
{ name: 'non-string date', dates: [20241202] },
|
|
{ name: 'date before fromDate', dates: ['2024-12-01', '2024-12-02'] },
|
|
{ name: 'date after toDate', dates: ['2024-12-02', '2024-12-04'] },
|
|
];
|
|
|
|
for (const tc of badSessionLists) {
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => [
|
|
{ listingId: 101, calendarCode: 'XNYS' },
|
|
{ listingId: 201, calendarCode: 'XTSE' },
|
|
],
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: (q) =>
|
|
q.calendarCode === 'XNYS' ? ['2024-12-02', '2024-12-03'] : (tc.dates as never),
|
|
},
|
|
});
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await resolver({
|
|
listingIds: [101, 201],
|
|
fromDate: '2024-12-02',
|
|
toDate: '2024-12-03',
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError);
|
|
expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe('INVALID_SESSION_DATES');
|
|
}
|
|
});
|
|
|
|
test('rejects invalid earlyCloses minutes, dates, and shapes at construction with zero port calls', () => {
|
|
let listingCalls = 0;
|
|
let sessionCalls = 0;
|
|
const listingCalendars: ListingCalendarPort = {
|
|
getListingCalendars: () => {
|
|
listingCalls += 1;
|
|
return [];
|
|
},
|
|
};
|
|
const sessionDates: SessionDatesPort = {
|
|
listSessionDates: () => {
|
|
sessionCalls += 1;
|
|
return [];
|
|
},
|
|
};
|
|
|
|
const invalidCases: readonly { readonly earlyCloses: unknown; readonly expectedCode: string }[] =
|
|
[
|
|
{ earlyCloses: null, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: [], expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: 'XNYS', expectedCode: 'INVALID_OPTION' },
|
|
{
|
|
earlyCloses: new Map([['XNYS', { '2024-11-29': 780 }]]),
|
|
expectedCode: 'INVALID_OPTION',
|
|
},
|
|
{
|
|
earlyCloses: { XNYS: new Map([['2024-11-29', 780]]) },
|
|
expectedCode: 'INVALID_OPTION',
|
|
},
|
|
{ earlyCloses: new Set(['XNYS']), expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: new Date('2024-11-29T00:00:00Z') }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { '': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { ' XNYS ': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: null }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: [] }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '2024-02-30': 780 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { 'not-a-date': 780 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '1975-12-31': 780 } }, expectedCode: 'UNSUPPORTED_DATE' },
|
|
{ earlyCloses: { XNYS: { '2031-01-01': 780 } }, expectedCode: 'UNSUPPORTED_DATE' },
|
|
{ earlyCloses: { XNYS: { '2024-11-29': 0 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '2024-11-29': -1 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '2024-11-29': 961 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '2024-11-29': 780.5 } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '2024-11-29': Number.NaN } }, expectedCode: 'INVALID_OPTION' },
|
|
{ earlyCloses: { XNYS: { '2024-11-29': '780' } }, expectedCode: 'INVALID_OPTION' },
|
|
];
|
|
|
|
for (const tc of invalidCases) {
|
|
let caught: unknown;
|
|
try {
|
|
createExchangeCalendarResolver({
|
|
listingCalendars,
|
|
sessionDates,
|
|
earlyCloses: tc.earlyCloses as never,
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect(caught).toBeInstanceOf(ExchangeCalendarResolverError);
|
|
expect((caught as ExchangeCalendarResolverError).code).toBe(tc.expectedCode);
|
|
}
|
|
|
|
expect(listingCalls).toBe(0);
|
|
expect(sessionCalls).toBe(0);
|
|
});
|
|
|
|
test('accepts null-prototype records at both levels of earlyCloses', async () => {
|
|
const xnysOverrides = Object.create(null) as Record<string, number>;
|
|
xnysOverrides['2024-11-29'] = 780;
|
|
const earlyCloses = Object.create(null) as Record<string, Record<string, number>>;
|
|
earlyCloses.XNYS = xnysOverrides;
|
|
|
|
const resolver = createExchangeCalendarResolver({
|
|
listingCalendars: {
|
|
getListingCalendars: () => [{ listingId: 101, calendarCode: 'XNYS' }],
|
|
},
|
|
sessionDates: {
|
|
listSessionDates: () => ['2024-11-29', '2024-12-02'],
|
|
},
|
|
earlyCloses,
|
|
});
|
|
|
|
const result = await resolver({
|
|
listingIds: [101],
|
|
fromDate: '2024-11-29',
|
|
toDate: '2024-12-02',
|
|
});
|
|
|
|
expect(result.calendars).toEqual({
|
|
XNYS: [
|
|
{ date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) },
|
|
{ date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) },
|
|
],
|
|
});
|
|
});
|
|
});
|