1448 lines
50 KiB
TypeScript
1448 lines
50 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
BarSpanIndex,
|
|
type BarSpan,
|
|
type ComputeBarSpansResult,
|
|
} from '../../apps/stock/data-pipeline/src/normalization/bar-spans';
|
|
import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers';
|
|
import {
|
|
attachBarSpansToStageBInput,
|
|
classifySourceExchanges,
|
|
composeSecurityMasterRun,
|
|
CONTINUITY_KIND_OTC_DELIST_TRANSFER,
|
|
derivePass4CandidatePairs,
|
|
deriveSourceCountries,
|
|
filterSampleClosesByMappingBounds,
|
|
formatListingNaturalKey,
|
|
type ComposeSecurityMasterRunInput,
|
|
type FxRateByDateRecord,
|
|
type SampleCloseRecord,
|
|
type SecurityMasterSourcesResult,
|
|
type SecurityMasterStageBSourceInput,
|
|
type SecurityType,
|
|
type StageASourceRecord,
|
|
type StageBEodListingInput,
|
|
type StageBIbContractInput,
|
|
type StageBSymbolChangeInput,
|
|
type StageBTickerSourceInput,
|
|
} from '../../apps/stock/data-pipeline/src/security-master';
|
|
|
|
const runSourcePath = fileURLToPath(
|
|
new URL('../../apps/stock/data-pipeline/src/security-master/run.ts', import.meta.url)
|
|
);
|
|
|
|
function makeRng(seed: number): () => number {
|
|
let state = seed >>> 0;
|
|
return () => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let t = state;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
};
|
|
}
|
|
|
|
function shuffleWithSeed<T>(items: readonly T[], seed: number): T[] {
|
|
const copy = [...items];
|
|
const rng = makeRng(seed);
|
|
for (let i = copy.length - 1; i > 0; i--) {
|
|
const j = Math.floor(rng() * (i + 1));
|
|
const a = copy[i];
|
|
const b = copy[j];
|
|
if (a !== undefined && b !== undefined) {
|
|
copy[i] = b;
|
|
copy[j] = a;
|
|
}
|
|
}
|
|
return copy;
|
|
}
|
|
|
|
function makeEmptyCollectionStats(
|
|
collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange'
|
|
) {
|
|
return {
|
|
collection,
|
|
docsRead: 0,
|
|
emitted: 0,
|
|
invalidIdentifiersNulled: 0,
|
|
skips: {
|
|
missingId: 0,
|
|
invalidFieldType: 0,
|
|
invalidIdentifier: 0,
|
|
excludedMutualFund: 0,
|
|
unmappedExchange: 0,
|
|
outOfScopeCountry: 0,
|
|
},
|
|
};
|
|
}
|
|
|
|
function makeSourcesResult(params: {
|
|
stageARecords: StageASourceRecord[];
|
|
eodListings: StageBEodListingInput[];
|
|
ibContracts: StageBIbContractInput[];
|
|
tickerSources: StageBTickerSourceInput[];
|
|
symbolChanges?: StageBSymbolChangeInput[];
|
|
securityTypeByIsin: Map<string, SecurityType>;
|
|
}): SecurityMasterSourcesResult {
|
|
return {
|
|
stageARecords: params.stageARecords,
|
|
stageBInput: {
|
|
eodListings: params.eodListings,
|
|
ibContracts: params.ibContracts,
|
|
tickerSources: params.tickerSources,
|
|
symbolChanges: params.symbolChanges ?? [],
|
|
},
|
|
securityTypeRecords: [],
|
|
securityTypeByIsin: params.securityTypeByIsin,
|
|
securityTypeStats: {
|
|
totalRecords: 0,
|
|
mapped: 0,
|
|
missingType: 0,
|
|
unknownType: 0,
|
|
invalidIsin: 0,
|
|
isinsResolved: params.securityTypeByIsin.size,
|
|
isinsConflicting: 0,
|
|
conflictsTruncated: 0,
|
|
},
|
|
securityTypeLoaderStats: {
|
|
totalRecords: 0,
|
|
mapped: 0,
|
|
missingType: 0,
|
|
unknownType: 0,
|
|
invalidIsin: 0,
|
|
isinsResolved: params.securityTypeByIsin.size,
|
|
isinsConflicting: 0,
|
|
conflictsTruncated: 0,
|
|
},
|
|
unknownSecurityTypes: [],
|
|
securityTypeConflicts: [],
|
|
stats: {
|
|
eodSymbols: makeEmptyCollectionStats('eodSymbols'),
|
|
ibSymbols: makeEmptyCollectionStats('ibSymbols'),
|
|
qmSymbols: makeEmptyCollectionStats('qmSymbols'),
|
|
ceoSymbols: makeEmptyCollectionStats('ceoSymbols'),
|
|
eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'),
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Canonical M1 exit-criterion fixture:
|
|
* - AAPL (`US0378331005`): EOD + IB + QM on XNAS (USD)
|
|
* - FB common (`US30303M1027`, 2012-2022) vs FB ETF (`US4642872000`, 2025) on XNAS (USD)
|
|
* - SIVB (`US78486Q1013`) XNAS (2015..2023-03-10) -> SIVBQ OTCM (2023-03-28..2024-11-07)
|
|
* - SHOP (`CA82509L1076`) interlisted XTSE (CAD) + XNYS (USD) with IB contracts in CAD & USD
|
|
*/
|
|
function buildCanonicalFixture(): {
|
|
input: ComposeSecurityMasterRunInput;
|
|
sampleCloses: SampleCloseRecord[];
|
|
fxRates: FxRateByDateRecord[];
|
|
} {
|
|
const stageARecords: StageASourceRecord[] = [
|
|
{
|
|
source: 'ib',
|
|
sourceId: '265598',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Apple Inc.',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Apple Inc',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'FB_OLD.US',
|
|
isin: 'US30303M1027',
|
|
cusip: '30303M102',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Meta Platforms Inc',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'FB_ETF.US',
|
|
isin: 'US4642872000',
|
|
cusip: '464287200',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'FB Thematic ETF',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SIVB.US',
|
|
isin: 'US78486Q1013',
|
|
cusip: '78486Q101',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'SVB Financial Group',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SIVBQ.US',
|
|
isin: 'US78486Q1013',
|
|
cusip: '78486Q101',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'SVB Financial Group',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SHOP.TO',
|
|
isin: 'CA82509L1076',
|
|
cusip: '82509L107',
|
|
country: 'CA',
|
|
currency: 'CAD',
|
|
name: 'Shopify Inc.',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SHOP.US',
|
|
isin: 'CA82509L1076',
|
|
cusip: '82509L107',
|
|
country: 'CA',
|
|
currency: 'USD',
|
|
name: 'Shopify Inc.',
|
|
},
|
|
{
|
|
source: 'ib',
|
|
sourceId: '2001',
|
|
isin: 'CA82509L1076',
|
|
cusip: '82509L107',
|
|
country: 'CA',
|
|
currency: 'CAD',
|
|
name: 'Shopify Inc.',
|
|
},
|
|
{
|
|
source: 'ib',
|
|
sourceId: '2002',
|
|
isin: 'CA82509L1076',
|
|
cusip: '82509L107',
|
|
country: 'CA',
|
|
currency: 'USD',
|
|
name: 'Shopify Inc.',
|
|
},
|
|
];
|
|
|
|
// Spans start as null on EOD/QM to verify attachBarSpansToStageBInput wires them from barSpans.
|
|
const eodListings: StageBEodListingInput[] = [
|
|
{
|
|
sourceId: 'AAPL.US',
|
|
ticker: 'AAPL',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'FB_OLD.US',
|
|
ticker: 'FB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'FB_ETF.US',
|
|
ticker: 'FB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'SIVB.US',
|
|
ticker: 'SIVB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'SIVBQ.US',
|
|
ticker: 'SIVBQ',
|
|
mic: 'OTCM',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'SHOP.TO',
|
|
ticker: 'SHOP',
|
|
mic: 'XTSE',
|
|
role: 'primary_venue',
|
|
currency: 'CAD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'SHOP.US',
|
|
ticker: 'SHOP',
|
|
mic: 'XNYS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
];
|
|
|
|
const ibContracts: StageBIbContractInput[] = [
|
|
{ sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' },
|
|
{ sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' },
|
|
{ sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' },
|
|
];
|
|
|
|
const tickerSources: StageBTickerSourceInput[] = [
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'AAPL:US',
|
|
ticker: 'AAPL',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'FB_OLD:US',
|
|
ticker: 'FB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'FB_ETF:US',
|
|
ticker: 'FB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'SHOP:CA',
|
|
ticker: 'SHOP',
|
|
mic: 'XTSE',
|
|
role: 'primary_venue',
|
|
currency: 'CAD',
|
|
span: null,
|
|
},
|
|
{
|
|
source: 'ceo',
|
|
sourceId: 'ceo:SHOP',
|
|
ticker: 'SHOP',
|
|
mic: 'XTSE',
|
|
role: 'primary_venue',
|
|
currency: 'CAD',
|
|
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' },
|
|
},
|
|
];
|
|
|
|
const barSpans: BarSpan[] = [
|
|
{ source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 },
|
|
{ source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 },
|
|
{ source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 },
|
|
{ source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 },
|
|
{ source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 },
|
|
{ source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 },
|
|
{ source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 },
|
|
{ source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 },
|
|
{ source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 },
|
|
{ source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 },
|
|
{ source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 },
|
|
];
|
|
|
|
const securityTypeByIsin = new Map<string, SecurityType>([
|
|
['US0378331005', 'common'],
|
|
['US30303M1027', 'common'],
|
|
['US4642872000', 'etf'],
|
|
['US78486Q1013', 'common'],
|
|
['CA82509L1076', 'common'],
|
|
]);
|
|
|
|
const exchanges = classifySourceExchanges([
|
|
{ source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' },
|
|
{ source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' },
|
|
{ source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' },
|
|
{ source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' },
|
|
]);
|
|
|
|
const dates = [
|
|
'2025-01-02',
|
|
'2025-01-03',
|
|
'2025-01-06',
|
|
'2025-01-07',
|
|
'2025-01-08',
|
|
'2025-01-09',
|
|
];
|
|
const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1];
|
|
const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0];
|
|
|
|
const sampleCloses: SampleCloseRecord[] = [];
|
|
const fxRates: FxRateByDateRecord[] = [];
|
|
for (let i = 0; i < dates.length; i++) {
|
|
const date = dates[i]!;
|
|
const aapl = aaplPrices[i]!;
|
|
const shop = shopCadPrices[i]!;
|
|
fxRates.push({ date, usdCad: 1.38 + i * 0.005 });
|
|
// AAPL: eod vs qm matching closes -> confirmed
|
|
sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl });
|
|
sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 });
|
|
// SHOP.TO: eod vs qm deliberately 1.5x ratio mismatch -> price_ratio_mismatch
|
|
sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop });
|
|
sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 1.5 });
|
|
// ceo:SHOP also mismatches eod SHOP.TO (2.0x) to exercise two mismatches sharing a left endpoint
|
|
sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop * 2.0 });
|
|
}
|
|
|
|
const input: ComposeSecurityMasterRunInput = {
|
|
sources: makeSourcesResult({
|
|
stageARecords,
|
|
eodListings,
|
|
ibContracts,
|
|
tickerSources,
|
|
securityTypeByIsin,
|
|
}),
|
|
barSpans,
|
|
exchanges,
|
|
};
|
|
|
|
return { input, sampleCloses, fxRates };
|
|
}
|
|
|
|
describe('security-master run composer purity & exports', () => {
|
|
test('contains zero I/O imports and zero wall-clock calls', () => {
|
|
const src = readFileSync(runSourcePath, 'utf8');
|
|
expect(src).not.toMatch(/\bfrom\s+['"](node:)?(fs|net|http|https|pg|mongodb)['"]/);
|
|
expect(src).not.toMatch(/\bfrom\s+['"]@stock-bot\/(mongodb|postgres)['"]/);
|
|
expect(src).not.toMatch(/\bDate\.now\b/);
|
|
expect(src).not.toMatch(/\bnew\s+Date\b/);
|
|
expect(src).not.toMatch(/\bperformance\.now\b/);
|
|
|
|
expect(typeof composeSecurityMasterRun).toBe('function');
|
|
expect(typeof attachBarSpansToStageBInput).toBe('function');
|
|
expect(typeof derivePass4CandidatePairs).toBe('function');
|
|
expect(typeof deriveSourceCountries).toBe('function');
|
|
});
|
|
});
|
|
|
|
describe('security-master run composer adapter helpers', () => {
|
|
test('attachBarSpansToStageBInput supports BarSpan[], BarSpanIndex, ComputeBarSpansResult, merges duplicates, preserves CEO spans, and skips malformed entries', () => {
|
|
const baseStageB: SecurityMasterStageBSourceInput = {
|
|
eodListings: [
|
|
{ sourceId: 'A.US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null },
|
|
{
|
|
sourceId: 'B.US',
|
|
ticker: 'B',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: { firstBarDate: '2020-01-02', lastBarDate: '2020-12-31' },
|
|
},
|
|
],
|
|
ibContracts: [{ sourceId: '101', conid: 101, currency: 'USD', primaryExchange: 'NASDAQ' }],
|
|
tickerSources: [
|
|
{ source: 'qm', sourceId: 'A:US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null },
|
|
{
|
|
source: 'ceo',
|
|
sourceId: 'ceo:A',
|
|
ticker: 'A',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: { firstBarDate: '2021-01-04', lastBarDate: '2024-12-31' },
|
|
},
|
|
],
|
|
symbolChanges: [],
|
|
};
|
|
|
|
const barSpansArray: BarSpan[] = [
|
|
{ source: 'eod', sourceId: 'A.US', firstBarDate: '2018-01-02', lastBarDate: '2022-12-30', barCount: 1000 },
|
|
{ source: 'eod', sourceId: 'A.US', firstBarDate: '2016-01-04', lastBarDate: '2024-12-31', barCount: 500 },
|
|
{ source: 'qm', sourceId: 'A:US', firstBarDate: '2019-01-02', lastBarDate: '2024-12-31', barCount: 1500 },
|
|
// Malformed entry (inverted dates)
|
|
{ source: 'eod', sourceId: 'BAD.US', firstBarDate: '2025-01-02', lastBarDate: '2024-01-02', barCount: 10 },
|
|
];
|
|
|
|
const fromArray = attachBarSpansToStageBInput(baseStageB, barSpansArray);
|
|
expect(fromArray.stats.recordsIn).toBe(4);
|
|
expect(fromArray.stats.resolved).toBe(3);
|
|
expect(fromArray.stats.skipped).toBe(1);
|
|
expect(fromArray.stats.attachedEodListings).toBe(1);
|
|
expect(fromArray.stats.attachedQmTickerSources).toBe(1);
|
|
// Merged min/max span for A.US
|
|
expect(fromArray.stageBInput.eodListings[0]?.span).toEqual({
|
|
firstBarDate: '2016-01-04',
|
|
lastBarDate: '2024-12-31',
|
|
});
|
|
// Existing span on B.US preserved when absent from barSpans
|
|
expect(fromArray.stageBInput.eodListings[1]?.span).toEqual({
|
|
firstBarDate: '2020-01-02',
|
|
lastBarDate: '2020-12-31',
|
|
});
|
|
// QM span attached, CEO span preserved
|
|
expect(fromArray.stageBInput.tickerSources[0]?.span).toEqual({
|
|
firstBarDate: '2019-01-02',
|
|
lastBarDate: '2024-12-31',
|
|
});
|
|
expect(fromArray.stageBInput.tickerSources[1]?.span).toEqual({
|
|
firstBarDate: '2021-01-04',
|
|
lastBarDate: '2024-12-31',
|
|
});
|
|
// Original input not mutated
|
|
expect(baseStageB.eodListings[0]?.span).toBeNull();
|
|
|
|
// BarSpanIndex and ComputeBarSpansResult inputs produce identical spans
|
|
const index = new BarSpanIndex();
|
|
index.merge(barSpansArray[0]!);
|
|
index.merge(barSpansArray[1]!);
|
|
index.merge(barSpansArray[2]!);
|
|
|
|
const fromIndex = attachBarSpansToStageBInput(baseStageB, index);
|
|
expect(fromIndex.stageBInput).toEqual(fromArray.stageBInput);
|
|
|
|
const computeResult: ComputeBarSpansResult = {
|
|
index,
|
|
bySource: {},
|
|
skipped: { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 },
|
|
totalRowsRead: 3,
|
|
totalSpans: index.size,
|
|
};
|
|
const fromComputeResult = attachBarSpansToStageBInput(baseStageB, computeResult);
|
|
expect(fromComputeResult.stageBInput).toEqual(fromArray.stageBInput);
|
|
});
|
|
|
|
test('derivePass4CandidatePairs emits deduplicated ASCII-sorted cross-source pairs per listing', () => {
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const mappings = [
|
|
{ source: 'qm' as const, sourceId: 'AAPL:US', listingKey: key, method: 'tier3_ticker_span' as const, validFrom: null, validTo: null },
|
|
{ source: 'eod' as const, sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null },
|
|
{ source: 'eod' as const, sourceId: 'AAPL_DUP.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null },
|
|
{ source: 'ib' as const, sourceId: '265598', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null },
|
|
];
|
|
|
|
const pairsA = derivePass4CandidatePairs(mappings);
|
|
const pairsB = derivePass4CandidatePairs([...mappings].reverse());
|
|
expect(pairsA).toEqual(pairsB);
|
|
// Same-source pair (eod, eod) must never be emitted
|
|
for (const pair of pairsA) {
|
|
expect(pair.left.source).not.toBe(pair.right.source);
|
|
}
|
|
// 2 eod * 1 ib + 2 eod * 1 qm + 1 ib * 1 qm = 5 cross-source pairs
|
|
expect(pairsA.length).toBe(5);
|
|
});
|
|
|
|
test('deriveSourceCountries resolves MIC countries with Stage A fallback deterministically', () => {
|
|
const stageARecords: StageASourceRecord[] = [
|
|
{ source: 'ib', sourceId: '265598', isin: 'US0378331005', country: 'US' },
|
|
{ source: 'eod', sourceId: 'SHOP.TO', isin: 'CA82509L1076', country: 'CA' },
|
|
];
|
|
const stageBInput = {
|
|
eodListings: [
|
|
{ sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null },
|
|
],
|
|
tickerSources: [
|
|
{ source: 'qm' as const, sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null },
|
|
],
|
|
};
|
|
const countries = deriveSourceCountries(stageARecords, stageBInput, { providerMappings: [] });
|
|
expect(countries.get('ib:265598')).toBe('US');
|
|
expect(countries.get('eod:SHOP.TO')).toBe('CA');
|
|
expect(countries.get('qm:SHOP:CA')).toBe('CA');
|
|
});
|
|
});
|
|
|
|
describe('composeSecurityMasterRun', () => {
|
|
test('resolves FB common vs FB ETF to two distinct instruments and listings, chains SIVB -> SIVBQ, and attaches IB + interlisted SHOP', () => {
|
|
const { input } = buildCanonicalFixture();
|
|
const result = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' });
|
|
|
|
// FB common (US30303M1027) vs FB ETF (US4642872000)
|
|
const fbListings = result.stageB.listings.filter(l => l.tickerRoot === 'FB');
|
|
expect(fbListings.length).toBe(2);
|
|
const fbKeys = fbListings.map(l => formatListingNaturalKey(l));
|
|
expect(new Set(fbKeys).size).toBe(2);
|
|
expect(new Set(fbListings.map(l => l.primaryIsin))).toEqual(
|
|
new Set(['US30303M1027', 'US4642872000'])
|
|
);
|
|
expect(result.persistInput.stageA.instruments.filter(i => i.primaryIsin === 'US30303M1027' || i.primaryIsin === 'US4642872000').length).toBe(2);
|
|
expect(result.persistInput.securityTypeByIsin.get('US30303M1027')).toBe('common');
|
|
expect(result.persistInput.securityTypeByIsin.get('US4642872000')).toBe('etf');
|
|
|
|
// QM FB_OLD:US -> US30303M1027, QM FB_ETF:US -> US4642872000
|
|
const qmFbOld = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_OLD:US');
|
|
const qmFbEtf = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_ETF:US');
|
|
expect(qmFbOld?.listingKey.primaryIsin).toBe('US30303M1027');
|
|
expect(qmFbEtf?.listingKey.primaryIsin).toBe('US4642872000');
|
|
|
|
// SIVB -> SIVBQ OTC continuity
|
|
expect(result.pass6.continuities.length).toBe(1);
|
|
const continuity = result.pass6.continuities[0]!;
|
|
expect(continuity.fromListingKey.tickerRoot).toBe('SIVB');
|
|
expect(continuity.fromListingKey.mic).toBe('XNAS');
|
|
expect(continuity.toListingKey.tickerRoot).toBe('SIVBQ');
|
|
expect(continuity.toListingKey.mic).toBe('OTCM');
|
|
expect(continuity.kind).toBe(CONTINUITY_KIND_OTC_DELIST_TRANSFER);
|
|
expect(result.persistInput.pass6?.continuities).toEqual(result.pass6.continuities);
|
|
expect(result.report.delistingChains?.continuitiesCreated).toBe(1);
|
|
expect(result.reportMarkdown).toContain('- Continuities Created: 1');
|
|
|
|
// Interlisted SHOP (CA82509L1076) -> 1 instrument, 2 listings (CAD + USD), IB attached at (instrument, currency)
|
|
const shopInstruments = result.stageA.instruments.filter(i => i.primaryIsin === 'CA82509L1076');
|
|
expect(shopInstruments.length).toBe(1);
|
|
const shopListings = result.stageB.listings.filter(l => l.primaryIsin === 'CA82509L1076');
|
|
expect(shopListings.length).toBe(2);
|
|
const shopCad = shopListings.find(l => l.currency === 'CAD');
|
|
const shopUsd = shopListings.find(l => l.currency === 'USD');
|
|
expect(shopCad?.mic).toBe('XTSE');
|
|
expect(shopCad?.ibConid).toBe(2001);
|
|
expect(shopUsd?.mic).toBe('XNYS');
|
|
expect(shopUsd?.ibConid).toBe(2002);
|
|
|
|
// IB AAPL attached at (US0378331005, USD)
|
|
const aaplListing = result.stageB.listings.find(l => l.primaryIsin === 'US0378331005');
|
|
expect(aaplListing?.ibConid).toBe(265598);
|
|
});
|
|
|
|
test('Pass 4 supplied confirms matching pairs and emits price_ratio_mismatch into report, CSV, SQL, and persistInput; omitted marks Pass 4 skipped', () => {
|
|
const { input, sampleCloses, fxRates } = buildCanonicalFixture();
|
|
|
|
// 1. Omitted sampleCloses -> Pass 4 skipped (never reported as passed)
|
|
const skippedRun = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' });
|
|
expect(skippedRun.pass4).toBeNull();
|
|
expect(skippedRun.persistInput.pass4).toBeUndefined();
|
|
expect(skippedRun.stats.pass4.status).toBe('skipped');
|
|
expect(skippedRun.stats.pass4.resolved).toBe(0);
|
|
expect(skippedRun.stats.pass4.skipped).toBe(skippedRun.pass4CandidatePairs.length);
|
|
expect(skippedRun.report.priceCrossCheck).toBeNull();
|
|
expect(skippedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe(0);
|
|
expect(skippedRun.reportMarkdown).toContain('- Status: skipped (no sample closes supplied)');
|
|
|
|
// 2. Supplied sampleCloses + fxRates -> AAPL confirmed, SHOP mismatches emitted everywhere
|
|
const suppliedRun = composeSecurityMasterRun(
|
|
{ ...input, sampleCloses, fxRates },
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
expect(suppliedRun.pass4).not.toBeNull();
|
|
expect(suppliedRun.persistInput.pass4).toBe(suppliedRun.pass4);
|
|
expect(suppliedRun.stats.pass4.status).toBe('executed');
|
|
expect(suppliedRun.reportMarkdown).not.toContain('Status: skipped');
|
|
|
|
const aaplRow = suppliedRun.pass4!.results.find(
|
|
r => r.left.sourceId === 'AAPL.US' && r.right.sourceId === 'AAPL:US'
|
|
);
|
|
expect(aaplRow?.verdict).toBe('confirmed');
|
|
|
|
const pass4Conflicts = suppliedRun.pass4!.conflicts;
|
|
expect(pass4Conflicts.length).toBeGreaterThanOrEqual(2);
|
|
expect(pass4Conflicts.every(c => c.conflictKind === 'price_ratio_mismatch')).toBe(true);
|
|
expect(suppliedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe(
|
|
pass4Conflicts.length
|
|
);
|
|
expect(suppliedRun.conflictsCsv).toContain('price_ratio_mismatch');
|
|
expect(suppliedRun.overrideTemplateSql).toContain('price_ratio_mismatch');
|
|
expect(suppliedRun.persistInput.pass4?.conflicts).toEqual(pass4Conflicts);
|
|
});
|
|
|
|
test('produces byte-identical Markdown, CSV, override SQL, and deep-equal persistInput under shuffled inputs', () => {
|
|
const { input, sampleCloses, fxRates } = buildCanonicalFixture();
|
|
const baseline = composeSecurityMasterRun(
|
|
{ ...input, sampleCloses, fxRates },
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
|
|
const shuffledSecTypes = new Map<string, SecurityType>(
|
|
shuffleWithSeed(Array.from(input.sources.securityTypeByIsin.entries()), 77)
|
|
);
|
|
const shuffledInput: ComposeSecurityMasterRunInput = {
|
|
sources: makeSourcesResult({
|
|
stageARecords: shuffleWithSeed(input.sources.stageARecords, 11),
|
|
eodListings: shuffleWithSeed(input.sources.stageBInput.eodListings, 22),
|
|
ibContracts: shuffleWithSeed(input.sources.stageBInput.ibContracts, 33),
|
|
tickerSources: shuffleWithSeed(input.sources.stageBInput.tickerSources, 44),
|
|
symbolChanges: shuffleWithSeed(input.sources.stageBInput.symbolChanges, 55),
|
|
securityTypeByIsin: shuffledSecTypes,
|
|
}),
|
|
barSpans: shuffleWithSeed(input.barSpans as readonly BarSpan[], 66),
|
|
exchanges: input.exchanges,
|
|
sampleCloses: shuffleWithSeed(sampleCloses, 88),
|
|
fxRates: shuffleWithSeed(fxRates, 99),
|
|
};
|
|
|
|
const shuffled = composeSecurityMasterRun(shuffledInput, { asOfDate: '2025-11-28' });
|
|
|
|
expect(shuffled.reportMarkdown).toBe(baseline.reportMarkdown);
|
|
expect(shuffled.conflictsCsv).toBe(baseline.conflictsCsv);
|
|
expect(shuffled.overrideTemplateSql).toBe(baseline.overrideTemplateSql);
|
|
expect(shuffled.persistInput).toEqual(baseline.persistInput);
|
|
expect(Array.from(shuffled.persistInput.securityTypeByIsin.entries())).toEqual(
|
|
Array.from(baseline.persistInput.securityTypeByIsin.entries())
|
|
);
|
|
expect(shuffled.stats).toEqual(baseline.stats);
|
|
});
|
|
|
|
test('reconciles per-step stats and conflict totals while counting malformed/sparse records without throwing', () => {
|
|
const { input, sampleCloses, fxRates } = buildCanonicalFixture();
|
|
|
|
// Add a Stage A conflict (isin_cusip_mismatch) so conflicts come from multiple passes
|
|
const stageARecords: StageASourceRecord[] = [
|
|
...input.sources.stageARecords,
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'CONFLICT_A.US',
|
|
isin: 'US0378331005',
|
|
cusip: '594918104',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Conflict Co',
|
|
},
|
|
// Malformed Stage A records
|
|
null as unknown as StageASourceRecord,
|
|
{ source: 'bogus' as 'eod', sourceId: 'X.US' },
|
|
{ source: 'eod', sourceId: '' },
|
|
];
|
|
// Sparse slot
|
|
stageARecords.length += 1;
|
|
|
|
const eodListings: StageBEodListingInput[] = [
|
|
...input.sources.stageBInput.eodListings,
|
|
null as unknown as StageBEodListingInput,
|
|
{ sourceId: 'BAD_ROLE.US', ticker: 'BR', mic: 'XNAS', role: 'invalid_role' as 'primary_venue', currency: 'USD', span: null },
|
|
];
|
|
const ibContracts: StageBIbContractInput[] = [
|
|
...input.sources.stageBInput.ibContracts,
|
|
{ sourceId: '', conid: 999, currency: 'USD', primaryExchange: 'NASDAQ' },
|
|
];
|
|
const tickerSources: StageBTickerSourceInput[] = [
|
|
...input.sources.stageBInput.tickerSources,
|
|
{ source: 'unknown' as 'qm', sourceId: 'U:US', ticker: 'U', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null },
|
|
];
|
|
const symbolChanges: StageBSymbolChangeInput[] = [
|
|
{ eodSourceId: '', oldTicker: 'OLD', effectiveDate: '2022-01-01' },
|
|
{ eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: 'not-a-date' },
|
|
{ eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: '2022-01-01', validFrom: '2023-01-01' },
|
|
];
|
|
const barSpans: BarSpan[] = [
|
|
...(input.barSpans as readonly BarSpan[]),
|
|
null as unknown as BarSpan,
|
|
{ source: 'eod', sourceId: 'NEG.US', firstBarDate: '2020-01-02', lastBarDate: '2020-12-31', barCount: -5 },
|
|
];
|
|
const badCloses: SampleCloseRecord[] = [
|
|
...sampleCloses,
|
|
{ source: 'eod', sourceId: 'AAPL.US', date: 'bad-date', close: 100 },
|
|
{ source: 'eod', sourceId: 'AAPL.US', date: '2025-01-02', close: -1 },
|
|
];
|
|
const badFx: FxRateByDateRecord[] = [
|
|
...fxRates,
|
|
{ date: '2025-01-02', usdCad: 0 },
|
|
];
|
|
|
|
const result = composeSecurityMasterRun(
|
|
{
|
|
sources: makeSourcesResult({
|
|
stageARecords,
|
|
eodListings,
|
|
ibContracts,
|
|
tickerSources,
|
|
symbolChanges,
|
|
securityTypeByIsin: input.sources.securityTypeByIsin,
|
|
}),
|
|
barSpans,
|
|
exchanges: input.exchanges,
|
|
sampleCloses: badCloses,
|
|
fxRates: badFx,
|
|
},
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
|
|
// Every step reconciles: recordsIn === resolved + unresolved + skipped
|
|
const { stats } = result;
|
|
expect(stats.barSpans.recordsIn).toBe(
|
|
stats.barSpans.resolved + stats.barSpans.unresolved + stats.barSpans.skipped
|
|
);
|
|
expect(stats.stageA.recordsIn).toBe(
|
|
stats.stageA.resolved + stats.stageA.unresolved + stats.stageA.skipped
|
|
);
|
|
expect(stats.stageB.recordsIn).toBe(
|
|
stats.stageB.resolved + stats.stageB.unresolved + stats.stageB.skipped
|
|
);
|
|
expect(stats.pass6.recordsIn).toBe(
|
|
stats.pass6.resolved + stats.pass6.unresolved + stats.pass6.skipped
|
|
);
|
|
expect(stats.pass4.recordsIn).toBe(
|
|
stats.pass4.resolved + stats.pass4.unresolved + stats.pass4.skipped
|
|
);
|
|
|
|
// Malformed counts surfaced accurately
|
|
expect(stats.malformedInputs.stageARecords).toBe(4); // null + bogus source + empty sourceId + sparse slot
|
|
expect(stats.malformedInputs.eodListings).toBe(2);
|
|
expect(stats.malformedInputs.ibContracts).toBe(1);
|
|
expect(stats.malformedInputs.tickerSources).toBe(1);
|
|
expect(stats.malformedInputs.symbolChanges).toBe(3);
|
|
expect(stats.malformedInputs.barSpans).toBe(2);
|
|
expect(stats.malformedInputs.sampleCloses).toBe(2);
|
|
expect(stats.malformedInputs.fxRates).toBe(1);
|
|
expect(stats.malformedInputs.total).toBe(16);
|
|
|
|
// Conflict totals reconcile with report.conflicts.length
|
|
expect(stats.conflicts.stageA).toBe(1);
|
|
expect(stats.conflicts.pass4).toBeGreaterThanOrEqual(2);
|
|
expect(stats.conflicts.total).toBe(
|
|
stats.conflicts.stageA +
|
|
stats.conflicts.stageB +
|
|
stats.conflicts.pass4 +
|
|
stats.conflicts.pass6
|
|
);
|
|
expect(result.report.conflicts.length).toBe(stats.conflicts.total);
|
|
});
|
|
|
|
test('fails the 95% equity-resolution gate when Stage A rejects >5% of eligible EOD records despite 100% Stage B coverage', () => {
|
|
const stageARecords: StageASourceRecord[] = [];
|
|
const eodListings: StageBEodListingInput[] = [];
|
|
const barSpans: BarSpan[] = [];
|
|
const securityTypeByIsin = new Map<string, SecurityType>();
|
|
|
|
// 90 valid in-scope EOD equities that all pass Stage A and match in Stage B (100% Stage B)
|
|
for (let i = 0; i < 90; i++) {
|
|
const base8 = `B${String(i).padStart(7, '0')}`;
|
|
let sum = 0;
|
|
for (let pos = 0; pos < 8; pos++) {
|
|
const ch = base8.charCodeAt(pos);
|
|
let v = ch >= 65 ? ch - 55 : ch - 48;
|
|
if (pos % 2 === 1) {
|
|
v *= 2;
|
|
}
|
|
sum += Math.floor(v / 10) + (v % 10);
|
|
}
|
|
const cusip = `${base8}${(10 - (sum % 10)) % 10}`;
|
|
const isin = cusipToIsin(cusip, 'US')!;
|
|
const ticker = `E${String(i).padStart(3, '0')}`;
|
|
const sourceId = `${ticker}.US`;
|
|
stageARecords.push({
|
|
source: 'eod',
|
|
sourceId,
|
|
isin,
|
|
cusip,
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: `Equity ${i}`,
|
|
});
|
|
eodListings.push({
|
|
sourceId,
|
|
ticker,
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
});
|
|
barSpans.push({
|
|
source: 'eod',
|
|
sourceId,
|
|
firstBarDate: '2020-01-02',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 1500,
|
|
});
|
|
securityTypeByIsin.set(isin, 'common');
|
|
}
|
|
|
|
// 10 in-scope EOD equities lacking usable identifiers (rejected by Stage A, never reach Stage B)
|
|
for (let i = 0; i < 10; i++) {
|
|
const ticker = `N${String(i).padStart(3, '0')}`;
|
|
const sourceId = `${ticker}.US`;
|
|
stageARecords.push({
|
|
source: 'eod',
|
|
sourceId,
|
|
isin: null,
|
|
cusip: null,
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: `NoId Equity ${i}`,
|
|
});
|
|
eodListings.push({
|
|
sourceId,
|
|
ticker,
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
});
|
|
}
|
|
|
|
// 5 excluded_fund EOD records also lacking identifiers (must be excludedByDesign, not penalizing eligibleTotal)
|
|
for (let i = 0; i < 5; i++) {
|
|
const ticker = `F${String(i).padStart(3, '0')}`;
|
|
const sourceId = `${ticker}.US`;
|
|
stageARecords.push({
|
|
source: 'eod',
|
|
sourceId,
|
|
isin: null,
|
|
cusip: null,
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: `Mutual Fund ${i}`,
|
|
});
|
|
eodListings.push({
|
|
sourceId,
|
|
ticker,
|
|
mic: 'XNAS',
|
|
role: 'excluded_fund',
|
|
currency: 'USD',
|
|
span: null,
|
|
});
|
|
}
|
|
|
|
const sources = makeSourcesResult({
|
|
stageARecords,
|
|
eodListings,
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
securityTypeByIsin,
|
|
});
|
|
|
|
const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' });
|
|
|
|
// Stage B itself saw 90/90 matched (100%), but end-to-end eligible coverage is 90/100 (90%)
|
|
expect(result.stageB.stats.bySource.eod.total).toBe(90);
|
|
expect(result.stageB.stats.bySource.eod.matched).toBe(90);
|
|
|
|
const eodRow = result.report.resolutionBySource.find(r => r.source === 'eod');
|
|
expect(eodRow).toBeDefined();
|
|
expect(eodRow?.total).toBe(105);
|
|
expect(eodRow?.matched).toBe(90);
|
|
expect(eodRow?.unresolved).toBe(15);
|
|
expect(eodRow?.conflict).toBe(0);
|
|
expect(eodRow?.excludedByDesign).toBe(5);
|
|
expect(eodRow?.eligibleTotal).toBe(100);
|
|
expect(eodRow?.eligibleResolvedPct).toBeCloseTo(0.9, 10);
|
|
expect(result.report.meetsExitThresholds.equitiesResolved95).toBe(false);
|
|
expect(result.reportMarkdown).toContain('| Equities Resolved (Eligible) | FAIL | >= 95.00% |');
|
|
|
|
const usRow = result.report.resolutionByCountry.find(r => r.country === 'US');
|
|
expect(usRow?.eligibleTotal).toBe(100);
|
|
expect(usRow?.matched).toBe(90);
|
|
expect(usRow?.eligibleResolvedPct).toBeCloseTo(0.9, 10);
|
|
|
|
// Duplicate sourceId in both stageARecords (2 rows) and eodListings (2 rows) must not be counted 3 times
|
|
const dupSources = makeSourcesResult({
|
|
stageARecords: [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'DUP.US',
|
|
isin: 'US0378331005',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Dup A',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'DUP.US',
|
|
isin: 'US0378331005',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Dup B',
|
|
},
|
|
],
|
|
eodListings: [
|
|
{
|
|
sourceId: 'DUP.US',
|
|
ticker: 'DUP',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'DUP.US',
|
|
ticker: 'DUP',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
});
|
|
const dupResult = composeSecurityMasterRun({ sources: dupSources }, { asOfDate: '2025-11-28' });
|
|
const dupEodRow = dupResult.report.resolutionBySource.find(r => r.source === 'eod');
|
|
expect(dupEodRow?.total).toBe(2);
|
|
expect(dupEodRow?.conflict).toBe(2);
|
|
expect(dupResult.report.meetsExitThresholds.equitiesResolved95).toBe(false);
|
|
});
|
|
|
|
test('restricts Pass 4 sample closes to Stage B mapping validity windows on reused tickers', () => {
|
|
const sources = makeSourcesResult({
|
|
stageARecords: [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'META.US',
|
|
isin: 'US30303M1027',
|
|
cusip: '30303M102',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Meta Platforms Inc.',
|
|
},
|
|
],
|
|
eodListings: [
|
|
{
|
|
sourceId: 'META.US',
|
|
ticker: 'META',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'FB:US',
|
|
ticker: 'FB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
symbolChanges: [
|
|
{
|
|
eodSourceId: 'META.US',
|
|
oldTicker: 'FB',
|
|
effectiveDate: '2022-06-09',
|
|
},
|
|
],
|
|
securityTypeByIsin: new Map([['US30303M1027', 'common']]),
|
|
});
|
|
|
|
const barSpans: BarSpan[] = [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'META.US',
|
|
firstBarDate: '2012-05-18',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 3400,
|
|
},
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'FB:US',
|
|
firstBarDate: '2012-05-18',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 3400,
|
|
},
|
|
];
|
|
|
|
// 2 matching closes before rename (too few for minCommonDates=5) + 5 mismatched post-rename closes
|
|
const postRenameMismatchedCloses: SampleCloseRecord[] = [
|
|
{ source: 'eod', sourceId: 'META.US', date: '2025-03-03', close: 650.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-03', close: 25.0 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2025-03-04', close: 655.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-04', close: 25.5 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2025-03-05', close: 660.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-05', close: 24.8 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2025-03-06', close: 645.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-06', close: 25.1 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2025-03-07', close: 670.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-07', close: 26.0 },
|
|
];
|
|
|
|
const twoPreRenameCloses: SampleCloseRecord[] = [
|
|
{ source: 'eod', sourceId: 'META.US', date: '2022-05-02', close: 211.13 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-02', close: 211.15 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2022-05-03', close: 212.03 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-03', close: 212.0 },
|
|
];
|
|
|
|
const insufficientResult = composeSecurityMasterRun(
|
|
{
|
|
sources,
|
|
barSpans,
|
|
sampleCloses: [...twoPreRenameCloses, ...postRenameMismatchedCloses],
|
|
},
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
|
|
const qmMapping = insufficientResult.stageB.providerMappings.find(
|
|
m => m.source === 'qm' && m.sourceId === 'FB:US'
|
|
);
|
|
expect(qmMapping?.validTo).toBe('2022-06-08');
|
|
expect(insufficientResult.pass4).not.toBeNull();
|
|
expect(insufficientResult.pass4?.results.length).toBe(1);
|
|
expect(insufficientResult.pass4?.results[0]?.verdict).toBe('insufficient_data');
|
|
expect(insufficientResult.pass4?.results[0]?.usableDates).toBe(2);
|
|
expect(insufficientResult.pass4?.conflicts.length).toBe(0);
|
|
|
|
// 5 matching closes inside the valid window + 5 mismatched post-rename closes -> confirmed, 0 conflicts
|
|
const fivePreRenameCloses: SampleCloseRecord[] = [
|
|
...twoPreRenameCloses,
|
|
{ source: 'eod', sourceId: 'META.US', date: '2022-05-04', close: 223.41 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-04', close: 223.4 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2022-05-05', close: 208.28 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-05', close: 208.3 },
|
|
{ source: 'eod', sourceId: 'META.US', date: '2022-05-06', close: 203.77 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-06', close: 203.75 },
|
|
];
|
|
|
|
const confirmedResult = composeSecurityMasterRun(
|
|
{
|
|
sources,
|
|
barSpans,
|
|
sampleCloses: [...fivePreRenameCloses, ...postRenameMismatchedCloses],
|
|
},
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
|
|
expect(confirmedResult.pass4?.results[0]?.verdict).toBe('confirmed');
|
|
expect(confirmedResult.pass4?.results[0]?.usableDates).toBe(5);
|
|
expect(confirmedResult.pass4?.conflicts.length).toBe(0);
|
|
|
|
// Direct helper check: malformed closes pass through so crossCheckPrices counts droppedInvalidCloses
|
|
const filtered = filterSampleClosesByMappingBounds(insufficientResult.stageB.providerMappings, [
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-06-08', close: 195.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: '2022-06-09', close: 25.0 },
|
|
{ source: 'qm', sourceId: 'FB:US', date: 'bad-date', close: 10.0 },
|
|
]);
|
|
expect(filtered.map(c => c.date)).toEqual(['2022-06-08', 'bad-date']);
|
|
});
|
|
|
|
test('rejects zero-bar spans as malformed and prevents a zero-bar OTC span from establishing continuity', () => {
|
|
const sources = makeSourcesResult({
|
|
stageARecords: [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SIVB.US',
|
|
isin: 'US78486Q1013',
|
|
cusip: '78486Q101',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'SVB Financial Group',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SIVBQ.US',
|
|
isin: 'US78486Q1013',
|
|
cusip: '78486Q101',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'SVB Financial Group OTC',
|
|
},
|
|
],
|
|
eodListings: [
|
|
{
|
|
sourceId: 'SIVB.US',
|
|
ticker: 'SIVB',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
{
|
|
sourceId: 'SIVBQ.US',
|
|
ticker: 'SIVBQ',
|
|
mic: 'OTCM',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
securityTypeByIsin: new Map([['US78486Q1013', 'common']]),
|
|
});
|
|
|
|
const barSpans: BarSpan[] = [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SIVB.US',
|
|
firstBarDate: '2015-01-02',
|
|
lastBarDate: '2023-03-10',
|
|
barCount: 2050,
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SIVBQ.US',
|
|
firstBarDate: '2023-03-28',
|
|
lastBarDate: '2024-11-07',
|
|
barCount: 0,
|
|
},
|
|
];
|
|
|
|
const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' });
|
|
|
|
expect(result.stats.barSpans.recordsIn).toBe(2);
|
|
expect(result.stats.barSpans.resolved).toBe(1);
|
|
expect(result.stats.barSpans.unresolved).toBe(0);
|
|
expect(result.stats.barSpans.skipped).toBe(1);
|
|
expect(result.stats.barSpans.indexedSpans).toBe(1);
|
|
expect(result.stats.malformedInputs.barSpans).toBe(1);
|
|
|
|
const sivbqListing = result.stageB.listings.find(l => l.tickerRoot === 'SIVBQ');
|
|
expect(sivbqListing?.listedFrom).toBeNull();
|
|
expect(sivbqListing?.listedTo).toBeNull();
|
|
expect(result.pass6.continuities.length).toBe(0);
|
|
});
|
|
|
|
test('carries through totalRowsRead and skipped.total from ComputeBarSpansResult and separates accepted rows from distinct indexed spans', () => {
|
|
const index = new BarSpanIndex();
|
|
for (let i = 0; i < 99; i++) {
|
|
index.merge({
|
|
source: 'eod',
|
|
sourceId: `SYM${i}.US`,
|
|
firstBarDate: '2020-01-02',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 1000,
|
|
});
|
|
}
|
|
// Merge one duplicate row into an existing span: 100 accepted rows -> 99 distinct indexed spans
|
|
index.merge({
|
|
source: 'eod',
|
|
sourceId: 'SYM0.US',
|
|
firstBarDate: '2019-01-02',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 250,
|
|
});
|
|
|
|
const readerResult: ComputeBarSpansResult = {
|
|
index,
|
|
bySource: {
|
|
eod: {
|
|
source: 'eod',
|
|
collection: 'eodPrices',
|
|
batchesRun: 1,
|
|
rowsRead: 101,
|
|
spansIndexed: 99,
|
|
skipped: { invalidId: 0, invalidDate: 1, invalidCount: 0, total: 1 },
|
|
},
|
|
},
|
|
skipped: { invalidId: 0, invalidDate: 1, invalidCount: 0, total: 1 },
|
|
totalRowsRead: 101,
|
|
totalSpans: 99,
|
|
};
|
|
|
|
const attached = attachBarSpansToStageBInput(
|
|
{
|
|
eodListings: [
|
|
{
|
|
sourceId: 'SYM0.US',
|
|
ticker: 'SYM0',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
symbolChanges: [],
|
|
},
|
|
readerResult
|
|
);
|
|
|
|
expect(attached.stats.recordsIn).toBe(101);
|
|
expect(attached.stats.resolved).toBe(100);
|
|
expect(attached.stats.unresolved).toBe(0);
|
|
expect(attached.stats.skipped).toBe(1);
|
|
expect(attached.stats.indexedSpans).toBe(99);
|
|
expect(attached.stats.recordsIn).toBe(
|
|
attached.stats.resolved + attached.stats.unresolved + attached.stats.skipped
|
|
);
|
|
expect(attached.malformed.barSpans).toBe(1);
|
|
expect(attached.stageBInput.eodListings[0]?.span).toEqual({
|
|
firstBarDate: '2019-01-02',
|
|
lastBarDate: '2025-11-28',
|
|
});
|
|
|
|
const sources = makeSourcesResult({
|
|
stageARecords: [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SYM0.US',
|
|
isin: 'US0378331005',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Sym Zero',
|
|
},
|
|
],
|
|
eodListings: [
|
|
{
|
|
sourceId: 'SYM0.US',
|
|
ticker: 'SYM0',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
});
|
|
|
|
const composed = composeSecurityMasterRun(
|
|
{ sources, barSpans: readerResult },
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
expect(composed.stats.barSpans.recordsIn).toBe(101);
|
|
expect(composed.stats.barSpans.resolved).toBe(100);
|
|
expect(composed.stats.barSpans.skipped).toBe(1);
|
|
expect(composed.stats.barSpans.indexedSpans).toBe(99);
|
|
expect(composed.stats.malformedInputs.barSpans).toBe(1);
|
|
});
|
|
|
|
test('composes a fixed-seed 100,000-record synthetic workload end to end above the sandbox throughput floor', () => {
|
|
// 50,000 EOD + 25,000 IB + 25,000 QM = 100,000 source records
|
|
const numInstruments = 50_000;
|
|
const numIb = 25_000;
|
|
const numQm = 25_000;
|
|
const totalSourceRecords = numInstruments + numIb + numQm;
|
|
|
|
const stageARecords: StageASourceRecord[] = new Array(numInstruments + numIb);
|
|
const eodListings: StageBEodListingInput[] = new Array(numInstruments);
|
|
const ibContracts: StageBIbContractInput[] = new Array(numIb);
|
|
const tickerSources: StageBTickerSourceInput[] = new Array(numQm);
|
|
const barSpans: BarSpan[] = new Array(numInstruments + numQm);
|
|
const securityTypeByIsin = new Map<string, SecurityType>();
|
|
|
|
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
let stageAIdx = 0;
|
|
let spanIdx = 0;
|
|
|
|
for (let i = 0; i < numInstruments; i++) {
|
|
// Deterministic valid US ISIN via cusipToIsin (9-char CUSIP: 6-digit issuer + 2-char issue + check)
|
|
// Construct a valid 9-char CUSIP using cusipToIsin after computing CUSIP check digit, or direct ISIN:
|
|
const base8 = `A${String(i).padStart(7, '0')}`;
|
|
// Compute CUSIP check digit (Luhn mod 10 over A=10..Z=35)
|
|
let sum = 0;
|
|
for (let pos = 0; pos < 8; pos++) {
|
|
const ch = base8.charCodeAt(pos);
|
|
let v = ch >= 65 ? ch - 55 : ch - 48;
|
|
if (pos % 2 === 1) {
|
|
v *= 2;
|
|
}
|
|
sum += Math.floor(v / 10) + (v % 10);
|
|
}
|
|
const checkDigit = (10 - (sum % 10)) % 10;
|
|
const cusip = `${base8}${checkDigit}`;
|
|
const isin = cusipToIsin(cusip, 'US')!;
|
|
|
|
// Unique 4-letter ticker from i
|
|
const c0 = alphabet[Math.floor(i / (26 * 26 * 26)) % 26]!;
|
|
const c1 = alphabet[Math.floor(i / (26 * 26)) % 26]!;
|
|
const c2 = alphabet[Math.floor(i / 26) % 26]!;
|
|
const c3 = alphabet[i % 26]!;
|
|
const ticker = `${c0}${c1}${c2}${c3}`;
|
|
const eodId = `${ticker}.US`;
|
|
|
|
stageARecords[stageAIdx++] = {
|
|
source: 'eod',
|
|
sourceId: eodId,
|
|
isin,
|
|
cusip,
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: `Bench Corp ${i}`,
|
|
};
|
|
eodListings[i] = {
|
|
sourceId: eodId,
|
|
ticker,
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
};
|
|
barSpans[spanIdx++] = {
|
|
source: 'eod',
|
|
sourceId: eodId,
|
|
firstBarDate: '2018-01-02',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 1980,
|
|
};
|
|
securityTypeByIsin.set(isin, 'common');
|
|
|
|
if (i < numIb) {
|
|
const ibId = String(1_000_000 + i);
|
|
stageARecords[stageAIdx++] = {
|
|
source: 'ib',
|
|
sourceId: ibId,
|
|
isin,
|
|
cusip,
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: `Bench Corp ${i}`,
|
|
};
|
|
ibContracts[i] = {
|
|
sourceId: ibId,
|
|
conid: 1_000_000 + i,
|
|
currency: 'USD',
|
|
primaryExchange: 'NASDAQ',
|
|
};
|
|
}
|
|
|
|
if (i < numQm) {
|
|
const qmId = `${ticker}:US`;
|
|
tickerSources[i] = {
|
|
source: 'qm',
|
|
sourceId: qmId,
|
|
ticker,
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
};
|
|
barSpans[spanIdx++] = {
|
|
source: 'qm',
|
|
sourceId: qmId,
|
|
firstBarDate: '2020-01-02',
|
|
lastBarDate: '2025-11-28',
|
|
barCount: 1480,
|
|
};
|
|
}
|
|
}
|
|
|
|
const sources = makeSourcesResult({
|
|
stageARecords,
|
|
eodListings,
|
|
ibContracts,
|
|
tickerSources,
|
|
securityTypeByIsin,
|
|
});
|
|
|
|
const startMs = performance.now();
|
|
const result = composeSecurityMasterRun(
|
|
{ sources, barSpans },
|
|
{ asOfDate: '2025-11-28' }
|
|
);
|
|
const elapsedMs = performance.now() - startMs;
|
|
const recordsPerSec = totalSourceRecords / (elapsedMs / 1000);
|
|
|
|
expect(totalSourceRecords).toBe(100_000);
|
|
expect(result.stageA.instruments.length).toBe(numInstruments);
|
|
expect(result.stageB.listings.length).toBe(numInstruments);
|
|
expect(result.stageB.providerMappings.length).toBe(totalSourceRecords);
|
|
expect(result.stats.stageA.recordsIn).toBe(
|
|
result.stats.stageA.resolved + result.stats.stageA.unresolved + result.stats.stageA.skipped
|
|
);
|
|
expect(result.stats.stageB.recordsIn).toBe(
|
|
result.stats.stageB.resolved + result.stats.stageB.unresolved + result.stats.stageB.skipped
|
|
);
|
|
expect(result.stats.pass4.status).toBe('skipped');
|
|
// Assert conservative sandbox throughput floor (>= 10,000 records/s)
|
|
expect(recordsPerSec).toBeGreaterThanOrEqual(10_000);
|
|
});
|
|
});
|