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

@ -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.