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
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue