stock-bot/libs/research/test/signal-panel-qa.test.ts
2026-11-29 15:26:38 -05:00

540 lines
19 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from 'bun:test';
import {
SignalPanelError,
buildForwardReturnPanel,
type BarRecord,
type BuildForwardReturnPanelResult,
type SignalObservation,
} from '@stock-bot/research';
// QA suite for T-121: compares `buildForwardReturnPanel` against a deliberately naive
// O(n^2) reference model on seeded random panels (gaps, mixed EST/EDT close stamps,
// exact-close and after-close signals, bad closes, exact duplicates, post-cutoff bars),
// plus targeted PIT/Vault probes the authored suite does not pin down.
const MS_PER_DAY = 86_400_000;
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 makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, ms = 0): number {
const [y, m, d] = date.split('-').map(Number);
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms);
}
function makeBusinessDates(startDate: string, count: number): string[] {
const out: string[] = [];
const current = new Date(`${startDate}T00:00:00.000Z`);
while (out.length < count) {
const day = current.getUTCDay();
if (day !== 0 && day !== 6) {
out.push(current.toISOString().slice(0, 10));
}
current.setUTCDate(current.getUTCDate() + 1);
}
return out;
}
function makeBarAt(listingId: number, ts: number, close: number): BarRecord {
return {
listingId,
ts,
open: close,
high: close,
low: close,
close,
volume: 1_000,
vwap: close,
knownAt: ts,
};
}
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;
}
interface ReferenceObservation {
readonly date: string;
readonly listingId: number;
readonly signal: number;
readonly forwardReturn: number;
}
interface ReferenceResult {
readonly observations: ReferenceObservation[];
readonly sessionDates: string[];
readonly diagnostics: BuildForwardReturnPanelResult['diagnostics'];
}
/**
* Naive reference implementation of the documented contract. Intentionally written
* with linear scans and plain objects so it shares no code paths with the optimized
* CSR / merge-pass implementation.
*/
function referencePanel(
bars: readonly BarRecord[],
signals: readonly SignalObservation[],
horizon: number,
vaultCutoffDate: string,
maxAge: number | undefined
): ReferenceResult {
const cutoffDayKey = Date.parse(`${vaultCutoffDate}T00:00:00.000Z`) / MS_PER_DAY;
const preBars = bars.filter(b => Math.floor(b.ts / MS_PER_DAY) < cutoffDayKey);
const postDays = new Set(
bars.map(b => Math.floor(b.ts / MS_PER_DAY)).filter(dk => dk >= cutoffDayKey)
);
const dayKeys = [...new Set(preBars.map(b => Math.floor(b.ts / MS_PER_DAY)))].sort(
(a, b) => a - b
);
const sessionDates = dayKeys.map(dk => new Date(dk * MS_PER_DAY).toISOString().slice(0, 10));
const sessionMaxTs = dayKeys.map(dk =>
Math.max(...preBars.filter(b => Math.floor(b.ts / MS_PER_DAY) === dk).map(b => b.ts))
);
const preCount = dayKeys.length;
const emittable = Math.max(0, preCount - horizon);
const hasPost = postDays.size > 0;
let duplicateBars = 0;
let droppedNoSignal = 0;
let droppedStaleSignal = 0;
let droppedMissingForwardBar = 0;
let droppedNonPositiveClose = 0;
const observations: ReferenceObservation[] = [];
const listingIds = [...new Set(preBars.map(b => b.listingId))].sort((a, b) => a - b);
for (const lid of listingIds) {
const bySession = new Map<number, BarRecord>();
for (const b of preBars.filter(x => x.listingId === lid)) {
const s = dayKeys.indexOf(Math.floor(b.ts / MS_PER_DAY));
const prev = bySession.get(s);
if (prev !== undefined) {
const same =
prev.ts === b.ts && (Object.is(prev.close, b.close) || prev.close === b.close);
if (!same) {
throw new Error('reference: conflicting duplicate');
}
duplicateBars += 1;
continue;
}
bySession.set(s, b);
}
const listingSignals = signals.filter(s => s.listingId === lid);
for (const [t, bar] of [...bySession.entries()].sort((a, b) => a[0] - b[0])) {
if (hasPost && t >= emittable) {
continue;
}
let active: SignalObservation | undefined;
for (const s of listingSignals) {
if (s.knownAt > bar.ts) {
continue;
}
if (
active === undefined ||
s.knownAt > active.knownAt ||
(s.knownAt === active.knownAt && s.value > active.value)
) {
active = s;
}
}
if (active === undefined) {
droppedNoSignal += 1;
continue;
}
if (maxAge !== undefined) {
let first = sessionMaxTs.findIndex(mx => mx >= active!.knownAt);
if (first < 0) {
first = preCount;
}
if (t - first > maxAge) {
droppedStaleSignal += 1;
continue;
}
}
const fwd = bySession.get(t + horizon);
if (t + horizon >= preCount || fwd === undefined) {
droppedMissingForwardBar += 1;
continue;
}
const c0 = bar.close;
const c1 = fwd.close;
if (!Number.isFinite(c0) || c0 <= 0 || !Number.isFinite(c1) || c1 <= 0) {
droppedNonPositiveClose += 1;
continue;
}
observations.push({
date: sessionDates[t]!,
listingId: lid,
signal: active.value === 0 ? 0 : active.value,
forwardReturn: c1 / c0 - 1 === 0 ? 0 : c1 / c0 - 1,
});
}
}
observations.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.listingId - b.listingId));
return {
observations,
sessionDates,
diagnostics: {
vaultExcludedDates: hasPost ? preCount - emittable + postDays.size : 0,
droppedNoSignal,
droppedStaleSignal,
droppedMissingForwardBar,
droppedNonPositiveClose,
duplicateBars,
},
};
}
function flattenPanel(result: BuildForwardReturnPanelResult): ReferenceObservation[] {
const out: ReferenceObservation[] = [];
for (const slice of result.panel) {
for (let i = 0; i < slice.ids.length; i += 1) {
out.push({
date: slice.date,
listingId: slice.ids[i]!,
signal: slice.signal[i]!,
forwardReturn: slice.forwardReturn[i]!,
});
}
}
return out;
}
interface RandomPanel {
readonly bars: BarRecord[];
readonly signals: SignalObservation[];
readonly dates: string[];
}
function buildRandomPanel(seed: number): RandomPanel {
const rand = createSeededRng(seed);
const sessionCount = 30 + Math.floor(rand() * 30);
const listingCount = 3 + Math.floor(rand() * 8);
const dates = makeBusinessDates('2023-02-20', sessionCount); // straddles the March DST switch
const bars: BarRecord[] = [];
const signals: SignalObservation[] = [];
for (let l = 0; l < listingCount; l += 1) {
const listingId = 1_000 - l * 37; // descending ids to exercise id sorting
let price = 20 + l;
for (let t = 0; t < sessionCount; t += 1) {
price *= 1 + (rand() - 0.5) * 0.04;
if (rand() < 0.12) {
continue; // gap
}
const closeHourUtc = rand() < 0.5 ? 20 : 21; // EDT vs EST close stamp
const ts = makeUtcMs(dates[t]!, closeHourUtc);
const roll = rand();
const close =
roll < 0.03 ? 0 : roll < 0.05 ? Number.NaN : roll < 0.06 ? -1 : Number(price.toFixed(4));
const bar = makeBarAt(listingId, ts, close);
bars.push(bar);
if (rand() < 0.05) {
bars.push({ ...bar }); // exact duplicate
}
const sigRoll = rand();
if (sigRoll < 0.15) {
signals.push({ listingId, knownAt: ts, value: Math.round(rand() * 100) / 10 }); // exactly at close
} else if (sigRoll < 0.3) {
signals.push({ listingId, knownAt: ts + 1, value: Math.round(rand() * 100) / 10 }); // 1 ms after
} else if (sigRoll < 0.4) {
signals.push({ listingId, knownAt: ts + 3_600_000, value: -Math.round(rand() * 100) / 10 });
} else if (sigRoll < 0.45) {
// Equal-knownAt tie pair.
const knownAt = makeUtcMs(dates[t]!, 13);
signals.push({ listingId, knownAt, value: 1 }, { listingId, knownAt, value: 2 });
}
}
}
// Signals for an unknown listing must be ignored.
signals.push({ listingId: 7, knownAt: makeUtcMs(dates[0]!, 10), value: 99 });
return { bars, signals, dates };
}
describe('buildForwardReturnPanel vs naive reference model (seeded)', () => {
it('matches the reference panel, sessionDates and diagnostics across random panels', () => {
let totalEmitted = 0;
let totalStale = 0;
let totalExcluded = 0;
for (let seed = 1; seed <= 60; seed += 1) {
const { bars, signals, dates } = buildRandomPanel(seed);
const rand = createSeededRng(seed * 7919);
const horizon = [1, 2, 5, 20][seed % 4]!;
const maxAge = seed % 3 === 0 ? undefined : Math.floor(rand() * 6);
// Cutoff either inside the sample (post-cutoff bars exist) or after it.
const cutoff =
seed % 5 === 0 ? '2030-01-01' : dates[Math.floor(dates.length * (0.6 + rand() * 0.3))]!;
const actual = buildForwardReturnPanel({
bars: shuffle(bars, seed),
signals: shuffle(signals, seed + 1),
horizonSessions: horizon,
vaultCutoffDate: cutoff,
maxSignalAgeSessions: maxAge,
});
const expected = referencePanel(bars, signals, horizon, cutoff, maxAge);
expect(actual.sessionDates).toEqual(expected.sessionDates);
expect(actual.diagnostics).toEqual(expected.diagnostics);
const flat = flattenPanel(actual);
expect(flat.length).toBe(expected.observations.length);
for (let i = 0; i < flat.length; i += 1) {
const a = flat[i]!;
const e = expected.observations[i]!;
expect(a.date).toBe(e.date);
expect(a.listingId).toBe(e.listingId);
expect(a.signal).toBe(e.signal);
expect(a.forwardReturn).toBe(e.forwardReturn);
}
// Structural invariants on the emitted panel.
for (let p = 0; p < actual.panel.length; p += 1) {
const slice = actual.panel[p]!;
expect(slice.ids.length).toBeGreaterThan(0);
expect(slice.date < cutoff).toBe(true);
const t = actual.sessionDates.indexOf(slice.date);
expect(t + horizon).toBeLessThan(actual.sessionDates.length);
if (p > 0) {
expect(actual.panel[p - 1]!.date < slice.date).toBe(true);
}
for (let i = 1; i < slice.ids.length; i += 1) {
expect(slice.ids[i]!).toBeGreaterThan(slice.ids[i - 1]!);
}
}
totalEmitted += flat.length;
totalStale += actual.diagnostics.droppedStaleSignal;
totalExcluded += actual.diagnostics.vaultExcludedDates;
}
// Guard against a vacuous fixture: every branch was actually exercised.
expect(totalEmitted).toBeGreaterThan(1_000);
expect(totalStale).toBeGreaterThan(0);
expect(totalExcluded).toBeGreaterThan(0);
});
});
describe('buildForwardReturnPanel point-in-time probes', () => {
it('activates a signal published 1 ms after a close on the very next session (not superseded)', () => {
const dates = makeBusinessDates('2024-03-04', 6);
const bars = dates.map((d, i) => makeBarAt(1, makeUtcMs(d), 100 + i));
const day0Close = makeUtcMs(dates[0]!);
const day2Close = makeUtcMs(dates[2]!);
const result = buildForwardReturnPanel({
bars,
signals: [
{ listingId: 1, knownAt: day0Close + 1, value: 10 },
{ listingId: 1, knownAt: day2Close, value: 20 },
],
horizonSessions: 1,
vaultCutoffDate: '2025-01-01',
});
expect(result.panel.map(s => [s.date, s.signal[0]])).toEqual([
[dates[1], 10],
[dates[2], 20],
[dates[3], 20],
[dates[4], 20],
]);
expect(result.diagnostics.droppedNoSignal).toBe(1);
});
it('adding future signals never changes the signal used on earlier dates (poison test)', () => {
for (let seed = 101; seed <= 115; seed += 1) {
const { bars, signals, dates } = buildRandomPanel(seed);
const base = { bars, horizonSessions: 1, vaultCutoffDate: '2030-01-01' } as const;
const pivot = Math.floor(dates.length / 2);
// Truncate to signals known on or before the pivot close, then poison with absurd
// values published 1 ms after the pivot session's latest close.
const pivotMaxTs = Math.max(
...bars.filter(b => new Date(b.ts).toISOString().slice(0, 10) === dates[pivot]).map(b => b.ts)
);
const truncated = signals.filter(s => s.knownAt <= pivotMaxTs);
const poison: SignalObservation[] = [...new Set(bars.map(b => b.listingId))].map(lid => ({
listingId: lid,
knownAt: pivotMaxTs + 1,
value: 1e12,
}));
const clean = buildForwardReturnPanel({ ...base, signals: truncated });
const poisoned = buildForwardReturnPanel({ ...base, signals: [...truncated, ...poison] });
const pivotDate = dates[pivot]!;
const pick = (r: BuildForwardReturnPanelResult) =>
flattenPanel(r).filter(o => o.date <= pivotDate);
expect(pick(poisoned)).toEqual(pick(clean));
expect(pick(clean).length).toBeGreaterThan(0);
expect(flattenPanel(poisoned).some(o => o.signal === 1e12)).toBe(true);
}
});
it('uses each listing’s own close time for PIT, not the latest close across listings', () => {
// Listing 1 closes 20:00 UTC, listing 2 closes 21:00 UTC on the same session date.
const dates = makeBusinessDates('2024-04-01', 4);
const bars = dates.flatMap((d, i) => [
makeBarAt(1, makeUtcMs(d, 20), 100 + i),
makeBarAt(2, makeUtcMs(d, 21), 200 + i),
]);
const knownAt = makeUtcMs(dates[0]!, 20, 30);
const result = buildForwardReturnPanel({
bars,
signals: [
{ listingId: 1, knownAt, value: 1 },
{ listingId: 2, knownAt, value: 2 },
],
horizonSessions: 1,
vaultCutoffDate: '2025-01-01',
});
// Day 0: listing 1 bar at 20:00 precedes knownAt 20:30 -> dropped; listing 2 at 21:00 -> used.
expect(result.panel[0]!.date).toBe(dates[0]);
expect(Array.from(result.panel[0]!.ids)).toEqual([2]);
expect(Array.from(result.panel[1]!.ids)).toEqual([1, 2]);
expect(result.diagnostics.droppedNoSignal).toBe(1);
});
});
describe('buildForwardReturnPanel Vault fence probes', () => {
it('treats a bar at 00:00 UTC on the cutoff date as Vault and 23:59:59.999 the day before as pre-cutoff', () => {
const cutoff = '2024-06-10';
const preTs = Date.parse('2024-06-09T23:59:59.999Z');
const postTs = Date.parse('2024-06-10T00:00:00.000Z');
let postReads = 0;
const trapped = { ...makeBarAt(1, postTs, 1) } as Record<string, unknown>;
Object.defineProperty(trapped, 'close', {
enumerable: true,
get() {
postReads += 1;
return 1;
},
});
const result = buildForwardReturnPanel({
bars: [
makeBarAt(1, Date.parse('2024-06-07T20:00:00.000Z'), 100),
makeBarAt(1, preTs, 110),
trapped as unknown as BarRecord,
],
signals: [{ listingId: 1, knownAt: 0, value: 1 }],
horizonSessions: 1,
vaultCutoffDate: cutoff,
});
expect(postReads).toBe(0);
expect(result.sessionDates).toEqual(['2024-06-07', '2024-06-09']);
expect(result.panel).toHaveLength(1);
expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12);
// h = 1 tail session + 1 post-cutoff day.
expect(result.diagnostics.vaultExcludedDates).toBe(2);
});
it('never emits a date whose forward session is in the Vault, even when only another listing reaches the cutoff', () => {
// Listing 1 stops trading well before the cutoff; listing 2 continues into the Vault.
const dates = makeBusinessDates('2024-01-02', 20);
const cutoff = dates[15]!;
const bars: BarRecord[] = [];
for (let t = 0; t < dates.length; t += 1) {
if (t < 10) {
bars.push(makeBarAt(1, makeUtcMs(dates[t]!), 100 + t));
}
bars.push(makeBarAt(2, makeUtcMs(dates[t]!), 50 + t));
}
const result = buildForwardReturnPanel({
bars,
signals: [
{ listingId: 1, knownAt: 0, value: 1 },
{ listingId: 2, knownAt: 0, value: 2 },
],
horizonSessions: 3,
vaultCutoffDate: cutoff,
});
const last = result.panel[result.panel.length - 1]!;
expect(last.date).toBe(dates[11]); // 15 pre-cutoff sessions, last emittable index 15 - 1 - 3
for (const slice of result.panel) {
const t = dates.indexOf(slice.date);
expect(dates[t + 3]! < cutoff).toBe(true);
}
});
it('rejects conflicting duplicates only before the cutoff and ignores them inside the Vault', () => {
const dates = makeBusinessDates('2024-01-02', 4);
const cutoff = dates[2]!;
const vaultBar = makeBarAt(1, makeUtcMs(dates[3]!), 100);
const ok = buildForwardReturnPanel({
bars: [
makeBarAt(1, makeUtcMs(dates[0]!), 100),
makeBarAt(1, makeUtcMs(dates[1]!), 101),
vaultBar,
{ ...vaultBar, close: 999 },
],
signals: [{ listingId: 1, knownAt: 0, value: 1 }],
horizonSessions: 1,
vaultCutoffDate: cutoff,
});
expect(ok.panel).toHaveLength(1);
expect(() =>
buildForwardReturnPanel({
bars: [makeBarAt(1, makeUtcMs(dates[0]!), 100), makeBarAt(1, makeUtcMs(dates[0]!, 20), 100)],
signals: [],
horizonSessions: 1,
vaultCutoffDate: cutoff,
})
).toThrow(SignalPanelError);
});
});
describe('buildForwardReturnPanel calendar edge cases', () => {
it('uses the sparse Map calendar path for spans above 200,000 days and stays exact', () => {
// ~600 years apart -> day span > 200,000 forces the Map lookup branch.
const ancient = Date.UTC(1500, 0, 3, 21);
const bars = [
makeBarAt(1, ancient, 10),
makeBarAt(1, Date.UTC(2100, 0, 4, 21), 20),
makeBarAt(1, Date.UTC(2100, 0, 5, 21), 30),
];
const result = buildForwardReturnPanel({
bars: shuffle(bars, 3),
signals: [{ listingId: 1, knownAt: ancient, value: 5 }],
horizonSessions: 1,
vaultCutoffDate: '2200-01-01',
});
expect(result.sessionDates).toEqual(['1500-01-03', '2100-01-04', '2100-01-05']);
expect(result.panel.map(s => [s.date, s.forwardReturn[0]])).toEqual([
['1500-01-03', 1],
['2100-01-04', 0.5],
]);
});
it('measures horizon in shared calendar sessions, so a holiday for one listing is a missing forward bar', () => {
const dates = makeBusinessDates('2024-07-01', 5);
const bars = [
...dates.map((d, i) => makeBarAt(1, makeUtcMs(d), 100 + i)),
// Listing 2 is closed on dates[2] (e.g. a cross-listed holiday).
...dates.filter((_, i) => i !== 2).map((d, i) => makeBarAt(2, makeUtcMs(d), 200 + i)),
];
const result = buildForwardReturnPanel({
bars,
signals: [
{ listingId: 1, knownAt: 0, value: 1 },
{ listingId: 2, knownAt: 0, value: 2 },
],
horizonSessions: 1,
vaultCutoffDate: '2025-01-01',
});
const day1 = result.panel.find(s => s.date === dates[1])!;
expect(Array.from(day1.ids)).toEqual([1]);
// Listing 2 has no bar on dates[2]: dropped as entry (no row) and as exit for dates[1].
expect(result.panel.find(s => s.date === dates[2])!.ids.length).toBe(1);
});
});