T-181: tests
This commit is contained in:
parent
fbc0aa0725
commit
b022112068
1 changed files with 249 additions and 0 deletions
249
libs/research/test/mcp-bar-session-dates-qa.test.ts
Normal file
249
libs/research/test/mcp-bar-session-dates-qa.test.ts
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { VaultHoldoutFenceError } from '../src/market-data-store';
|
||||
import {
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
createDuckDbMarketDataStore,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import {
|
||||
type ListingCalendarPort,
|
||||
createBarSessionDatesPort,
|
||||
createExchangeCalendarResolver,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
/**
|
||||
* QA: the bar-derived SessionDatesPort composed with the real DuckDB store
|
||||
* planner (`planBars1dQuery` + `mapBarRows`) over a recording fake executor that
|
||||
* emulates the raw 1d SQL predicate (`listing_id IN (...) AND ts >= ? AND ts <= ?
|
||||
* AND known_at <= ?` ordered by `listing_id, ts`) on a pinned in-memory dataset.
|
||||
*/
|
||||
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z
|
||||
const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z';
|
||||
|
||||
interface FixtureBar {
|
||||
readonly listingId: number;
|
||||
readonly ts: number;
|
||||
readonly knownAt: number;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** 16:00 ET daily stamp (curate_bars.rs convention): 20:00Z in EDT. Known shortly after close. */
|
||||
function edtBar(listingId: number, date: string, knownAt?: number): FixtureBar {
|
||||
const ts = utcMs(date, 20);
|
||||
return { listingId, ts, knownAt: knownAt ?? ts + 60_000 };
|
||||
}
|
||||
|
||||
/** Parses `YYYY-MM-DDTHH:MM:SS(.ffffff)?Z` to fractional epoch ms (µs precision kept). */
|
||||
function isoToMs(iso: string): number {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso);
|
||||
if (m === null) {
|
||||
throw new Error(`Unexpected ISO bound: ${iso}`);
|
||||
}
|
||||
const frac = Number(`0.${(m[7] ?? '0').padEnd(6, '0').slice(0, 6)}`);
|
||||
return (
|
||||
Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])) +
|
||||
frac * 1000
|
||||
);
|
||||
}
|
||||
|
||||
function createFixtureExecutor(dataset: readonly FixtureBar[]): {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly queries: Array<{ sql: string; params: readonly DuckDbParam[] }>;
|
||||
} {
|
||||
const queries: Array<{ sql: string; params: readonly DuckDbParam[] }> = [];
|
||||
const executor: DuckDbExecutor = {
|
||||
async run(): Promise<void> {},
|
||||
async query(sql: string, params: readonly DuckDbParam[]) {
|
||||
queries.push({ sql, params: [...params] });
|
||||
const listingIds = new Set(params.slice(0, -3) as number[]);
|
||||
const [fromIso, toIso, asOfIso] = params.slice(-3) as [string, string, string];
|
||||
const fromMs = isoToMs(fromIso);
|
||||
const toMs = isoToMs(toIso);
|
||||
const asOfMs = isoToMs(asOfIso);
|
||||
return dataset
|
||||
.filter(
|
||||
(b) =>
|
||||
listingIds.has(b.listingId) && b.ts >= fromMs && b.ts <= toMs && b.knownAt <= asOfMs
|
||||
)
|
||||
.sort((a, b) => a.listingId - b.listingId || a.ts - b.ts)
|
||||
.map((b) => ({
|
||||
listing_id: b.listingId,
|
||||
ts: b.ts,
|
||||
open: 10,
|
||||
high: 11,
|
||||
low: 9,
|
||||
close: 10.5,
|
||||
volume: 1000,
|
||||
vwap: null,
|
||||
known_at: b.knownAt,
|
||||
}));
|
||||
},
|
||||
};
|
||||
return { executor, queries };
|
||||
}
|
||||
|
||||
const DATASET: readonly FixtureBar[] = [
|
||||
// XNYS reference listings 11 and 12 (overlapping + one-sided dates).
|
||||
edtBar(11, '2026-05-21'),
|
||||
edtBar(12, '2026-05-22'),
|
||||
edtBar(11, '2026-05-26'),
|
||||
edtBar(12, '2026-05-26'),
|
||||
edtBar(12, '2026-05-27'),
|
||||
// Held-out Vault sessions at and after the cutoff date.
|
||||
edtBar(11, '2026-05-28'),
|
||||
edtBar(12, '2026-05-29'),
|
||||
edtBar(11, '2026-06-01'),
|
||||
// XTSE reference listing 21.
|
||||
edtBar(21, '2026-05-25'), // Victoria Day: XTSE closed in reality, but present here to prove per-calendar isolation.
|
||||
edtBar(21, '2026-05-26'),
|
||||
// Pre-cutoff session whose bar only became known after the cutoff: must stay hidden.
|
||||
edtBar(21, '2026-05-27', CUTOFF_MS + 3_600_000),
|
||||
edtBar(21, '2026-05-28'),
|
||||
];
|
||||
|
||||
function makeStore(barBatchSize?: number) {
|
||||
const fake = createFixtureExecutor(DATASET);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: {},
|
||||
...(barBatchSize !== undefined ? { barBatchSize } : {}),
|
||||
});
|
||||
return { store, queries: fake.queries };
|
||||
}
|
||||
|
||||
describe('bar-session-dates QA — DuckDB store planner at the Vault cutoff', () => {
|
||||
test('window straddling the cutoff returns only pre-cutoff sessions with a raw bars_1d plan clamped to cutoff - 1µs', async () => {
|
||||
const { store, queries } = makeStore();
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [12, 11], XTSE: [21] },
|
||||
});
|
||||
|
||||
const dates = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2026-05-22',
|
||||
toDate: '2026-06-02',
|
||||
});
|
||||
|
||||
expect(dates).toEqual(['2026-05-22', '2026-05-26', '2026-05-27']);
|
||||
expect(queries).toHaveLength(1);
|
||||
const q = queries[0]!;
|
||||
expect(q.sql).toContain(`read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet'`);
|
||||
expect(q.sql).not.toContain('adj_factors');
|
||||
expect(q.params).toEqual([
|
||||
12,
|
||||
11,
|
||||
'2026-05-22T00:00:00.000Z',
|
||||
MAX_ALLOWED_ISO_MICROS,
|
||||
MAX_ALLOWED_ISO_MICROS,
|
||||
]);
|
||||
});
|
||||
|
||||
test('pre-cutoff bar first known after the cutoff is excluded via the default known_at fence', async () => {
|
||||
const { store } = makeStore();
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12], XTSE: [21] },
|
||||
});
|
||||
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XTSE',
|
||||
fromDate: '2026-05-25',
|
||||
toDate: '2026-05-31',
|
||||
})
|
||||
).toEqual(['2026-05-25', '2026-05-26']);
|
||||
});
|
||||
|
||||
test('fromDate on or after the cutoff date rejects with VaultHoldoutFenceError before any executor query', async () => {
|
||||
const { store, queries } = makeStore();
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12] },
|
||||
});
|
||||
|
||||
for (const fromDate of ['2026-05-28', '2026-06-01']) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({ calendarCode: 'XNYS', fromDate, toDate: '2026-06-02' });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(VaultHoldoutFenceError);
|
||||
}
|
||||
expect(queries).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('last pre-cutoff day as a single-day window is included, and output is identical across barBatchSize settings', async () => {
|
||||
const results: string[][] = [];
|
||||
for (const batchSize of [undefined, 1, 2]) {
|
||||
const { store } = makeStore(batchSize);
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12] },
|
||||
});
|
||||
results.push([
|
||||
...(await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2026-05-21',
|
||||
toDate: '2026-05-27',
|
||||
})),
|
||||
]);
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2026-05-27',
|
||||
toDate: '2026-05-27',
|
||||
})
|
||||
).toEqual(['2026-05-27']);
|
||||
}
|
||||
const expected = ['2026-05-21', '2026-05-22', '2026-05-26', '2026-05-27'];
|
||||
expect(results).toEqual([expected, expected, expected]);
|
||||
});
|
||||
|
||||
test('resolver composed over the DuckDB-backed port yields no post-cutoff session closes', async () => {
|
||||
const { store, queries } = makeStore();
|
||||
const sessionDates = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12], XTSE: [21] },
|
||||
});
|
||||
const listingCalendars: ListingCalendarPort = {
|
||||
getListingCalendars(listingIds) {
|
||||
return listingIds.map((listingId) => ({
|
||||
listingId,
|
||||
calendarCode: listingId === 901 ? 'XNYS' : 'XTSE',
|
||||
}));
|
||||
},
|
||||
};
|
||||
const resolve = createExchangeCalendarResolver({ listingCalendars, sessionDates });
|
||||
|
||||
const resolved = await resolve({
|
||||
listingIds: [901, 902],
|
||||
fromDate: '2026-05-26',
|
||||
toDate: '2026-06-02',
|
||||
});
|
||||
|
||||
expect(resolved.listingCalendarId).toEqual({ 901: 'XNYS', 902: 'XTSE' });
|
||||
expect(resolved.calendars).toEqual({
|
||||
XNYS: [
|
||||
{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) },
|
||||
{ date: '2026-05-27', closeTs: utcMs('2026-05-27', 20) },
|
||||
],
|
||||
XTSE: [{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }],
|
||||
});
|
||||
for (const closes of Object.values(resolved.calendars)) {
|
||||
for (const c of closes) {
|
||||
expect(c.closeTs).toBeLessThan(CUTOFF_MS);
|
||||
}
|
||||
}
|
||||
expect(queries).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue