358 lines
12 KiB
TypeScript
358 lines
12 KiB
TypeScript
/**
|
|
* Reproducible headless benchmark for Pass 4b `runSecurityMaster` end-to-end wiring.
|
|
* Streams 20,000 EOD<->QM candidate pairs x 25 sample dates (1,000,025 sample-close/FX docs)
|
|
* through in-memory async-generator fake readers with zero database or disk writes.
|
|
*
|
|
* Usage:
|
|
* bun run apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts
|
|
*/
|
|
|
|
import type {
|
|
BarSpanAggregateReader,
|
|
GroupedBarSpanRow,
|
|
} from '../src/normalization/bar-spans';
|
|
import {
|
|
FX_USD_CAD_SOURCE_ID,
|
|
runSecurityMaster,
|
|
type ReadOnlyMongoCollectionClient,
|
|
} from '../src/security-master';
|
|
|
|
const PAIR_COUNT = 20_000;
|
|
const SAMPLE_DATE_COUNT = 25;
|
|
const MISMATCH_EVERY = 200; // 100 ratio_mismatch pairs, 19,900 confirmed pairs
|
|
const AS_OF_DATE = '2026-01-15';
|
|
const FIRST_BAR_DATE = '2020-01-02';
|
|
const LAST_BAR_DATE = '2026-01-14';
|
|
|
|
function computeIsinCheckDigit(isinBody11: string): string {
|
|
let digits = '';
|
|
for (let i = 0; i < isinBody11.length; i++) {
|
|
const code = isinBody11.charCodeAt(i);
|
|
if (code >= 65 && code <= 90) {
|
|
digits += String(code - 55);
|
|
} else {
|
|
digits += isinBody11[i] ?? '';
|
|
}
|
|
}
|
|
let sum = 0;
|
|
let doubleDigit = true;
|
|
for (let i = digits.length - 1; i >= 0; i--) {
|
|
let val = digits.charCodeAt(i) - 48;
|
|
if (doubleDigit) {
|
|
val *= 2;
|
|
if (val > 9) {
|
|
val -= 9;
|
|
}
|
|
}
|
|
sum += val;
|
|
doubleDigit = !doubleDigit;
|
|
}
|
|
return String((10 - (sum % 10)) % 10);
|
|
}
|
|
|
|
function makeSyntheticIsin(index: number): string {
|
|
const body = `US${String(100_000_000 + index).padStart(9, '0')}`;
|
|
return `${body}${computeIsinCheckDigit(body)}`;
|
|
}
|
|
|
|
function makePureLetterTicker(index: number): string {
|
|
let n = index;
|
|
const c3 = String.fromCharCode(65 + (n % 26));
|
|
n = Math.floor(n / 26);
|
|
const c2 = String.fromCharCode(65 + (n % 26));
|
|
n = Math.floor(n / 26);
|
|
const c1 = String.fromCharCode(65 + (n % 26));
|
|
n = Math.floor(n / 26);
|
|
const c0 = String.fromCharCode(65 + (n % 26));
|
|
return `${c0}${c1}${c2}${c3}`;
|
|
}
|
|
|
|
function deterministicClose(pairIndex: number, dateIndex: number): number {
|
|
// Deterministic non-constant trajectory per pair so log-return variance is strictly positive.
|
|
const base = 20 + (pairIndex % 180);
|
|
const wave = ((pairIndex * 31 + dateIndex * 17) % 37) * 0.45;
|
|
const trend = dateIndex * (0.35 + (pairIndex % 7) * 0.05);
|
|
return Number((base + wave + trend).toFixed(4));
|
|
}
|
|
|
|
function createBenchmarkMongo(pairCount: number): {
|
|
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
|
|
readonly barSpanReader: BarSpanAggregateReader;
|
|
} {
|
|
const tickers = new Array<string>(pairCount);
|
|
const isins = new Array<string>(pairCount);
|
|
const eodIndexById = new Map<string, number>();
|
|
const qmIndexById = new Map<string, number>();
|
|
|
|
for (let i = 0; i < pairCount; i++) {
|
|
const ticker = makePureLetterTicker(i);
|
|
tickers[i] = ticker;
|
|
isins[i] = makeSyntheticIsin(i);
|
|
eodIndexById.set(`${ticker}.US`, i);
|
|
qmIndexById.set(`${ticker}:US`, i);
|
|
}
|
|
|
|
const eodExchanges = [
|
|
{ Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' },
|
|
];
|
|
const ibExchanges = [{ exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' }];
|
|
const qmExchanges = [{ exchange: 'NSD', country: 'US', currency: 'USD' }];
|
|
|
|
const mongoCollectionClient: ReadOnlyMongoCollectionClient = {
|
|
isReadOnly(): boolean {
|
|
return true;
|
|
},
|
|
getCollection(collectionName: string) {
|
|
return {
|
|
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
filter: Record<string, unknown> = {}
|
|
) {
|
|
return {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
if (collectionName === 'eodExchanges') {
|
|
for (const doc of eodExchanges) {
|
|
yield doc as unknown as T;
|
|
}
|
|
return;
|
|
}
|
|
if (collectionName === 'ibExchanges') {
|
|
for (const doc of ibExchanges) {
|
|
yield doc as unknown as T;
|
|
}
|
|
return;
|
|
}
|
|
if (collectionName === 'qmExchanges') {
|
|
for (const doc of qmExchanges) {
|
|
yield doc as unknown as T;
|
|
}
|
|
return;
|
|
}
|
|
if (
|
|
collectionName === 'ceoExchanges' ||
|
|
collectionName === 'ibSymbols' ||
|
|
collectionName === 'ceoSymbols' ||
|
|
collectionName === 'eodSymbolChange'
|
|
) {
|
|
return;
|
|
}
|
|
if (collectionName === 'eodSymbols') {
|
|
for (let i = 0; i < pairCount; i++) {
|
|
const ticker = tickers[i];
|
|
const isin = isins[i];
|
|
if (ticker === undefined || isin === undefined) {
|
|
continue;
|
|
}
|
|
yield {
|
|
eodSearchCode: `${ticker}.US`,
|
|
Code: ticker,
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: isin,
|
|
Name: `Bench Corp ${ticker}`,
|
|
Type: 'Common Stock',
|
|
delisted: false,
|
|
} as unknown as T;
|
|
}
|
|
return;
|
|
}
|
|
if (collectionName === 'qmSymbols') {
|
|
for (let i = 0; i < pairCount; i++) {
|
|
const ticker = tickers[i];
|
|
if (ticker === undefined) {
|
|
continue;
|
|
}
|
|
yield {
|
|
qmSearchCode: `${ticker}:US`,
|
|
symbol: ticker,
|
|
exchange: 'NSD',
|
|
countryCode: 'US',
|
|
currency: 'USD',
|
|
name: `Bench Corp ${ticker}`,
|
|
active: true,
|
|
} as unknown as T;
|
|
}
|
|
return;
|
|
}
|
|
|
|
const dates = ((filter.date as { $in?: string[] } | undefined)?.$in ?? []) as string[];
|
|
if (collectionName === 'eodPrices') {
|
|
const ids =
|
|
((filter.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[];
|
|
if (ids.length === 1 && ids[0] === FX_USD_CAD_SOURCE_ID) {
|
|
for (let d = 0; d < dates.length; d++) {
|
|
yield {
|
|
eodSearchCode: FX_USD_CAD_SOURCE_ID,
|
|
date: dates[d],
|
|
close: Number((1.34 + (d % 7) * 0.005).toFixed(4)),
|
|
} as unknown as T;
|
|
}
|
|
return;
|
|
}
|
|
for (let d = 0; d < dates.length; d++) {
|
|
const date = dates[d];
|
|
for (let i = 0; i < ids.length; i++) {
|
|
const id = ids[i];
|
|
if (id === undefined) {
|
|
continue;
|
|
}
|
|
const idx = eodIndexById.get(id);
|
|
if (idx === undefined) {
|
|
continue;
|
|
}
|
|
yield {
|
|
eodSearchCode: id,
|
|
date,
|
|
close: deterministicClose(idx, d),
|
|
} as unknown as T;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (collectionName === 'qmPrices') {
|
|
const ids =
|
|
((filter.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[];
|
|
for (let d = 0; d < dates.length; d++) {
|
|
const date = dates[d];
|
|
for (let i = 0; i < ids.length; i++) {
|
|
const id = ids[i];
|
|
if (id === undefined) {
|
|
continue;
|
|
}
|
|
const idx = qmIndexById.get(id);
|
|
if (idx === undefined) {
|
|
continue;
|
|
}
|
|
const baseClose = deterministicClose(idx, d);
|
|
const mult = idx % MISMATCH_EVERY === 0 ? 2 : 1;
|
|
yield {
|
|
qmSearchCode: id,
|
|
date,
|
|
unadjustedclose: Number((baseClose * mult).toFixed(4)),
|
|
} as unknown as T;
|
|
}
|
|
}
|
|
}
|
|
},
|
|
async close(): Promise<void> {
|
|
// No-op for in-memory benchmark cursor.
|
|
},
|
|
};
|
|
},
|
|
};
|
|
},
|
|
};
|
|
|
|
const barSpanReader: BarSpanAggregateReader = {
|
|
aggregate<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
collectionName: string,
|
|
pipeline: Record<string, unknown>[]
|
|
): AsyncIterable<T> {
|
|
let requestedIds: string[] = [];
|
|
for (const stage of pipeline) {
|
|
const match = stage.$match as Record<string, unknown> | undefined;
|
|
if (match && typeof match === 'object') {
|
|
for (const value of Object.values(match)) {
|
|
if (
|
|
value &&
|
|
typeof value === 'object' &&
|
|
Array.isArray((value as { $in?: unknown }).$in)
|
|
) {
|
|
requestedIds = (value as { $in: string[] }).$in;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const isEod = collectionName === 'eodPrices';
|
|
return {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
for (let i = 0; i < requestedIds.length; i++) {
|
|
const id = requestedIds[i];
|
|
if (id === undefined) {
|
|
continue;
|
|
}
|
|
const exists = isEod ? eodIndexById.has(id) : qmIndexById.has(id);
|
|
if (!exists) {
|
|
continue;
|
|
}
|
|
const row: GroupedBarSpanRow = {
|
|
_id: id,
|
|
firstBarDate: FIRST_BAR_DATE,
|
|
lastBarDate: LAST_BAR_DATE,
|
|
barCount: 1510,
|
|
};
|
|
yield row as unknown as T;
|
|
}
|
|
},
|
|
};
|
|
},
|
|
};
|
|
|
|
return { mongoCollectionClient, barSpanReader };
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const { mongoCollectionClient, barSpanReader } = createBenchmarkMongo(PAIR_COUNT);
|
|
|
|
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
|
|
Bun.gc(true);
|
|
}
|
|
const heapBefore = process.memoryUsage().heapUsed;
|
|
const startedAt = performance.now();
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient,
|
|
barSpanReader,
|
|
writeFile: () => {},
|
|
writeStdout: () => {},
|
|
},
|
|
{
|
|
asOfDate: AS_OF_DATE,
|
|
outDir: '/virtual/benchmark-out',
|
|
batchSize: 5_000,
|
|
pass4: { enabled: true, sampleDateCount: SAMPLE_DATE_COUNT },
|
|
}
|
|
);
|
|
|
|
const elapsedMs = performance.now() - startedAt;
|
|
const heapAfter = process.memoryUsage().heapUsed;
|
|
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
|
|
|
|
if (result.composed.pass4 === null || result.sampleCloses === null) {
|
|
throw new Error('Benchmark failed: Pass 4 did not execute');
|
|
}
|
|
|
|
const expectedMismatches = Math.ceil(PAIR_COUNT / MISMATCH_EVERY);
|
|
const expectedConfirmed = PAIR_COUNT - expectedMismatches;
|
|
const { pairsIn, byVerdict } = result.composed.pass4.stats;
|
|
if (
|
|
pairsIn !== PAIR_COUNT ||
|
|
byVerdict.confirmed !== expectedConfirmed ||
|
|
byVerdict.ratio_mismatch !== expectedMismatches
|
|
) {
|
|
throw new Error(
|
|
`Benchmark verdict mismatch: pairsIn=${pairsIn}, confirmed=${byVerdict.confirmed} (expected ${expectedConfirmed}), ratio_mismatch=${byVerdict.ratio_mismatch} (expected ${expectedMismatches})`
|
|
);
|
|
}
|
|
|
|
const totalDocsRead =
|
|
result.sampleCloses.stats.eod.docsRead +
|
|
result.sampleCloses.stats.qm.docsRead +
|
|
result.sampleCloses.stats.fx.docsRead;
|
|
const pairsPerSec = Math.round(PAIR_COUNT / (elapsedMs / 1000));
|
|
const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000));
|
|
|
|
const lines = [
|
|
'Pass 4b runSecurityMaster benchmark (in-memory async cursor, zero DB, zero disk)',
|
|
` Workload: ${PAIR_COUNT.toLocaleString('en-US')} EOD<->QM pairs x ${SAMPLE_DATE_COUNT} dates (${totalDocsRead.toLocaleString('en-US')} sample-close/FX docs)`,
|
|
` Verdicts: confirmed=${byVerdict.confirmed.toLocaleString('en-US')}, ratio_mismatch=${byVerdict.ratio_mismatch.toLocaleString('en-US')}, low_correlation=${byVerdict.low_correlation}, insufficient_data=${byVerdict.insufficient_data}`,
|
|
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
|
|
` Throughput: ${pairsPerSec.toLocaleString('en-US')} pairs/s | ${docsPerSec.toLocaleString('en-US')} docs/s`,
|
|
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
|
|
];
|
|
process.stdout.write(`${lines.join('\n')}\n`);
|
|
}
|
|
|
|
await main();
|