Compare commits
4 commits
5d97786254
...
abe114f415
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
abe114f415 | ||
|
|
ee983cb349 | ||
|
|
5e626b083b | ||
|
|
112b830985 |
10 changed files with 4107 additions and 161 deletions
|
|
@ -159,3 +159,40 @@ Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3
|
|||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-signal-panel.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 817.24 ms`, `rowsPerSec = 18,501,301 rows/s` (`5,014` emitted panel dates, `15,042,000` emitted observations, `25` Vault-excluded dates, pinned checksum `f0f28bdf`)
|
||||
|
||||
## Event Study Panel Builder
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (`libs/research/src/event-panel.ts`). The module is pure, synchronous, dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers).
|
||||
|
||||
### API
|
||||
|
||||
- **`eventsTableToEventRows(table, filter?)`** — Maps a `MarketDataStore.events` `Table` into point-in-time `EventObservation[]` (`{ listingId, knownAt, kind, subtype }`), validating every row upfront (before applying optional exact-match `filter.kinds` / `filter.subtypes` allow-lists), normalizing `-0` to `0`, and rejecting missing columns, empty filter arrays, or malformed rows with `EventPanelError`.
|
||||
- **`buildEventStudyInput({ bars, events, vaultCutoffDate, exchangeCalendars, benchmark? })`** — Transforms daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) and `EventObservation[]` rows into a Vault-safe `EventStudyInput` (`{ sessionDates, entityReturns, benchmarkReturns?, events }`) plus `EventPanelDiagnostics` ready for `runEventStudy` / `eventStudy`. Output is deterministic under any input permutation (entities inserted in ascending `listingId` order; events sorted by `(dayIndex ASC, entityId ASC)`) without mutating caller inputs.
|
||||
- `exchangeCalendars: { calendars, listingCalendarId }` (**required**): caller-supplied exchange close calendars (`{ date, closeTs }[]` per calendar ID, plus `listingId -> calendarId` mapping). Every pre-Vault listing in `bars` must be mapped to a calendar that covers all of its pre-Vault bar dates (coverage gaps or missing mappings throw `EventPanelError('invalid_option')`). Each listing's events are anchored against its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (`16:00 ET`), and the eligible session date is then mapped onto the shared `sessionDates` index.
|
||||
- `benchmark?: 'equal_weight' | 'none'` (default `'none'` when omitted/`undefined`; `null` or any other value throws `EventPanelError('invalid_option')`): `'none'` omits `benchmarkReturns`; `'equal_weight'` sets `benchmarkReturns[d]` to the mean of finite `entityReturns` on session `d` (`NaN` when none).
|
||||
|
||||
### UTC Session Calendar, PIT Anchoring, `NaN` Returns & Vault Rules
|
||||
|
||||
- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`.
|
||||
- **Consecutive-session returns & `NaN` contract (`eventStudy`):** For each listing, `entityReturns` is a `Float64Array` aligned to `sessionDates`. Simple close-to-close return `close[d] / close[d - 1] - 1` is computed strictly when the listing has bars on consecutive exchange-calendar sessions (`currCalIdx === prevCalIdx + 1`) and both closes are finite and `> 0` with a finite ratio. Session `0`, missing-bar sessions (including an open exchange session missing for all listings), the first resumption session after a gap, and non-positive/non-finite/overflowing transitions (counted in `diagnostics.nonPositiveCloseReturns`) are written as `NaN` (never `±Infinity`), matching `eventStudy`'s contract in `libs/calculations/src/analytics/event-study.ts` (which rejects `±Infinity` with `NON_FINITE_RETURN` and cleanly drops events with any `NaN` in `[-preDays, +postDays]`).
|
||||
- **Duplicate-bar policy:** Exact pre-cutoff duplicate bars (`ts` and `close` identical, including `NaN === NaN`) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `EventPanelError('duplicate_bar')`.
|
||||
- **Strict PIT event anchoring & drop precedence:** Each event is classified in strict order: (1) `knownAt >= vaultCutoffDate (00:00:00.000Z)` → `diagnostics.vaultExcludedEvents`; (2) listing has no pre-Vault bars → `diagnostics.droppedUnknownListing`; (3) `knownAt` is after the listing's last pre-Vault exchange close (or its eligible calendar date exceeds the last pre-Vault bar date) → `diagnostics.droppedAfterLastSession`; (4) eligible pre-Vault exchange session dates absent from `sessionDates` → `diagnostics.droppedMissingCalendarSession`; (5) lower-bound binary search over the listing's exchange close timestamps, matching `eventDayIndex` semantics so after-close and post-half-day-close filings always anchor to the next trading session. Exact duplicate `(listingId, dayIndex)` events collapse to one (`diagnostics.duplicateEvents`), preserving `events.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + droppedMissingCalendarSession + duplicateEvents`.
|
||||
- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate` (post-cutoff dates are counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
|
||||
|
||||
### `EventPanelError` Codes
|
||||
|
||||
| Code | Meaning |
|
||||
| --- | --- |
|
||||
| `'invalid_input'` | Non-object input envelope, non-array `bars`/`events`, malformed `Table`, or missing required columns (`listing_id`, `known_at`, `kind`, `subtype`) |
|
||||
| `'invalid_date'` | `vaultCutoffDate` or an `exchangeCalendars` session `date` is not a valid strict calendar `YYYY-MM-DD` date |
|
||||
| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, or non-number pre-cutoff `close` |
|
||||
| `'invalid_event'` | Malformed event or table row, invalid `listingId`/`knownAt`, `kind` outside `EVENT_KINDS`, or non-string/non-null `subtype` |
|
||||
| `'invalid_option'` | Invalid `benchmark` mode, missing/malformed/incomplete `exchangeCalendars` (including pre-Vault bar coverage gaps), or invalid/empty `eventsTableToEventRows` filter (`kinds`/`subtypes`) |
|
||||
| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` |
|
||||
|
||||
### Local In-Memory Benchmark (`buildEventStudyInput`)
|
||||
|
||||
Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `240,000` after-close `17:00 ET` filing events at stride `63`, `vaultCutoffDate = '2025-03-31'`, `benchmark: 'equal_weight'`, `XNYS`/`XTSE` exchange calendars):
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
".": "./src/index.ts",
|
||||
"./dataset-contracts": "./src/dataset-contracts.ts",
|
||||
"./datasets": "./src/datasets.ts",
|
||||
"./event-panel": "./src/event-panel.ts",
|
||||
"./market-data-store": "./src/market-data-store.ts",
|
||||
"./market-data-store-duckdb": "./src/market-data-store-duckdb.ts",
|
||||
"./results": "./src/results.ts",
|
||||
|
|
|
|||
230
libs/research/scripts/benchmark-event-panel.ts
Normal file
230
libs/research/scripts/benchmark-event-panel.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import {
|
||||
type EventObservation,
|
||||
type EventStudyExchangeCalendars,
|
||||
buildEventStudyInput,
|
||||
} from '../src/event-panel';
|
||||
import type { BarRecord } from '../src/market-data-store';
|
||||
|
||||
const SEED = 20261129;
|
||||
const SESSIONS = 5_040;
|
||||
const LISTINGS = 3_000;
|
||||
const EVENT_STRIDE_SESSIONS = 63; // 5040 / 63 = 80 filings/listing -> 240,000 total events
|
||||
const PRE_CUTOFF_SESSIONS = 5_020;
|
||||
|
||||
function createMulberry32(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 isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function generateBusinessCalendar(count: number, startYear: number): {
|
||||
dates: string[];
|
||||
closeTs: Float64Array;
|
||||
afterCloseTs: Float64Array;
|
||||
} {
|
||||
const dates: string[] = new Array<string>(count);
|
||||
const closeTs = new Float64Array(count);
|
||||
const afterCloseTs = new Float64Array(count);
|
||||
let year = startYear;
|
||||
let month = 1;
|
||||
let day = 1;
|
||||
// 2006-01-01 was a Sunday (dow = 0)
|
||||
let dow = 0;
|
||||
let produced = 0;
|
||||
|
||||
while (produced < count) {
|
||||
if (dow !== 0 && dow !== 6) {
|
||||
const yyyy = String(year).padStart(4, '0');
|
||||
const mm = String(month).padStart(2, '0');
|
||||
const dd = String(day).padStart(2, '0');
|
||||
dates[produced] = `${yyyy}-${mm}-${dd}`;
|
||||
closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET
|
||||
afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET
|
||||
produced += 1;
|
||||
}
|
||||
|
||||
dow = (dow + 1) % 7;
|
||||
day += 1;
|
||||
const baseDays = DAYS_IN_MONTH[month] ?? 31;
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
|
||||
if (day > maxDay) {
|
||||
day = 1;
|
||||
month += 1;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { dates, closeTs, afterCloseTs };
|
||||
}
|
||||
|
||||
function fnv1aByte(hash: number, byte: number): number {
|
||||
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
|
||||
function fnv1aUint32(hash: number, value: number): number {
|
||||
const v = value >>> 0;
|
||||
let h = fnv1aByte(hash, v & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 8) & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 16) & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 24) & 0xff);
|
||||
return h;
|
||||
}
|
||||
|
||||
function fnv1aBytes(hash: number, bytes: Uint8Array): number {
|
||||
let h = hash >>> 0;
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
const rng = createMulberry32(SEED);
|
||||
const calendar = generateBusinessCalendar(SESSIONS, 2006);
|
||||
const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string;
|
||||
|
||||
const totalBars = SESSIONS * LISTINGS;
|
||||
const bars: BarRecord[] = new Array<BarRecord>(totalBars);
|
||||
const eventsPerListing = Math.ceil(SESSIONS / EVENT_STRIDE_SESSIONS);
|
||||
const totalEvents = LISTINGS * eventsPerListing;
|
||||
const events: EventObservation[] = new Array<EventObservation>(totalEvents);
|
||||
|
||||
let barIdx = 0;
|
||||
let evIdx = 0;
|
||||
|
||||
for (let l = 0; l < LISTINGS; l += 1) {
|
||||
const listingId = l + 1;
|
||||
const subtype = l % 2 === 0 ? '10-q' : 'interim_financial_statements';
|
||||
let price = 10 + (l % 200) * 0.5;
|
||||
for (let t = 0; t < SESSIONS; t += 1) {
|
||||
const ts = calendar.closeTs[t] as number;
|
||||
price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02));
|
||||
bars[barIdx++] = {
|
||||
listingId,
|
||||
ts,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 10_000,
|
||||
vwap: price,
|
||||
knownAt: ts,
|
||||
};
|
||||
if (t % EVENT_STRIDE_SESSIONS === 0) {
|
||||
events[evIdx++] = {
|
||||
listingId,
|
||||
knownAt: calendar.afterCloseTs[t] as number,
|
||||
kind: 'filing',
|
||||
subtype,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sessionCloses = calendar.dates.map((date, idx) => ({
|
||||
date,
|
||||
closeTs: calendar.closeTs[idx] as number,
|
||||
}));
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (let l = 0; l < LISTINGS; l += 1) {
|
||||
listingCalendarId.set(l + 1, l % 2 === 0 ? 'XNYS' : 'XTSE');
|
||||
}
|
||||
const exchangeCalendars: EventStudyExchangeCalendars = {
|
||||
calendars: new Map([
|
||||
['XNYS', sessionCloses],
|
||||
['XTSE', sessionCloses],
|
||||
]),
|
||||
listingCalendarId,
|
||||
};
|
||||
|
||||
// Timed section: pure buildEventStudyInput execution (no fixture generation or checksum).
|
||||
const started = performance.now();
|
||||
const result = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars,
|
||||
});
|
||||
const elapsedMs = performance.now() - started;
|
||||
|
||||
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, returns, and events.
|
||||
let checksum = 0x811c9dc5;
|
||||
checksum = fnv1aUint32(checksum, result.input.sessionDates.length);
|
||||
checksum = fnv1aUint32(checksum, result.input.entityReturns.size);
|
||||
checksum = fnv1aUint32(checksum, result.input.events.length);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedEvents);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedUnknownListing);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedAfterLastSession);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingCalendarSession);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateEvents);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.nonPositiveCloseReturns);
|
||||
|
||||
if (result.input.benchmarkReturns !== undefined) {
|
||||
const bench = result.input.benchmarkReturns as Float64Array;
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(bench.buffer, bench.byteOffset, bench.byteLength));
|
||||
}
|
||||
|
||||
for (const [entityId, series] of result.input.entityReturns) {
|
||||
checksum = fnv1aUint32(checksum, Number(entityId));
|
||||
const arr = series as Float64Array;
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength));
|
||||
}
|
||||
|
||||
for (let i = 0; i < result.input.events.length; i += 1) {
|
||||
const ev = result.input.events[i];
|
||||
if (ev === undefined) {
|
||||
continue;
|
||||
}
|
||||
checksum = fnv1aUint32(checksum, ev.dayIndex);
|
||||
checksum = fnv1aUint32(checksum, Number(ev.entityId));
|
||||
}
|
||||
|
||||
const checksumHex = checksum.toString(16).padStart(8, '0');
|
||||
|
||||
const EXPECTED_CHECKSUM = '01b356d3';
|
||||
if (checksumHex !== EXPECTED_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
|
||||
);
|
||||
}
|
||||
|
||||
const elapsedSec = elapsedMs / 1000;
|
||||
const barsPerSec = Math.round(totalBars / elapsedSec);
|
||||
const eventsPerSec = Math.round(totalEvents / elapsedSec);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
seed: SEED,
|
||||
sessions: SESSIONS,
|
||||
listings: LISTINGS,
|
||||
vaultCutoffDate,
|
||||
inputBars: totalBars,
|
||||
inputEvents: totalEvents,
|
||||
sessionDates: result.input.sessionDates.length,
|
||||
anchoredEvents: result.input.events.length,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
barsPerSec,
|
||||
eventsPerSec,
|
||||
diagnostics: result.diagnostics,
|
||||
checksum: checksumHex,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
1069
libs/research/src/event-panel.ts
Normal file
1069
libs/research/src/event-panel.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +1,6 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
export * from './event-panel';
|
||||
export * from './market-data-store';
|
||||
export * from './market-data-store-duckdb';
|
||||
export * from './signal-panel';
|
||||
|
|
|
|||
172
libs/research/src/panel-shared.ts
Normal file
172
libs/research/src/panel-shared.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
/**
|
||||
* Internal, browser-safe helpers shared by `signal-panel.ts` and `event-panel.ts`.
|
||||
*
|
||||
* Pure, synchronous, and dependency-free: zero `node:*` imports and zero bare
|
||||
* `process` access. Not exported from the package root.
|
||||
*/
|
||||
|
||||
import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store';
|
||||
|
||||
export const INT32_MIN = -2_147_483_648;
|
||||
export const INT32_MAX = 2_147_483_647;
|
||||
export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
export const MS_PER_DAY = 86_400_000;
|
||||
export const MAX_DIRECT_DAY_SPAN = 200_000;
|
||||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function normalizeZero(value: number): number {
|
||||
return value === 0 ? 0 : value;
|
||||
}
|
||||
|
||||
export function isValidInt32(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= INT32_MIN &&
|
||||
value <= INT32_MAX
|
||||
);
|
||||
}
|
||||
|
||||
export function isValidEpochMs(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a strict `YYYY-MM-DD` calendar date string into an integer UTC day key
|
||||
* (`Math.floor(epochMs / MS_PER_DAY)`), delegating calendar validation to
|
||||
* `applyVaultFence`.
|
||||
*/
|
||||
export function parseCalendarDayKey(
|
||||
value: unknown,
|
||||
field: string,
|
||||
createError: (message: string, cause?: unknown) => Error
|
||||
): number {
|
||||
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
|
||||
throw createError(
|
||||
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
|
||||
);
|
||||
}
|
||||
try {
|
||||
const fenced = applyVaultFence(
|
||||
{ from: value, to: value, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
return fenced.fromMs / MS_PER_DAY;
|
||||
} catch (error) {
|
||||
if (error instanceof MarketDataStoreValidationError) {
|
||||
throw createError(`Invalid "${field}": ${error.message}`, error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDayKeyUtc(dayKey: number): string {
|
||||
const date = new Date(dayKey * MS_PER_DAY);
|
||||
const year = String(date.getUTCFullYear()).padStart(4, '0');
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getUTCDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
export interface BarSortScratch {
|
||||
sessionIdx: Int32Array;
|
||||
ts: Float64Array;
|
||||
close: Float64Array;
|
||||
}
|
||||
|
||||
function ensureBarScratch(scratch: BarSortScratch, len: number): void {
|
||||
if (scratch.sessionIdx.length < len) {
|
||||
scratch.sessionIdx = new Int32Array(len);
|
||||
scratch.ts = new Float64Array(len);
|
||||
scratch.close = new Float64Array(len);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered
|
||||
* by `sessionIdx ASC`. Skips sorting when already non-decreasing.
|
||||
*/
|
||||
export function sortBarSliceBySession(
|
||||
sessionIdx: Int32Array,
|
||||
ts: Float64Array,
|
||||
close: Float64Array,
|
||||
start: number,
|
||||
end: number,
|
||||
scratch: BarSortScratch
|
||||
): void {
|
||||
const len = end - start;
|
||||
if (len <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted = true;
|
||||
for (let i = start + 1; i < end; i += 1) {
|
||||
if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) {
|
||||
sorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sorted) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureBarScratch(scratch, len);
|
||||
const tmpSession = scratch.sessionIdx;
|
||||
const tmpTs = scratch.ts;
|
||||
const tmpClose = scratch.close;
|
||||
|
||||
for (let width = 1; width < len; width *= 2) {
|
||||
for (let left = 0; left < len; left += 2 * width) {
|
||||
const mid = Math.min(left + width, len);
|
||||
const right = Math.min(left + 2 * width, len);
|
||||
let i = left;
|
||||
let j = mid;
|
||||
let k = left;
|
||||
|
||||
while (i < mid && j < right) {
|
||||
const si = sessionIdx[start + i] as number;
|
||||
const sj = sessionIdx[start + j] as number;
|
||||
if (si <= sj) {
|
||||
tmpSession[k] = si;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
} else {
|
||||
tmpSession[k] = sj;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
while (i < mid) {
|
||||
tmpSession[k] = sessionIdx[start + i] as number;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
while (j < right) {
|
||||
tmpSession[k] = sessionIdx[start + j] as number;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < len; k += 1) {
|
||||
sessionIdx[start + k] = tmpSession[k] as number;
|
||||
ts[start + k] = tmpTs[k] as number;
|
||||
close[start + k] = tmpClose[k] as number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -21,20 +21,19 @@
|
|||
*/
|
||||
|
||||
import type { SignalCrossSection } from '@stock-bot/calculations';
|
||||
import type { BarBatch, BarRecord, Table } from './market-data-store';
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
applyVaultFence,
|
||||
} from './market-data-store';
|
||||
|
||||
const INT32_MIN = -2_147_483_648;
|
||||
const INT32_MAX = 2_147_483_647;
|
||||
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const MAX_DIRECT_DAY_SPAN = 200_000;
|
||||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
type BarSortScratch,
|
||||
MAX_DIRECT_DAY_SPAN,
|
||||
MS_PER_DAY,
|
||||
formatDayKeyUtc,
|
||||
isPlainRecord,
|
||||
isValidEpochMs,
|
||||
isValidInt32,
|
||||
normalizeZero,
|
||||
parseCalendarDayKey,
|
||||
sortBarSliceBySession,
|
||||
} from './panel-shared';
|
||||
|
||||
export type SignalPanelErrorCode =
|
||||
| 'invalid_input'
|
||||
|
|
@ -103,60 +102,10 @@ export interface BuildForwardReturnPanelResult {
|
|||
readonly diagnostics: SignalPanelDiagnostics;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function normalizeZero(value: number): number {
|
||||
return value === 0 ? 0 : value;
|
||||
}
|
||||
|
||||
function isValidInt32(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= INT32_MIN &&
|
||||
value <= INT32_MAX
|
||||
);
|
||||
}
|
||||
|
||||
function isValidEpochMs(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS
|
||||
);
|
||||
}
|
||||
|
||||
function parseStrictCalendarDayKey(value: unknown, field: string): number {
|
||||
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_date',
|
||||
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
|
||||
);
|
||||
}
|
||||
try {
|
||||
const fenced = applyVaultFence(
|
||||
{ from: value, to: value, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
return fenced.fromMs / MS_PER_DAY;
|
||||
} catch (error) {
|
||||
if (error instanceof MarketDataStoreValidationError) {
|
||||
throw new SignalPanelError('invalid_date', `Invalid "${field}": ${error.message}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDayKeyUtc(dayKey: number): string {
|
||||
const date = new Date(dayKey * MS_PER_DAY);
|
||||
const year = String(date.getUTCFullYear()).padStart(4, '0');
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getUTCDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
return parseCalendarDayKey(value, field, (message, cause) =>
|
||||
new SignalPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -291,25 +240,11 @@ export function shortsTableToSignalRows(
|
|||
return out;
|
||||
}
|
||||
|
||||
interface BarSortScratch {
|
||||
sessionIdx: Int32Array;
|
||||
ts: Float64Array;
|
||||
close: Float64Array;
|
||||
}
|
||||
|
||||
interface SignalSortScratch {
|
||||
knownAt: Float64Array;
|
||||
value: Float64Array;
|
||||
}
|
||||
|
||||
function ensureBarScratch(scratch: BarSortScratch, len: number): void {
|
||||
if (scratch.sessionIdx.length < len) {
|
||||
scratch.sessionIdx = new Int32Array(len);
|
||||
scratch.ts = new Float64Array(len);
|
||||
scratch.close = new Float64Array(len);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureSignalScratch(scratch: SignalSortScratch, len: number): void {
|
||||
if (scratch.knownAt.length < len) {
|
||||
scratch.knownAt = new Float64Array(len);
|
||||
|
|
@ -317,87 +252,6 @@ function ensureSignalScratch(scratch: SignalSortScratch, len: number): void {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered
|
||||
* by `sessionIdx ASC`. Skips sorting when already non-decreasing.
|
||||
*/
|
||||
function sortBarSliceBySession(
|
||||
sessionIdx: Int32Array,
|
||||
ts: Float64Array,
|
||||
close: Float64Array,
|
||||
start: number,
|
||||
end: number,
|
||||
scratch: BarSortScratch
|
||||
): void {
|
||||
const len = end - start;
|
||||
if (len <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted = true;
|
||||
for (let i = start + 1; i < end; i += 1) {
|
||||
if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) {
|
||||
sorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sorted) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureBarScratch(scratch, len);
|
||||
const tmpSession = scratch.sessionIdx;
|
||||
const tmpTs = scratch.ts;
|
||||
const tmpClose = scratch.close;
|
||||
|
||||
for (let width = 1; width < len; width *= 2) {
|
||||
for (let left = 0; left < len; left += 2 * width) {
|
||||
const mid = Math.min(left + width, len);
|
||||
const right = Math.min(left + 2 * width, len);
|
||||
let i = left;
|
||||
let j = mid;
|
||||
let k = left;
|
||||
|
||||
while (i < mid && j < right) {
|
||||
const si = sessionIdx[start + i] as number;
|
||||
const sj = sessionIdx[start + j] as number;
|
||||
if (si <= sj) {
|
||||
tmpSession[k] = si;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
} else {
|
||||
tmpSession[k] = sj;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
while (i < mid) {
|
||||
tmpSession[k] = sessionIdx[start + i] as number;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
while (j < right) {
|
||||
tmpSession[k] = sessionIdx[start + j] as number;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < len; k += 1) {
|
||||
sessionIdx[start + k] = tmpSession[k] as number;
|
||||
ts[start + k] = tmpTs[k] as number;
|
||||
close[start + k] = tmpClose[k] as number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's signal slice `[start, end)`
|
||||
* ordered by `(knownAt ASC, value ASC)` for deterministic tie-breaking.
|
||||
|
|
|
|||
729
libs/research/test/event-panel-e2e.test.ts
Normal file
729
libs/research/test/event-panel-e2e.test.ts
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
buildEventStudyInput,
|
||||
collectBars,
|
||||
createDuckDbMarketDataStore,
|
||||
eventsTableToEventRows,
|
||||
runEventStudy,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type EventStudyExchangeCalendars,
|
||||
type TableRow,
|
||||
type TrialLedgerExecutor,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const IMMUTABLE_ADJ_PATH = `${CURATED_ROOT}/adj_factors/snapshots/qmfilings_e2e_fenced.parquet`;
|
||||
const SEED = 20261129;
|
||||
|
||||
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 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 makeUtcMs(date: string, hourUtc: number): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
|
||||
}
|
||||
|
||||
interface StoredTrialRow {
|
||||
readonly trial_id: string;
|
||||
readonly created_at: Date;
|
||||
readonly principal_id: string;
|
||||
readonly campaign_id: string | null;
|
||||
readonly stage: string;
|
||||
readonly universe_market: string;
|
||||
readonly horizon_bucket: string;
|
||||
readonly hypothesis_id: string | null;
|
||||
readonly expression_hash: string;
|
||||
readonly sample_start: string;
|
||||
readonly sample_end: string;
|
||||
readonly n_obs: number;
|
||||
readonly sharpe_unann: number;
|
||||
readonly skewness: number;
|
||||
readonly kurtosis: number;
|
||||
readonly daily_series: readonly number[];
|
||||
}
|
||||
|
||||
function createInMemoryTrialExecutor(): {
|
||||
executor: TrialLedgerExecutor;
|
||||
rows: StoredTrialRow[];
|
||||
} {
|
||||
const rows: StoredTrialRow[] = [];
|
||||
let nextTrialId = 1;
|
||||
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
const p = params ?? [];
|
||||
const trialId = nextTrialId++;
|
||||
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
|
||||
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
||||
const stored: StoredTrialRow = {
|
||||
trial_id: String(trialId),
|
||||
created_at: createdAt,
|
||||
principal_id: p[0] as string,
|
||||
campaign_id: (p[1] as string | null) ?? null,
|
||||
stage: p[2] as string,
|
||||
universe_market: p[3] as string,
|
||||
horizon_bucket: p[4] as string,
|
||||
hypothesis_id: (p[5] as string | null) ?? null,
|
||||
expression_hash: p[6] as string,
|
||||
sample_start: p[7] as string,
|
||||
sample_end: p[8] as string,
|
||||
n_obs: p[9] as number,
|
||||
sharpe_unann: p[10] as number,
|
||||
skewness: p[11] as number,
|
||||
kurtosis: p[12] as number,
|
||||
daily_series: dailySeries,
|
||||
};
|
||||
rows.push(stored);
|
||||
return {
|
||||
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const targetId = String(params?.[0]);
|
||||
const matched = rows.filter(r => r.trial_id === targetId);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const market = params?.[0] as string;
|
||||
const bucket = params?.[1] as string;
|
||||
const matched = rows.filter(
|
||||
r => r.universe_market === market && r.horizon_bucket === bucket
|
||||
);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, rows };
|
||||
}
|
||||
|
||||
interface AdjFactorRow {
|
||||
readonly listing_id: number;
|
||||
readonly ex_date: string;
|
||||
readonly cum_split_factor: number;
|
||||
readonly cum_total_factor: number;
|
||||
readonly known_at: number;
|
||||
}
|
||||
|
||||
interface QmFilingsFixture {
|
||||
readonly listingIds: number[];
|
||||
readonly usListingIds: ReadonlySet<number>;
|
||||
readonly caListingIds: ReadonlySet<number>;
|
||||
readonly allDates: string[];
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly barRows: TableRow[];
|
||||
readonly adjFactorRows: AdjFactorRow[];
|
||||
readonly eventRows: TableRow[];
|
||||
readonly exchangeCalendars: EventStudyExchangeCalendars;
|
||||
readonly dividendCase: {
|
||||
readonly listingId: number;
|
||||
readonly exDate: string;
|
||||
readonly exDayIdx: number;
|
||||
readonly expectedTotalReturn: number;
|
||||
readonly rawDropReturn: number;
|
||||
};
|
||||
readonly halfDayCase: {
|
||||
readonly usListingId: number;
|
||||
readonly caListingId: number;
|
||||
readonly halfDayDate: string;
|
||||
readonly halfDayIdx: number;
|
||||
readonly nextSessionDate: string;
|
||||
readonly nextSessionIdx: number;
|
||||
readonly usHalfDayReturn: number;
|
||||
readonly usNextSessionReturn: number;
|
||||
};
|
||||
}
|
||||
|
||||
function makeFencedAdjKvRows(vaultCutoffTs: number, rowsWritten: number): TableRow[] {
|
||||
return [
|
||||
{ key: 'stock_bot.adj_factors.format_version', value: '1' },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' },
|
||||
{ key: 'stock_bot.adj_factors.as_of_micros', value: 'none' },
|
||||
{ key: 'stock_bot.adj_factors.vault_cutoff_micros', value: String(vaultCutoffTs * 1000) },
|
||||
{ key: 'stock_bot.adj_factors.rows_written', value: String(rowsWritten) },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x024ec73a1afe7e6b' },
|
||||
];
|
||||
}
|
||||
|
||||
function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
||||
const rand = createSeededRng(SEED);
|
||||
const listingCount = 24; // 12 US ('10-q') + 12 CA ('interim_financial_statements')
|
||||
const preCutoffSessions = 160; // spans late 2022 through spring 2023 (pre-2023 & post-2023)
|
||||
const postCutoffSessions = 10;
|
||||
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
|
||||
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
||||
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
||||
|
||||
const listingIds = Array.from({ length: listingCount }, (_, i) =>
|
||||
i < 12 ? 10_001 + i : 50_001 + (i - 12)
|
||||
);
|
||||
const usListingIds = new Set(listingIds.slice(0, 12));
|
||||
const caListingIds = new Set(listingIds.slice(12));
|
||||
const barRows: TableRow[] = [];
|
||||
const adjFactorRows: AdjFactorRow[] = [];
|
||||
const eventRows: TableRow[] = [];
|
||||
|
||||
// Black Friday 2022-11-25: NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at
|
||||
// 16:00 ET (21:00 UTC), even though curated bars_1d.ts stamps both at 16:00 ET (21:00 UTC).
|
||||
const halfDayDate = '2022-11-25';
|
||||
const halfDayIdx = allDates.indexOf(halfDayDate);
|
||||
if (halfDayIdx < 1 || halfDayIdx + 1 >= preCutoffSessions) {
|
||||
throw new Error(`Expected half-day ${halfDayDate} inside pre-cutoff range.`);
|
||||
}
|
||||
const nextSessionIdx = halfDayIdx + 1;
|
||||
const nextSessionDate = allDates[nextSessionIdx]!;
|
||||
const halfDayUsIdx = 0; // listingId 10_001 (XNYS)
|
||||
const halfDayCaIdx = 12; // listingId 50_001 (XTSE)
|
||||
const halfDayUsListingId = listingIds[halfDayUsIdx]!;
|
||||
const halfDayCaListingId = listingIds[halfDayCaIdx]!;
|
||||
let usHalfDayReturn = 0;
|
||||
let usNextSessionReturn = 0;
|
||||
|
||||
const nyseCalendar = allDates.map(date => ({
|
||||
date,
|
||||
closeTs: makeUtcMs(date, date === halfDayDate ? 18 : 21), // 13:00 ET on Black Friday, else 16:00 ET
|
||||
}));
|
||||
const tsxCalendar = allDates.map(date => ({
|
||||
date,
|
||||
closeTs: makeUtcMs(date, 21), // 16:00 ET on all sessions including Black Friday
|
||||
}));
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
listingCalendarId.set(listingIds[l]!, l < 12 ? 'XNYS' : 'XTSE');
|
||||
}
|
||||
const exchangeCalendars: EventStudyExchangeCalendars = {
|
||||
calendars: new Map([
|
||||
['XNYS', nyseCalendar],
|
||||
['XTSE', tsxCalendar],
|
||||
]),
|
||||
listingCalendarId,
|
||||
};
|
||||
|
||||
// Plant a 10% cash dividend inside a filing window for listing 0 (US, 10-q):
|
||||
// On t = 12, listing l = ((12/4)*2 + 0) % 24 = 6 files after close; choose listing 6
|
||||
// and ex-date t = 15 (day +2 inside its [0..+5] filing window).
|
||||
const divListingIdx = 6;
|
||||
const divListingId = listingIds[divListingIdx]!;
|
||||
const divExIdx = 15;
|
||||
const divExDate = allDates[divExIdx]!;
|
||||
const divYield = 0.1; // 10% cash dividend -> cum_total_factor = 1 / (1 - 0.1) = 10/9
|
||||
let divExpectedTotalReturn = 0;
|
||||
let divRawDropReturn = 0;
|
||||
|
||||
// Track active post-filing drift per listing: zero look-ahead because a filing stamped
|
||||
// after close on session `t` (`22:00 UTC` / `17:00 ET`) only boosts returns starting on
|
||||
// session `t + 1` (the event's anchored `dayIndex`) for 5 sessions.
|
||||
const remainingBoostSessions = new Int32Array(listingCount);
|
||||
const rawPrices = new Float64Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
rawPrices[l] = 15 + l * 1.25;
|
||||
}
|
||||
|
||||
for (let t = 0; t < allDates.length; t += 1) {
|
||||
const date = allDates[t]!;
|
||||
const closeTs = makeUtcMs(date, 21); // 16:00 ET
|
||||
const afterCloseTs = makeUtcMs(date, 22); // 17:00 ET
|
||||
const isPostCutoff = date >= vaultCutoffDate;
|
||||
|
||||
// Emit daily bars using ONLY boosts already active before today's close.
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const boost = remainingBoostSessions[l]! > 0 ? 0.008 : 0;
|
||||
if (remainingBoostSessions[l]! > 0) {
|
||||
remainingBoostSessions[l] = remainingBoostSessions[l]! - 1;
|
||||
}
|
||||
const dailyRet = boost + (rand() * 2 - 1) * 0.006;
|
||||
|
||||
if (l === divListingIdx && t === divExIdx) {
|
||||
const prevRaw = rawPrices[l]!;
|
||||
const exRawBase = prevRaw * (1 - divYield);
|
||||
const nextRaw = exRawBase * (1 + dailyRet);
|
||||
const cumTotalFactor = prevRaw / exRawBase; // 1 / (1 - divYield)
|
||||
adjFactorRows.push({
|
||||
listing_id: divListingId,
|
||||
ex_date: divExDate,
|
||||
cum_split_factor: 1.0,
|
||||
cum_total_factor: cumTotalFactor,
|
||||
known_at: makeUtcMs(allDates[divExIdx - 1]!, 21),
|
||||
});
|
||||
divExpectedTotalReturn = nextRaw / (prevRaw / cumTotalFactor) - 1;
|
||||
divRawDropReturn = nextRaw / prevRaw - 1;
|
||||
rawPrices[l] = nextRaw;
|
||||
} else {
|
||||
const prevRaw = rawPrices[l]!;
|
||||
const nextRaw = Math.max(0.5, prevRaw * (1 + dailyRet));
|
||||
if (l === halfDayUsIdx && t === halfDayIdx) {
|
||||
usHalfDayReturn = nextRaw / prevRaw - 1;
|
||||
} else if (l === halfDayUsIdx && t === nextSessionIdx) {
|
||||
usNextSessionReturn = nextRaw / prevRaw - 1;
|
||||
}
|
||||
rawPrices[l] = nextRaw;
|
||||
}
|
||||
|
||||
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : rawPrices[l]!;
|
||||
barRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
session_date: date,
|
||||
ts: closeTs,
|
||||
open: closeVal,
|
||||
high: closeVal,
|
||||
low: closeVal,
|
||||
close: closeVal,
|
||||
volume: 75_000,
|
||||
vwap: closeVal,
|
||||
known_at: closeTs,
|
||||
});
|
||||
}
|
||||
|
||||
// Schedule staggered after-close filing events across pre-2023 and post-2023 sessions
|
||||
// (plus post-cutoff filings to verify Vault isolation) using exact curator subtypes.
|
||||
if (t >= 12 && (t - 12) % 4 === 0) {
|
||||
for (let k = 0; k < 2; k += 1) {
|
||||
const l = ((t / 4) * 2 + k) % listingCount;
|
||||
const isUs = l < 12;
|
||||
const subtype = isUs ? '10-q' : 'interim_financial_statements';
|
||||
eventRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
ts: afterCloseTs,
|
||||
known_at: afterCloseTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: poisonPostCutoff && isPostCutoff ? 'poison_filing' : subtype,
|
||||
payload_json: JSON.stringify({ market: isUs ? 'US' : 'CA', form: subtype }),
|
||||
});
|
||||
// Activate drift starting on session `t + 1`.
|
||||
remainingBoostSessions[l] = 5;
|
||||
}
|
||||
|
||||
// Also emit a non-matching curated subtype filing on another listing to verify subtype filtering.
|
||||
const otherL = (t + 7) % listingCount;
|
||||
eventRows.push({
|
||||
listing_id: listingIds[otherL]!,
|
||||
ts: afterCloseTs,
|
||||
known_at: afterCloseTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: 'other',
|
||||
payload_json: '{}',
|
||||
});
|
||||
}
|
||||
|
||||
// Emit half-day filings at 14:00 ET (19:00 UTC) on Black Friday 2022-11-25:
|
||||
// - NYSE already closed at 13:00 ET (18:00 UTC) -> anchors to Monday 2022-11-28.
|
||||
// - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2022-11-25.
|
||||
if (t === halfDayIdx) {
|
||||
const halfDay14EtTs = makeUtcMs(date, 19);
|
||||
eventRows.push({
|
||||
listing_id: halfDayUsListingId,
|
||||
ts: halfDay14EtTs,
|
||||
known_at: halfDay14EtTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '10-q',
|
||||
payload_json: JSON.stringify({ market: 'US', form: '10-q', halfDay: true }),
|
||||
});
|
||||
eventRows.push({
|
||||
listing_id: halfDayCaListingId,
|
||||
ts: halfDay14EtTs,
|
||||
known_at: halfDay14EtTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: 'interim_financial_statements',
|
||||
payload_json: JSON.stringify({
|
||||
market: 'CA',
|
||||
form: 'interim_financial_statements',
|
||||
halfDay: true,
|
||||
}),
|
||||
});
|
||||
remainingBoostSessions[halfDayUsIdx] = 5;
|
||||
remainingBoostSessions[halfDayCaIdx] = 5;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
listingIds,
|
||||
usListingIds,
|
||||
caListingIds,
|
||||
allDates,
|
||||
vaultCutoffDate,
|
||||
vaultCutoffTs,
|
||||
barRows,
|
||||
adjFactorRows,
|
||||
eventRows,
|
||||
exchangeCalendars,
|
||||
dividendCase: {
|
||||
listingId: divListingId,
|
||||
exDate: divExDate,
|
||||
exDayIdx: divExIdx,
|
||||
expectedTotalReturn: divExpectedTotalReturn,
|
||||
rawDropReturn: divRawDropReturn,
|
||||
},
|
||||
halfDayCase: {
|
||||
usListingId: halfDayUsListingId,
|
||||
caListingId: halfDayCaListingId,
|
||||
halfDayDate,
|
||||
halfDayIdx,
|
||||
nextSessionDate,
|
||||
nextSessionIdx,
|
||||
usHalfDayReturn,
|
||||
usNextSessionReturn,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface RecordedQuery {
|
||||
readonly sql: string;
|
||||
readonly params: readonly DuckDbParam[];
|
||||
}
|
||||
|
||||
function createFakeDuckDbExecutor(fixture: QmFilingsFixture): {
|
||||
executor: DuckDbExecutor;
|
||||
runStatements: string[];
|
||||
queries: RecordedQuery[];
|
||||
} {
|
||||
const runStatements: string[] = [];
|
||||
const queries: RecordedQuery[] = [];
|
||||
|
||||
const executor: DuckDbExecutor = {
|
||||
async run(sql: string) {
|
||||
runStatements.push(sql);
|
||||
},
|
||||
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
||||
queries.push({ sql, params: [...params] });
|
||||
|
||||
if (sql.includes('parquet_kv_metadata')) {
|
||||
return makeFencedAdjKvRows(fixture.vaultCutoffTs, fixture.adjFactorRows.length);
|
||||
}
|
||||
|
||||
if (sql.includes('bars_1d/year=*/part.parquet')) {
|
||||
const nIds = fixture.listingIds.length;
|
||||
const isAdjusted = sql.includes('ASOF LEFT JOIN');
|
||||
let idSet: Set<number>;
|
||||
let fromMs: number;
|
||||
let toMs: number;
|
||||
let asOfMs: number;
|
||||
let adjAsOfMs: number | null = null;
|
||||
|
||||
if (isAdjusted) {
|
||||
// Bound params: [...listingIds, adjAsOfIso, ...listingIds, fromIso, toIso, asOfIso]
|
||||
adjAsOfMs = Date.parse(params[nIds] as string);
|
||||
idSet = new Set<number>(params.slice(nIds + 1, 2 * nIds + 1) as number[]);
|
||||
fromMs = Date.parse(params[2 * nIds + 1] as string);
|
||||
toMs = Date.parse(params[2 * nIds + 2] as string);
|
||||
asOfMs = Date.parse(params[2 * nIds + 3] as string);
|
||||
} else {
|
||||
// Bound params: [...listingIds, fromIso, toIso, asOfIso]
|
||||
idSet = new Set<number>(params.slice(0, nIds) as number[]);
|
||||
fromMs = Date.parse(params[nIds] as string);
|
||||
toMs = Date.parse(params[nIds + 1] as string);
|
||||
asOfMs = Date.parse(params[nIds + 2] as string);
|
||||
}
|
||||
|
||||
const out: TableRow[] = [];
|
||||
for (const row of fixture.barRows) {
|
||||
const lid = row.listing_id as number;
|
||||
const ts = row.ts as number;
|
||||
const knownAt = row.known_at as number;
|
||||
if (!idSet.has(lid) || ts < fromMs || ts > toMs || knownAt > asOfMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let priceDivisor = 1.0;
|
||||
let splitFactor = 1.0;
|
||||
if (isAdjusted && adjAsOfMs !== null) {
|
||||
const sessionDate = row.session_date as string;
|
||||
// ASOF LEFT JOIN: first adj_factors row with ex_date > session_date and known_at <= adjAsOfMs
|
||||
let bestAdj: AdjFactorRow | null = null;
|
||||
for (const adj of fixture.adjFactorRows) {
|
||||
if (
|
||||
adj.listing_id === lid &&
|
||||
adj.known_at <= adjAsOfMs &&
|
||||
sessionDate < adj.ex_date &&
|
||||
(bestAdj === null || adj.ex_date < bestAdj.ex_date)
|
||||
) {
|
||||
bestAdj = adj;
|
||||
}
|
||||
}
|
||||
if (bestAdj !== null) {
|
||||
priceDivisor = sql.includes('cum_total_factor')
|
||||
? bestAdj.cum_total_factor
|
||||
: bestAdj.cum_split_factor;
|
||||
splitFactor = bestAdj.cum_split_factor;
|
||||
}
|
||||
}
|
||||
|
||||
out.push({
|
||||
listing_id: lid,
|
||||
ts,
|
||||
open: (row.open as number) / priceDivisor,
|
||||
high: (row.high as number) / priceDivisor,
|
||||
low: (row.low as number) / priceDivisor,
|
||||
close: (row.close as number) / priceDivisor,
|
||||
volume: (row.volume as number) * splitFactor,
|
||||
vwap: (row.vwap as number) / priceDivisor,
|
||||
known_at: knownAt,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if (sql.includes('events/year=*/part.parquet')) {
|
||||
// Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso]
|
||||
const nIds = fixture.listingIds.length;
|
||||
const nKinds = params.length - nIds - 3;
|
||||
const kindSet = new Set<string>(params.slice(0, nKinds) as string[]);
|
||||
const idSet = new Set<number>(params.slice(nKinds, nKinds + nIds) as number[]);
|
||||
const fromMs = Date.parse(params[nKinds + nIds] as string);
|
||||
const toMs = Date.parse(params[nKinds + nIds + 1] as string);
|
||||
const asOfMs = Date.parse(params[nKinds + nIds + 2] as string);
|
||||
return fixture.eventRows.filter(row => {
|
||||
const kind = row.kind as string;
|
||||
const lid = row.listing_id as number;
|
||||
const ts = row.ts as number;
|
||||
const knownAt = row.known_at as number;
|
||||
return (
|
||||
kindSet.has(kind) &&
|
||||
idSet.has(lid) &&
|
||||
ts >= fromMs &&
|
||||
ts <= toMs &&
|
||||
knownAt <= asOfMs
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`);
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, runStatements, queries };
|
||||
}
|
||||
|
||||
describe('qmFilings end-to-end event study (headless, no database)', () => {
|
||||
async function runQmFilingsStudy(poisonPostCutoff: boolean) {
|
||||
const fixture = buildQmFilingsFixture(poisonPostCutoff);
|
||||
const duck = createFakeDuckDbExecutor(fixture);
|
||||
const ledger = createInMemoryTrialExecutor();
|
||||
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: duck.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: fixture.vaultCutoffTs,
|
||||
immutableAdjFactorsPath: IMMUTABLE_ADJ_PATH,
|
||||
barBatchSize: 256,
|
||||
});
|
||||
|
||||
const from = fixture.allDates[0]!;
|
||||
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
||||
|
||||
const bars = await collectBars(
|
||||
store.bars({
|
||||
listingIds: fixture.listingIds,
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
adjustment: 'total',
|
||||
})
|
||||
);
|
||||
const eventsTable = await store.events({
|
||||
kinds: ['filing'],
|
||||
listingIds: fixture.listingIds,
|
||||
from,
|
||||
to,
|
||||
});
|
||||
|
||||
const events = eventsTableToEventRows(eventsTable, {
|
||||
kinds: ['filing'],
|
||||
subtypes: ['10-q', 'interim_financial_statements'],
|
||||
});
|
||||
const built = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: fixture.exchangeCalendars,
|
||||
});
|
||||
|
||||
const studyResult = await runEventStudy(ledger.executor, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'qmfilings_interim_10q_sedar_event_study',
|
||||
params: {
|
||||
kinds: ['filing'],
|
||||
subtypes: ['10-q', 'interim_financial_statements'],
|
||||
preDays: 5,
|
||||
postDays: 5,
|
||||
},
|
||||
universe: 'US_CA_EQ_FIXTURE',
|
||||
horizon: '5d',
|
||||
},
|
||||
input: built.input,
|
||||
options: { preDays: 5, postDays: 5, minEvents: 10 },
|
||||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
});
|
||||
|
||||
return { fixture, duck, ledger, events, built, studyResult };
|
||||
}
|
||||
|
||||
it('flows DuckDbMarketDataStore (total-adjusted) -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => {
|
||||
const clean = await runQmFilingsStudy(false);
|
||||
|
||||
// DuckDB connection budget SET statements ran once; 3 queries ran (adj_factors kv metadata + bars + events).
|
||||
expect(clean.duck.runStatements).toHaveLength(3);
|
||||
expect(clean.duck.runStatements[0]).toContain('SET memory_limit');
|
||||
expect(clean.duck.runStatements[1]).toContain('SET threads');
|
||||
expect(clean.duck.runStatements[2]).toContain('SET temp_directory');
|
||||
expect(clean.duck.queries).toHaveLength(3);
|
||||
expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata');
|
||||
expect(clean.duck.queries[1]!.sql).toContain('cum_total_factor');
|
||||
expect(clean.duck.queries[2]!.sql).toContain('events/year=*/part.parquet');
|
||||
|
||||
// Every bound timestamp parameter (`asOfIso`, `fromIso`, `toIso`) in every data query
|
||||
// is strictly `< vaultCutoffTs`.
|
||||
const isoRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
|
||||
let checkedTimestamps = 0;
|
||||
for (const q of clean.duck.queries) {
|
||||
for (const param of q.params) {
|
||||
if (typeof param === 'string' && isoRe.test(param)) {
|
||||
const parsedMs = Date.parse(param);
|
||||
expect(Number.isFinite(parsedMs)).toBe(true);
|
||||
expect(parsedMs).toBeLessThan(clean.fixture.vaultCutoffTs);
|
||||
checkedTimestamps += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// bars_1d total-adjusted binds 4 timestamps (adjAsOfIso, fromIso, toIso, barsAsOfIso) + events binds 3.
|
||||
expect(checkedTimestamps).toBe(7);
|
||||
|
||||
// Both curated filing groups ('10-q' for US and 'interim_financial_statements' for CA) contribute events.
|
||||
const usFilteredCount = clean.events.filter(e => e.subtype === '10-q').length;
|
||||
const caFilteredCount = clean.events.filter(
|
||||
e => e.subtype === 'interim_financial_statements'
|
||||
).length;
|
||||
expect(usFilteredCount).toBeGreaterThan(0);
|
||||
expect(caFilteredCount).toBeGreaterThan(0);
|
||||
expect(usFilteredCount + caFilteredCount).toBe(clean.events.length);
|
||||
|
||||
// Total-return adjustment eliminates the raw -10% dividend drop inside the filing window.
|
||||
const divCase = clean.fixture.dividendCase;
|
||||
expect(divCase.rawDropReturn).toBeLessThan(-0.08);
|
||||
expect(divCase.expectedTotalReturn).toBeGreaterThan(-0.02);
|
||||
const divSeries = clean.built.input.entityReturns.get(divCase.listingId)!;
|
||||
expect(divSeries[divCase.exDayIdx]!).toBeCloseTo(divCase.expectedTotalReturn, 10);
|
||||
|
||||
// Half-day anchoring: a US ('10-q') filing published at 14:00 ET on Black Friday 2022-11-25
|
||||
// (after NYSE's 13:00 ET close, even though curated bars_1d.ts stamps 16:00 ET) MUST anchor
|
||||
// to Monday 2022-11-28 (not Friday), while the CA ('interim_financial_statements') filing at
|
||||
// 14:00 ET anchors to Friday 2022-11-25 (before TSX's 16:00 ET close).
|
||||
const halfDay = clean.fixture.halfDayCase;
|
||||
expect(
|
||||
clean.built.input.events.some(
|
||||
e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.halfDayIdx
|
||||
)
|
||||
).toBe(false);
|
||||
expect(
|
||||
clean.built.input.events.some(
|
||||
e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.nextSessionIdx
|
||||
)
|
||||
).toBe(true);
|
||||
expect(
|
||||
clean.built.input.events.some(
|
||||
e => e.entityId === halfDay.caListingId && e.dayIndex === halfDay.halfDayIdx
|
||||
)
|
||||
).toBe(true);
|
||||
const usHalfDaySeries = clean.built.input.entityReturns.get(halfDay.usListingId)!;
|
||||
expect(clean.built.input.sessionDates[halfDay.nextSessionIdx]).toBe(halfDay.nextSessionDate);
|
||||
expect(usHalfDaySeries[halfDay.nextSessionIdx]!).toBeCloseTo(halfDay.usNextSessionReturn, 12);
|
||||
expect(halfDay.usNextSessionReturn).not.toBeCloseTo(halfDay.usHalfDayReturn, 6);
|
||||
|
||||
// Event study succeeded and appended exactly one `event_study` row to trial_ledger.
|
||||
expect(clean.studyResult.status).toBe('ok');
|
||||
if (clean.studyResult.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Both US ('10-q') and CA ('interim_financial_statements') listings contributed usable events to the study.
|
||||
const usedIds = clean.studyResult.study.eventCars.entityIds;
|
||||
const usUsedCount = usedIds.filter(id => clean.fixture.usListingIds.has(Number(id))).length;
|
||||
const caUsedCount = usedIds.filter(id => clean.fixture.caListingIds.has(Number(id))).length;
|
||||
expect(usUsedCount).toBeGreaterThan(0);
|
||||
expect(caUsedCount).toBeGreaterThan(0);
|
||||
|
||||
expect(clean.ledger.rows).toHaveLength(1);
|
||||
const stored = clean.ledger.rows[0]!;
|
||||
expect(stored.stage).toBe('event_study');
|
||||
expect(stored.universe_market).toBe('US_CA_EQ');
|
||||
expect(stored.horizon_bucket).toBe('swing_1_10d');
|
||||
expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
|
||||
// Stored daily_series matches study.clustered.meanCars at float32 precision.
|
||||
const expectedMeanCars = Array.from(clean.studyResult.study.clustered.meanCars, v =>
|
||||
Math.fround(v)
|
||||
);
|
||||
expect(stored.daily_series).toEqual(expectedMeanCars);
|
||||
|
||||
// Finite cluster-deflated Sharpe with effectiveTrials >= 1.
|
||||
expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull();
|
||||
expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true);
|
||||
expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Planted positive post-filing abnormal return produces positive clustered CAR mean.
|
||||
expect(clean.studyResult.study.clustered.carMean).toBeGreaterThan(0);
|
||||
|
||||
// Poisoning post-cutoff bars & events leaves built input, study result, and ledger byte-identical.
|
||||
const poisoned = await runQmFilingsStudy(true);
|
||||
expect(poisoned.built.diagnostics).toEqual(clean.built.diagnostics);
|
||||
expect(poisoned.built.input.sessionDates).toEqual(clean.built.input.sessionDates);
|
||||
expect(poisoned.built.input.events).toEqual(clean.built.input.events);
|
||||
expect(Array.from(poisoned.built.input.entityReturns.keys())).toEqual(
|
||||
Array.from(clean.built.input.entityReturns.keys())
|
||||
);
|
||||
for (const [id, cleanSeries] of clean.built.input.entityReturns) {
|
||||
const a = poisoned.built.input.entityReturns.get(id) as Float64Array;
|
||||
const b = cleanSeries as Float64Array;
|
||||
expect(new Uint8Array(a.buffer, a.byteOffset, a.byteLength)).toEqual(
|
||||
new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
|
||||
);
|
||||
}
|
||||
const cleanBench = clean.built.input.benchmarkReturns as Float64Array;
|
||||
const poisonedBench = poisoned.built.input.benchmarkReturns as Float64Array;
|
||||
expect(
|
||||
new Uint8Array(poisonedBench.buffer, poisonedBench.byteOffset, poisonedBench.byteLength)
|
||||
).toEqual(new Uint8Array(cleanBench.buffer, cleanBench.byteOffset, cleanBench.byteLength));
|
||||
expect(poisoned.studyResult).toEqual(clean.studyResult);
|
||||
expect(poisoned.ledger.rows).toEqual(clean.ledger.rows);
|
||||
});
|
||||
});
|
||||
672
libs/research/test/event-panel-qa.test.ts
Normal file
672
libs/research/test/event-panel-qa.test.ts
Normal file
|
|
@ -0,0 +1,672 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
type BarRecord,
|
||||
type BuildEventStudyInputResult,
|
||||
type EventObservation,
|
||||
type EventStudyExchangeCalendars,
|
||||
type ExchangeSessionClose,
|
||||
type TrialLedgerExecutor,
|
||||
buildEventStudyInput,
|
||||
runEventStudy,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
// QA suite for T-123: compares `buildEventStudyInput` against a deliberately naive reference
|
||||
// model on seeded random panels (two exchange calendars with different holidays and an NYSE
|
||||
// half-day, EDT/EST close stamps, gaps, bad closes, exact duplicate bars, late-listing /
|
||||
// early-delisting, events at/around exact close timestamps, weekends, pre-history and
|
||||
// post-cutoff), plus truncation (prefix-stability) and an end-to-end half-day CAR probe.
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0, ms = 0): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms);
|
||||
}
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = [];
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
while (out.length < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out.push(current.toISOString().slice(0, 10));
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 16:00 ET in UTC: 20:00 during EDT (before 2022-11-06 / from 2023-03-12), 21:00 during EST.
|
||||
function regularCloseHourUtc(date: string): number {
|
||||
return date < '2022-11-06' || date >= '2023-03-12' ? 20 : 21;
|
||||
}
|
||||
|
||||
function makeBar(listingId: number, ts: number, close: number): BarRecord {
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 1_000,
|
||||
vwap: close,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTrappedBar(listingId: number, ts: number): BarRecord {
|
||||
const bar = { ...makeBar(listingId, ts, 1) } as Record<string, unknown>;
|
||||
Object.defineProperty(bar, 'close', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
throw new Error(`Vault breach: close read for listing ${listingId} at ${ts}`);
|
||||
},
|
||||
});
|
||||
return bar as unknown as BarRecord;
|
||||
}
|
||||
|
||||
function shuffle<T>(items: readonly T[], seed: number): T[] {
|
||||
const copy = [...items];
|
||||
const rand = createSeededRng(seed);
|
||||
for (let i = copy.length - 1; i > 0; i -= 1) {
|
||||
const j = Math.floor(rand() * (i + 1));
|
||||
[copy[i], copy[j]] = [copy[j]!, copy[i]!];
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
const US_HOLIDAYS = new Set(['2022-11-24', '2022-12-26', '2023-01-02', '2023-01-16', '2023-02-20']);
|
||||
const CA_HOLIDAYS = new Set(['2022-10-10', '2022-12-26', '2022-12-27', '2023-01-02', '2023-02-20']);
|
||||
const NYSE_HALF_DAYS = new Set(['2022-11-25']);
|
||||
|
||||
function buildCalendars(dates: readonly string[]): {
|
||||
xnys: ExchangeSessionClose[];
|
||||
xtse: ExchangeSessionClose[];
|
||||
} {
|
||||
const xnys: ExchangeSessionClose[] = [];
|
||||
const xtse: ExchangeSessionClose[] = [];
|
||||
for (const date of dates) {
|
||||
const regular = regularCloseHourUtc(date);
|
||||
if (!US_HOLIDAYS.has(date)) {
|
||||
xnys.push({ date, closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? regular - 3 : regular) });
|
||||
}
|
||||
if (!CA_HOLIDAYS.has(date)) {
|
||||
xtse.push({ date, closeTs: makeUtcMs(date, regular) });
|
||||
}
|
||||
}
|
||||
return { xnys, xtse };
|
||||
}
|
||||
|
||||
interface RandomPanel {
|
||||
readonly bars: BarRecord[];
|
||||
readonly events: EventObservation[];
|
||||
readonly calendars: EventStudyExchangeCalendars;
|
||||
readonly calendarByListing: Map<number, ExchangeSessionClose[]>;
|
||||
readonly dates: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a seeded random panel. Bars dated on/after `trapFromDate` get a throwing `close`
|
||||
* getter so any Vault breach fails the test.
|
||||
*/
|
||||
function buildRandomPanel(seed: number, trapFromDate: string | null): RandomPanel {
|
||||
const rand = createSeededRng(seed);
|
||||
const dates = makeBusinessDates('2022-10-03', 110);
|
||||
const { xnys, xtse } = buildCalendars(dates);
|
||||
const listingCount = 12;
|
||||
const listingIds = Array.from({ length: listingCount }, (_, i) => 100 + i * 7);
|
||||
const calendarByListing = new Map<number, ExchangeSessionClose[]>();
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
const bars: BarRecord[] = [];
|
||||
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const listingId = listingIds[l]!;
|
||||
const isUs = l % 2 === 0;
|
||||
const cal = isUs ? xnys : xtse;
|
||||
calendarByListing.set(listingId, cal);
|
||||
listingCalendarId.set(listingId, isUs ? 'XNYS' : 'XTSE');
|
||||
|
||||
const startIdx = l % 4 === 3 ? 20 + Math.floor(rand() * 20) : 0;
|
||||
const endIdx = l % 5 === 4 ? cal.length - 30 - Math.floor(rand() * 10) : cal.length;
|
||||
let price = 20 + l;
|
||||
for (let s = startIdx; s < endIdx; s += 1) {
|
||||
const session = cal[s]!;
|
||||
if (rand() < 0.08) {
|
||||
continue; // gap
|
||||
}
|
||||
price *= 1 + (rand() * 2 - 1) * 0.02;
|
||||
const ts = makeUtcMs(session.date, regularCloseHourUtc(session.date)); // curated 16:00 ET
|
||||
const trapped = trapFromDate !== null && session.date >= trapFromDate;
|
||||
if (trapped) {
|
||||
bars.push(makeTrappedBar(listingId, ts));
|
||||
continue;
|
||||
}
|
||||
const u = rand();
|
||||
const close = u < 0.01 ? 0 : u < 0.02 ? -1 : u < 0.025 ? Number.NaN : u < 0.03 ? Number.POSITIVE_INFINITY : price;
|
||||
bars.push(makeBar(listingId, ts, close));
|
||||
if (rand() < 0.03) {
|
||||
bars.push(makeBar(listingId, ts, close)); // exact duplicate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const events: EventObservation[] = [];
|
||||
const eventCount = 160;
|
||||
for (let i = 0; i < eventCount; i += 1) {
|
||||
const unknown = rand() < 0.05;
|
||||
const listingId = unknown ? 9_999 : listingIds[Math.floor(rand() * listingCount)]!;
|
||||
const cal = calendarByListing.get(listingId) ?? xnys;
|
||||
const anchorSession = cal[Math.floor(rand() * cal.length)]!;
|
||||
const mode = Math.floor(rand() * 7);
|
||||
let knownAt: number;
|
||||
if (mode === 0) {
|
||||
knownAt = anchorSession.closeTs; // exactly at close -> same session
|
||||
} else if (mode === 1) {
|
||||
knownAt = anchorSession.closeTs + 1; // 1 ms after close -> next session
|
||||
} else if (mode === 2) {
|
||||
knownAt = anchorSession.closeTs - 1;
|
||||
} else if (mode === 3) {
|
||||
knownAt = makeUtcMs(anchorSession.date, 19); // 14:00/15:00 ET intraday (after half-day close)
|
||||
} else if (mode === 4) {
|
||||
knownAt = makeUtcMs(anchorSession.date, 22, 30); // after close
|
||||
} else if (mode === 5) {
|
||||
knownAt = makeUtcMs(anchorSession.date, 12) + 2 * MS_PER_DAY; // may land on weekend
|
||||
} else {
|
||||
knownAt = makeUtcMs('2022-09-15', 15) + Math.floor(rand() * 200) * MS_PER_DAY; // pre-history .. post-cutoff
|
||||
}
|
||||
events.push({ listingId, knownAt, kind: 'filing', subtype: rand() < 0.5 ? '10-q' : 'interim_financial_statements' });
|
||||
if (rand() < 0.05) {
|
||||
events.push({ listingId, knownAt, kind: 'filing', subtype: 'other' }); // duplicate anchor
|
||||
}
|
||||
}
|
||||
// Explicit NYSE half-day probe: 14:00 ET on Black Friday for a US and a CA listing.
|
||||
events.push({ listingId: listingIds[0]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' });
|
||||
events.push({ listingId: listingIds[1]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: null });
|
||||
|
||||
return {
|
||||
bars,
|
||||
events,
|
||||
calendars: {
|
||||
calendars: new Map([
|
||||
['XNYS', xnys],
|
||||
['XTSE', xtse],
|
||||
]),
|
||||
listingCalendarId,
|
||||
},
|
||||
calendarByListing,
|
||||
dates,
|
||||
};
|
||||
}
|
||||
|
||||
interface ReferenceResult {
|
||||
sessionDates: string[];
|
||||
entityIds: number[];
|
||||
returns: Map<number, number[]>;
|
||||
benchmark: number[];
|
||||
events: { entityId: number; dayIndex: number }[];
|
||||
diagnostics: Record<string, number>;
|
||||
}
|
||||
|
||||
/** Naive O(n^2) reference model of the documented contract. */
|
||||
function referenceBuild(panel: RandomPanel, vaultCutoffDate: string): ReferenceResult {
|
||||
const cutoffMs = makeUtcMs(vaultCutoffDate, 0);
|
||||
const dateOf = (ts: number) => new Date(Math.floor(ts / MS_PER_DAY) * MS_PER_DAY).toISOString().slice(0, 10);
|
||||
const postDates = new Set<string>();
|
||||
const perListing = new Map<number, Map<string, number>>();
|
||||
let duplicateBars = 0;
|
||||
for (const bar of panel.bars) {
|
||||
const date = dateOf(bar.ts);
|
||||
if (date >= vaultCutoffDate) {
|
||||
postDates.add(date);
|
||||
continue;
|
||||
}
|
||||
const m = perListing.get(bar.listingId) ?? new Map<string, number>();
|
||||
perListing.set(bar.listingId, m);
|
||||
if (m.has(date)) {
|
||||
duplicateBars += 1;
|
||||
continue;
|
||||
}
|
||||
m.set(date, bar.close);
|
||||
}
|
||||
const sessionDates = [...new Set([...perListing.values()].flatMap(m => [...m.keys()]))].sort();
|
||||
const entityIds = [...perListing.keys()].sort((a, b) => a - b);
|
||||
const returns = new Map<number, number[]>();
|
||||
const benchSum = new Array<number>(sessionDates.length).fill(0);
|
||||
const benchCount = new Array<number>(sessionDates.length).fill(0);
|
||||
let nonPositiveCloseReturns = 0;
|
||||
for (const id of entityIds) {
|
||||
const closes = perListing.get(id)!;
|
||||
const calDates = panel.calendarByListing.get(id)!.map(s => s.date);
|
||||
const series = sessionDates.map((date, d) => {
|
||||
if (!closes.has(date)) {
|
||||
return Number.NaN;
|
||||
}
|
||||
const c = calDates.indexOf(date);
|
||||
if (c <= 0 || !closes.has(calDates[c - 1]!)) {
|
||||
return Number.NaN;
|
||||
}
|
||||
const prev = closes.get(calDates[c - 1]!)!;
|
||||
const curr = closes.get(date)!;
|
||||
const ret = curr / prev - 1;
|
||||
if (!(prev > 0 && curr > 0 && Number.isFinite(prev) && Number.isFinite(curr) && Number.isFinite(ret))) {
|
||||
nonPositiveCloseReturns += 1;
|
||||
return Number.NaN;
|
||||
}
|
||||
benchSum[d] += ret;
|
||||
benchCount[d] += 1;
|
||||
return ret;
|
||||
});
|
||||
returns.set(id, series);
|
||||
}
|
||||
const benchmark = benchSum.map((s, d) => (benchCount[d]! > 0 ? s / benchCount[d]! : Number.NaN));
|
||||
|
||||
let vaultExcludedEvents = 0;
|
||||
let droppedUnknownListing = 0;
|
||||
let droppedAfterLastSession = 0;
|
||||
let droppedMissingCalendarSession = 0;
|
||||
const cands: { entityId: number; dayIndex: number }[] = [];
|
||||
for (const ev of panel.events) {
|
||||
if (ev.knownAt >= cutoffMs) {
|
||||
vaultExcludedEvents += 1;
|
||||
continue;
|
||||
}
|
||||
if (!perListing.has(ev.listingId)) {
|
||||
droppedUnknownListing += 1;
|
||||
continue;
|
||||
}
|
||||
const preCal = panel.calendarByListing.get(ev.listingId)!.filter(s => s.date < vaultCutoffDate);
|
||||
const eligible = preCal.find(s => s.closeTs >= ev.knownAt);
|
||||
if (eligible === undefined || eligible.date > sessionDates[sessionDates.length - 1]!) {
|
||||
droppedAfterLastSession += 1;
|
||||
continue;
|
||||
}
|
||||
const dayIndex = sessionDates.indexOf(eligible.date);
|
||||
if (dayIndex < 0) {
|
||||
droppedMissingCalendarSession += 1;
|
||||
continue;
|
||||
}
|
||||
cands.push({ entityId: ev.listingId, dayIndex });
|
||||
}
|
||||
cands.sort((a, b) => a.dayIndex - b.dayIndex || a.entityId - b.entityId);
|
||||
const events = cands.filter(
|
||||
(c, i) => i === 0 || c.dayIndex !== cands[i - 1]!.dayIndex || c.entityId !== cands[i - 1]!.entityId
|
||||
);
|
||||
|
||||
return {
|
||||
sessionDates,
|
||||
entityIds,
|
||||
returns,
|
||||
benchmark,
|
||||
events,
|
||||
diagnostics: {
|
||||
vaultExcludedDates: postDates.size,
|
||||
vaultExcludedEvents,
|
||||
droppedUnknownListing,
|
||||
droppedAfterLastSession,
|
||||
droppedMissingCalendarSession,
|
||||
duplicateEvents: cands.length - events.length,
|
||||
duplicateBars,
|
||||
nonPositiveCloseReturns,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function nanSafe(values: ArrayLike<number>): (number | string)[] {
|
||||
return Array.from(values, v => (Number.isNaN(v) ? 'NaN' : v));
|
||||
}
|
||||
|
||||
function expectSameAsReference(actual: BuildEventStudyInputResult, ref: ReferenceResult): void {
|
||||
expect(actual.input.sessionDates).toEqual(ref.sessionDates);
|
||||
expect(Array.from(actual.input.entityReturns.keys())).toEqual(ref.entityIds);
|
||||
for (const id of ref.entityIds) {
|
||||
expect(nanSafe(actual.input.entityReturns.get(id)!)).toEqual(nanSafe(ref.returns.get(id)!));
|
||||
}
|
||||
expect(nanSafe(actual.input.benchmarkReturns!)).toEqual(nanSafe(ref.benchmark));
|
||||
expect(actual.input.events.map(e => ({ entityId: e.entityId, dayIndex: e.dayIndex }))).toEqual(ref.events);
|
||||
expect({ ...actual.diagnostics }).toEqual(ref.diagnostics);
|
||||
}
|
||||
|
||||
describe('buildEventStudyInput QA — seeded reference-model comparison', () => {
|
||||
const VAULT_CUTOFF = '2023-02-01';
|
||||
|
||||
for (const seed of [20261129, 7, 424242, 99]) {
|
||||
it(`matches the naive reference model exactly and never reads vaulted closes (seed ${seed})`, () => {
|
||||
const panel = buildRandomPanel(seed, VAULT_CUTOFF);
|
||||
const ref = referenceBuild(panel, VAULT_CUTOFF);
|
||||
|
||||
const actual = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
|
||||
expectSameAsReference(actual, ref);
|
||||
// Conservation identity.
|
||||
const d = actual.diagnostics;
|
||||
expect(
|
||||
actual.input.events.length +
|
||||
d.vaultExcludedEvents +
|
||||
d.droppedUnknownListing +
|
||||
d.droppedAfterLastSession +
|
||||
d.droppedMissingCalendarSession +
|
||||
d.duplicateEvents
|
||||
).toBe(panel.events.length);
|
||||
// No session date reaches the Vault and no event anchors onto a Vault session.
|
||||
expect(actual.input.sessionDates.every(date => date < VAULT_CUTOFF)).toBe(true);
|
||||
// Fixture actually exercises the interesting branches.
|
||||
expect(d.vaultExcludedEvents).toBeGreaterThan(0);
|
||||
expect(d.droppedUnknownListing).toBeGreaterThan(0);
|
||||
expect(d.vaultExcludedDates).toBeGreaterThan(0);
|
||||
expect(d.nonPositiveCloseReturns).toBeGreaterThan(0);
|
||||
|
||||
// Shuffled inputs give the identical result.
|
||||
const shuffled = buildEventStudyInput({
|
||||
bars: shuffle(panel.bars, seed + 1),
|
||||
events: shuffle(panel.events, seed + 2),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
expectSameAsReference(shuffled, ref);
|
||||
});
|
||||
}
|
||||
|
||||
it('anchors the NYSE Black Friday 14:00 ET filing to Monday and the TSX one to Friday', () => {
|
||||
const panel = buildRandomPanel(20261129, VAULT_CUTOFF);
|
||||
const actual = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
const usId = 100;
|
||||
const caId = 107;
|
||||
const dates = actual.input.sessionDates;
|
||||
const usDates = actual.input.events.filter(e => e.entityId === usId).map(e => dates[e.dayIndex]);
|
||||
const caDates = actual.input.events.filter(e => e.entityId === caId).map(e => dates[e.dayIndex]);
|
||||
expect(usDates).toContain('2022-11-28');
|
||||
expect(caDates).toContain('2022-11-25');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildEventStudyInput QA — truncation (prefix stability) across Vault cutoffs', () => {
|
||||
it('earlier-cutoff output is an exact prefix of later-cutoff output (no future-dependent values)', () => {
|
||||
const panel = buildRandomPanel(31337, null);
|
||||
const cutoffs = ['2022-11-25', '2022-12-27', '2023-01-17', '2023-02-21'];
|
||||
const results = cutoffs.map(vaultCutoffDate =>
|
||||
buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
})
|
||||
);
|
||||
|
||||
for (let i = 0; i + 1 < results.length; i += 1) {
|
||||
const early = results[i]!.input;
|
||||
const late = results[i + 1]!.input;
|
||||
const n = early.sessionDates.length;
|
||||
expect(n).toBeGreaterThan(0);
|
||||
expect(late.sessionDates.slice(0, n)).toEqual([...early.sessionDates]);
|
||||
for (const [id, series] of early.entityReturns) {
|
||||
const lateSeries = late.entityReturns.get(id)!;
|
||||
expect(nanSafe(Array.from(lateSeries).slice(0, n))).toEqual(nanSafe(series));
|
||||
}
|
||||
expect(nanSafe(Array.from(late.benchmarkReturns!).slice(0, n))).toEqual(
|
||||
nanSafe(early.benchmarkReturns!)
|
||||
);
|
||||
const lateKeys = new Set(late.events.map(e => `${e.entityId}@${e.dayIndex}`));
|
||||
for (const ev of early.events) {
|
||||
expect(lateKeys.has(`${ev.entityId}@${ev.dayIndex}`)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('a poisoned future (absurd closes, extra filings, calendar tail) leaves pre-cutoff output byte-identical', () => {
|
||||
const cutoff = '2023-01-17';
|
||||
const panel = buildRandomPanel(555, null);
|
||||
const base = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
|
||||
const cutoffMs = makeUtcMs(cutoff, 0);
|
||||
const poisonedBars = panel.bars.map(b =>
|
||||
b.ts >= cutoffMs ? makeBar(b.listingId, b.ts, b.close * 1_000_000) : b
|
||||
);
|
||||
const poisonedEvents: EventObservation[] = [
|
||||
...panel.events,
|
||||
...[100, 107, 114].map(listingId => ({
|
||||
listingId,
|
||||
knownAt: cutoffMs,
|
||||
kind: 'filing' as const,
|
||||
subtype: 'poison',
|
||||
})),
|
||||
];
|
||||
const result = buildEventStudyInput({
|
||||
bars: poisonedBars,
|
||||
events: poisonedEvents,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
|
||||
expect(result.input.sessionDates).toEqual(base.input.sessionDates);
|
||||
expect(result.input.events).toEqual(base.input.events);
|
||||
for (const [id, series] of base.input.entityReturns) {
|
||||
expect(nanSafe(result.input.entityReturns.get(id)!)).toEqual(nanSafe(series));
|
||||
}
|
||||
expect(nanSafe(result.input.benchmarkReturns!)).toEqual(nanSafe(base.input.benchmarkReturns!));
|
||||
expect(result.diagnostics.vaultExcludedEvents).toBe(base.diagnostics.vaultExcludedEvents + 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildEventStudyInput QA — calendar input forms and exact-close boundaries', () => {
|
||||
it('treats plain-object calendars/mappings identically to Maps', () => {
|
||||
const panel = buildRandomPanel(8080, null);
|
||||
const cutoff = '2023-02-01';
|
||||
const cals = panel.calendars.calendars as ReadonlyMap<string, readonly ExchangeSessionClose[]>;
|
||||
const mapping = panel.calendars.listingCalendarId as ReadonlyMap<number, string>;
|
||||
const asMaps = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
const asRecords = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: {
|
||||
calendars: Object.fromEntries(cals),
|
||||
listingCalendarId: Object.fromEntries(mapping),
|
||||
},
|
||||
});
|
||||
expect(asRecords.input.events).toEqual(asMaps.input.events);
|
||||
expect(asRecords.diagnostics).toEqual(asMaps.diagnostics);
|
||||
for (const [id, series] of asMaps.input.entityReturns) {
|
||||
expect(nanSafe(asRecords.input.entityReturns.get(id)!)).toEqual(nanSafe(series));
|
||||
}
|
||||
});
|
||||
|
||||
it('anchors knownAt == close to that session and close + 1 ms to the next (half-day close included)', () => {
|
||||
const dates = ['2022-11-22', '2022-11-23', '2022-11-25', '2022-11-28'];
|
||||
const xnys = dates.map(date => ({
|
||||
date,
|
||||
closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? 18 : 21),
|
||||
}));
|
||||
const bars = dates.map((date, i) => makeBar(1, makeUtcMs(date, 21), 10 + i));
|
||||
const halfClose = makeUtcMs('2022-11-25', 18);
|
||||
const result = buildEventStudyInput({
|
||||
bars,
|
||||
events: [
|
||||
{ listingId: 1, knownAt: halfClose, kind: 'filing', subtype: '10-q' },
|
||||
{ listingId: 1, knownAt: halfClose + 1, kind: 'filing', subtype: '10-q' },
|
||||
// Thanksgiving (NYSE closed) intraday -> Friday half-day session.
|
||||
{ listingId: 1, knownAt: makeUtcMs('2022-11-24', 15), kind: 'filing', subtype: '10-q' },
|
||||
],
|
||||
vaultCutoffDate: '2022-12-01',
|
||||
exchangeCalendars: { calendars: { XNYS: xnys }, listingCalendarId: { 1: 'XNYS' } },
|
||||
});
|
||||
expect(result.input.events).toEqual([
|
||||
{ entityId: 1, dayIndex: 2 },
|
||||
{ entityId: 1, dayIndex: 3 },
|
||||
]);
|
||||
expect(result.diagnostics.duplicateEvents).toBe(1);
|
||||
// Wed -> Fri is consecutive on the NYSE calendar (Thanksgiving closed), so Friday's return is valid.
|
||||
expect(result.input.entityReturns.get(1)![2]).toBeCloseTo(12 / 11 - 1, 15);
|
||||
});
|
||||
});
|
||||
|
||||
function createInMemoryTrialExecutor(): { executor: TrialLedgerExecutor; rows: Record<string, unknown>[] } {
|
||||
const rows: Record<string, unknown>[] = [];
|
||||
let nextTrialId = 1;
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
const p = params ?? [];
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
const trialId = String(nextTrialId++);
|
||||
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, Number(trialId)));
|
||||
const stored = {
|
||||
trial_id: trialId,
|
||||
created_at: createdAt,
|
||||
principal_id: p[0],
|
||||
campaign_id: p[1] ?? null,
|
||||
stage: p[2],
|
||||
universe_market: p[3],
|
||||
horizon_bucket: p[4],
|
||||
hypothesis_id: p[5] ?? null,
|
||||
expression_hash: p[6],
|
||||
sample_start: p[7],
|
||||
sample_end: p[8],
|
||||
n_obs: p[9],
|
||||
sharpe_unann: p[10],
|
||||
skewness: p[11],
|
||||
kurtosis: p[12],
|
||||
daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)),
|
||||
};
|
||||
rows.push(stored);
|
||||
return { rows: [{ trial_id: trialId, created_at: createdAt } as unknown as Row], rowCount: 1 };
|
||||
}
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const matched = rows.filter(r => r.trial_id === String(p[0]));
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const matched = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
return { executor, rows };
|
||||
}
|
||||
|
||||
describe('buildEventStudyInput QA — half-day filing reaches runEventStudy eventCars on Monday', () => {
|
||||
it('keeps the NYSE Black Friday filing in study.eventCars dated Monday with the expected benchmark-adjusted CAR', async () => {
|
||||
const rand = createSeededRng(20261129);
|
||||
const dates = makeBusinessDates('2022-10-03', 90);
|
||||
const { xnys, xtse } = buildCalendars(dates);
|
||||
const vaultCutoffDate = dates[80]!;
|
||||
const usIds = [11, 12, 13, 14];
|
||||
const caIds = [21, 22, 23, 24];
|
||||
const bars: BarRecord[] = [];
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (const [ids, cal, calId] of [
|
||||
[usIds, xnys, 'XNYS'],
|
||||
[caIds, xtse, 'XTSE'],
|
||||
] as const) {
|
||||
for (const id of ids) {
|
||||
listingCalendarId.set(id, calId);
|
||||
let price = 30 + id;
|
||||
for (const s of cal) {
|
||||
price *= 1 + (rand() * 2 - 1) * 0.015;
|
||||
bars.push(makeBar(id, makeUtcMs(s.date, regularCloseHourUtc(s.date)), price));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regular after-close filings every 5 sessions in windows that avoid cross-border holidays,
|
||||
// plus the 14:00 ET Black Friday filing for listing 11 (after NYSE's 13:00 ET close).
|
||||
const events: EventObservation[] = [];
|
||||
for (let t = 3; t < 75; t += 5) {
|
||||
const date = dates[t]!;
|
||||
for (const id of [...usIds, ...caIds]) {
|
||||
if ((t + id) % 3 === 0) {
|
||||
events.push({ listingId: id, knownAt: makeUtcMs(date, 23), kind: 'filing', subtype: '10-q' });
|
||||
}
|
||||
}
|
||||
}
|
||||
events.push({ listingId: 11, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' });
|
||||
|
||||
const built = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: { calendars: { XNYS: xnys, XTSE: xtse }, listingCalendarId },
|
||||
});
|
||||
|
||||
const postDays = 3;
|
||||
const ledger = createInMemoryTrialExecutor();
|
||||
const result = await runEventStudy(ledger.executor, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'qa_half_day_filing_event_study',
|
||||
params: { preDays: 0, postDays },
|
||||
universe: 'US_CA_EQ_QA',
|
||||
horizon: '3d',
|
||||
},
|
||||
input: built.input,
|
||||
options: { preDays: 0, postDays, minEvents: 5 },
|
||||
vaultCutoffDate,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
if (result.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
expect(ledger.rows).toHaveLength(1);
|
||||
|
||||
const cars = result.study.eventCars;
|
||||
const usHalfDayIdx = cars.entityIds.findIndex((id, i) => id === 11 && cars.dates[i] === '2022-11-28');
|
||||
expect(usHalfDayIdx).toBeGreaterThanOrEqual(0);
|
||||
expect(cars.entityIds.some((id, i) => id === 11 && cars.dates[i] === '2022-11-25')).toBe(false);
|
||||
|
||||
const sessionDates = built.input.sessionDates;
|
||||
const d = sessionDates.indexOf('2022-11-28');
|
||||
expect(cars.dayIndices[usHalfDayIdx]).toBe(d);
|
||||
const r = built.input.entityReturns.get(11)!;
|
||||
const b = built.input.benchmarkReturns!;
|
||||
let expectedCar = 0;
|
||||
for (let k = 0; k <= postDays; k += 1) {
|
||||
expectedCar += (r[d + k] as number) - (b[d + k] as number);
|
||||
}
|
||||
expect(cars.cars[usHalfDayIdx]!).toBeCloseTo(expectedCar, 12);
|
||||
expect(Number.isFinite(result.deflatedSharpe.dsr ?? Number.NaN)).toBe(true);
|
||||
});
|
||||
});
|
||||
1181
libs/research/test/event-panel.test.ts
Normal file
1181
libs/research/test/event-panel.test.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue