diff --git a/libs/research/README.md b/libs/research/README.md index 527a8551..919c2b6d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -167,16 +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?, 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. +- **`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). - - `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]`). +- **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 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`. +- **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 @@ -187,12 +187,12 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` ( | `'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, malformed/missing `exchangeCalendars` entry, or invalid/empty `eventsTableToEventRows` filter (`kinds`/`subtypes`) | +| `'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'`): +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 = 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`) +- **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`) diff --git a/libs/research/scripts/benchmark-event-panel.ts b/libs/research/scripts/benchmark-event-panel.ts index bf80796b..de8e2c60 100644 --- a/libs/research/scripts/benchmark-event-panel.ts +++ b/libs/research/scripts/benchmark-event-panel.ts @@ -1,4 +1,8 @@ -import { type EventObservation, buildEventStudyInput } from '../src/event-panel'; +import { + type EventObservation, + type EventStudyExchangeCalendars, + buildEventStudyInput, +} from '../src/event-panel'; import type { BarRecord } from '../src/market-data-store'; const SEED = 20261129; @@ -129,6 +133,22 @@ for (let l = 0; l < LISTINGS; l += 1) { } } +const sessionCloses = calendar.dates.map((date, idx) => ({ + date, + closeTs: calendar.closeTs[idx] as number, +})); +const listingCalendarId = new Map(); +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({ @@ -136,6 +156,7 @@ const result = buildEventStudyInput({ events, vaultCutoffDate, benchmark: 'equal_weight', + exchangeCalendars, }); const elapsedMs = performance.now() - started; diff --git a/libs/research/src/event-panel.ts b/libs/research/src/event-panel.ts index 70804459..53928a35 100644 --- a/libs/research/src/event-panel.ts +++ b/libs/research/src/event-panel.ts @@ -16,8 +16,10 @@ * - `entityReturns` maps each pre-cutoff `listingId` (inserted in ascending order) * to a `Float64Array` aligned 1:1 with `sessionDates`. * - Simple close-to-close return `close[d] / close[d - 1] - 1` is computed - * strictly across consecutive calendar sessions (`currSessionIdx === prevSessionIdx + 1`) - * where both closes are finite and `> 0` and the resulting return is finite. + * strictly across consecutive exchange-calendar sessions for that listing + * (`currCalIdx === prevCalIdx + 1`) where both closes are finite and `> 0` and + * the resulting return is finite. If an open exchange session is missing for a + * listing (or for all listings), the subsequent session's return is `NaN`. * - `NaN` is written at session `0`, on any missing-bar session, on the first * resumption session after a gap, and on any non-positive/non-finite close or * overflowing ratio (`eventStudy` rejects `±Infinity` with `NON_FINITE_RETURN` @@ -28,16 +30,13 @@ * `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`. - * - 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. + * - Caller-supplied `exchangeCalendars` is required and must cover every pre-Vault + * bar date of every mapped listing. 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. An after-close or post-half-day-close + * event always anchors to the next trading session, never the same day. */ import { @@ -137,7 +136,7 @@ export interface BuildEventStudyInputParams { readonly events: readonly EventObservation[]; readonly vaultCutoffDate: string; readonly benchmark?: EventStudyBenchmarkMode; - readonly exchangeCalendars?: EventStudyExchangeCalendars; + readonly exchangeCalendars: EventStudyExchangeCalendars; } /** Per-run diagnostic counters reported by {@link buildEventStudyInput}. */ @@ -161,8 +160,23 @@ export interface BuildEventStudyInputResult { const STRICT_INT_KEY_RE = /^(?:0|-?[1-9]\d*)$/; interface ParsedExchangeCalendar { + readonly id: string; readonly dayKeys: Int32Array; readonly closeTs: Float64Array; + readonly minDayKey: number; + readonly maxDayKey: number; + readonly dayKeyToIdxArr: Int32Array | null; + readonly dayKeyToIdxMap: Map | null; +} + +function lookupCalendarDayIdx(cal: ParsedExchangeCalendar, dayKey: number): number { + if (cal.dayKeys.length === 0 || dayKey < cal.minDayKey || dayKey > cal.maxDayKey) { + return -1; + } + if (cal.dayKeyToIdxArr !== null) { + return cal.dayKeyToIdxArr[dayKey - cal.minDayKey] as number; + } + return (cal.dayKeyToIdxMap as Map).get(dayKey) ?? -1; } function parseStrictCalendarDayKey(value: unknown, field: string): number { @@ -283,11 +297,38 @@ function parseExchangeCalendars( } } + let minDayKey = 0; + let maxDayKey = -1; + let dayKeyToIdxArr: Int32Array | null = null; + let dayKeyToIdxMap: Map | null = null; if (preCount > 0) { eventDayIndex(closeTs, closeTs[0] as number); + minDayKey = dayKeys[0] as number; + maxDayKey = dayKeys[preCount - 1] as number; + const calSpan = maxDayKey - minDayKey + 1; + if (calSpan <= MAX_DIRECT_DAY_SPAN) { + dayKeyToIdxArr = new Int32Array(calSpan); + dayKeyToIdxArr.fill(-1); + for (let i = 0; i < preCount; i += 1) { + dayKeyToIdxArr[(dayKeys[i] as number) - minDayKey] = i; + } + } else { + dayKeyToIdxMap = new Map(); + for (let i = 0; i < preCount; i += 1) { + dayKeyToIdxMap.set(dayKeys[i] as number, i); + } + } } - parsedByCalId.set(calId, { dayKeys, closeTs }); + parsedByCalId.set(calId, { + id: calId, + dayKeys, + closeTs, + minDayKey, + maxDayKey, + dayKeyToIdxArr, + dayKeyToIdxMap, + }); } const rawMapping = raw.listingCalendarId; @@ -523,10 +564,7 @@ export function buildEventStudyInput( ); } - const listingCalendars = - params.exchangeCalendars !== undefined - ? parseExchangeCalendars(params.exchangeCalendars, vaultCutoffDayKey) - : null; + const listingCalendars = parseExchangeCalendars(params.exchangeCalendars, vaultCutoffDayKey); if (!Array.isArray(params.bars)) { throw new EventPanelError('invalid_input', 'params.bars must be an array of BarRecord.'); @@ -544,7 +582,7 @@ export function buildEventStudyInput( // Pass 1 over bars: validate structure, build pre-cutoff calendar, count bars per listing. // Never access `bar.close` when the bar's UTC dayKey reaches or exceeds `vaultCutoffDayKey`. const postCutoffDays = new Set(); - const preCutoffDayMaxTs = new Map(); + const preCutoffDays = new Set(); const listingBarCounts = new Map(); let preCutoffBarTotal = 0; @@ -586,10 +624,7 @@ export function buildEventStudyInput( throw new EventPanelError('invalid_bar', `Invalid close at bars[${i}]: expected a number.`); } - const prevMaxTs = preCutoffDayMaxTs.get(dayKey); - if (prevMaxTs === undefined || ts > prevMaxTs) { - preCutoffDayMaxTs.set(dayKey, ts); - } + preCutoffDays.add(dayKey); const normListingId = normalizeZero(listingId); listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1); @@ -672,29 +707,22 @@ export function buildEventStudyInput( } // Build strictly ascending pre-cutoff session calendar. - const preCount = preCutoffDayMaxTs.size; + const preCount = preCutoffDays.size; const preDayKeys = new Int32Array(preCount); { let idx = 0; - for (const dayKey of preCutoffDayMaxTs.keys()) { + for (const dayKey of preCutoffDays) { preDayKeys[idx] = dayKey; idx += 1; } preDayKeys.sort(); } - const sessionMaxTs = new Float64Array(preCount); const sessionDates: string[] = new Array(preCount); for (let i = 0; i < preCount; i += 1) { - const dk = preDayKeys[i] as number; - sessionMaxTs[i] = preCutoffDayMaxTs.get(dk) as number; - sessionDates[i] = formatDayKeyUtc(dk); + sessionDates[i] = formatDayKeyUtc(preDayKeys[i] as number); } - // Validate sessionMaxTs once against eventDayIndex so the per-event O(log T) lower-bound - // search matches eventDayIndex semantics without repeating its O(T) calendar scan. - eventDayIndex(sessionMaxTs, sessionMaxTs[0] as number); - // Sort unique listingIds ascending for deterministic entityReturns Map insertion order. const listingCount = listingBarCounts.size; const sortedListingIds = new Int32Array(listingCount); @@ -778,6 +806,14 @@ export function buildEventStudyInput( for (let l = 0; l < listingCount; l += 1) { const listingId = sortedListingIds[l] as number; + const cal = listingCalendars.get(listingId); + if (cal === undefined) { + throw new EventPanelError( + 'invalid_option', + `Missing exchange calendar mapping for listingId ${listingId}.` + ); + } + const bStart = barOffsets[l] as number; const bEnd = barOffsets[l + 1] as number; @@ -812,13 +848,32 @@ export function buildEventStudyInput( } const uniqueEnd = write + 1; + // Verify that the listing's mapped exchange calendar covers every pre-Vault bar date, + // and compute close-to-close returns strictly across consecutive exchange sessions. + const firstSIdx = barSessionIdx[bStart] as number; + let prevCalIdx = lookupCalendarDayIdx(cal, preDayKeys[firstSIdx] as number); + if (prevCalIdx < 0) { + throw new EventPanelError( + 'invalid_option', + `Exchange calendar "${cal.id}" for listingId ${listingId} does not cover pre-Vault bar session ${sessionDates[firstSIdx]}.` + ); + } + const returns = new Float64Array(preCount); returns.fill(Number.NaN); for (let i = bStart + 1; i < uniqueEnd; i += 1) { - const prevSIdx = barSessionIdx[i - 1] as number; const currSIdx = barSessionIdx[i] as number; - if (currSIdx !== prevSIdx + 1) { + const currCalIdx = lookupCalendarDayIdx(cal, preDayKeys[currSIdx] as number); + if (currCalIdx < 0) { + throw new EventPanelError( + 'invalid_option', + `Exchange calendar "${cal.id}" for listingId ${listingId} does not cover pre-Vault bar session ${sessionDates[currSIdx]}.` + ); + } + const isConsecutiveSession = currCalIdx === prevCalIdx + 1; + prevCalIdx = currCalIdx; + if (!isConsecutiveSession) { continue; } const prevClose = barClose[i - 1] as number; @@ -860,8 +915,7 @@ export function buildEventStudyInput( // Classify and anchor events in strict precedence order: // (1) vaultExcludedEvents -> (2) droppedUnknownListing -> (3) droppedAfterLastSession - // -> (4) droppedMissingCalendarSession (when exchangeCalendars is supplied) -> (5) anchor. - const lastSessionMaxTs = sessionMaxTs[preCount - 1] as number; + // -> (4) droppedMissingCalendarSession -> (5) anchor via the listing's exchange calendar. const candDay = new Int32Array(events.length); const candListing = new Int32Array(events.length); let candCount = 0; @@ -885,71 +939,43 @@ export function buildEventStudyInput( continue; } - 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).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; + const cal = listingCalendars.get(normListingId) as ParsedExchangeCalendar; + const calLen = cal.closeTs.length; + if (calLen === 0 || knownAt > (cal.closeTs[calLen - 1] as number)) { + droppedAfterLastSession += 1; + continue; } - candDay[candCount] = anchoredDayIdx; + // 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).get(eligibleDayKey) ?? -1); + if (mappedIdx < 0) { + droppedMissingCalendarSession += 1; + continue; + } + + candDay[candCount] = mappedIdx; candListing[candCount] = l; candCount += 1; } diff --git a/libs/research/test/event-panel-e2e.test.ts b/libs/research/test/event-panel-e2e.test.ts index 12b335bb..4ac07daa 100644 --- a/libs/research/test/event-panel-e2e.test.ts +++ b/libs/research/test/event-panel-e2e.test.ts @@ -7,6 +7,7 @@ import { runEventStudy, type DuckDbExecutor, type DuckDbParam, + type EventStudyExchangeCalendars, type TableRow, type TrialLedgerExecutor, } from '@stock-bot/research'; @@ -145,6 +146,7 @@ interface QmFilingsFixture { readonly barRows: TableRow[]; readonly adjFactorRows: AdjFactorRow[]; readonly eventRows: TableRow[]; + readonly exchangeCalendars: EventStudyExchangeCalendars; readonly dividendCase: { readonly listingId: number; readonly exDate: string; @@ -152,6 +154,16 @@ interface QmFilingsFixture { 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[] { @@ -183,6 +195,42 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { 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(); + 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). @@ -233,7 +281,14 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { divRawDropReturn = nextRaw / prevRaw - 1; rawPrices[l] = nextRaw; } else { - rawPrices[l] = Math.max(0.5, rawPrices[l]! * (1 + dailyRet)); + 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]!; @@ -283,6 +338,37 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { 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 { @@ -295,6 +381,7 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { barRows, adjFactorRows, eventRows, + exchangeCalendars, dividendCase: { listingId: divListingId, exDate: divExDate, @@ -302,6 +389,16 @@ function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture { expectedTotalReturn: divExpectedTotalReturn, rawDropReturn: divRawDropReturn, }, + halfDayCase: { + usListingId: halfDayUsListingId, + caListingId: halfDayCaListingId, + halfDayDate, + halfDayIdx, + nextSessionDate, + nextSessionIdx, + usHalfDayReturn, + usNextSessionReturn, + }, }; } @@ -474,6 +571,7 @@ describe('qmFilings end-to-end event study (headless, no database)', () => { events, vaultCutoffDate: fixture.vaultCutoffDate, benchmark: 'equal_weight', + exchangeCalendars: fixture.exchangeCalendars, }); const studyResult = await runEventStudy(ledger.executor, { @@ -545,6 +643,31 @@ describe('qmFilings end-to-end event study (headless, no database)', () => { 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') { diff --git a/libs/research/test/event-panel.test.ts b/libs/research/test/event-panel.test.ts index b5aafbf5..a5979670 100644 --- a/libs/research/test/event-panel.test.ts +++ b/libs/research/test/event-panel.test.ts @@ -8,6 +8,7 @@ import { type BarRecord, type EventObservation, type EventPanelErrorCode, + type EventStudyExchangeCalendars, type Table, } from '@stock-bot/research'; import { @@ -51,6 +52,22 @@ function makeBar(listingId: number, date: string, close: number, hourUtc = 21): }; } +function makeExchangeCalendars( + listingIds: readonly number[], + dates: readonly string[], + hourUtc = 21 +): EventStudyExchangeCalendars { + const sessions = dates.map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) })); + const listingCalendarId = new Map(); + for (const id of listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { + calendars: new Map([['XNYS', sessions]]), + listingCalendarId, + }; +} + function createSeededRng(seed: number): () => number { let state = seed >>> 0; return () => { @@ -311,10 +328,13 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva { listingId: 10, knownAt: makeUtcMs(dates[1]!, 21), kind: 'filing', subtype: '10-Q' }, ]; + const exchangeCalendars = makeExchangeCalendars([10, 20], dates); + const resNone = buildEventStudyInput({ bars, events, vaultCutoffDate: '2024-02-01', + exchangeCalendars, }); expect(resNone.input.sessionDates).toEqual(dates); @@ -340,6 +360,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events, vaultCutoffDate: '2024-02-01', benchmark: 'equal_weight', + exchangeCalendars, }); expect(resEq.input.benchmarkReturns).toBeInstanceOf(Float64Array); const b = resEq.input.benchmarkReturns!; @@ -366,6 +387,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events: [], vaultCutoffDate: '2024-02-01', benchmark: 'equal_weight', + exchangeCalendars: makeExchangeCalendars([1], dates), }); const series = res.input.entityReturns.get(1)!; @@ -428,6 +450,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars, events, vaultCutoffDate: '2024-01-13', + exchangeCalendars: makeExchangeCalendars([1, 2], dates), }); expect(res.input.events).toEqual([ @@ -450,10 +473,13 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva const b1 = makeBar(1, dates[1]!, 12); const b2 = makeBar(1, dates[2]!, Number.NaN); + const exchangeCalendars = makeExchangeCalendars([1], dates); + const exactDup = buildEventStudyInput({ bars: [b0, { ...b0 }, b1, b2, { ...b2 }], events: [], vaultCutoffDate: '2024-02-01', + exchangeCalendars, }); expect(exactDup.diagnostics.duplicateBars).toBe(2); expect(exactDup.input.entityReturns.get(1)![1]).toBeCloseTo(0.2, 12); @@ -465,6 +491,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars: [b0, { ...b0, close: 10.01 }, b1], events: [], vaultCutoffDate: '2024-02-01', + exchangeCalendars, }), 'duplicate_bar' ); @@ -476,6 +503,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1], events: [], vaultCutoffDate: '2024-02-01', + exchangeCalendars, }), 'duplicate_bar' ); @@ -533,11 +561,14 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva { listingId: 10, knownAt: makeUtcMs(dates[5]!, 22), kind: 'filing', subtype: '10-Q' }, ]; + const exchangeCalendars = makeExchangeCalendars([10], dates); + const trappedResult = buildEventStudyInput({ bars: [...preBars, ...postBars], events, vaultCutoffDate, benchmark: 'equal_weight', + exchangeCalendars, }); expect(postCutoffCloseReads).toBe(0); @@ -578,6 +609,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva ], vaultCutoffDate, benchmark: 'equal_weight', + exchangeCalendars, }); expectBitIdenticalEventStudyInput(poisonedResult.input, trappedResult.input); }); @@ -607,6 +639,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva }); } + const exchangeCalendars = makeExchangeCalendars([10, 20, 30], dates); const frozenBars = Object.freeze(bars.map(b => Object.freeze({ ...b }))); const frozenEvents = Object.freeze(events.map(e => Object.freeze({ ...e }))); const frozenParams = Object.freeze({ @@ -614,6 +647,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events: frozenEvents, vaultCutoffDate: dates[6]!, benchmark: 'equal_weight' as const, + exchangeCalendars, }); const baseline = buildEventStudyInput(frozenParams); @@ -623,6 +657,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events: shuffle(events, seed + 17), vaultCutoffDate: dates[6]!, benchmark: 'equal_weight', + exchangeCalendars, }); expectBitIdenticalEventStudyInput(permuted.input, baseline.input); expect(permuted.diagnostics).toEqual(baseline.diagnostics); @@ -631,6 +666,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva }); it('handles empty and post-cutoff-only inputs cleanly', () => { + const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} }; const emptyRes = buildEventStudyInput({ bars: [], events: [ @@ -638,6 +674,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva { listingId: 1, knownAt: makeUtcMs('2024-02-01', 0), kind: 'filing', subtype: '10-Q' }, ], vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, }); expect(emptyRes.input.sessionDates).toEqual([]); expect(emptyRes.input.entityReturns.size).toBe(0); @@ -659,6 +696,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events: [], vaultCutoffDate: '2024-02-01', benchmark: 'equal_weight', + exchangeCalendars: emptyCalendars, }); expect(postOnlyRes.input.sessionDates).toEqual([]); expect(postOnlyRes.input.benchmarkReturns).toEqual(new Float64Array(0)); @@ -666,6 +704,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva }); it('throws typed EventPanelError for every remaining validation error code', () => { + const emptyCalendars: EventStudyExchangeCalendars = { calendars: {}, listingCalendarId: {} }; expectEventPanelError( () => buildEventStudyInput(null as unknown as Parameters[0]), 'invalid_input' @@ -676,6 +715,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars: 'not-array' as unknown as BarRecord[], events: [], vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, }), 'invalid_input' ); @@ -685,16 +725,29 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars: [], events: 'not-array' as unknown as EventObservation[], vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, }), 'invalid_input' ); expectEventPanelError( - () => buildEventStudyInput({ bars: [], events: [], vaultCutoffDate: '2024-02-30' }), + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024-02-30', + exchangeCalendars: emptyCalendars, + }), 'invalid_date' ); expectEventPanelError( - () => buildEventStudyInput({ bars: [], events: [], vaultCutoffDate: '2024/02/01' }), + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024/02/01', + exchangeCalendars: emptyCalendars, + }), 'invalid_date' ); @@ -705,6 +758,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events: [], vaultCutoffDate: '2024-02-01', benchmark: 'cap_weight' as unknown as 'none', + exchangeCalendars: emptyCalendars, }), 'invalid_option' ); @@ -715,6 +769,17 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva events: [], vaultCutoffDate: '2024-02-01', benchmark: null as unknown as 'none', + exchangeCalendars: emptyCalendars, + }), + 'invalid_option' + ); + expectEventPanelError( + () => + buildEventStudyInput({ + bars: [], + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: undefined as unknown as EventStudyExchangeCalendars, }), 'invalid_option' ); @@ -733,6 +798,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars: [badBar as BarRecord], events: [], vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, }), 'invalid_bar' ); @@ -757,6 +823,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva bars: [], events: [badEv as EventObservation], vaultCutoffDate: '2024-02-01', + exchangeCalendars: emptyCalendars, }), 'invalid_event' ); @@ -837,6 +904,12 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva { 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) ]); + // Cross-border holiday: NYSE was closed on Thanksgiving 2024-11-28, so its Friday + // 2024-11-29 return (index 2) is a valid 1-session NYSE return (102 / 100 - 1 = 0.02). + const nyseRets = mapResult.input.entityReturns.get(nyseId)!; + expect(Number.isNaN(nyseRets[1]!)).toBe(true); + expect(nyseRets[2]!).toBeCloseTo(0.02, 12); + expect(nyseRets[3]!).toBeCloseTo(105 / 102 - 1, 12); expect(mapResult.diagnostics.duplicateEvents).toBe(1); expect(mapResult.diagnostics.droppedAfterLastSession).toBe(0); expect(mapResult.diagnostics.droppedMissingCalendarSession).toBe(0); @@ -991,9 +1064,7 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva () => buildEventStudyInput({ bars, - events: [ - { listingId: nyseId, knownAt: makeUtcMs('2024-11-27', 15), kind: 'filing', subtype: '10-q' }, - ], + events: [], vaultCutoffDate: '2024-12-02', exchangeCalendars: { calendars: { XNYS: nyseCalendar }, @@ -1003,4 +1074,108 @@ describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and inva 'invalid_option' ); }); + + it('rejects incomplete exchange calendar coverage when a calendar starts after or omits pre-Vault bar dates', () => { + const nyseId = 10_001; + const dec2023AndJan2024Bars: BarRecord[] = [ + makeBar(nyseId, '2023-12-28', 100, 21), + makeBar(nyseId, '2023-12-29', 101, 21), + makeBar(nyseId, '2024-01-02', 103, 21), + makeBar(nyseId, '2024-01-03', 104, 21), + ]; + + // Calendar starts on Jan 2, 2024 while bars include December 2023 -> must throw invalid_option. + expectEventPanelError( + () => + buildEventStudyInput({ + bars: dec2023AndJan2024Bars, + events: [ + { + listingId: nyseId, + knownAt: makeUtcMs('2023-12-29', 19), // 14:00 ET on Dec 29 + kind: 'filing', + subtype: '10-q', + }, + ], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: { + calendars: { + XNYS: [ + { date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) }, + { date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) }, + ], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_option' + ); + + // Calendar omits a mid-history bar session (2023-12-29) -> must throw invalid_option. + expectEventPanelError( + () => + buildEventStudyInput({ + bars: dec2023AndJan2024Bars, + events: [], + vaultCutoffDate: '2024-02-01', + exchangeCalendars: { + calendars: { + XNYS: [ + { date: '2023-12-28', closeTs: makeUtcMs('2023-12-28', 21) }, + { date: '2024-01-02', closeTs: makeUtcMs('2024-01-02', 21) }, + { date: '2024-01-03', closeTs: makeUtcMs('2024-01-03', 21) }, + ], + }, + listingCalendarId: { [nyseId]: 'XNYS' }, + }, + }), + 'invalid_option' + ); + }); + + it('uses exchange-calendar adjacency so a missing open session for all listings yields NaN on the next bar', () => { + // Exchange is open Mon, Tue, Wed, Thu, but bars exist only on Mon, Wed, Thu (Tue missing for ALL listings). + const mon = '2024-01-08'; + const tue = '2024-01-09'; + const wed = '2024-01-10'; + const thu = '2024-01-11'; + const bars: BarRecord[] = [ + makeBar(10, mon, 100), + makeBar(10, wed, 110), + makeBar(10, thu, 121), + makeBar(20, mon, 50), + makeBar(20, wed, 55), + makeBar(20, thu, 60.5), + ]; + + const res = buildEventStudyInput({ + bars, + events: [], + vaultCutoffDate: '2024-02-01', + benchmark: 'equal_weight', + exchangeCalendars: makeExchangeCalendars([10, 20], [mon, tue, wed, thu]), + }); + + // sessionDates contains only observed bar dates [Mon, Wed, Thu]. + expect(res.input.sessionDates).toEqual([mon, wed, thu]); + + const r10 = res.input.entityReturns.get(10)!; + const r20 = res.input.entityReturns.get(20)!; + const bench = res.input.benchmarkReturns!; + + // Mon (index 0): NaN (first bar) + expect(Number.isNaN(r10[0]!)).toBe(true); + expect(Number.isNaN(r20[0]!)).toBe(true); + expect(Number.isNaN(bench[0]!)).toBe(true); + + // Wed (index 1): MUST be NaN because Tue was an open exchange session (not consecutive). + expect(Number.isNaN(r10[1]!)).toBe(true); + expect(Number.isNaN(r20[1]!)).toBe(true); + expect(Number.isNaN(bench[1]!)).toBe(true); + + // Thu (index 2): consecutive with Wed -> valid +10% return. + expect(r10[2]!).toBeCloseTo(0.1, 12); + expect(r20[2]!).toBeCloseTo(0.1, 12); + expect(bench[2]!).toBeCloseTo(0.1, 12); + }); });