766 lines
26 KiB
TypeScript
766 lines
26 KiB
TypeScript
import { describe, expect, it } from 'bun:test';
|
|
import { readFileSync } from 'node:fs';
|
|
import {
|
|
SHORTS_SIGNAL_FIELDS,
|
|
SignalPanelError,
|
|
buildForwardReturnPanel,
|
|
collectBars,
|
|
shortsTableToSignalRows,
|
|
type BarBatch,
|
|
type BarRecord,
|
|
type SignalObservation,
|
|
type SignalPanelErrorCode,
|
|
type Table,
|
|
} from '@stock-bot/research';
|
|
import {
|
|
SHORTS_SIGNAL_FIELDS as SubpathShortsSignalFields,
|
|
SignalPanelError as SubpathSignalPanelError,
|
|
buildForwardReturnPanel as subpathBuildForwardReturnPanel,
|
|
collectBars as subpathCollectBars,
|
|
shortsTableToSignalRows as subpathShortsTableToSignalRows,
|
|
} from '@stock-bot/research/signal-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 expectSignalPanelError(fn: () => unknown, code: SignalPanelErrorCode): SignalPanelError {
|
|
try {
|
|
fn();
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(SignalPanelError);
|
|
const typed = err as SignalPanelError;
|
|
expect(typed.code).toBe(code);
|
|
return typed;
|
|
}
|
|
throw new Error(`Expected SignalPanelError(${code}), but function did not throw.`);
|
|
}
|
|
|
|
async function expectSignalPanelErrorAsync(
|
|
fn: () => Promise<unknown>,
|
|
code: SignalPanelErrorCode
|
|
): Promise<SignalPanelError> {
|
|
try {
|
|
await fn();
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(SignalPanelError);
|
|
const typed = err as SignalPanelError;
|
|
expect(typed.code).toBe(code);
|
|
return typed;
|
|
}
|
|
throw new Error(`Expected async SignalPanelError(${code}), but promise resolved.`);
|
|
}
|
|
|
|
describe('@stock-bot/research signal-panel exports and browser safety', () => {
|
|
it('exposes identical symbols from root and ./signal-panel subpath', () => {
|
|
expect(buildForwardReturnPanel).toBe(subpathBuildForwardReturnPanel);
|
|
expect(shortsTableToSignalRows).toBe(subpathShortsTableToSignalRows);
|
|
expect(collectBars).toBe(subpathCollectBars);
|
|
expect(SignalPanelError).toBe(SubpathSignalPanelError);
|
|
expect(SHORTS_SIGNAL_FIELDS).toBe(SubpathShortsSignalFields);
|
|
});
|
|
|
|
it('has zero node:* imports, zero bare process access, and no new package dependencies', () => {
|
|
const src = readFileSync(new URL('../src/signal-panel.ts', 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 {
|
|
exports: Record<string, string>;
|
|
dependencies: Record<string, string>;
|
|
};
|
|
expect(pkg.exports['./signal-panel']).toBe('./src/signal-panel.ts');
|
|
expect(Object.keys(pkg.dependencies).sort()).toEqual([
|
|
'@stock-bot/calculations',
|
|
'@stock-bot/stock-config',
|
|
'@stock-bot/types',
|
|
'zod',
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('buildForwardReturnPanel', () => {
|
|
it('computes exact hand-verified forward returns for horizons 1, 5, and 20', () => {
|
|
const dates = makeBusinessDates('2024-01-02', 25);
|
|
const bars: BarRecord[] = [];
|
|
const signals: SignalObservation[] = [];
|
|
|
|
// Listing 20 and Listing 10 intentionally inserted out of order to verify ascending ids.
|
|
for (let i = 0; i < dates.length; i += 1) {
|
|
bars.push(makeBar(20, dates[i]!, 100 + i * 2));
|
|
bars.push(makeBar(10, dates[i]!, 50 + i));
|
|
}
|
|
signals.push(
|
|
{ listingId: 10, knownAt: makeUtcMs(dates[0]!, 20), value: 1.5 },
|
|
{ listingId: 20, knownAt: makeUtcMs(dates[0]!, 20), value: -2.5 }
|
|
);
|
|
|
|
for (const horizon of [1, 5, 20] as const) {
|
|
const result = buildForwardReturnPanel({
|
|
bars,
|
|
signals,
|
|
horizonSessions: horizon,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
|
|
const expectedEmittedDates = dates.length - horizon;
|
|
expect(result.sessionDates).toEqual(dates);
|
|
expect(result.panel).toHaveLength(expectedEmittedDates);
|
|
expect(result.diagnostics.vaultExcludedDates).toBe(0);
|
|
expect(result.diagnostics.droppedNoSignal).toBe(0);
|
|
expect(result.diagnostics.droppedStaleSignal).toBe(0);
|
|
expect(result.diagnostics.droppedMissingForwardBar).toBe(horizon * 2);
|
|
expect(result.diagnostics.droppedNonPositiveClose).toBe(0);
|
|
expect(result.diagnostics.duplicateBars).toBe(0);
|
|
|
|
let emittedObs = 0;
|
|
for (let t = 0; t < expectedEmittedDates; t += 1) {
|
|
const slice = result.panel[t]!;
|
|
expect(slice.date).toBe(dates[t]);
|
|
expect(slice.ids).toBeInstanceOf(Int32Array);
|
|
expect(slice.signal).toBeInstanceOf(Float64Array);
|
|
expect(slice.forwardReturn).toBeInstanceOf(Float64Array);
|
|
expect(Array.from(slice.ids)).toEqual([10, 20]);
|
|
expect(Array.from(slice.signal)).toEqual([1.5, -2.5]);
|
|
|
|
const expectedRet10 = (50 + t + horizon) / (50 + t) - 1;
|
|
const expectedRet20 = (100 + (t + horizon) * 2) / (100 + t * 2) - 1;
|
|
expect(slice.forwardReturn[0]).toBeCloseTo(expectedRet10, 12);
|
|
expect(slice.forwardReturn[1]).toBeCloseTo(expectedRet20, 12);
|
|
emittedObs += slice.ids.length;
|
|
}
|
|
|
|
// Conservation identity: emitted + all drops === unique pre-cutoff bars.
|
|
const totalDrops =
|
|
result.diagnostics.droppedNoSignal +
|
|
result.diagnostics.droppedStaleSignal +
|
|
result.diagnostics.droppedMissingForwardBar +
|
|
result.diagnostics.droppedNonPositiveClose;
|
|
expect(emittedObs + totalDrops).toBe(bars.length);
|
|
}
|
|
});
|
|
|
|
it('enforces strict knownAt <= bar.ts point-in-time rule and deterministic tie-breaking', () => {
|
|
const dates = makeBusinessDates('2024-03-04', 5);
|
|
const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx * 10));
|
|
|
|
const day0CloseTs = makeUtcMs(dates[0]!, 21, 0, 0, 0);
|
|
const day1CloseTs = makeUtcMs(dates[1]!, 21, 0, 0, 0);
|
|
const signals: SignalObservation[] = [
|
|
// Known 1 ms AFTER day 0 close -> must NOT apply on day 0, MUST apply on day 1.
|
|
{ listingId: 1, knownAt: day0CloseTs + 1, value: 10 },
|
|
// Known EXACTLY at day 1 close -> MUST apply on day 1, overriding the day0+1ms signal.
|
|
{ listingId: 1, knownAt: day1CloseTs, value: 20 },
|
|
// Tie at exact same knownAt on day 1 close -> deterministic max value (25) regardless of order.
|
|
{ listingId: 1, knownAt: day1CloseTs, value: 25 },
|
|
];
|
|
|
|
const result = buildForwardReturnPanel({
|
|
bars,
|
|
signals,
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
|
|
expect(result.diagnostics.droppedNoSignal).toBe(1); // day 0 had no eligible signal
|
|
expect(result.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]);
|
|
expect(result.panel[0]!.signal[0]).toBe(25);
|
|
expect(result.panel[1]!.signal[0]).toBe(25);
|
|
expect(result.panel[2]!.signal[0]).toBe(25);
|
|
|
|
// Reverse signal order must produce the exact same tie-break value.
|
|
const reversed = buildForwardReturnPanel({
|
|
bars,
|
|
signals: [...signals].reverse(),
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
expect(reversed.panel.map(s => s.signal[0])).toEqual([25, 25, 25]);
|
|
});
|
|
|
|
it('drops observations whose forward bar at d + h is missing instead of shifting to d + h + 1', () => {
|
|
const dates = makeBusinessDates('2024-04-01', 6);
|
|
// Listing 1 has all 6 sessions; Listing 2 is missing dates[3].
|
|
const bars: BarRecord[] = [];
|
|
for (let i = 0; i < dates.length; i += 1) {
|
|
bars.push(makeBar(1, dates[i]!, 100 + i));
|
|
if (i !== 3) {
|
|
bars.push(makeBar(2, dates[i]!, 200 + i));
|
|
}
|
|
}
|
|
const signals: SignalObservation[] = [
|
|
{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 },
|
|
{ listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 },
|
|
];
|
|
|
|
const result = buildForwardReturnPanel({
|
|
bars,
|
|
signals,
|
|
horizonSessions: 2,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
|
|
// On dates[1], target is dates[3]. Listing 2 has no bar on dates[3], so it must be dropped
|
|
// rather than using dates[4].
|
|
const sliceDay1 = result.panel.find(s => s.date === dates[1])!;
|
|
expect(Array.from(sliceDay1.ids)).toEqual([1]);
|
|
// On dates[2], target is dates[4], which Listing 2 DOES have.
|
|
const sliceDay2 = result.panel.find(s => s.date === dates[2])!;
|
|
expect(Array.from(sliceDay2.ids)).toEqual([1, 2]);
|
|
expect(sliceDay2.forwardReturn[1]).toBeCloseTo(204 / 202 - 1, 12);
|
|
|
|
// Missing forward bars: Listing 1 misses dates[4], dates[5] (2);
|
|
// Listing 2 misses dates[1] (-> dates[3]), dates[4], dates[5] (3). Total = 5.
|
|
expect(result.diagnostics.droppedMissingForwardBar).toBe(5);
|
|
});
|
|
|
|
it('enforces maxSignalAgeSessions including age 0 and after-close 17:00 ET signals', () => {
|
|
const dates = makeBusinessDates('2024-05-06', 6);
|
|
const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx, 20)); // 16:00 EDT = 20:00 UTC
|
|
|
|
// Signal published at 17:00 EDT (21:00 UTC) on dates[0] -> first actionable session is dates[1] (age 0).
|
|
const signals: SignalObservation[] = [
|
|
{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 21, 0), value: 3.14 },
|
|
];
|
|
|
|
// maxSignalAgeSessions = 0: only dates[1] is emitted; dates[2], dates[3], dates[4], dates[5] are stale.
|
|
const age0 = buildForwardReturnPanel({
|
|
bars,
|
|
signals,
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
maxSignalAgeSessions: 0,
|
|
});
|
|
expect(age0.panel.map(s => s.date)).toEqual([dates[1]]);
|
|
expect(age0.diagnostics.droppedNoSignal).toBe(1); // dates[0]
|
|
expect(age0.diagnostics.droppedStaleSignal).toBe(4); // dates[2..5]
|
|
|
|
// maxSignalAgeSessions = 2: dates[1] (age 0), dates[2] (age 1), dates[3] (age 2) emitted;
|
|
// dates[4] (age 3) and dates[5] (age 4) dropped as stale.
|
|
const age2 = buildForwardReturnPanel({
|
|
bars,
|
|
signals,
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
maxSignalAgeSessions: 2,
|
|
});
|
|
expect(age2.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]);
|
|
expect(age2.diagnostics.droppedNoSignal).toBe(1);
|
|
expect(age2.diagnostics.droppedStaleSignal).toBe(2);
|
|
});
|
|
|
|
it('drops non-positive and non-finite entry/exit closes into droppedNonPositiveClose without throwing', () => {
|
|
const dates = makeBusinessDates('2024-06-03', 6);
|
|
const closes = [100, 0, -5, Number.NaN, Number.POSITIVE_INFINITY, 120];
|
|
const bars: BarRecord[] = dates.map((d, i) => makeBar(1, d, closes[i]!));
|
|
// Add a clean listing so we also verify normal rows survive alongside bad closes.
|
|
for (let i = 0; i < dates.length; i += 1) {
|
|
bars.push(makeBar(2, dates[i]!, 50 + i));
|
|
}
|
|
|
|
const signals: SignalObservation[] = [
|
|
{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 },
|
|
{ listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 },
|
|
];
|
|
|
|
const result = buildForwardReturnPanel({
|
|
bars,
|
|
signals,
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
|
|
// Every pair for listing 1 touches a non-positive/non-finite close (0->1, 1->2, 2->3, 3->4, 4->5).
|
|
expect(result.diagnostics.droppedNonPositiveClose).toBe(5);
|
|
expect(result.panel).toHaveLength(5);
|
|
for (const slice of result.panel) {
|
|
expect(Array.from(slice.ids)).toEqual([2]);
|
|
}
|
|
});
|
|
|
|
it('deduplicates exact pre-cutoff bars and rejects conflicting duplicates', () => {
|
|
const dates = makeBusinessDates('2024-07-01', 3);
|
|
const b0 = makeBar(1, dates[0]!, 100);
|
|
const b1 = makeBar(1, dates[1]!, 110);
|
|
const b2 = makeBar(1, dates[2]!, 121);
|
|
const bNaN = makeBar(2, dates[0]!, Number.NaN);
|
|
|
|
const result = buildForwardReturnPanel({
|
|
bars: [b0, { ...b0 }, b1, b2, bNaN, { ...bNaN }],
|
|
signals: [{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
|
|
expect(result.diagnostics.duplicateBars).toBe(2);
|
|
expect(result.panel).toHaveLength(2);
|
|
expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12);
|
|
|
|
// Conflicting close on same (listingId, date) must throw duplicate_bar.
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [b0, { ...b0, close: 101 }, b1],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'duplicate_bar'
|
|
);
|
|
|
|
// Conflicting ts on same (listingId, date) must throw duplicate_bar.
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'duplicate_bar'
|
|
);
|
|
});
|
|
|
|
it('enforces strict Vault cutoff across both d and d + h and never reads post-cutoff closes', () => {
|
|
const preCutoffCount = 30;
|
|
const postCutoffCount = 6;
|
|
const allDates = makeBusinessDates('2024-01-02', preCutoffCount + postCutoffCount);
|
|
const vaultCutoffDate = allDates[preCutoffCount]!;
|
|
|
|
const baseBars: BarRecord[] = [];
|
|
for (let i = 0; i < allDates.length; i += 1) {
|
|
baseBars.push(makeBar(1, allDates[i]!, 100 + i));
|
|
baseBars.push(makeBar(2, allDates[i]!, 200 + i * 2));
|
|
}
|
|
const signals: SignalObservation[] = [
|
|
{ listingId: 1, knownAt: makeUtcMs(allDates[0]!, 10), value: 0.5 },
|
|
{ listingId: 2, knownAt: makeUtcMs(allDates[0]!, 10), value: -0.5 },
|
|
];
|
|
|
|
for (const horizon of [1, 5, 20] as const) {
|
|
const clean = buildForwardReturnPanel({
|
|
bars: baseBars,
|
|
signals,
|
|
horizonSessions: horizon,
|
|
vaultCutoffDate,
|
|
});
|
|
|
|
const expectedEmittable = preCutoffCount - horizon;
|
|
expect(clean.sessionDates).toEqual(allDates.slice(0, preCutoffCount));
|
|
expect(clean.sessionDates.every(d => d < vaultCutoffDate)).toBe(true);
|
|
expect(clean.panel).toHaveLength(expectedEmittable);
|
|
expect(clean.panel[clean.panel.length - 1]!.date).toBe(allDates[preCutoffCount - 1 - horizon]);
|
|
expect(clean.diagnostics.vaultExcludedDates).toBe(horizon + postCutoffCount);
|
|
|
|
for (const slice of clean.panel) {
|
|
const idx = clean.sessionDates.indexOf(slice.date);
|
|
expect(idx).toBeGreaterThanOrEqual(0);
|
|
expect(slice.date < vaultCutoffDate).toBe(true);
|
|
const fwdDate = allDates[idx + horizon]!;
|
|
expect(fwdDate < vaultCutoffDate).toBe(true);
|
|
}
|
|
|
|
// Poison every post-cutoff close with NaN -> output must be byte-identical.
|
|
const poisonedBars: BarRecord[] = baseBars.map(b => {
|
|
const date = new Date(b.ts).toISOString().slice(0, 10);
|
|
return date >= vaultCutoffDate ? { ...b, close: Number.NaN } : b;
|
|
});
|
|
const poisoned = buildForwardReturnPanel({
|
|
bars: poisonedBars,
|
|
signals,
|
|
horizonSessions: horizon,
|
|
vaultCutoffDate,
|
|
});
|
|
expect(poisoned).toEqual(clean);
|
|
|
|
// Getter trap on every post-cutoff bar's `close` -> must never be accessed.
|
|
let closeReadsPostCutoff = 0;
|
|
const trappedBars: BarRecord[] = baseBars.map(b => {
|
|
const date = new Date(b.ts).toISOString().slice(0, 10);
|
|
if (date < vaultCutoffDate) {
|
|
return b;
|
|
}
|
|
const trapped = {
|
|
listingId: b.listingId,
|
|
ts: b.ts,
|
|
open: b.open,
|
|
high: b.high,
|
|
low: b.low,
|
|
volume: b.volume,
|
|
vwap: b.vwap,
|
|
knownAt: b.knownAt,
|
|
} as Record<string, unknown>;
|
|
Object.defineProperty(trapped, 'close', {
|
|
enumerable: true,
|
|
get() {
|
|
closeReadsPostCutoff += 1;
|
|
throw new Error('Post-cutoff close must never be read!');
|
|
},
|
|
});
|
|
return trapped as unknown as BarRecord;
|
|
});
|
|
|
|
const trappedResult = buildForwardReturnPanel({
|
|
bars: trappedBars,
|
|
signals,
|
|
horizonSessions: horizon,
|
|
vaultCutoffDate,
|
|
});
|
|
expect(closeReadsPostCutoff).toBe(0);
|
|
expect(trappedResult).toEqual(clean);
|
|
}
|
|
});
|
|
|
|
it('produces byte-identical output for shuffled bars and signals and never mutates frozen inputs', () => {
|
|
const dates = makeBusinessDates('2024-08-01', 15);
|
|
const bars: BarRecord[] = [];
|
|
const signals: SignalObservation[] = [];
|
|
|
|
for (const lid of [101, 202, 303, 404]) {
|
|
for (let i = 0; i < dates.length; i += 1) {
|
|
bars.push(makeBar(lid, dates[i]!, 50 + lid * 0.1 + i * 0.5));
|
|
}
|
|
signals.push(
|
|
{ listingId: lid, knownAt: makeUtcMs(dates[0]!, 18), value: lid * 0.01 },
|
|
{ listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * -0.02 },
|
|
{ listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * 0.03 } // intentional tie
|
|
);
|
|
}
|
|
|
|
const frozenInput = Object.freeze({
|
|
bars: Object.freeze(bars.map(b => Object.freeze({ ...b }))),
|
|
signals: Object.freeze(signals.map(s => Object.freeze({ ...s }))),
|
|
horizonSessions: 3,
|
|
vaultCutoffDate: dates[12]!,
|
|
maxSignalAgeSessions: 6,
|
|
});
|
|
|
|
const baseline = buildForwardReturnPanel(frozenInput);
|
|
|
|
for (const seed of [1, 2, 3, 42]) {
|
|
const shuffledResult = buildForwardReturnPanel({
|
|
bars: shuffle(bars, seed),
|
|
signals: shuffle(signals, seed + 100),
|
|
horizonSessions: 3,
|
|
vaultCutoffDate: dates[12]!,
|
|
maxSignalAgeSessions: 6,
|
|
});
|
|
expect(shuffledResult).toEqual(baseline);
|
|
}
|
|
});
|
|
|
|
it('handles empty bars and post-cutoff-only bars cleanly', () => {
|
|
const empty = buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: 1 }],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
expect(empty.panel).toEqual([]);
|
|
expect(empty.sessionDates).toEqual([]);
|
|
expect(empty.diagnostics).toEqual({
|
|
vaultExcludedDates: 0,
|
|
droppedNoSignal: 0,
|
|
droppedStaleSignal: 0,
|
|
droppedMissingForwardBar: 0,
|
|
droppedNonPositiveClose: 0,
|
|
duplicateBars: 0,
|
|
});
|
|
|
|
const postOnly = buildForwardReturnPanel({
|
|
bars: [makeBar(1, '2025-01-02', 100), makeBar(1, '2025-01-03', 101)],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
});
|
|
expect(postOnly.panel).toEqual([]);
|
|
expect(postOnly.sessionDates).toEqual([]);
|
|
expect(postOnly.diagnostics.vaultExcludedDates).toBe(2);
|
|
});
|
|
|
|
it('throws typed SignalPanelError for every invalid input, option, date, bar, and signal', () => {
|
|
expectSignalPanelError(
|
|
() => buildForwardReturnPanel(null as unknown as Parameters<typeof buildForwardReturnPanel>[0]),
|
|
'invalid_input'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: 'not-an-array' as unknown as BarRecord[],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_input'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: 'not-an-array' as unknown as SignalObservation[],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_input'
|
|
);
|
|
|
|
for (const badHorizon of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: [],
|
|
horizonSessions: badHorizon,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_horizon'
|
|
);
|
|
}
|
|
|
|
for (const badAge of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
maxSignalAgeSessions: badAge,
|
|
}),
|
|
'invalid_option'
|
|
);
|
|
}
|
|
|
|
for (const badDate of ['', '2025-02-29', '2025-13-01', '2025-01-01T00:00:00Z']) {
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: badDate,
|
|
}),
|
|
'invalid_date'
|
|
);
|
|
}
|
|
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [null as unknown as BarRecord],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_bar'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [{ ...makeBar(1, '2024-01-02', 100), listingId: 1.5 }],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_bar'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [{ ...makeBar(1, '2024-01-02', 100), close: '100' as unknown as number }],
|
|
signals: [],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_bar'
|
|
);
|
|
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: [null as unknown as SignalObservation],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_signal'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
buildForwardReturnPanel({
|
|
bars: [],
|
|
signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: Number.NaN }],
|
|
horizonSessions: 1,
|
|
vaultCutoffDate: '2025-01-01',
|
|
}),
|
|
'invalid_signal'
|
|
);
|
|
});
|
|
});
|
|
|
|
describe('shortsTableToSignalRows and collectBars', () => {
|
|
it('maps shortsAsOf table fields, skips nulls, normalizes -0, and rejects malformed inputs', () => {
|
|
const knownAt1 = makeUtcMs('2024-02-01', 22, 0);
|
|
const knownAt2 = makeUtcMs('2024-02-15', 22, 0);
|
|
const table: Table = {
|
|
columns: ['listing_id', 'report_date', 'known_at', 'shares_short', 'net_change', 'pct_float', 'source'],
|
|
rows: [
|
|
{
|
|
listing_id: 10,
|
|
report_date: '2024-01-31',
|
|
known_at: knownAt1,
|
|
shares_short: 50_000,
|
|
net_change: -0,
|
|
pct_float: 0.042,
|
|
source: 'ceoShorts',
|
|
},
|
|
{
|
|
listing_id: 20,
|
|
report_date: '2024-02-15',
|
|
known_at: knownAt2,
|
|
shares_short: 12_000,
|
|
net_change: null,
|
|
pct_float: null,
|
|
source: 'ceoShorts',
|
|
},
|
|
],
|
|
};
|
|
|
|
expect(shortsTableToSignalRows(table, 'shares_short')).toEqual([
|
|
{ listingId: 10, knownAt: knownAt1, value: 50_000 },
|
|
{ listingId: 20, knownAt: knownAt2, value: 12_000 },
|
|
]);
|
|
|
|
const netChangeRows = shortsTableToSignalRows(table, 'net_change');
|
|
expect(netChangeRows).toEqual([{ listingId: 10, knownAt: knownAt1, value: 0 }]);
|
|
expect(Object.is(netChangeRows[0]!.value, 0)).toBe(true);
|
|
|
|
expect(shortsTableToSignalRows(table, 'pct_float')).toEqual([
|
|
{ listingId: 10, knownAt: knownAt1, value: 0.042 },
|
|
]);
|
|
|
|
expectSignalPanelError(
|
|
() => shortsTableToSignalRows(table, 'bad_field' as unknown as 'net_change'),
|
|
'invalid_input'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
shortsTableToSignalRows(
|
|
{ columns: ['listing_id', 'known_at'], rows: [] },
|
|
'net_change'
|
|
),
|
|
'invalid_input'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
shortsTableToSignalRows(
|
|
{
|
|
columns: ['listing_id', 'known_at', 'net_change'],
|
|
rows: [{ listing_id: 1, known_at: knownAt1, net_change: Number.POSITIVE_INFINITY }],
|
|
},
|
|
'net_change'
|
|
),
|
|
'invalid_signal'
|
|
);
|
|
expectSignalPanelError(
|
|
() =>
|
|
shortsTableToSignalRows(
|
|
{
|
|
columns: ['listing_id', 'known_at', 'net_change'],
|
|
rows: [{ listing_id: 1, known_at: knownAt1 }],
|
|
},
|
|
'net_change'
|
|
),
|
|
'invalid_signal'
|
|
);
|
|
});
|
|
|
|
it('collects multi-batch async iterables without mutating batches and rejects invalid inputs', async () => {
|
|
const b1 = makeBar(1, '2024-01-02', 100);
|
|
const b2 = makeBar(1, '2024-01-03', 101);
|
|
const b3 = makeBar(2, '2024-01-02', 50);
|
|
|
|
const batch1: BarBatch = Object.freeze({ rows: Object.freeze([b1, b2]) });
|
|
const batch2: BarBatch = Object.freeze({ rows: Object.freeze([b3]) });
|
|
|
|
async function* gen(): AsyncIterable<BarBatch> {
|
|
yield batch1;
|
|
yield { rows: [] };
|
|
yield batch2;
|
|
}
|
|
|
|
const collected = await collectBars(gen());
|
|
expect(collected).toEqual([b1, b2, b3]);
|
|
|
|
async function* emptyGen(): AsyncIterable<BarBatch> {
|
|
// empty
|
|
}
|
|
expect(await collectBars(emptyGen())).toEqual([]);
|
|
|
|
await expectSignalPanelErrorAsync(
|
|
() => collectBars(null as unknown as AsyncIterable<BarBatch>),
|
|
'invalid_input'
|
|
);
|
|
|
|
async function* badBatchGen(): AsyncIterable<BarBatch> {
|
|
yield { rows: 'not-array' } as unknown as BarBatch;
|
|
}
|
|
await expectSignalPanelErrorAsync(() => collectBars(badBatchGen()), 'invalid_bar');
|
|
});
|
|
});
|