T-123: M1.3h — @stock-bot/research: pure event-study panel builder (MarketDataStore daily bars + events table → Vault-safe EventStudyInput) with an end-to-end qmFilings event study test (store → runEventStudy → trial_ledger → DSR) and local benchmark (no new dependencies)
This commit is contained in:
parent
112b830985
commit
5e626b083b
5 changed files with 756 additions and 62 deletions
|
|
@ -167,15 +167,16 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (
|
|||
### 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, 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.
|
||||
- `benchmark?: 'equal_weight' | 'none'` (default `'none'`): `'none'` omits `benchmarkReturns`; `'equal_weight'` sets `benchmarkReturns[d]` to the mean of finite `entityReturns` on session `d` (`NaN` when none).
|
||||
- **`buildEventStudyInput({ bars, events, vaultCutoffDate, benchmark?, exchangeCalendars? })`** — 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.
|
||||
- `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).
|
||||
- `exchangeCalendars?: { calendars, listingCalendarId }`: optional caller-supplied exchange close calendars (`{ date, closeTs }[]` per calendar ID, plus `listingId -> calendarId` mapping). When provided, 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.
|
||||
|
||||
### 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 calendar sessions (`currSessionIdx === prevSessionIdx + 1`) and both closes are finite and `> 0` with a finite ratio. Session `0`, missing-bar sessions, 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 > sessionMaxTs[last]` → `diagnostics.droppedAfterLastSession`; (4) lower-bound binary search over `sessionMaxTs` (matching `eventDayIndex` semantics: first pre-Vault session with `sessionMaxTs[d] >= knownAt`, so an after-close `17:00 ET` filing always anchors to the next trading session). Exact duplicate `(listingId, dayIndex)` events collapse to one (`diagnostics.duplicateEvents`), preserving `events.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + duplicateEvents`.
|
||||
- **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 close (or its eligible calendar date exceeds the last pre-Vault bar date) → `diagnostics.droppedAfterLastSession`; (4) when `exchangeCalendars` is supplied, eligible pre-Vault exchange session dates absent from `sessionDates` → `diagnostics.droppedMissingCalendarSession`; (5) lower-bound binary search over the listing's exchange close timestamps (or `sessionMaxTs` when `exchangeCalendars` is omitted), 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
|
||||
|
|
@ -183,10 +184,10 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (
|
|||
| 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` is not a valid strict calendar `YYYY-MM-DD` date |
|
||||
| `'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 or invalid/empty `eventsTableToEventRows` filter (`kinds`/`subtypes`) |
|
||||
| `'invalid_option'` | Invalid `benchmark` mode, malformed/missing `exchangeCalendars` entry, 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`)
|
||||
|
|
@ -194,4 +195,4 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (
|
|||
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'`):
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 704.39 ms`, `barsPerSec = 21,465,264 bars/s`, `eventsPerSec = 340,718 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `92bb8ae3`)
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 721.03 ms`, `barsPerSec = 20,970,040 bars/s`, `eventsPerSec = 332,858 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`)
|
||||
|
|
|
|||
|
|
@ -102,7 +102,7 @@ let evIdx = 0;
|
|||
|
||||
for (let l = 0; l < LISTINGS; l += 1) {
|
||||
const listingId = l + 1;
|
||||
const subtype = l % 2 === 0 ? '10-Q' : 'SEDAR_INTERIM';
|
||||
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;
|
||||
|
|
@ -148,6 +148,7 @@ 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);
|
||||
|
|
@ -174,7 +175,7 @@ for (let i = 0; i < result.input.events.length; i += 1) {
|
|||
|
||||
const checksumHex = checksum.toString(16).padStart(8, '0');
|
||||
|
||||
const EXPECTED_CHECKSUM = '92bb8ae3';
|
||||
const EXPECTED_CHECKSUM = '01b356d3';
|
||||
if (checksumHex !== EXPECTED_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
|
||||
|
|
|
|||
|
|
@ -28,10 +28,16 @@
|
|||
* `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
|
||||
* - Events with `knownAt >= vaultCutoffDate (00:00:00.000Z)` are excluded and
|
||||
* counted in `diagnostics.vaultExcludedEvents`.
|
||||
* - Remaining events for known listings anchor strictly to the first pre-Vault
|
||||
* session whose close timestamp `sessionMaxTs[d] >= knownAt` (matching
|
||||
* `eventDayIndex` semantics). An after-close event (e.g. `17:00 ET`) always
|
||||
* anchors to the next trading session, never the same day.
|
||||
* - When `exchangeCalendars` is supplied, 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` (which is always stamped at `16:00 ET`), and the eligible
|
||||
* session date is then mapped onto the shared `sessionDates` index.
|
||||
* - When `exchangeCalendars` is omitted, remaining events for known listings
|
||||
* anchor strictly to the first pre-Vault session whose close timestamp
|
||||
* `sessionMaxTs[d] >= knownAt` (matching `eventDayIndex` semantics). An
|
||||
* after-close event (e.g. `17:00 ET`) always anchors to the next trading
|
||||
* session, never the same day.
|
||||
*/
|
||||
|
||||
import {
|
||||
|
|
@ -102,12 +108,36 @@ export interface EventsTableFilter {
|
|||
/** Benchmark return construction mode for {@link buildEventStudyInput}. */
|
||||
export type EventStudyBenchmarkMode = 'equal_weight' | 'none';
|
||||
|
||||
/** Single exchange trading session close entry (`YYYY-MM-DD` date + actual close UTC epoch ms). */
|
||||
export interface ExchangeSessionClose {
|
||||
readonly date: string;
|
||||
readonly closeTs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Caller-supplied exchange close calendars for point-in-time event anchoring.
|
||||
*
|
||||
* Curated `bars_1d.ts` is stamped at `16:00 ET` even on exchange half-days (e.g.
|
||||
* `13:00 ET` on NYSE Black Friday). Passing `exchangeCalendars` anchors each
|
||||
* listing's events against its exchange's actual session close timestamps and
|
||||
* maps the resulting eligible session date onto the shared `sessionDates` index.
|
||||
*/
|
||||
export interface EventStudyExchangeCalendars {
|
||||
readonly calendars:
|
||||
| ReadonlyMap<string, readonly ExchangeSessionClose[]>
|
||||
| Readonly<Record<string, readonly ExchangeSessionClose[]>>;
|
||||
readonly listingCalendarId:
|
||||
| ReadonlyMap<number, string>
|
||||
| Readonly<Record<number, string>>;
|
||||
}
|
||||
|
||||
/** Input contract for {@link buildEventStudyInput}. */
|
||||
export interface BuildEventStudyInputParams {
|
||||
readonly bars: readonly BarRecord[];
|
||||
readonly events: readonly EventObservation[];
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly benchmark?: EventStudyBenchmarkMode;
|
||||
readonly exchangeCalendars?: EventStudyExchangeCalendars;
|
||||
}
|
||||
|
||||
/** Per-run diagnostic counters reported by {@link buildEventStudyInput}. */
|
||||
|
|
@ -116,6 +146,7 @@ export interface EventPanelDiagnostics {
|
|||
readonly vaultExcludedEvents: number;
|
||||
readonly droppedUnknownListing: number;
|
||||
readonly droppedAfterLastSession: number;
|
||||
readonly droppedMissingCalendarSession: number;
|
||||
readonly duplicateEvents: number;
|
||||
readonly duplicateBars: number;
|
||||
readonly nonPositiveCloseReturns: number;
|
||||
|
|
@ -127,12 +158,189 @@ export interface BuildEventStudyInputResult {
|
|||
readonly diagnostics: EventPanelDiagnostics;
|
||||
}
|
||||
|
||||
const STRICT_INT_KEY_RE = /^(?:0|-?[1-9]\d*)$/;
|
||||
|
||||
interface ParsedExchangeCalendar {
|
||||
readonly dayKeys: Int32Array;
|
||||
readonly closeTs: Float64Array;
|
||||
}
|
||||
|
||||
function parseStrictCalendarDayKey(value: unknown, field: string): number {
|
||||
return parseCalendarDayKey(value, field, (message, cause) =>
|
||||
new EventPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined)
|
||||
);
|
||||
}
|
||||
|
||||
function parseExchangeCalendars(
|
||||
raw: unknown,
|
||||
vaultCutoffDayKey: number
|
||||
): Map<number, ParsedExchangeCalendar> {
|
||||
if (!isPlainRecord(raw)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
'exchangeCalendars must be a non-null plain object.'
|
||||
);
|
||||
}
|
||||
|
||||
const rawCalendars = raw.calendars;
|
||||
let calendarEntries: Array<[unknown, unknown]>;
|
||||
if (rawCalendars instanceof Map) {
|
||||
calendarEntries = Array.from(rawCalendars.entries());
|
||||
} else if (isPlainRecord(rawCalendars)) {
|
||||
calendarEntries = Object.entries(rawCalendars);
|
||||
} else {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
'exchangeCalendars.calendars must be a Map or plain object.'
|
||||
);
|
||||
}
|
||||
|
||||
const parsedByCalId = new Map<string, ParsedExchangeCalendar>();
|
||||
for (let c = 0; c < calendarEntries.length; c += 1) {
|
||||
const [calId, rawSessions] = calendarEntries[c] as [unknown, unknown];
|
||||
if (typeof calId !== 'string' || calId.length === 0) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Invalid exchange calendar ID "${String(calId)}": expected a non-empty string.`
|
||||
);
|
||||
}
|
||||
if (!Array.isArray(rawSessions)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`exchangeCalendars.calendars["${calId}"] must be an array of { date, closeTs }.`
|
||||
);
|
||||
}
|
||||
|
||||
const n = rawSessions.length;
|
||||
const allDayKeys = new Int32Array(n);
|
||||
const allCloseTs = new Float64Array(n);
|
||||
const order = new Int32Array(n);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const entry: unknown = rawSessions[i];
|
||||
if (!isPlainRecord(entry)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`exchangeCalendars.calendars["${calId}"][${i}] must be a plain object.`
|
||||
);
|
||||
}
|
||||
const dk = parseStrictCalendarDayKey(
|
||||
entry.date,
|
||||
`exchangeCalendars.calendars["${calId}"][${i}].date`
|
||||
);
|
||||
const closeTs = entry.closeTs;
|
||||
if (!isValidEpochMs(closeTs)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Invalid closeTs in exchangeCalendars.calendars["${calId}"][${i}]: ${String(closeTs)}.`
|
||||
);
|
||||
}
|
||||
allDayKeys[i] = dk;
|
||||
allCloseTs[i] = normalizeZero(closeTs);
|
||||
order[i] = i;
|
||||
}
|
||||
|
||||
if (n > 1) {
|
||||
order.sort((a, b) => (allDayKeys[a] as number) - (allDayKeys[b] as number));
|
||||
}
|
||||
|
||||
let preCount = 0;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const currIdx = order[i] as number;
|
||||
const dk = allDayKeys[currIdx] as number;
|
||||
const ct = allCloseTs[currIdx] as number;
|
||||
if (i > 0) {
|
||||
const prevIdx = order[i - 1] as number;
|
||||
const prevDk = allDayKeys[prevIdx] as number;
|
||||
const prevCt = allCloseTs[prevIdx] as number;
|
||||
if (dk === prevDk) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Duplicate session date "${formatDayKeyUtc(dk)}" in exchange calendar "${calId}".`
|
||||
);
|
||||
}
|
||||
if (ct <= prevCt) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Non-ascending closeTs in exchange calendar "${calId}" at session "${formatDayKeyUtc(dk)}".`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (dk < vaultCutoffDayKey) {
|
||||
preCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const dayKeys = new Int32Array(preCount);
|
||||
const closeTs = new Float64Array(preCount);
|
||||
let outIdx = 0;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const idx = order[i] as number;
|
||||
const dk = allDayKeys[idx] as number;
|
||||
if (dk < vaultCutoffDayKey) {
|
||||
dayKeys[outIdx] = dk;
|
||||
closeTs[outIdx] = allCloseTs[idx] as number;
|
||||
outIdx += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (preCount > 0) {
|
||||
eventDayIndex(closeTs, closeTs[0] as number);
|
||||
}
|
||||
|
||||
parsedByCalId.set(calId, { dayKeys, closeTs });
|
||||
}
|
||||
|
||||
const rawMapping = raw.listingCalendarId;
|
||||
const listingCalendars = new Map<number, ParsedExchangeCalendar>();
|
||||
if (rawMapping instanceof Map) {
|
||||
for (const [rawLid, calId] of rawMapping.entries()) {
|
||||
if (!isValidInt32(rawLid)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Invalid listingId in exchangeCalendars.listingCalendarId: ${String(rawLid)}.`
|
||||
);
|
||||
}
|
||||
if (typeof calId !== 'string' || !parsedByCalId.has(calId)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Unknown exchange calendar "${String(calId)}" for listingId ${rawLid}.`
|
||||
);
|
||||
}
|
||||
listingCalendars.set(normalizeZero(rawLid), parsedByCalId.get(calId) as ParsedExchangeCalendar);
|
||||
}
|
||||
} else if (isPlainRecord(rawMapping)) {
|
||||
for (const [key, calId] of Object.entries(rawMapping)) {
|
||||
if (!STRICT_INT_KEY_RE.test(key)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Invalid listingId key "${key}" in exchangeCalendars.listingCalendarId.`
|
||||
);
|
||||
}
|
||||
const lid = Number(key);
|
||||
if (!isValidInt32(lid)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Invalid INT32 listingId key "${key}" in exchangeCalendars.listingCalendarId.`
|
||||
);
|
||||
}
|
||||
if (typeof calId !== 'string' || !parsedByCalId.has(calId)) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Unknown exchange calendar "${String(calId)}" for listingId ${lid}.`
|
||||
);
|
||||
}
|
||||
listingCalendars.set(normalizeZero(lid), parsedByCalId.get(calId) as ParsedExchangeCalendar);
|
||||
}
|
||||
} else {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
'exchangeCalendars.listingCalendarId must be a Map or plain object.'
|
||||
);
|
||||
}
|
||||
|
||||
return listingCalendars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a `MarketDataStore.events` `Table` into point-in-time {@link EventObservation}
|
||||
* rows, validating every row upfront (before applying optional exact-match allow-lists)
|
||||
|
|
@ -305,7 +513,9 @@ export function buildEventStudyInput(
|
|||
const vaultCutoffDayKey = parseStrictCalendarDayKey(params.vaultCutoffDate, 'vaultCutoffDate');
|
||||
const vaultCutoffMs = vaultCutoffDayKey * MS_PER_DAY;
|
||||
|
||||
const benchmark: EventStudyBenchmarkMode = params.benchmark ?? 'none';
|
||||
const rawBenchmark: unknown = params.benchmark;
|
||||
const benchmark: EventStudyBenchmarkMode =
|
||||
rawBenchmark === undefined ? 'none' : (rawBenchmark as EventStudyBenchmarkMode);
|
||||
if (benchmark !== 'none' && benchmark !== 'equal_weight') {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
|
|
@ -313,6 +523,11 @@ export function buildEventStudyInput(
|
|||
);
|
||||
}
|
||||
|
||||
const listingCalendars =
|
||||
params.exchangeCalendars !== undefined
|
||||
? parseExchangeCalendars(params.exchangeCalendars, vaultCutoffDayKey)
|
||||
: null;
|
||||
|
||||
if (!Array.isArray(params.bars)) {
|
||||
throw new EventPanelError('invalid_input', 'params.bars must be an array of BarRecord.');
|
||||
}
|
||||
|
|
@ -448,6 +663,7 @@ export function buildEventStudyInput(
|
|||
vaultExcludedEvents,
|
||||
droppedUnknownListing,
|
||||
droppedAfterLastSession: 0,
|
||||
droppedMissingCalendarSession: 0,
|
||||
duplicateEvents: 0,
|
||||
duplicateBars: 0,
|
||||
nonPositiveCloseReturns: 0,
|
||||
|
|
@ -643,7 +859,8 @@ export function buildEventStudyInput(
|
|||
}
|
||||
|
||||
// Classify and anchor events in strict precedence order:
|
||||
// (1) vaultExcludedEvents -> (2) droppedUnknownListing -> (3) droppedAfterLastSession -> (4) anchor.
|
||||
// (1) vaultExcludedEvents -> (2) droppedUnknownListing -> (3) droppedAfterLastSession
|
||||
// -> (4) droppedMissingCalendarSession (when exchangeCalendars is supplied) -> (5) anchor.
|
||||
const lastSessionMaxTs = sessionMaxTs[preCount - 1] as number;
|
||||
const candDay = new Int32Array(events.length);
|
||||
const candListing = new Int32Array(events.length);
|
||||
|
|
@ -651,6 +868,7 @@ export function buildEventStudyInput(
|
|||
let vaultExcludedEvents = 0;
|
||||
let droppedUnknownListing = 0;
|
||||
let droppedAfterLastSession = 0;
|
||||
let droppedMissingCalendarSession = 0;
|
||||
|
||||
for (let i = 0; i < events.length; i += 1) {
|
||||
const ev = events[i] as EventObservation;
|
||||
|
|
@ -660,30 +878,78 @@ export function buildEventStudyInput(
|
|||
continue;
|
||||
}
|
||||
|
||||
const l = listingIdToIdx.get(normalizeZero(ev.listingId));
|
||||
const normListingId = normalizeZero(ev.listingId);
|
||||
const l = listingIdToIdx.get(normListingId);
|
||||
if (l === undefined) {
|
||||
droppedUnknownListing += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (knownAt > lastSessionMaxTs) {
|
||||
droppedAfterLastSession += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lower-bound binary search: first session index with sessionMaxTs[lo] >= knownAt.
|
||||
let lo = 0;
|
||||
let hi = preCount - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if ((sessionMaxTs[mid] as number) < knownAt) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
let anchoredDayIdx: number;
|
||||
if (listingCalendars !== null) {
|
||||
const cal = listingCalendars.get(normListingId);
|
||||
if (cal === undefined) {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
`Missing exchange calendar mapping for listingId ${normListingId}.`
|
||||
);
|
||||
}
|
||||
const calLen = cal.closeTs.length;
|
||||
if (calLen === 0 || knownAt > (cal.closeTs[calLen - 1] as number)) {
|
||||
droppedAfterLastSession += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lower-bound binary search over the listing's actual exchange close timestamps.
|
||||
let lo = 0;
|
||||
let hi = calLen - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if ((cal.closeTs[mid] as number) < knownAt) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
|
||||
const eligibleDayKey = cal.dayKeys[lo] as number;
|
||||
if (eligibleDayKey > maxDayKey) {
|
||||
droppedAfterLastSession += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const mappedIdx =
|
||||
eligibleDayKey < minDayKey
|
||||
? -1
|
||||
: dayKeyToIdxArr !== null
|
||||
? (dayKeyToIdxArr[eligibleDayKey - minDayKey] as number)
|
||||
: ((dayKeyToIdxMap as Map<number, number>).get(eligibleDayKey) ?? -1);
|
||||
if (mappedIdx < 0) {
|
||||
droppedMissingCalendarSession += 1;
|
||||
continue;
|
||||
}
|
||||
anchoredDayIdx = mappedIdx;
|
||||
} else {
|
||||
if (knownAt > lastSessionMaxTs) {
|
||||
droppedAfterLastSession += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lower-bound binary search: first session index with sessionMaxTs[lo] >= knownAt.
|
||||
let lo = 0;
|
||||
let hi = preCount - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if ((sessionMaxTs[mid] as number) < knownAt) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
anchoredDayIdx = lo;
|
||||
}
|
||||
|
||||
candDay[candCount] = lo;
|
||||
candDay[candCount] = anchoredDayIdx;
|
||||
candListing[candCount] = l;
|
||||
candCount += 1;
|
||||
}
|
||||
|
|
@ -768,6 +1034,7 @@ export function buildEventStudyInput(
|
|||
vaultExcludedEvents,
|
||||
droppedUnknownListing,
|
||||
droppedAfterLastSession,
|
||||
droppedMissingCalendarSession,
|
||||
duplicateEvents,
|
||||
duplicateBars,
|
||||
nonPositiveCloseReturns,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
} 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 {
|
||||
|
|
@ -126,18 +127,47 @@ function createInMemoryTrialExecutor(): {
|
|||
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 dividendCase: {
|
||||
readonly listingId: number;
|
||||
readonly exDate: string;
|
||||
readonly exDayIdx: number;
|
||||
readonly expectedTotalReturn: number;
|
||||
readonly rawDropReturn: 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 (SEDAR_INTERIM)
|
||||
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);
|
||||
|
|
@ -147,16 +177,30 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
|||
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[] = [];
|
||||
|
||||
// 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 prices = new Float64Array(listingCount);
|
||||
const rawPrices = new Float64Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
prices[l] = 15 + l * 1.25;
|
||||
rawPrices[l] = 15 + l * 1.25;
|
||||
}
|
||||
|
||||
for (let t = 0; t < allDates.length; t += 1) {
|
||||
|
|
@ -172,11 +216,30 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
|||
remainingBoostSessions[l] = remainingBoostSessions[l]! - 1;
|
||||
}
|
||||
const dailyRet = boost + (rand() * 2 - 1) * 0.006;
|
||||
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
|
||||
|
||||
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6));
|
||||
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 {
|
||||
rawPrices[l] = Math.max(0.5, rawPrices[l]! * (1 + dailyRet));
|
||||
}
|
||||
|
||||
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : rawPrices[l]!;
|
||||
barRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
session_date: date,
|
||||
ts: closeTs,
|
||||
open: closeVal,
|
||||
high: closeVal,
|
||||
|
|
@ -189,26 +252,26 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
|||
}
|
||||
|
||||
// Schedule staggered after-close filing events across pre-2023 and post-2023 sessions
|
||||
// (plus post-cutoff filings to verify Vault isolation).
|
||||
// (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' : 'SEDAR_INTERIM';
|
||||
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,
|
||||
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 subtype filing on another listing to verify subtype filtering.
|
||||
// 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]!,
|
||||
|
|
@ -216,7 +279,7 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
|||
known_at: afterCloseTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: 'S-3',
|
||||
subtype: 'other',
|
||||
payload_json: '{}',
|
||||
});
|
||||
}
|
||||
|
|
@ -224,11 +287,21 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
|||
|
||||
return {
|
||||
listingIds,
|
||||
usListingIds,
|
||||
caListingIds,
|
||||
allDates,
|
||||
vaultCutoffDate,
|
||||
vaultCutoffTs,
|
||||
barRows,
|
||||
adjFactorRows,
|
||||
eventRows,
|
||||
dividendCase: {
|
||||
listingId: divListingId,
|
||||
exDate: divExDate,
|
||||
exDayIdx: divExIdx,
|
||||
expectedTotalReturn: divExpectedTotalReturn,
|
||||
rawDropReturn: divRawDropReturn,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -252,19 +325,80 @@ function createFakeDuckDbExecutor(fixture: QmFilingsFixture): {
|
|||
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')) {
|
||||
// Bound params: [...listingIds, fromIso, toIso, asOfIso]
|
||||
const nIds = fixture.listingIds.length;
|
||||
const idSet = new Set<number>(params.slice(0, nIds) as number[]);
|
||||
const fromMs = Date.parse(params[nIds] as string);
|
||||
const toMs = Date.parse(params[nIds + 1] as string);
|
||||
const asOfMs = Date.parse(params[nIds + 2] as string);
|
||||
return fixture.barRows.filter(row => {
|
||||
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;
|
||||
return idSet.has(lid) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs;
|
||||
});
|
||||
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')) {
|
||||
|
|
@ -308,6 +442,7 @@ describe('qmFilings end-to-end event study (headless, no database)', () => {
|
|||
executor: duck.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: fixture.vaultCutoffTs,
|
||||
immutableAdjFactorsPath: IMMUTABLE_ADJ_PATH,
|
||||
barBatchSize: 256,
|
||||
});
|
||||
|
||||
|
|
@ -320,7 +455,7 @@ describe('qmFilings end-to-end event study (headless, no database)', () => {
|
|||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
adjustment: 'raw',
|
||||
adjustment: 'total',
|
||||
})
|
||||
);
|
||||
const eventsTable = await store.events({
|
||||
|
|
@ -332,7 +467,7 @@ describe('qmFilings end-to-end event study (headless, no database)', () => {
|
|||
|
||||
const events = eventsTableToEventRows(eventsTable, {
|
||||
kinds: ['filing'],
|
||||
subtypes: ['10-Q', 'SEDAR_INTERIM'],
|
||||
subtypes: ['10-q', 'interim_financial_statements'],
|
||||
});
|
||||
const built = buildEventStudyInput({
|
||||
bars,
|
||||
|
|
@ -347,7 +482,12 @@ describe('qmFilings end-to-end event study (headless, no database)', () => {
|
|||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'qmfilings_interim_10q_sedar_event_study',
|
||||
params: { kinds: ['filing'], subtypes: ['10-Q', 'SEDAR_INTERIM'], preDays: 5, postDays: 5 },
|
||||
params: {
|
||||
kinds: ['filing'],
|
||||
subtypes: ['10-q', 'interim_financial_statements'],
|
||||
preDays: 5,
|
||||
postDays: 5,
|
||||
},
|
||||
universe: 'US_CA_EQ_FIXTURE',
|
||||
horizon: '5d',
|
||||
},
|
||||
|
|
@ -356,30 +496,54 @@ describe('qmFilings end-to-end event study (headless, no database)', () => {
|
|||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
});
|
||||
|
||||
return { fixture, duck, ledger, built, studyResult };
|
||||
return { fixture, duck, ledger, events, built, studyResult };
|
||||
}
|
||||
|
||||
it('flows DuckDbMarketDataStore -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => {
|
||||
it('flows DuckDbMarketDataStore (total-adjusted) -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => {
|
||||
const clean = await runQmFilingsStudy(false);
|
||||
|
||||
// DuckDB connection budget SET statements ran once; 2 queries ran (bars + events).
|
||||
// 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(2);
|
||||
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 (`fromIso`, `toIso`, `asOfIso`) in every executor query
|
||||
// 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) {
|
||||
const boundTimestamps = q.params.slice(-3) as string[];
|
||||
expect(boundTimestamps).toHaveLength(3);
|
||||
for (const iso of boundTimestamps) {
|
||||
const parsedMs = Date.parse(iso);
|
||||
expect(Number.isFinite(parsedMs)).toBe(true);
|
||||
expect(parsedMs).toBeLessThan(clean.fixture.vaultCutoffTs);
|
||||
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);
|
||||
|
||||
// Event study succeeded and appended exactly one `event_study` row to trial_ledger.
|
||||
expect(clean.studyResult.status).toBe('ok');
|
||||
|
|
@ -387,6 +551,13 @@ describe('qmFilings end-to-end event study (headless, no database)', () => {
|
|||
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');
|
||||
|
|
|
|||
|
|
@ -548,6 +548,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva
|
|||
vaultExcludedEvents: 2,
|
||||
droppedUnknownListing: 1,
|
||||
droppedAfterLastSession: 1,
|
||||
droppedMissingCalendarSession: 0,
|
||||
duplicateEvents: 1,
|
||||
duplicateBars: 0,
|
||||
nonPositiveCloseReturns: 0,
|
||||
|
|
@ -560,6 +561,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva
|
|||
d.vaultExcludedEvents +
|
||||
d.droppedUnknownListing +
|
||||
d.droppedAfterLastSession +
|
||||
d.droppedMissingCalendarSession +
|
||||
d.duplicateEvents
|
||||
).toBe(events.length);
|
||||
|
||||
|
|
@ -646,6 +648,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva
|
|||
vaultExcludedEvents: 1,
|
||||
droppedUnknownListing: 1,
|
||||
droppedAfterLastSession: 0,
|
||||
droppedMissingCalendarSession: 0,
|
||||
duplicateEvents: 0,
|
||||
duplicateBars: 0,
|
||||
nonPositiveCloseReturns: 0,
|
||||
|
|
@ -705,6 +708,16 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva
|
|||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars: [],
|
||||
events: [],
|
||||
vaultCutoffDate: '2024-02-01',
|
||||
benchmark: null as unknown as 'none',
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
|
||||
const goodBar = makeBar(1, '2024-01-05', 10);
|
||||
for (const badBar of [
|
||||
|
|
@ -749,4 +762,245 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva
|
|||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('uses caller-supplied exchangeCalendars for half-day US vs CA close times and cross-border holidays', () => {
|
||||
// Black Friday 2024-11-29: curated bars_1d.ts stamps BOTH NYSE and TSX at 16:00 ET (21:00 UTC),
|
||||
// even though NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at 16:00 ET (21:00 UTC).
|
||||
// Also include US Thanksgiving 2024-11-28 (TSX open, NYSE closed).
|
||||
const sharedDates = ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02', '2024-12-03'];
|
||||
const nyseId = 10_001;
|
||||
const tsxId = 50_001;
|
||||
|
||||
const bars: BarRecord[] = [
|
||||
// NYSE bars (closed 2024-11-28; half-day 2024-11-29 still stamped 21:00 UTC by curator)
|
||||
makeBar(nyseId, '2024-11-27', 100, 21),
|
||||
makeBar(nyseId, '2024-11-29', 102, 21),
|
||||
makeBar(nyseId, '2024-12-02', 105, 21),
|
||||
makeBar(nyseId, '2024-12-03', 106, 21),
|
||||
// TSX bars (open all 5 days, stamped 21:00 UTC)
|
||||
makeBar(tsxId, '2024-11-27', 50, 21),
|
||||
makeBar(tsxId, '2024-11-28', 50.5, 21),
|
||||
makeBar(tsxId, '2024-11-29', 51, 21),
|
||||
makeBar(tsxId, '2024-12-02', 52, 21),
|
||||
makeBar(tsxId, '2024-12-03', 52.5, 21),
|
||||
];
|
||||
|
||||
const nyseCalendar = [
|
||||
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET
|
||||
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET early close
|
||||
{ date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET
|
||||
{ date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET
|
||||
];
|
||||
const tsxCalendar = [
|
||||
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) }, // 16:00 ET
|
||||
{ date: '2024-11-28', closeTs: makeUtcMs('2024-11-28', 21) }, // 16:00 ET (US holiday)
|
||||
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 21) }, // 16:00 ET (normal close)
|
||||
{ date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // 16:00 ET
|
||||
{ date: '2024-12-03', closeTs: makeUtcMs('2024-12-03', 21) }, // 16:00 ET
|
||||
];
|
||||
|
||||
// Filing published at 14:00 ET (19:00 UTC) on Friday 2024-11-29:
|
||||
// - NYSE already closed at 13:00 ET (18:00 UTC) -> MUST anchor to Monday 2024-12-02 (index 3).
|
||||
// - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2024-11-29 (index 2).
|
||||
// Filing published at 12:30 ET (17:30 UTC) on Friday 2024-11-29 for NYSE -> anchors to Friday 2024-11-29 (index 2).
|
||||
// Filing published on US Thanksgiving 2024-11-28 at 10:00 ET (15:00 UTC):
|
||||
// - NYSE closed -> anchors to Friday 2024-11-29 (index 2, collapses with 12:30 ET NYSE event).
|
||||
// - TSX open -> anchors to Thursday 2024-11-28 (index 1).
|
||||
const events: EventObservation[] = [
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' },
|
||||
{ listingId: tsxId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: 'interim_financial_statements' },
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 17, 30), kind: 'filing', subtype: '10-q' },
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: '10-q' },
|
||||
{ listingId: tsxId, knownAt: makeUtcMs('2024-11-28', 15), kind: 'filing', subtype: 'interim_financial_statements' },
|
||||
];
|
||||
|
||||
const mapResult = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate: '2024-12-04',
|
||||
exchangeCalendars: {
|
||||
calendars: new Map([
|
||||
['XNYS', nyseCalendar],
|
||||
['XTSE', tsxCalendar],
|
||||
]),
|
||||
listingCalendarId: new Map([
|
||||
[nyseId, 'XNYS'],
|
||||
[tsxId, 'XTSE'],
|
||||
]),
|
||||
},
|
||||
});
|
||||
|
||||
expect(mapResult.input.sessionDates).toEqual(sharedDates);
|
||||
expect(mapResult.input.events).toEqual([
|
||||
{ entityId: tsxId, dayIndex: 1 }, // 2024-11-28
|
||||
{ entityId: nyseId, dayIndex: 2 }, // 2024-11-29 (12:30 ET & Thanksgiving deduped)
|
||||
{ entityId: tsxId, dayIndex: 2 }, // 2024-11-29 (14:00 ET still before TSX 16:00 ET close)
|
||||
{ entityId: nyseId, dayIndex: 3 }, // 2024-12-02 (14:00 ET after NYSE 13:00 ET close)
|
||||
]);
|
||||
expect(mapResult.diagnostics.duplicateEvents).toBe(1);
|
||||
expect(mapResult.diagnostics.droppedAfterLastSession).toBe(0);
|
||||
expect(mapResult.diagnostics.droppedMissingCalendarSession).toBe(0);
|
||||
|
||||
// Record-based calendars with shuffled sessions/bars/events produce bit-identical output.
|
||||
const recordResult = buildEventStudyInput({
|
||||
bars: shuffle(bars, 7),
|
||||
events: shuffle(events, 11),
|
||||
vaultCutoffDate: '2024-12-04',
|
||||
exchangeCalendars: {
|
||||
calendars: {
|
||||
XNYS: shuffle(nyseCalendar, 13),
|
||||
XTSE: shuffle(tsxCalendar, 17),
|
||||
},
|
||||
listingCalendarId: {
|
||||
[nyseId]: 'XNYS',
|
||||
[tsxId]: 'XTSE',
|
||||
},
|
||||
},
|
||||
});
|
||||
expectBitIdenticalEventStudyInput(recordResult.input, mapResult.input);
|
||||
expect(recordResult.diagnostics).toEqual(mapResult.diagnostics);
|
||||
|
||||
// NYSE-only study: filing at 14:00 ET on 2024-11-29 anchors to Monday 2024-12-02 (index 2 in NYSE-only dates),
|
||||
// even though curated bars_1d.ts for 2024-11-29 is stamped at 16:00 ET (21:00 UTC).
|
||||
const nyseOnly = buildEventStudyInput({
|
||||
bars: bars.filter(b => b.listingId === nyseId),
|
||||
events: [
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' },
|
||||
],
|
||||
vaultCutoffDate: '2024-12-04',
|
||||
exchangeCalendars: {
|
||||
calendars: { XNYS: nyseCalendar },
|
||||
listingCalendarId: { [nyseId]: 'XNYS' },
|
||||
},
|
||||
});
|
||||
expect(nyseOnly.input.sessionDates).toEqual(['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03']);
|
||||
expect(nyseOnly.input.events).toEqual([{ entityId: nyseId, dayIndex: 2 }]); // 2024-12-02
|
||||
});
|
||||
|
||||
it('enforces Vault fencing, drop counters, and strict validation on exchangeCalendars', () => {
|
||||
const nyseId = 10_001;
|
||||
const bars = [
|
||||
makeBar(nyseId, '2024-11-27', 100, 21),
|
||||
makeBar(nyseId, '2024-11-29', 102, 21),
|
||||
];
|
||||
const nyseCalendar = [
|
||||
{ date: '2024-11-26', closeTs: makeUtcMs('2024-11-26', 21) }, // before first bar -> droppedMissingCalendarSession
|
||||
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) },
|
||||
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-29', 18) }, // 13:00 ET half-day
|
||||
{ date: '2024-12-02', closeTs: makeUtcMs('2024-12-02', 21) }, // post-cutoff (excluded from calendar)
|
||||
];
|
||||
|
||||
const res = buildEventStudyInput({
|
||||
bars,
|
||||
events: [
|
||||
// Anchors to 2024-11-26 which has no bar in sessionDates -> droppedMissingCalendarSession
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-26', 15), kind: 'filing', subtype: '10-q' },
|
||||
// 14:00 ET on 2024-11-29 is after 13:00 ET close; 2024-12-02 is Vault-excluded -> droppedAfterLastSession
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-29', 19), kind: 'filing', subtype: '10-q' },
|
||||
],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: {
|
||||
calendars: { XNYS: nyseCalendar },
|
||||
listingCalendarId: { [nyseId]: 'XNYS' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.input.events).toEqual([]);
|
||||
expect(res.diagnostics.droppedMissingCalendarSession).toBe(1);
|
||||
expect(res.diagnostics.droppedAfterLastSession).toBe(1);
|
||||
expect(res.diagnostics.vaultExcludedEvents).toBe(0);
|
||||
|
||||
// Invalid exchangeCalendars shapes and values
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars,
|
||||
events: [],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: null as unknown as NonNullable<
|
||||
Parameters<typeof buildEventStudyInput>[0]['exchangeCalendars']
|
||||
>,
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars,
|
||||
events: [],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: {
|
||||
calendars: {
|
||||
XNYS: [{ date: '2024-02-30', closeTs: makeUtcMs('2024-02-28', 21) }],
|
||||
},
|
||||
listingCalendarId: { [nyseId]: 'XNYS' },
|
||||
},
|
||||
}),
|
||||
'invalid_date'
|
||||
);
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars,
|
||||
events: [],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: {
|
||||
calendars: {
|
||||
XNYS: [
|
||||
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) },
|
||||
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-27', 21) },
|
||||
],
|
||||
},
|
||||
listingCalendarId: { [nyseId]: 'XNYS' },
|
||||
},
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars,
|
||||
events: [],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: {
|
||||
calendars: {
|
||||
XNYS: [
|
||||
{ date: '2024-11-27', closeTs: makeUtcMs('2024-11-29', 21) },
|
||||
{ date: '2024-11-29', closeTs: makeUtcMs('2024-11-27', 21) },
|
||||
],
|
||||
},
|
||||
listingCalendarId: { [nyseId]: 'XNYS' },
|
||||
},
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars,
|
||||
events: [],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: {
|
||||
calendars: { XNYS: nyseCalendar },
|
||||
listingCalendarId: { [nyseId]: 'UNKNOWN_CAL' },
|
||||
},
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
expectEventPanelError(
|
||||
() =>
|
||||
buildEventStudyInput({
|
||||
bars,
|
||||
events: [
|
||||
{ listingId: nyseId, knownAt: makeUtcMs('2024-11-27', 15), kind: 'filing', subtype: '10-q' },
|
||||
],
|
||||
vaultCutoffDate: '2024-12-02',
|
||||
exchangeCalendars: {
|
||||
calendars: { XNYS: nyseCalendar },
|
||||
listingCalendarId: {},
|
||||
},
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue