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
5e626b083b
commit
ee983cb349
5 changed files with 459 additions and 114 deletions
|
|
@ -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<number, number> | 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<number, number>).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<number, number> | 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<number, number>();
|
||||
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<number>();
|
||||
const preCutoffDayMaxTs = new Map<number, number>();
|
||||
const preCutoffDays = new Set<number>();
|
||||
const listingBarCounts = new Map<number, number>();
|
||||
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<string>(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<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;
|
||||
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<number, number>).get(eligibleDayKey) ?? -1);
|
||||
if (mappedIdx < 0) {
|
||||
droppedMissingCalendarSession += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
candDay[candCount] = mappedIdx;
|
||||
candListing[candCount] = l;
|
||||
candCount += 1;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue