stock-bot/libs/research/scripts/benchmark-signal-panel.ts

196 lines
6 KiB
TypeScript

import type { BarRecord } from '../src/market-data-store';
import { type SignalObservation, buildForwardReturnPanel } from '../src/signal-panel';
const SEED = 20261129;
const SESSIONS = 5_040;
const LISTINGS = 3_000;
const SIGNAL_STRIDE_SESSIONS = 21;
const HORIZON_SESSIONS = 5;
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 signalsPerListing = Math.ceil(SESSIONS / SIGNAL_STRIDE_SESSIONS);
const signals: SignalObservation[] = new Array<SignalObservation>(LISTINGS * signalsPerListing);
let barIdx = 0;
let sigIdx = 0;
for (let l = 0; l < LISTINGS; l += 1) {
const listingId = l + 1;
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 % SIGNAL_STRIDE_SESSIONS === 0) {
signals[sigIdx++] = {
listingId,
knownAt: calendar.afterCloseTs[t] as number,
value: rng() * 2 - 1,
};
}
}
}
// Timed section: pure buildForwardReturnPanel execution (no fixture generation or checksum).
const started = performance.now();
const result = buildForwardReturnPanel({
bars,
signals,
horizonSessions: HORIZON_SESSIONS,
vaultCutoffDate,
});
const elapsedMs = performance.now() - started;
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, and typed-array bytes.
let checksum = 0x811c9dc5;
checksum = fnv1aUint32(checksum, result.panel.length);
checksum = fnv1aUint32(checksum, result.sessionDates.length);
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedNoSignal);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedStaleSignal);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingForwardBar);
checksum = fnv1aUint32(checksum, result.diagnostics.droppedNonPositiveClose);
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
let emittedObservations = 0;
for (let i = 0; i < result.panel.length; i += 1) {
const slice = result.panel[i];
if (slice === undefined) {
continue;
}
const ids = slice.ids as Int32Array;
const sig = slice.signal as Float64Array;
const ret = slice.forwardReturn as Float64Array;
emittedObservations += ids.length;
checksum = fnv1aBytes(checksum, new Uint8Array(ids.buffer, ids.byteOffset, ids.byteLength));
checksum = fnv1aBytes(checksum, new Uint8Array(sig.buffer, sig.byteOffset, sig.byteLength));
checksum = fnv1aBytes(checksum, new Uint8Array(ret.buffer, ret.byteOffset, ret.byteLength));
}
const checksumHex = checksum.toString(16).padStart(8, '0');
const EXPECTED_CHECKSUM = 'f0f28bdf';
if (checksumHex !== EXPECTED_CHECKSUM) {
throw new Error(
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
);
}
const rowsPerSec = Math.round(totalBars / (elapsedMs / 1000));
console.log(
JSON.stringify(
{
seed: SEED,
sessions: SESSIONS,
listings: LISTINGS,
horizonSessions: HORIZON_SESSIONS,
vaultCutoffDate,
inputBars: totalBars,
inputSignals: signals.length,
panelDates: result.panel.length,
emittedObservations,
elapsedMs: Number(elapsedMs.toFixed(2)),
rowsPerSec,
diagnostics: result.diagnostics,
checksum: checksumHex,
},
null,
2
)
);