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:
Studio 2026-11-29 16:12:38 -05:00
parent 5d97786254
commit 112b830985
9 changed files with 2396 additions and 161 deletions

View file

@ -159,3 +159,39 @@ Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3
- **Command:** `bun run libs/research/scripts/benchmark-signal-panel.ts`
- **Observed (Bun 1.2.16):** `elapsedMs = 817.24 ms`, `rowsPerSec = 18,501,301 rows/s` (`5,014` emitted panel dates, `15,042,000` emitted observations, `25` Vault-excluded dates, pinned checksum `f0f28bdf`)
## Event Study Panel Builder
Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (`libs/research/src/event-panel.ts`). The module is pure, synchronous, dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers).
### API
- **`eventsTableToEventRows(table, filter?)`** — Maps a `MarketDataStore.events` `Table` into point-in-time `EventObservation[]` (`{ listingId, knownAt, kind, subtype }`), validating every row upfront (before applying optional exact-match `filter.kinds` / `filter.subtypes` allow-lists), normalizing `-0` to `0`, and rejecting missing columns, empty filter arrays, or malformed rows with `EventPanelError`.
- **`buildEventStudyInput({ bars, events, vaultCutoffDate, 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).
### 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`.
- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate` (post-cutoff dates are counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
### `EventPanelError` Codes
| Code | Meaning |
| --- | --- |
| `'invalid_input'` | Non-object input envelope, non-array `bars`/`events`, malformed `Table`, or missing required columns (`listing_id`, `known_at`, `kind`, `subtype`) |
| `'invalid_date'` | `vaultCutoffDate` 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`) |
| `'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'`):
- **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`)

View file

@ -10,6 +10,7 @@
".": "./src/index.ts",
"./dataset-contracts": "./src/dataset-contracts.ts",
"./datasets": "./src/datasets.ts",
"./event-panel": "./src/event-panel.ts",
"./market-data-store": "./src/market-data-store.ts",
"./market-data-store-duckdb": "./src/market-data-store-duckdb.ts",
"./results": "./src/results.ts",

View file

@ -0,0 +1,208 @@
import { type EventObservation, buildEventStudyInput } from '../src/event-panel';
import type { BarRecord } from '../src/market-data-store';
const SEED = 20261129;
const SESSIONS = 5_040;
const LISTINGS = 3_000;
const EVENT_STRIDE_SESSIONS = 63; // 5040 / 63 = 80 filings/listing -> 240,000 total events
const PRE_CUTOFF_SESSIONS = 5_020;
function createMulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
function generateBusinessCalendar(count: number, startYear: number): {
dates: string[];
closeTs: Float64Array;
afterCloseTs: Float64Array;
} {
const dates: string[] = new Array<string>(count);
const closeTs = new Float64Array(count);
const afterCloseTs = new Float64Array(count);
let year = startYear;
let month = 1;
let day = 1;
// 2006-01-01 was a Sunday (dow = 0)
let dow = 0;
let produced = 0;
while (produced < count) {
if (dow !== 0 && dow !== 6) {
const yyyy = String(year).padStart(4, '0');
const mm = String(month).padStart(2, '0');
const dd = String(day).padStart(2, '0');
dates[produced] = `${yyyy}-${mm}-${dd}`;
closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET
afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET
produced += 1;
}
dow = (dow + 1) % 7;
day += 1;
const baseDays = DAYS_IN_MONTH[month] ?? 31;
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
if (day > maxDay) {
day = 1;
month += 1;
if (month > 12) {
month = 1;
year += 1;
}
}
}
return { dates, closeTs, afterCloseTs };
}
function fnv1aByte(hash: number, byte: number): number {
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
}
function fnv1aUint32(hash: number, value: number): number {
const v = value >>> 0;
let h = fnv1aByte(hash, v & 0xff);
h = fnv1aByte(h, (v >>> 8) & 0xff);
h = fnv1aByte(h, (v >>> 16) & 0xff);
h = fnv1aByte(h, (v >>> 24) & 0xff);
return h;
}
function fnv1aBytes(hash: number, bytes: Uint8Array): number {
let h = hash >>> 0;
for (let i = 0; i < bytes.length; i += 1) {
h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0;
}
return h;
}
const rng = createMulberry32(SEED);
const calendar = generateBusinessCalendar(SESSIONS, 2006);
const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string;
const totalBars = SESSIONS * LISTINGS;
const bars: BarRecord[] = new Array<BarRecord>(totalBars);
const eventsPerListing = Math.ceil(SESSIONS / EVENT_STRIDE_SESSIONS);
const totalEvents = LISTINGS * eventsPerListing;
const events: EventObservation[] = new Array<EventObservation>(totalEvents);
let barIdx = 0;
let evIdx = 0;
for (let l = 0; l < LISTINGS; l += 1) {
const listingId = l + 1;
const subtype = l % 2 === 0 ? '10-Q' : 'SEDAR_INTERIM';
let price = 10 + (l % 200) * 0.5;
for (let t = 0; t < SESSIONS; t += 1) {
const ts = calendar.closeTs[t] as number;
price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02));
bars[barIdx++] = {
listingId,
ts,
open: price,
high: price,
low: price,
close: price,
volume: 10_000,
vwap: price,
knownAt: ts,
};
if (t % EVENT_STRIDE_SESSIONS === 0) {
events[evIdx++] = {
listingId,
knownAt: calendar.afterCloseTs[t] as number,
kind: 'filing',
subtype,
};
}
}
}
// Timed section: pure buildEventStudyInput execution (no fixture generation or checksum).
const started = performance.now();
const result = buildEventStudyInput({
bars,
events,
vaultCutoffDate,
benchmark: 'equal_weight',
});
const elapsedMs = performance.now() - started;
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, returns, and events.
let checksum = 0x811c9dc5;
checksum = fnv1aUint32(checksum, result.input.sessionDates.length);
checksum = fnv1aUint32(checksum, result.input.entityReturns.size);
checksum = fnv1aUint32(checksum, result.input.events.length);
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedEvents);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedUnknownListing);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedAfterLastSession);
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateEvents);
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
checksum = fnv1aUint32(checksum, result.diagnostics.nonPositiveCloseReturns);
if (result.input.benchmarkReturns !== undefined) {
const bench = result.input.benchmarkReturns as Float64Array;
checksum = fnv1aBytes(checksum, new Uint8Array(bench.buffer, bench.byteOffset, bench.byteLength));
}
for (const [entityId, series] of result.input.entityReturns) {
checksum = fnv1aUint32(checksum, Number(entityId));
const arr = series as Float64Array;
checksum = fnv1aBytes(checksum, new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength));
}
for (let i = 0; i < result.input.events.length; i += 1) {
const ev = result.input.events[i];
if (ev === undefined) {
continue;
}
checksum = fnv1aUint32(checksum, ev.dayIndex);
checksum = fnv1aUint32(checksum, Number(ev.entityId));
}
const checksumHex = checksum.toString(16).padStart(8, '0');
const EXPECTED_CHECKSUM = '92bb8ae3';
if (checksumHex !== EXPECTED_CHECKSUM) {
throw new Error(
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
);
}
const elapsedSec = elapsedMs / 1000;
const barsPerSec = Math.round(totalBars / elapsedSec);
const eventsPerSec = Math.round(totalEvents / elapsedSec);
console.log(
JSON.stringify(
{
seed: SEED,
sessions: SESSIONS,
listings: LISTINGS,
vaultCutoffDate,
inputBars: totalBars,
inputEvents: totalEvents,
sessionDates: result.input.sessionDates.length,
anchoredEvents: result.input.events.length,
elapsedMs: Number(elapsedMs.toFixed(2)),
barsPerSec,
eventsPerSec,
diagnostics: result.diagnostics,
checksum: checksumHex,
},
null,
2
)
);

View file

@ -0,0 +1,776 @@
/**
* Pure, dependency-free event-study panel builder that transforms `MarketDataStore`
* daily bars and point-in-time `events` rows into Vault-safe `EventStudyInput`
* panels for `runEventStudy` / `eventStudy` (`design/MILESTONES.md` M1).
*
* Browser-safe and dependency-free: zero `node:*` imports, zero bare `process`
* access, and no database drivers.
*
* UTC session-calendar derivation:
* - Curated daily bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or
* `21:00 UTC`), so the UTC calendar date `Math.floor(bar.ts / 86_400_000)`
* matches the exchange session date without timezone drift.
*
* Return-series & `NaN` contract (matching `eventStudy` in
* `libs/calculations/src/analytics/event-study.ts`):
* - `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.
* - `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`
* and cleanly drops events whose `[-preDays, +postDays]` window contains `NaN`).
*
* Point-in-time (PIT) & Vault rules:
* - `sessionDates` holds only calendar dates strictly `< vaultCutoffDate`, and
* `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.
*/
import {
type EventStudyEvent,
type EventStudyInput,
type NumericSeries,
eventDayIndex,
} from '@stock-bot/calculations';
import type { BarRecord, EventKind, Table } from './market-data-store';
import { EVENT_KINDS } from './market-data-store-duckdb';
import {
type BarSortScratch,
MAX_DIRECT_DAY_SPAN,
MS_PER_DAY,
formatDayKeyUtc,
isPlainRecord,
isValidEpochMs,
isValidInt32,
normalizeZero,
parseCalendarDayKey,
sortBarSliceBySession,
} from './panel-shared';
const EVENT_KIND_SET: ReadonlySet<string> = new Set<string>(EVENT_KINDS);
export type EventPanelErrorCode =
| 'invalid_input'
| 'invalid_date'
| 'invalid_bar'
| 'invalid_event'
| 'invalid_option'
| 'duplicate_bar';
export interface EventPanelErrorOptions {
readonly cause?: unknown;
}
/** Typed validation and data-integrity error thrown by the event-panel builder helpers. */
export class EventPanelError extends Error {
override readonly name = 'EventPanelError';
readonly code: EventPanelErrorCode;
override readonly cause?: unknown;
constructor(code: EventPanelErrorCode, message: string, options?: EventPanelErrorOptions) {
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
this.code = code;
if (options?.cause !== undefined) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Point-in-time event observation aligned to a listing ID and UTC epoch-ms `knownAt`. */
export interface EventObservation {
readonly listingId: number;
readonly knownAt: number;
readonly kind: EventKind;
readonly subtype: string | null;
}
/** Optional exact-match allow-list filter for {@link eventsTableToEventRows}. */
export interface EventsTableFilter {
readonly kinds?: readonly EventKind[];
readonly subtypes?: readonly string[];
}
/** Benchmark return construction mode for {@link buildEventStudyInput}. */
export type EventStudyBenchmarkMode = 'equal_weight' | 'none';
/** Input contract for {@link buildEventStudyInput}. */
export interface BuildEventStudyInputParams {
readonly bars: readonly BarRecord[];
readonly events: readonly EventObservation[];
readonly vaultCutoffDate: string;
readonly benchmark?: EventStudyBenchmarkMode;
}
/** Per-run diagnostic counters reported by {@link buildEventStudyInput}. */
export interface EventPanelDiagnostics {
readonly vaultExcludedDates: number;
readonly vaultExcludedEvents: number;
readonly droppedUnknownListing: number;
readonly droppedAfterLastSession: number;
readonly duplicateEvents: number;
readonly duplicateBars: number;
readonly nonPositiveCloseReturns: number;
}
/** Output contract returned by {@link buildEventStudyInput}. */
export interface BuildEventStudyInputResult {
readonly input: EventStudyInput;
readonly diagnostics: EventPanelDiagnostics;
}
function parseStrictCalendarDayKey(value: unknown, field: string): number {
return parseCalendarDayKey(value, field, (message, cause) =>
new EventPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined)
);
}
/**
* Maps a `MarketDataStore.events` `Table` into point-in-time {@link EventObservation}
* rows, validating every row upfront (before applying optional exact-match allow-lists)
* and rejecting malformed inputs with {@link EventPanelError}.
*/
export function eventsTableToEventRows(
table: Table,
filter?: EventsTableFilter
): EventObservation[] {
if (!isPlainRecord(table) || !Array.isArray(table.columns) || !Array.isArray(table.rows)) {
throw new EventPanelError(
'invalid_input',
'Expected a Table object with array columns and rows.'
);
}
let hasListingIdCol = false;
let hasKnownAtCol = false;
let hasKindCol = false;
let hasSubtypeCol = false;
for (let i = 0; i < table.columns.length; i += 1) {
const col: unknown = table.columns[i];
if (col === 'listing_id') {
hasListingIdCol = true;
} else if (col === 'known_at') {
hasKnownAtCol = true;
} else if (col === 'kind') {
hasKindCol = true;
} else if (col === 'subtype') {
hasSubtypeCol = true;
}
}
if (!hasListingIdCol || !hasKnownAtCol || !hasKindCol || !hasSubtypeCol) {
throw new EventPanelError(
'invalid_input',
'Events table is missing required column(s): expected "listing_id", "known_at", "kind", and "subtype".'
);
}
let kindFilterSet: Set<string> | null = null;
let subtypeFilterSet: Set<string> | null = null;
if (filter !== undefined) {
if (!isPlainRecord(filter)) {
throw new EventPanelError('invalid_option', 'filter must be a non-null plain object.');
}
if (filter.kinds !== undefined) {
if (!Array.isArray(filter.kinds) || filter.kinds.length === 0) {
throw new EventPanelError(
'invalid_option',
'filter.kinds must be a non-empty array of valid EventKind values.'
);
}
kindFilterSet = new Set<string>();
for (let i = 0; i < filter.kinds.length; i += 1) {
const k: unknown = filter.kinds[i];
if (typeof k !== 'string' || !EVENT_KIND_SET.has(k)) {
throw new EventPanelError(
'invalid_option',
`Invalid filter.kinds[${i}] "${String(k)}": expected one of ${EVENT_KINDS.join(', ')}.`
);
}
kindFilterSet.add(k);
}
}
if (filter.subtypes !== undefined) {
if (!Array.isArray(filter.subtypes) || filter.subtypes.length === 0) {
throw new EventPanelError(
'invalid_option',
'filter.subtypes must be a non-empty array of strings.'
);
}
subtypeFilterSet = new Set<string>();
for (let i = 0; i < filter.subtypes.length; i += 1) {
const s: unknown = filter.subtypes[i];
if (typeof s !== 'string') {
throw new EventPanelError(
'invalid_option',
`Invalid filter.subtypes[${i}]: expected a string, got ${typeof s}.`
);
}
subtypeFilterSet.add(s);
}
}
}
const out: EventObservation[] = [];
const rows = table.rows;
for (let i = 0; i < rows.length; i += 1) {
const row: unknown = rows[i];
if (!isPlainRecord(row)) {
throw new EventPanelError('invalid_event', `Events table row[${i}] must be a plain object.`);
}
if (
!Object.prototype.hasOwnProperty.call(row, 'listing_id') ||
!Object.prototype.hasOwnProperty.call(row, 'known_at') ||
!Object.prototype.hasOwnProperty.call(row, 'kind') ||
!Object.prototype.hasOwnProperty.call(row, 'subtype')
) {
throw new EventPanelError(
'invalid_event',
`Events table row[${i}] is missing required key "listing_id", "known_at", "kind", or "subtype".`
);
}
const listingId = row.listing_id;
if (!isValidInt32(listingId)) {
throw new EventPanelError(
'invalid_event',
`Invalid listing_id in events table row[${i}]: ${String(listingId)}.`
);
}
const knownAt = row.known_at;
if (!isValidEpochMs(knownAt)) {
throw new EventPanelError(
'invalid_event',
`Invalid known_at in events table row[${i}]: ${String(knownAt)}.`
);
}
const kind = row.kind;
if (typeof kind !== 'string' || !EVENT_KIND_SET.has(kind)) {
throw new EventPanelError(
'invalid_event',
`Invalid kind in events table row[${i}]: "${String(kind)}".`
);
}
const subtype = row.subtype;
if (subtype !== null && typeof subtype !== 'string') {
throw new EventPanelError(
'invalid_event',
`Invalid subtype in events table row[${i}]: expected string or null, got ${typeof subtype}.`
);
}
if (kindFilterSet !== null && !kindFilterSet.has(kind)) {
continue;
}
if (subtypeFilterSet !== null && (subtype === null || !subtypeFilterSet.has(subtype))) {
continue;
}
out.push({
listingId: normalizeZero(listingId),
knownAt: normalizeZero(knownAt),
kind: kind as EventKind,
subtype,
});
}
return out;
}
/**
* Pure, synchronous event-study panel builder.
*
* Transforms daily bars (caller-supplied `'total'`-adjusted closes in any order)
* and point-in-time {@link EventObservation} rows into a Vault-safe
* `EventStudyInput` ready for `runEventStudy` / `eventStudy`, without mutating
* caller inputs or ever reading `bar.close` on or after `vaultCutoffDate`.
*/
export function buildEventStudyInput(
params: BuildEventStudyInputParams
): BuildEventStudyInputResult {
if (!isPlainRecord(params)) {
throw new EventPanelError('invalid_input', 'Input must be a non-null plain object.');
}
const vaultCutoffDayKey = parseStrictCalendarDayKey(params.vaultCutoffDate, 'vaultCutoffDate');
const vaultCutoffMs = vaultCutoffDayKey * MS_PER_DAY;
const benchmark: EventStudyBenchmarkMode = params.benchmark ?? 'none';
if (benchmark !== 'none' && benchmark !== 'equal_weight') {
throw new EventPanelError(
'invalid_option',
`Invalid benchmark "${String(benchmark)}": expected "none" or "equal_weight".`
);
}
if (!Array.isArray(params.bars)) {
throw new EventPanelError('invalid_input', 'params.bars must be an array of BarRecord.');
}
if (!Array.isArray(params.events)) {
throw new EventPanelError(
'invalid_input',
'params.events must be an array of EventObservation.'
);
}
const bars = params.bars;
const events = params.events;
// 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 listingBarCounts = new Map<number, number>();
let preCutoffBarTotal = 0;
for (let i = 0; i < bars.length; i += 1) {
const rawBar: unknown = bars[i];
if (!isPlainRecord(rawBar)) {
throw new EventPanelError('invalid_bar', `bars[${i}] must be a non-null plain object.`);
}
const listingId = rawBar.listingId;
if (!isValidInt32(listingId)) {
throw new EventPanelError(
'invalid_bar',
`Invalid listingId at bars[${i}]: ${String(listingId)}.`
);
}
const ts = rawBar.ts;
if (!isValidEpochMs(ts)) {
throw new EventPanelError('invalid_bar', `Invalid ts at bars[${i}]: ${String(ts)}.`);
}
const knownAt = rawBar.knownAt;
if (!isValidEpochMs(knownAt)) {
throw new EventPanelError(
'invalid_bar',
`Invalid knownAt at bars[${i}]: ${String(knownAt)}.`
);
}
const dayKey = Math.floor(ts / MS_PER_DAY);
if (dayKey >= vaultCutoffDayKey) {
postCutoffDays.add(dayKey);
continue;
}
const close = rawBar.close;
if (typeof close !== 'number') {
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);
}
const normListingId = normalizeZero(listingId);
listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1);
preCutoffBarTotal += 1;
}
// Validate all events upfront (even if bars is empty).
for (let i = 0; i < events.length; i += 1) {
const rawEv: unknown = events[i];
if (!isPlainRecord(rawEv)) {
throw new EventPanelError('invalid_event', `events[${i}] must be a non-null plain object.`);
}
if (!isValidInt32(rawEv.listingId)) {
throw new EventPanelError(
'invalid_event',
`Invalid listingId at events[${i}]: ${String(rawEv.listingId)}.`
);
}
if (!isValidEpochMs(rawEv.knownAt)) {
throw new EventPanelError(
'invalid_event',
`Invalid knownAt at events[${i}]: ${String(rawEv.knownAt)}.`
);
}
if (typeof rawEv.kind !== 'string' || !EVENT_KIND_SET.has(rawEv.kind)) {
throw new EventPanelError(
'invalid_event',
`Invalid kind at events[${i}]: "${String(rawEv.kind)}".`
);
}
if (rawEv.subtype !== null && typeof rawEv.subtype !== 'string') {
throw new EventPanelError(
'invalid_event',
`Invalid subtype at events[${i}]: expected string or null, got ${typeof rawEv.subtype}.`
);
}
}
const vaultExcludedDates = postCutoffDays.size;
if (preCutoffBarTotal === 0) {
let vaultExcludedEvents = 0;
let droppedUnknownListing = 0;
for (let i = 0; i < events.length; i += 1) {
const ev = events[i] as EventObservation;
if (ev.knownAt >= vaultCutoffMs) {
vaultExcludedEvents += 1;
} else {
droppedUnknownListing += 1;
}
}
const emptyInput: EventStudyInput =
benchmark === 'equal_weight'
? {
sessionDates: [],
entityReturns: new Map<number, NumericSeries>(),
benchmarkReturns: new Float64Array(0),
events: [],
}
: {
sessionDates: [],
entityReturns: new Map<number, NumericSeries>(),
events: [],
};
return {
input: emptyInput,
diagnostics: {
vaultExcludedDates,
vaultExcludedEvents,
droppedUnknownListing,
droppedAfterLastSession: 0,
duplicateEvents: 0,
duplicateBars: 0,
nonPositiveCloseReturns: 0,
},
};
}
// Build strictly ascending pre-cutoff session calendar.
const preCount = preCutoffDayMaxTs.size;
const preDayKeys = new Int32Array(preCount);
{
let idx = 0;
for (const dayKey of preCutoffDayMaxTs.keys()) {
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);
}
// 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);
{
let idx = 0;
for (const lid of listingBarCounts.keys()) {
sortedListingIds[idx] = lid;
idx += 1;
}
sortedListingIds.sort();
}
const listingIdToIdx = new Map<number, number>();
const barOffsets = new Int32Array(listingCount + 1);
for (let l = 0; l < listingCount; l += 1) {
const lid = sortedListingIds[l] as number;
listingIdToIdx.set(lid, l);
barOffsets[l + 1] = (barOffsets[l] as number) + (listingBarCounts.get(lid) as number);
}
// Build O(1) dayKey -> sessionIdx lookup (direct Int32Array when span <= 200_000, else Map).
const minDayKey = preDayKeys[0] as number;
const maxDayKey = preDayKeys[preCount - 1] as number;
const daySpan = maxDayKey - minDayKey + 1;
let dayKeyToIdxArr: Int32Array | null = null;
let dayKeyToIdxMap: Map<number, number> | null = null;
if (daySpan <= MAX_DIRECT_DAY_SPAN) {
dayKeyToIdxArr = new Int32Array(daySpan);
dayKeyToIdxArr.fill(-1);
for (let i = 0; i < preCount; i += 1) {
dayKeyToIdxArr[(preDayKeys[i] as number) - minDayKey] = i;
}
} else {
dayKeyToIdxMap = new Map<number, number>();
for (let i = 0; i < preCount; i += 1) {
dayKeyToIdxMap.set(preDayKeys[i] as number, i);
}
}
// Scatter pre-cutoff bars into CSR typed arrays grouped by listing index.
const barSessionIdx = new Int32Array(preCutoffBarTotal);
const barTs = new Float64Array(preCutoffBarTotal);
const barClose = new Float64Array(preCutoffBarTotal);
const barCursor = new Int32Array(listingCount);
for (let l = 0; l < listingCount; l += 1) {
barCursor[l] = barOffsets[l] as number;
}
for (let i = 0; i < bars.length; i += 1) {
const bar = bars[i] as BarRecord;
const dayKey = Math.floor(bar.ts / MS_PER_DAY);
if (dayKey >= vaultCutoffDayKey) {
continue;
}
const l = listingIdToIdx.get(normalizeZero(bar.listingId)) as number;
const pos = barCursor[l] as number;
barCursor[l] = pos + 1;
const sIdx =
dayKeyToIdxArr !== null
? (dayKeyToIdxArr[dayKey - minDayKey] as number)
: ((dayKeyToIdxMap as Map<number, number>).get(dayKey) as number);
barSessionIdx[pos] = sIdx;
barTs[pos] = normalizeZero(bar.ts);
barClose[pos] = bar.close;
}
const barScratch: BarSortScratch = {
sessionIdx: new Int32Array(0),
ts: new Float64Array(0),
close: new Float64Array(0),
};
const entityReturns = new Map<number, Float64Array>();
const computeBench = benchmark === 'equal_weight';
const benchSum = computeBench ? new Float64Array(preCount) : null;
const benchCount = computeBench ? new Int32Array(preCount) : null;
let duplicateBars = 0;
let nonPositiveCloseReturns = 0;
for (let l = 0; l < listingCount; l += 1) {
const listingId = sortedListingIds[l] as number;
const bStart = barOffsets[l] as number;
const bEnd = barOffsets[l + 1] as number;
sortBarSliceBySession(barSessionIdx, barTs, barClose, bStart, bEnd, barScratch);
// Compact exact duplicates in place; reject conflicting duplicates on the same (listingId, date).
let write = bStart;
for (let i = bStart + 1; i < bEnd; i += 1) {
if (barSessionIdx[i] === barSessionIdx[write]) {
const prevTs = barTs[write] as number;
const currTs = barTs[i] as number;
const prevClose = barClose[write] as number;
const currClose = barClose[i] as number;
const sameClose =
prevClose === currClose || (Number.isNaN(prevClose) && Number.isNaN(currClose));
if (currTs === prevTs && sameClose) {
duplicateBars += 1;
continue;
}
const conflictDate = sessionDates[barSessionIdx[i] as number] as string;
throw new EventPanelError(
'duplicate_bar',
`Conflicting duplicate bars for listingId ${listingId} on session ${conflictDate}.`
);
}
write += 1;
if (write !== i) {
barSessionIdx[write] = barSessionIdx[i] as number;
barTs[write] = barTs[i] as number;
barClose[write] = barClose[i] as number;
}
}
const uniqueEnd = write + 1;
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) {
continue;
}
const prevClose = barClose[i - 1] as number;
const currClose = barClose[i] as number;
if (!Number.isFinite(prevClose) || prevClose <= 0 || !Number.isFinite(currClose) || currClose <= 0) {
nonPositiveCloseReturns += 1;
continue;
}
const ret = currClose / prevClose - 1;
if (!Number.isFinite(ret)) {
nonPositiveCloseReturns += 1;
continue;
}
const normRet = normalizeZero(ret);
returns[currSIdx] = normRet;
if (benchSum !== null && benchCount !== null) {
benchSum[currSIdx] = (benchSum[currSIdx] as number) + normRet;
benchCount[currSIdx] = (benchCount[currSIdx] as number) + 1;
}
}
entityReturns.set(listingId, returns);
}
let benchmarkReturns: Float64Array | undefined;
if (benchSum !== null && benchCount !== null) {
benchmarkReturns = new Float64Array(preCount);
benchmarkReturns.fill(Number.NaN);
for (let t = 0; t < preCount; t += 1) {
const count = benchCount[t] as number;
if (count > 0) {
const mean = (benchSum[t] as number) / count;
if (Number.isFinite(mean)) {
benchmarkReturns[t] = normalizeZero(mean);
}
}
}
}
// Classify and anchor events in strict precedence order:
// (1) vaultExcludedEvents -> (2) droppedUnknownListing -> (3) droppedAfterLastSession -> (4) anchor.
const lastSessionMaxTs = sessionMaxTs[preCount - 1] as number;
const candDay = new Int32Array(events.length);
const candListing = new Int32Array(events.length);
let candCount = 0;
let vaultExcludedEvents = 0;
let droppedUnknownListing = 0;
let droppedAfterLastSession = 0;
for (let i = 0; i < events.length; i += 1) {
const ev = events[i] as EventObservation;
const knownAt = normalizeZero(ev.knownAt);
if (knownAt >= vaultCutoffMs) {
vaultExcludedEvents += 1;
continue;
}
const l = listingIdToIdx.get(normalizeZero(ev.listingId));
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;
}
}
candDay[candCount] = lo;
candListing[candCount] = l;
candCount += 1;
}
// Canonical 2-pass counting sort into (dayIndex ASC, listingIdx ASC).
if (candCount > 1) {
const tmpDay = new Int32Array(candCount);
const tmpListing = new Int32Array(candCount);
const listingCounts = new Int32Array(listingCount + 1);
for (let i = 0; i < candCount; i += 1) {
const idx = (candListing[i] as number) + 1;
listingCounts[idx] = (listingCounts[idx] as number) + 1;
}
for (let l = 1; l <= listingCount; l += 1) {
listingCounts[l] = (listingCounts[l] as number) + (listingCounts[l - 1] as number);
}
for (let i = 0; i < candCount; i += 1) {
const l = candListing[i] as number;
const pos = listingCounts[l] as number;
listingCounts[l] = pos + 1;
tmpDay[pos] = candDay[i] as number;
tmpListing[pos] = l;
}
const dayCounts = new Int32Array(preCount + 1);
for (let i = 0; i < candCount; i += 1) {
const idx = (tmpDay[i] as number) + 1;
dayCounts[idx] = (dayCounts[idx] as number) + 1;
}
for (let d = 1; d <= preCount; d += 1) {
dayCounts[d] = (dayCounts[d] as number) + (dayCounts[d - 1] as number);
}
for (let i = 0; i < candCount; i += 1) {
const d = tmpDay[i] as number;
const pos = dayCounts[d] as number;
dayCounts[d] = pos + 1;
candDay[pos] = d;
candListing[pos] = tmpListing[i] as number;
}
}
// Collapse exact duplicate (listingId, dayIndex) events (keep one).
const anchoredEvents: EventStudyEvent[] = [];
let duplicateEvents = 0;
let prevDay = -1;
let prevListing = -1;
for (let i = 0; i < candCount; i += 1) {
const d = candDay[i] as number;
const l = candListing[i] as number;
if (d === prevDay && l === prevListing) {
duplicateEvents += 1;
continue;
}
prevDay = d;
prevListing = l;
anchoredEvents.push({
entityId: sortedListingIds[l] as number,
dayIndex: d,
});
}
const input: EventStudyInput =
benchmarkReturns !== undefined
? {
sessionDates,
entityReturns,
benchmarkReturns,
events: anchoredEvents,
}
: {
sessionDates,
entityReturns,
events: anchoredEvents,
};
return {
input,
diagnostics: {
vaultExcludedDates,
vaultExcludedEvents,
droppedUnknownListing,
droppedAfterLastSession,
duplicateEvents,
duplicateBars,
nonPositiveCloseReturns,
},
};
}

View file

@ -1,5 +1,6 @@
// The default entrypoint is browser safe; server validation is an explicit subpath.
export * from './dataset-contracts';
export * from './event-panel';
export * from './market-data-store';
export * from './market-data-store-duckdb';
export * from './signal-panel';

View file

@ -0,0 +1,172 @@
/**
* Internal, browser-safe helpers shared by `signal-panel.ts` and `event-panel.ts`.
*
* Pure, synchronous, and dependency-free: zero `node:*` imports and zero bare
* `process` access. Not exported from the package root.
*/
import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store';
export const INT32_MIN = -2_147_483_648;
export const INT32_MAX = 2_147_483_647;
export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
export const MS_PER_DAY = 86_400_000;
export const MAX_DIRECT_DAY_SPAN = 200_000;
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function normalizeZero(value: number): number {
return value === 0 ? 0 : value;
}
export function isValidInt32(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
value >= INT32_MIN &&
value <= INT32_MAX
);
}
export function isValidEpochMs(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS
);
}
/**
* Parses a strict `YYYY-MM-DD` calendar date string into an integer UTC day key
* (`Math.floor(epochMs / MS_PER_DAY)`), delegating calendar validation to
* `applyVaultFence`.
*/
export function parseCalendarDayKey(
value: unknown,
field: string,
createError: (message: string, cause?: unknown) => Error
): number {
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
throw createError(
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
);
}
try {
const fenced = applyVaultFence(
{ from: value, to: value, scope: 'vault_evaluation_only' },
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
);
return fenced.fromMs / MS_PER_DAY;
} catch (error) {
if (error instanceof MarketDataStoreValidationError) {
throw createError(`Invalid "${field}": ${error.message}`, error);
}
throw error;
}
}
export function formatDayKeyUtc(dayKey: number): string {
const date = new Date(dayKey * MS_PER_DAY);
const year = String(date.getUTCFullYear()).padStart(4, '0');
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
const day = String(date.getUTCDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
export interface BarSortScratch {
sessionIdx: Int32Array;
ts: Float64Array;
close: Float64Array;
}
function ensureBarScratch(scratch: BarSortScratch, len: number): void {
if (scratch.sessionIdx.length < len) {
scratch.sessionIdx = new Int32Array(len);
scratch.ts = new Float64Array(len);
scratch.close = new Float64Array(len);
}
}
/**
* Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered
* by `sessionIdx ASC`. Skips sorting when already non-decreasing.
*/
export function sortBarSliceBySession(
sessionIdx: Int32Array,
ts: Float64Array,
close: Float64Array,
start: number,
end: number,
scratch: BarSortScratch
): void {
const len = end - start;
if (len <= 1) {
return;
}
let sorted = true;
for (let i = start + 1; i < end; i += 1) {
if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) {
sorted = false;
break;
}
}
if (sorted) {
return;
}
ensureBarScratch(scratch, len);
const tmpSession = scratch.sessionIdx;
const tmpTs = scratch.ts;
const tmpClose = scratch.close;
for (let width = 1; width < len; width *= 2) {
for (let left = 0; left < len; left += 2 * width) {
const mid = Math.min(left + width, len);
const right = Math.min(left + 2 * width, len);
let i = left;
let j = mid;
let k = left;
while (i < mid && j < right) {
const si = sessionIdx[start + i] as number;
const sj = sessionIdx[start + j] as number;
if (si <= sj) {
tmpSession[k] = si;
tmpTs[k] = ts[start + i] as number;
tmpClose[k] = close[start + i] as number;
i += 1;
} else {
tmpSession[k] = sj;
tmpTs[k] = ts[start + j] as number;
tmpClose[k] = close[start + j] as number;
j += 1;
}
k += 1;
}
while (i < mid) {
tmpSession[k] = sessionIdx[start + i] as number;
tmpTs[k] = ts[start + i] as number;
tmpClose[k] = close[start + i] as number;
i += 1;
k += 1;
}
while (j < right) {
tmpSession[k] = sessionIdx[start + j] as number;
tmpTs[k] = ts[start + j] as number;
tmpClose[k] = close[start + j] as number;
j += 1;
k += 1;
}
}
for (let k = 0; k < len; k += 1) {
sessionIdx[start + k] = tmpSession[k] as number;
ts[start + k] = tmpTs[k] as number;
close[start + k] = tmpClose[k] as number;
}
}
}

View file

@ -21,20 +21,19 @@
*/
import type { SignalCrossSection } from '@stock-bot/calculations';
import type { BarBatch, BarRecord, Table } from './market-data-store';
import {
type BarBatch,
type BarRecord,
MarketDataStoreValidationError,
type Table,
applyVaultFence,
} from './market-data-store';
const INT32_MIN = -2_147_483_648;
const INT32_MAX = 2_147_483_647;
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
const MS_PER_DAY = 86_400_000;
const MAX_DIRECT_DAY_SPAN = 200_000;
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
type BarSortScratch,
MAX_DIRECT_DAY_SPAN,
MS_PER_DAY,
formatDayKeyUtc,
isPlainRecord,
isValidEpochMs,
isValidInt32,
normalizeZero,
parseCalendarDayKey,
sortBarSliceBySession,
} from './panel-shared';
export type SignalPanelErrorCode =
| 'invalid_input'
@ -103,60 +102,10 @@ export interface BuildForwardReturnPanelResult {
readonly diagnostics: SignalPanelDiagnostics;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function normalizeZero(value: number): number {
return value === 0 ? 0 : value;
}
function isValidInt32(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
value >= INT32_MIN &&
value <= INT32_MAX
);
}
function isValidEpochMs(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS
);
}
function parseStrictCalendarDayKey(value: unknown, field: string): number {
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
throw new SignalPanelError(
'invalid_date',
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
);
}
try {
const fenced = applyVaultFence(
{ from: value, to: value, scope: 'vault_evaluation_only' },
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
);
return fenced.fromMs / MS_PER_DAY;
} catch (error) {
if (error instanceof MarketDataStoreValidationError) {
throw new SignalPanelError('invalid_date', `Invalid "${field}": ${error.message}`, {
cause: error,
});
}
throw error;
}
}
function formatDayKeyUtc(dayKey: number): string {
const date = new Date(dayKey * MS_PER_DAY);
const year = String(date.getUTCFullYear()).padStart(4, '0');
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
const day = String(date.getUTCDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
return parseCalendarDayKey(value, field, (message, cause) =>
new SignalPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined)
);
}
/**
@ -291,25 +240,11 @@ export function shortsTableToSignalRows(
return out;
}
interface BarSortScratch {
sessionIdx: Int32Array;
ts: Float64Array;
close: Float64Array;
}
interface SignalSortScratch {
knownAt: Float64Array;
value: Float64Array;
}
function ensureBarScratch(scratch: BarSortScratch, len: number): void {
if (scratch.sessionIdx.length < len) {
scratch.sessionIdx = new Int32Array(len);
scratch.ts = new Float64Array(len);
scratch.close = new Float64Array(len);
}
}
function ensureSignalScratch(scratch: SignalSortScratch, len: number): void {
if (scratch.knownAt.length < len) {
scratch.knownAt = new Float64Array(len);
@ -317,87 +252,6 @@ function ensureSignalScratch(scratch: SignalSortScratch, len: number): void {
}
}
/**
* Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered
* by `sessionIdx ASC`. Skips sorting when already non-decreasing.
*/
function sortBarSliceBySession(
sessionIdx: Int32Array,
ts: Float64Array,
close: Float64Array,
start: number,
end: number,
scratch: BarSortScratch
): void {
const len = end - start;
if (len <= 1) {
return;
}
let sorted = true;
for (let i = start + 1; i < end; i += 1) {
if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) {
sorted = false;
break;
}
}
if (sorted) {
return;
}
ensureBarScratch(scratch, len);
const tmpSession = scratch.sessionIdx;
const tmpTs = scratch.ts;
const tmpClose = scratch.close;
for (let width = 1; width < len; width *= 2) {
for (let left = 0; left < len; left += 2 * width) {
const mid = Math.min(left + width, len);
const right = Math.min(left + 2 * width, len);
let i = left;
let j = mid;
let k = left;
while (i < mid && j < right) {
const si = sessionIdx[start + i] as number;
const sj = sessionIdx[start + j] as number;
if (si <= sj) {
tmpSession[k] = si;
tmpTs[k] = ts[start + i] as number;
tmpClose[k] = close[start + i] as number;
i += 1;
} else {
tmpSession[k] = sj;
tmpTs[k] = ts[start + j] as number;
tmpClose[k] = close[start + j] as number;
j += 1;
}
k += 1;
}
while (i < mid) {
tmpSession[k] = sessionIdx[start + i] as number;
tmpTs[k] = ts[start + i] as number;
tmpClose[k] = close[start + i] as number;
i += 1;
k += 1;
}
while (j < right) {
tmpSession[k] = sessionIdx[start + j] as number;
tmpTs[k] = ts[start + j] as number;
tmpClose[k] = close[start + j] as number;
j += 1;
k += 1;
}
}
for (let k = 0; k < len; k += 1) {
sessionIdx[start + k] = tmpSession[k] as number;
ts[start + k] = tmpTs[k] as number;
close[start + k] = tmpClose[k] as number;
}
}
}
/**
* Iterative bottom-up mergesort for a listing's signal slice `[start, end)`
* ordered by `(knownAt ASC, value ASC)` for deterministic tie-breaking.

View file

@ -0,0 +1,435 @@
import { describe, expect, it } from 'bun:test';
import {
buildEventStudyInput,
collectBars,
createDuckDbMarketDataStore,
eventsTableToEventRows,
runEventStudy,
type DuckDbExecutor,
type DuckDbParam,
type TableRow,
type TrialLedgerExecutor,
} from '@stock-bot/research';
const CURATED_ROOT = '/mnt/data/stockbot/curated';
const SEED = 20261129;
function createSeededRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function makeBusinessDates(startDate: string, count: number): string[] {
const out: string[] = new Array(count);
const current = new Date(`${startDate}T00:00:00.000Z`);
let written = 0;
while (written < count) {
const day = current.getUTCDay();
if (day !== 0 && day !== 6) {
out[written] = current.toISOString().slice(0, 10);
written += 1;
}
current.setUTCDate(current.getUTCDate() + 1);
}
return out;
}
function makeUtcMs(date: string, hourUtc: number): number {
const [y, m, d] = date.split('-').map(Number);
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
}
interface StoredTrialRow {
readonly trial_id: string;
readonly created_at: Date;
readonly principal_id: string;
readonly campaign_id: string | null;
readonly stage: string;
readonly universe_market: string;
readonly horizon_bucket: string;
readonly hypothesis_id: string | null;
readonly expression_hash: string;
readonly sample_start: string;
readonly sample_end: string;
readonly n_obs: number;
readonly sharpe_unann: number;
readonly skewness: number;
readonly kurtosis: number;
readonly daily_series: readonly number[];
}
function createInMemoryTrialExecutor(): {
executor: TrialLedgerExecutor;
rows: StoredTrialRow[];
} {
const rows: StoredTrialRow[] = [];
let nextTrialId = 1;
const executor: TrialLedgerExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
const trimmed = text.trimStart();
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
const p = params ?? [];
const trialId = nextTrialId++;
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
const stored: StoredTrialRow = {
trial_id: String(trialId),
created_at: createdAt,
principal_id: p[0] as string,
campaign_id: (p[1] as string | null) ?? null,
stage: p[2] as string,
universe_market: p[3] as string,
horizon_bucket: p[4] as string,
hypothesis_id: (p[5] as string | null) ?? null,
expression_hash: p[6] as string,
sample_start: p[7] as string,
sample_end: p[8] as string,
n_obs: p[9] as number,
sharpe_unann: p[10] as number,
skewness: p[11] as number,
kurtosis: p[12] as number,
daily_series: dailySeries,
};
rows.push(stored);
return {
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
rowCount: 1,
};
}
if (trimmed.startsWith('SELECT')) {
if (text.includes('WHERE trial_id = $1::bigint')) {
const targetId = String(params?.[0]);
const matched = rows.filter(r => r.trial_id === targetId);
return { rows: matched as unknown as Row[], rowCount: matched.length };
}
if (text.includes('WHERE universe_market = $1')) {
const market = params?.[0] as string;
const bucket = params?.[1] as string;
const matched = rows.filter(
r => r.universe_market === market && r.horizon_bucket === bucket
);
return { rows: matched as unknown as Row[], rowCount: matched.length };
}
}
return { rows: [], rowCount: 0 };
},
};
return { executor, rows };
}
interface QmFilingsFixture {
readonly listingIds: number[];
readonly allDates: string[];
readonly vaultCutoffDate: string;
readonly vaultCutoffTs: number;
readonly barRows: TableRow[];
readonly eventRows: TableRow[];
}
function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
const rand = createSeededRng(SEED);
const listingCount = 24; // 12 US (10-Q) + 12 CA (SEDAR_INTERIM)
const preCutoffSessions = 160; // spans late 2022 through spring 2023 (pre-2023 & post-2023)
const postCutoffSessions = 10;
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
const vaultCutoffDate = allDates[preCutoffSessions]!;
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
const listingIds = Array.from({ length: listingCount }, (_, i) =>
i < 12 ? 10_001 + i : 50_001 + (i - 12)
);
const barRows: TableRow[] = [];
const eventRows: TableRow[] = [];
// 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);
for (let l = 0; l < listingCount; l += 1) {
prices[l] = 15 + l * 1.25;
}
for (let t = 0; t < allDates.length; t += 1) {
const date = allDates[t]!;
const closeTs = makeUtcMs(date, 21); // 16:00 ET
const afterCloseTs = makeUtcMs(date, 22); // 17:00 ET
const isPostCutoff = date >= vaultCutoffDate;
// Emit daily bars using ONLY boosts already active before today's close.
for (let l = 0; l < listingCount; l += 1) {
const boost = remainingBoostSessions[l]! > 0 ? 0.008 : 0;
if (remainingBoostSessions[l]! > 0) {
remainingBoostSessions[l] = remainingBoostSessions[l]! - 1;
}
const dailyRet = boost + (rand() * 2 - 1) * 0.006;
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6));
barRows.push({
listing_id: listingIds[l]!,
ts: closeTs,
open: closeVal,
high: closeVal,
low: closeVal,
close: closeVal,
volume: 75_000,
vwap: closeVal,
known_at: closeTs,
});
}
// Schedule staggered after-close filing events across pre-2023 and post-2023 sessions
// (plus post-cutoff filings to verify Vault isolation).
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';
eventRows.push({
listing_id: listingIds[l]!,
ts: afterCloseTs,
known_at: afterCloseTs,
known_at_source: 'exact',
kind: 'filing',
subtype: poisonPostCutoff && isPostCutoff ? 'POISON_FILING' : subtype,
payload_json: JSON.stringify({ market: isUs ? 'US' : 'CA', form: subtype }),
});
// Activate drift starting on session `t + 1`.
remainingBoostSessions[l] = 5;
}
// Also emit a non-matching subtype filing on another listing to verify subtype filtering.
const otherL = (t + 7) % listingCount;
eventRows.push({
listing_id: listingIds[otherL]!,
ts: afterCloseTs,
known_at: afterCloseTs,
known_at_source: 'exact',
kind: 'filing',
subtype: 'S-3',
payload_json: '{}',
});
}
}
return {
listingIds,
allDates,
vaultCutoffDate,
vaultCutoffTs,
barRows,
eventRows,
};
}
interface RecordedQuery {
readonly sql: string;
readonly params: readonly DuckDbParam[];
}
function createFakeDuckDbExecutor(fixture: QmFilingsFixture): {
executor: DuckDbExecutor;
runStatements: string[];
queries: RecordedQuery[];
} {
const runStatements: string[] = [];
const queries: RecordedQuery[] = [];
const executor: DuckDbExecutor = {
async run(sql: string) {
runStatements.push(sql);
},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
queries.push({ sql, params: [...params] });
if (sql.includes('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 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 (sql.includes('events/year=*/part.parquet')) {
// Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso]
const nIds = fixture.listingIds.length;
const nKinds = params.length - nIds - 3;
const kindSet = new Set<string>(params.slice(0, nKinds) as string[]);
const idSet = new Set<number>(params.slice(nKinds, nKinds + nIds) as number[]);
const fromMs = Date.parse(params[nKinds + nIds] as string);
const toMs = Date.parse(params[nKinds + nIds + 1] as string);
const asOfMs = Date.parse(params[nKinds + nIds + 2] as string);
return fixture.eventRows.filter(row => {
const kind = row.kind as string;
const lid = row.listing_id as number;
const ts = row.ts as number;
const knownAt = row.known_at as number;
return (
kindSet.has(kind) &&
idSet.has(lid) &&
ts >= fromMs &&
ts <= toMs &&
knownAt <= asOfMs
);
});
}
throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`);
},
};
return { executor, runStatements, queries };
}
describe('qmFilings end-to-end event study (headless, no database)', () => {
async function runQmFilingsStudy(poisonPostCutoff: boolean) {
const fixture = buildQmFilingsFixture(poisonPostCutoff);
const duck = createFakeDuckDbExecutor(fixture);
const ledger = createInMemoryTrialExecutor();
const store = createDuckDbMarketDataStore({
executor: duck.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: fixture.vaultCutoffTs,
barBatchSize: 256,
});
const from = fixture.allDates[0]!;
const to = fixture.allDates[fixture.allDates.length - 1]!;
const bars = await collectBars(
store.bars({
listingIds: fixture.listingIds,
timeframe: '1d',
from,
to,
adjustment: 'raw',
})
);
const eventsTable = await store.events({
kinds: ['filing'],
listingIds: fixture.listingIds,
from,
to,
});
const events = eventsTableToEventRows(eventsTable, {
kinds: ['filing'],
subtypes: ['10-Q', 'SEDAR_INTERIM'],
});
const built = buildEventStudyInput({
bars,
events,
vaultCutoffDate: fixture.vaultCutoffDate,
benchmark: 'equal_weight',
});
const studyResult = await runEventStudy(ledger.executor, {
principalId: 'operator',
universeMarket: 'US_CA_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'qmfilings_interim_10q_sedar_event_study',
params: { kinds: ['filing'], subtypes: ['10-Q', 'SEDAR_INTERIM'], preDays: 5, postDays: 5 },
universe: 'US_CA_EQ_FIXTURE',
horizon: '5d',
},
input: built.input,
options: { preDays: 5, postDays: 5, minEvents: 10 },
vaultCutoffDate: fixture.vaultCutoffDate,
});
return { fixture, duck, ledger, built, studyResult };
}
it('flows DuckDbMarketDataStore -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => {
const clean = await runQmFilingsStudy(false);
// DuckDB connection budget SET statements ran once; 2 queries ran (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);
// Every bound timestamp parameter (`fromIso`, `toIso`, `asOfIso`) in every executor query
// is strictly `< vaultCutoffTs`.
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);
}
}
// Event study succeeded and appended exactly one `event_study` row to trial_ledger.
expect(clean.studyResult.status).toBe('ok');
if (clean.studyResult.status !== 'ok') {
return;
}
expect(clean.ledger.rows).toHaveLength(1);
const stored = clean.ledger.rows[0]!;
expect(stored.stage).toBe('event_study');
expect(stored.universe_market).toBe('US_CA_EQ');
expect(stored.horizon_bucket).toBe('swing_1_10d');
expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true);
expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true);
// Stored daily_series matches study.clustered.meanCars at float32 precision.
const expectedMeanCars = Array.from(clean.studyResult.study.clustered.meanCars, v =>
Math.fround(v)
);
expect(stored.daily_series).toEqual(expectedMeanCars);
// Finite cluster-deflated Sharpe with effectiveTrials >= 1.
expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull();
expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true);
expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1);
// Planted positive post-filing abnormal return produces positive clustered CAR mean.
expect(clean.studyResult.study.clustered.carMean).toBeGreaterThan(0);
// Poisoning post-cutoff bars & events leaves built input, study result, and ledger byte-identical.
const poisoned = await runQmFilingsStudy(true);
expect(poisoned.built.diagnostics).toEqual(clean.built.diagnostics);
expect(poisoned.built.input.sessionDates).toEqual(clean.built.input.sessionDates);
expect(poisoned.built.input.events).toEqual(clean.built.input.events);
expect(Array.from(poisoned.built.input.entityReturns.keys())).toEqual(
Array.from(clean.built.input.entityReturns.keys())
);
for (const [id, cleanSeries] of clean.built.input.entityReturns) {
const a = poisoned.built.input.entityReturns.get(id) as Float64Array;
const b = cleanSeries as Float64Array;
expect(new Uint8Array(a.buffer, a.byteOffset, a.byteLength)).toEqual(
new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
);
}
const cleanBench = clean.built.input.benchmarkReturns as Float64Array;
const poisonedBench = poisoned.built.input.benchmarkReturns as Float64Array;
expect(
new Uint8Array(poisonedBench.buffer, poisonedBench.byteOffset, poisonedBench.byteLength)
).toEqual(new Uint8Array(cleanBench.buffer, cleanBench.byteOffset, cleanBench.byteLength));
expect(poisoned.studyResult).toEqual(clean.studyResult);
expect(poisoned.ledger.rows).toEqual(clean.ledger.rows);
});
});

View file

@ -0,0 +1,752 @@
import { describe, expect, it } from 'bun:test';
import { readFileSync } from 'node:fs';
import { eventDayIndex, eventStudy } from '@stock-bot/calculations';
import {
EventPanelError,
buildEventStudyInput,
eventsTableToEventRows,
type BarRecord,
type EventObservation,
type EventPanelErrorCode,
type Table,
} from '@stock-bot/research';
import {
EventPanelError as SubpathEventPanelError,
buildEventStudyInput as subpathBuildEventStudyInput,
eventsTableToEventRows as subpathEventsTableToEventRows,
} from '@stock-bot/research/event-panel';
function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number {
const [y, m, d] = date.split('-').map(Number);
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms);
}
function makeBusinessDates(startDate: string, count: number): string[] {
const out: string[] = new Array(count);
const current = new Date(`${startDate}T00:00:00.000Z`);
let written = 0;
while (written < count) {
const day = current.getUTCDay();
if (day !== 0 && day !== 6) {
out[written] = current.toISOString().slice(0, 10);
written += 1;
}
current.setUTCDate(current.getUTCDate() + 1);
}
return out;
}
function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord {
const ts = makeUtcMs(date, hourUtc, 0, 0, 0);
return {
listingId,
ts,
open: close,
high: close,
low: close,
close,
volume: 1_000,
vwap: close,
knownAt: ts,
};
}
function createSeededRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
function shuffle<T>(items: readonly T[], seed: number): T[] {
const copy = [...items];
const rand = createSeededRng(seed);
for (let i = copy.length - 1; i > 0; i -= 1) {
const j = Math.floor(rand() * (i + 1));
const tmp = copy[i]!;
copy[i] = copy[j]!;
copy[j] = tmp;
}
return copy;
}
function expectEventPanelError(fn: () => unknown, code: EventPanelErrorCode): EventPanelError {
try {
fn();
} catch (err) {
expect(err).toBeInstanceOf(EventPanelError);
const typed = err as EventPanelError;
expect(typed.code).toBe(code);
return typed;
}
throw new Error(`Expected EventPanelError(${code}), but function did not throw.`);
}
function expectBitIdenticalFloat64(actual: Float64Array, expected: Float64Array): void {
expect(actual.length).toBe(expected.length);
const aBytes = new Uint8Array(actual.buffer, actual.byteOffset, actual.byteLength);
const eBytes = new Uint8Array(expected.buffer, expected.byteOffset, expected.byteLength);
expect(aBytes).toEqual(eBytes);
}
function expectBitIdenticalEventStudyInput(
actual: ReturnType<typeof buildEventStudyInput>['input'],
expected: ReturnType<typeof buildEventStudyInput>['input']
): void {
expect(actual.sessionDates).toEqual(expected.sessionDates);
expect(actual.events).toEqual(expected.events);
expect(Array.from(actual.entityReturns.keys())).toEqual(Array.from(expected.entityReturns.keys()));
for (const [id, expectedSeries] of expected.entityReturns) {
const actualSeries = actual.entityReturns.get(id);
expect(actualSeries).toBeInstanceOf(Float64Array);
expectBitIdenticalFloat64(actualSeries as Float64Array, expectedSeries as Float64Array);
}
if (expected.benchmarkReturns === undefined) {
expect(actual.benchmarkReturns).toBeUndefined();
} else {
expect(actual.benchmarkReturns).toBeInstanceOf(Float64Array);
expectBitIdenticalFloat64(
actual.benchmarkReturns as Float64Array,
expected.benchmarkReturns as Float64Array
);
}
}
describe('@stock-bot/research event-panel exports and browser safety', () => {
it('exposes identical symbols from root and ./event-panel subpath', () => {
expect(buildEventStudyInput).toBe(subpathBuildEventStudyInput);
expect(eventsTableToEventRows).toBe(subpathEventsTableToEventRows);
expect(EventPanelError).toBe(SubpathEventPanelError);
});
it('has zero node:* imports, zero bare process access, and unchanged package dependencies', () => {
for (const relPath of ['../src/event-panel.ts', '../src/panel-shared.ts']) {
const src = readFileSync(new URL(relPath, import.meta.url), 'utf8');
expect(src).not.toMatch(/from\s+['"]node:/);
expect(src).not.toMatch(/require\s*\(\s*['"]node:/);
expect(src).not.toMatch(/\bprocess\./);
}
const pkg = JSON.parse(
readFileSync(new URL('../package.json', import.meta.url), 'utf8')
) as { dependencies?: Record<string, string>; exports?: Record<string, string> };
expect(pkg.exports?.['./event-panel']).toBe('./src/event-panel.ts');
expect(Object.keys(pkg.dependencies ?? {}).sort()).toEqual([
'@stock-bot/calculations',
'@stock-bot/stock-config',
'@stock-bot/types',
'zod',
]);
});
});
describe('eventsTableToEventRows', () => {
const baseColumns = [
'listing_id',
'ts',
'known_at',
'known_at_source',
'kind',
'subtype',
'payload_json',
];
it('maps valid rows, normalizes -0, and preserves null/string subtypes', () => {
const table: Table = {
columns: baseColumns,
rows: [
{
listing_id: -0,
ts: makeUtcMs('2024-01-05', 22),
known_at: -0,
known_at_source: 'exact',
kind: 'filing',
subtype: '10-Q',
payload_json: '{}',
},
{
listing_id: 42,
ts: makeUtcMs('2024-01-08', 22),
known_at: makeUtcMs('2024-01-08', 22),
known_at_source: 'exact',
kind: 'earnings',
subtype: null,
payload_json: '{}',
},
],
};
const rows = eventsTableToEventRows(table);
expect(rows).toEqual([
{ listingId: 0, knownAt: 0, kind: 'filing', subtype: '10-Q' },
{ listingId: 42, knownAt: makeUtcMs('2024-01-08', 22), kind: 'earnings', subtype: null },
]);
expect(Object.is(rows[0]!.listingId, 0)).toBe(true);
expect(Object.is(rows[0]!.knownAt, 0)).toBe(true);
});
it('applies exact-match kinds and subtypes allow-lists', () => {
const table: Table = {
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
rows: [
{ listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' },
{ listing_id: 2, known_at: 2000, kind: 'filing', subtype: '10-K' },
{ listing_id: 3, known_at: 3000, kind: 'filing', subtype: null },
{ listing_id: 4, known_at: 4000, kind: 'earnings', subtype: '10-Q' },
],
};
expect(eventsTableToEventRows(table, { kinds: ['filing'] })).toHaveLength(3);
expect(eventsTableToEventRows(table, { subtypes: ['10-Q'] })).toEqual([
{ listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' },
{ listingId: 4, knownAt: 4000, kind: 'earnings', subtype: '10-Q' },
]);
expect(
eventsTableToEventRows(table, { kinds: ['filing'], subtypes: ['10-Q', '10-K'] })
).toEqual([
{ listingId: 1, knownAt: 1000, kind: 'filing', subtype: '10-Q' },
{ listingId: 2, knownAt: 2000, kind: 'filing', subtype: '10-K' },
]);
});
it('validates all rows upfront even when they would be filtered out', () => {
const table: Table = {
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
rows: [
{ listing_id: 1, known_at: 1000, kind: 'filing', subtype: '10-Q' },
{ listing_id: 2, known_at: Number.NaN, kind: 'earnings', subtype: 'Q1' },
],
};
expectEventPanelError(
() => eventsTableToEventRows(table, { kinds: ['filing'] }),
'invalid_event'
);
});
it('rejects malformed table, missing columns, invalid filter options, and malformed rows', () => {
expectEventPanelError(
() => eventsTableToEventRows(null as unknown as Table),
'invalid_input'
);
expectEventPanelError(
() => eventsTableToEventRows({ columns: ['listing_id', 'known_at', 'kind'], rows: [] }),
'invalid_input'
);
const validEmptyTable: Table = {
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
rows: [],
};
expectEventPanelError(
() => eventsTableToEventRows(validEmptyTable, { kinds: [] }),
'invalid_option'
);
expectEventPanelError(
() => eventsTableToEventRows(validEmptyTable, { subtypes: [] }),
'invalid_option'
);
expectEventPanelError(
() =>
eventsTableToEventRows(validEmptyTable, {
kinds: ['unknown_kind' as unknown as 'filing'],
}),
'invalid_option'
);
expectEventPanelError(
() =>
eventsTableToEventRows(validEmptyTable, {
subtypes: [123 as unknown as string],
}),
'invalid_option'
);
expectEventPanelError(
() => eventsTableToEventRows(validEmptyTable, [] as unknown as Record<string, never>),
'invalid_option'
);
const badRows: unknown[] = [
null,
{ listing_id: 1, known_at: 1000, kind: 'filing' }, // missing subtype
{ listing_id: 1.5, known_at: 1000, kind: 'filing', subtype: '10-Q' },
{ listing_id: 2_147_483_648, known_at: 1000, kind: 'filing', subtype: '10-Q' },
{ listing_id: 1, known_at: Number.POSITIVE_INFINITY, kind: 'filing', subtype: '10-Q' },
{ listing_id: 1, known_at: 1000, kind: 'bad_kind', subtype: '10-Q' },
{ listing_id: 1, known_at: 1000, kind: 'filing', subtype: 99 },
];
for (const badRow of badRows) {
expectEventPanelError(
() =>
eventsTableToEventRows({
columns: ['listing_id', 'known_at', 'kind', 'subtype'],
rows: [badRow as Table['rows'][number]],
}),
'invalid_event'
);
}
});
});
describe('buildEventStudyInput — returns, PIT anchoring, Vault fence, and invariants', () => {
it('computes consecutive-session simple returns, sets NaN on gaps/resumption, and handles equal_weight benchmark', () => {
const dates = makeBusinessDates('2024-01-02', 5); // 5 sessions: d0..d4
const bars: BarRecord[] = [
// Listing 10: present on all 5 sessions
makeBar(10, dates[0]!, 100),
makeBar(10, dates[1]!, 110), // +10%
makeBar(10, dates[2]!, 99), // -10%
makeBar(10, dates[3]!, 99), // 0%
makeBar(10, dates[4]!, 108.9), // +10%
// Listing 20: missing on d2 -> d2 is NaN AND d3 (resumption) is NaN; d4 is 120/100 - 1 = +20%
makeBar(20, dates[0]!, 50),
makeBar(20, dates[1]!, 60), // +20%
makeBar(20, dates[3]!, 100),
makeBar(20, dates[4]!, 120), // +20%
];
const events: EventObservation[] = [
{ listingId: 10, knownAt: makeUtcMs(dates[1]!, 21), kind: 'filing', subtype: '10-Q' },
];
const resNone = buildEventStudyInput({
bars,
events,
vaultCutoffDate: '2024-02-01',
});
expect(resNone.input.sessionDates).toEqual(dates);
expect('benchmarkReturns' in resNone.input).toBe(false);
expect(Array.from(resNone.input.entityReturns.keys())).toEqual([10, 20]);
const r10 = resNone.input.entityReturns.get(10)!;
const r20 = resNone.input.entityReturns.get(20)!;
expect(Number.isNaN(r10[0]!)).toBe(true);
expect(r10[1]!).toBeCloseTo(0.1, 12);
expect(r10[2]!).toBeCloseTo(-0.1, 12);
expect(r10[3]!).toBe(0);
expect(r10[4]!).toBeCloseTo(0.1, 12);
expect(Number.isNaN(r20[0]!)).toBe(true);
expect(r20[1]!).toBeCloseTo(0.2, 12);
expect(Number.isNaN(r20[2]!)).toBe(true);
expect(Number.isNaN(r20[3]!)).toBe(true);
expect(r20[4]!).toBeCloseTo(0.2, 12);
const resEq = buildEventStudyInput({
bars,
events,
vaultCutoffDate: '2024-02-01',
benchmark: 'equal_weight',
});
expect(resEq.input.benchmarkReturns).toBeInstanceOf(Float64Array);
const b = resEq.input.benchmarkReturns!;
expect(Number.isNaN(b[0]!)).toBe(true);
expect(b[1]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2
expect(b[2]!).toBeCloseTo(-0.1, 12); // only listing 10 finite
expect(b[3]!).toBe(0); // only listing 10 finite
expect(b[4]!).toBeCloseTo(0.15, 12); // (0.1 + 0.2) / 2
});
it('writes NaN (never Infinity) for non-positive, non-finite, or overflowing closes and passes eventStudy', () => {
const dates = makeBusinessDates('2024-01-02', 6);
const bars: BarRecord[] = [
makeBar(1, dates[0]!, 10),
makeBar(1, dates[1]!, 0), // non-positive
makeBar(1, dates[2]!, -5), // non-positive
makeBar(1, dates[3]!, Number.NaN), // non-finite
makeBar(1, dates[4]!, 1e-308),
makeBar(1, dates[5]!, 1e308), // close[5]/close[4] overflows to +Infinity
];
const res = buildEventStudyInput({
bars,
events: [],
vaultCutoffDate: '2024-02-01',
benchmark: 'equal_weight',
});
const series = res.input.entityReturns.get(1)!;
for (let t = 0; t < dates.length; t += 1) {
expect(Number.isNaN(series[t]!)).toBe(true);
expect(Number.isNaN(res.input.benchmarkReturns![t]!)).toBe(true);
}
expect(res.diagnostics.nonPositiveCloseReturns).toBe(5);
// Must not throw NON_FINITE_RETURN in eventStudy.
const study = eventStudy(res.input, { preDays: 1, postDays: 1, minEvents: 1 });
expect(study.status).toBe('insufficient_data');
});
it('anchors after-close, weekend, and holiday events to the next session and matches eventDayIndex exactly', () => {
// Include a Friday -> Monday weekend and a Wednesday holiday (skip 2024-01-10).
const dates = ['2024-01-05', '2024-01-08', '2024-01-09', '2024-01-11', '2024-01-12'];
const bars: BarRecord[] = [];
for (const d of dates) {
bars.push(makeBar(1, d, 100, 21)); // 16:00 ET = 21:00 UTC
bars.push(makeBar(2, d, 50, 21));
}
const sessionMaxTs = Float64Array.from(dates.map(d => makeUtcMs(d, 21)));
const probeTimestamps: Array<{ listingId: number; knownAt: number; expectedIdx: number | null }> = [
// Pre-market on first session -> day 0
{ listingId: 1, knownAt: makeUtcMs('2024-01-05', 13), expectedIdx: 0 },
// Exact close on Friday -> day 0
{ listingId: 2, knownAt: makeUtcMs('2024-01-05', 21), expectedIdx: 0 },
// After-close Friday 17:00 ET (22:00 UTC) -> Monday (day 1)
{ listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), expectedIdx: 1 },
// Saturday morning -> Monday (day 1)
{ listingId: 2, knownAt: makeUtcMs('2024-01-06', 14), expectedIdx: 1 },
// After-close Tuesday 21:00:00.001 UTC -> Thursday (day 3, skipping Wednesday holiday)
{ listingId: 1, knownAt: makeUtcMs('2024-01-09', 21, 0, 0, 1), expectedIdx: 3 },
// Holiday Wednesday -> Thursday (day 3)
{ listingId: 2, knownAt: makeUtcMs('2024-01-10', 15), expectedIdx: 3 },
// After-close Friday last session (22:00 UTC < Saturday cutoff 00:00Z) -> droppedAfterLastSession
{ listingId: 1, knownAt: makeUtcMs('2024-01-12', 22), expectedIdx: null },
];
// Verify exact equivalence with eventDayIndex from @stock-bot/calculations.
for (const p of probeTimestamps) {
const ref = eventDayIndex(sessionMaxTs, p.knownAt);
if (p.expectedIdx === null) {
expect(ref).toEqual({ status: 'no_session', reason: 'after_last_session' });
} else {
expect(ref).toEqual({ status: 'ok', dayIndex: p.expectedIdx });
}
}
const events: EventObservation[] = probeTimestamps.map(p => ({
listingId: p.listingId,
knownAt: p.knownAt,
kind: 'filing',
subtype: '10-Q',
}));
const res = buildEventStudyInput({
bars,
events,
vaultCutoffDate: '2024-01-13',
});
expect(res.input.events).toEqual([
{ entityId: 1, dayIndex: 0 },
{ entityId: 2, dayIndex: 0 },
{ entityId: 1, dayIndex: 1 },
{ entityId: 2, dayIndex: 1 },
{ entityId: 1, dayIndex: 3 },
{ entityId: 2, dayIndex: 3 },
]);
expect(res.diagnostics.droppedAfterLastSession).toBe(1);
expect(res.diagnostics.vaultExcludedEvents).toBe(0);
expect(res.diagnostics.droppedUnknownListing).toBe(0);
expect(res.diagnostics.duplicateEvents).toBe(0);
});
it('deduplicates exact duplicate bars and rejects conflicting duplicates', () => {
const dates = makeBusinessDates('2024-01-02', 3);
const b0 = makeBar(1, dates[0]!, 10);
const b1 = makeBar(1, dates[1]!, 12);
const b2 = makeBar(1, dates[2]!, Number.NaN);
const exactDup = buildEventStudyInput({
bars: [b0, { ...b0 }, b1, b2, { ...b2 }],
events: [],
vaultCutoffDate: '2024-02-01',
});
expect(exactDup.diagnostics.duplicateBars).toBe(2);
expect(exactDup.input.entityReturns.get(1)![1]).toBeCloseTo(0.2, 12);
// Conflicting close
expectEventPanelError(
() =>
buildEventStudyInput({
bars: [b0, { ...b0, close: 10.01 }, b1],
events: [],
vaultCutoffDate: '2024-02-01',
}),
'duplicate_bar'
);
// Conflicting timestamp on same UTC date
expectEventPanelError(
() =>
buildEventStudyInput({
bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1],
events: [],
vaultCutoffDate: '2024-02-01',
}),
'duplicate_bar'
);
});
it('enforces Vault exclusion without ever reading post-cutoff bar.close and obeys event conservation', () => {
const dates = makeBusinessDates('2024-01-02', 6); // d0..d3 pre-cutoff, d4..d5 post-cutoff
const vaultCutoffDate = dates[4]!;
let postCutoffCloseReads = 0;
const makeTrappedPostCutoffBar = (listingId: number, date: string): BarRecord => {
const ts = makeUtcMs(date, 21);
const bar = {
listingId,
ts,
open: 999,
high: 999,
low: 999,
volume: 100,
vwap: 999,
knownAt: ts,
};
Object.defineProperty(bar, 'close', {
enumerable: true,
get() {
postCutoffCloseReads += 1;
throw new Error('Vault violation: post-cutoff bar.close was accessed!');
},
});
return bar as unknown as BarRecord;
};
const preBars: BarRecord[] = [];
for (let t = 0; t < 4; t += 1) {
preBars.push(makeBar(10, dates[t]!, 100 + t * 5));
}
const postBars: BarRecord[] = [
makeTrappedPostCutoffBar(10, dates[4]!),
makeTrappedPostCutoffBar(10, dates[5]!),
makeTrappedPostCutoffBar(99, dates[4]!), // listing only exists post-cutoff
];
const events: EventObservation[] = [
// Valid event -> day 1
{ listingId: 10, knownAt: makeUtcMs(dates[0]!, 22), kind: 'filing', subtype: '10-Q' },
// Duplicate event anchoring to day 1 (different timestamp on same pre-market morning)
{ listingId: 10, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' },
// Unknown listing (pre-cutoff) -> droppedUnknownListing
{ listingId: 99, knownAt: makeUtcMs(dates[1]!, 14), kind: 'filing', subtype: '10-Q' },
// After last pre-cutoff session close, but still < vaultCutoffMs -> droppedAfterLastSession
{ listingId: 10, knownAt: makeUtcMs(dates[3]!, 22), kind: 'filing', subtype: '10-Q' },
// Exact vaultCutoffDate 00:00:00.000Z (even for unknown listing) -> vaultExcludedEvents
{ listingId: 99, knownAt: makeUtcMs(vaultCutoffDate, 0), kind: 'filing', subtype: '10-Q' },
// After vaultCutoffDate -> vaultExcludedEvents
{ listingId: 10, knownAt: makeUtcMs(dates[5]!, 22), kind: 'filing', subtype: '10-Q' },
];
const trappedResult = buildEventStudyInput({
bars: [...preBars, ...postBars],
events,
vaultCutoffDate,
benchmark: 'equal_weight',
});
expect(postCutoffCloseReads).toBe(0);
expect(trappedResult.input.sessionDates).toEqual(dates.slice(0, 4));
expect(trappedResult.input.events).toEqual([{ entityId: 10, dayIndex: 1 }]);
expect(trappedResult.diagnostics).toEqual({
vaultExcludedDates: 2,
vaultExcludedEvents: 2,
droppedUnknownListing: 1,
droppedAfterLastSession: 1,
duplicateEvents: 1,
duplicateBars: 0,
nonPositiveCloseReturns: 0,
});
// Event conservation identity
const d = trappedResult.diagnostics;
expect(
trappedResult.input.events.length +
d.vaultExcludedEvents +
d.droppedUnknownListing +
d.droppedAfterLastSession +
d.duplicateEvents
).toBe(events.length);
// Poisoned post-cutoff bars/events leave pre-cutoff input byte-identical
const poisonedResult = buildEventStudyInput({
bars: [
...preBars,
makeBar(10, dates[4]!, 999_999),
makeBar(10, dates[5]!, Number.NaN),
],
events: [
...events.slice(0, 4),
{ listingId: 10, knownAt: makeUtcMs(dates[4]!, 22), kind: 'filing', subtype: '10-K' },
],
vaultCutoffDate,
benchmark: 'equal_weight',
});
expectBitIdenticalEventStudyInput(poisonedResult.input, trappedResult.input);
});
it('is bit-identical under arbitrary permutations and never mutates frozen inputs', () => {
const dates = makeBusinessDates('2024-01-02', 8);
const bars: BarRecord[] = [];
const events: EventObservation[] = [];
for (const lid of [30, 10, 20]) {
for (let t = 0; t < dates.length; t += 1) {
if (lid === 20 && t === 3) {
continue; // gap
}
bars.push(makeBar(lid, dates[t]!, 20 + lid + t * 0.75));
}
events.push({
listingId: lid,
knownAt: makeUtcMs(dates[1]!, 22),
kind: 'filing',
subtype: '10-Q',
});
events.push({
listingId: lid,
knownAt: makeUtcMs(dates[4]!, 15),
kind: 'filing',
subtype: '8-K',
});
}
const frozenBars = Object.freeze(bars.map(b => Object.freeze({ ...b })));
const frozenEvents = Object.freeze(events.map(e => Object.freeze({ ...e })));
const frozenParams = Object.freeze({
bars: frozenBars,
events: frozenEvents,
vaultCutoffDate: dates[6]!,
benchmark: 'equal_weight' as const,
});
const baseline = buildEventStudyInput(frozenParams);
for (const seed of [1, 42, 999, 20261129]) {
const permuted = buildEventStudyInput({
bars: shuffle(bars, seed),
events: shuffle(events, seed + 17),
vaultCutoffDate: dates[6]!,
benchmark: 'equal_weight',
});
expectBitIdenticalEventStudyInput(permuted.input, baseline.input);
expect(permuted.diagnostics).toEqual(baseline.diagnostics);
expect(Array.from(permuted.input.entityReturns.keys())).toEqual([10, 20, 30]);
}
});
it('handles empty and post-cutoff-only inputs cleanly', () => {
const emptyRes = buildEventStudyInput({
bars: [],
events: [
{ listingId: 1, knownAt: makeUtcMs('2024-01-05', 22), kind: 'filing', subtype: '10-Q' },
{ listingId: 1, knownAt: makeUtcMs('2024-02-01', 0), kind: 'filing', subtype: '10-Q' },
],
vaultCutoffDate: '2024-02-01',
});
expect(emptyRes.input.sessionDates).toEqual([]);
expect(emptyRes.input.entityReturns.size).toBe(0);
expect(emptyRes.input.events).toEqual([]);
expect('benchmarkReturns' in emptyRes.input).toBe(false);
expect(emptyRes.diagnostics).toEqual({
vaultExcludedDates: 0,
vaultExcludedEvents: 1,
droppedUnknownListing: 1,
droppedAfterLastSession: 0,
duplicateEvents: 0,
duplicateBars: 0,
nonPositiveCloseReturns: 0,
});
const postOnlyRes = buildEventStudyInput({
bars: [makeBar(1, '2024-02-01', 100), makeBar(1, '2024-02-02', 105)],
events: [],
vaultCutoffDate: '2024-02-01',
benchmark: 'equal_weight',
});
expect(postOnlyRes.input.sessionDates).toEqual([]);
expect(postOnlyRes.input.benchmarkReturns).toEqual(new Float64Array(0));
expect(postOnlyRes.diagnostics.vaultExcludedDates).toBe(2);
});
it('throws typed EventPanelError for every remaining validation error code', () => {
expectEventPanelError(
() => buildEventStudyInput(null as unknown as Parameters<typeof buildEventStudyInput>[0]),
'invalid_input'
);
expectEventPanelError(
() =>
buildEventStudyInput({
bars: 'not-array' as unknown as BarRecord[],
events: [],
vaultCutoffDate: '2024-02-01',
}),
'invalid_input'
);
expectEventPanelError(
() =>
buildEventStudyInput({
bars: [],
events: 'not-array' as unknown as EventObservation[],
vaultCutoffDate: '2024-02-01',
}),
'invalid_input'
);
expectEventPanelError(
() => buildEventStudyInput({ bars: [], events: [], vaultCutoffDate: '2024-02-30' }),
'invalid_date'
);
expectEventPanelError(
() => buildEventStudyInput({ bars: [], events: [], vaultCutoffDate: '2024/02/01' }),
'invalid_date'
);
expectEventPanelError(
() =>
buildEventStudyInput({
bars: [],
events: [],
vaultCutoffDate: '2024-02-01',
benchmark: 'cap_weight' as unknown as 'none',
}),
'invalid_option'
);
const goodBar = makeBar(1, '2024-01-05', 10);
for (const badBar of [
null,
{ ...goodBar, listingId: 1.5 },
{ ...goodBar, ts: Number.NaN },
{ ...goodBar, knownAt: Number.POSITIVE_INFINITY },
{ ...goodBar, close: '10' },
]) {
expectEventPanelError(
() =>
buildEventStudyInput({
bars: [badBar as BarRecord],
events: [],
vaultCutoffDate: '2024-02-01',
}),
'invalid_bar'
);
}
const goodEv: EventObservation = {
listingId: 1,
knownAt: makeUtcMs('2024-01-05', 22),
kind: 'filing',
subtype: '10-Q',
};
for (const badEv of [
null,
{ ...goodEv, listingId: 2_147_483_648 },
{ ...goodEv, knownAt: Number.NaN },
{ ...goodEv, kind: 'not_a_kind' },
{ ...goodEv, subtype: 42 },
]) {
expectEventPanelError(
() =>
buildEventStudyInput({
bars: [],
events: [badEv as EventObservation],
vaultCutoffDate: '2024-02-01',
}),
'invalid_event'
);
}
});
});