T-87: M1.1l — Security-type classifier: eodSymbols.Type → securityTypeByIsin for the security-master loader (no new dependencies)
This commit is contained in:
parent
c9a4adabad
commit
2f5ac2e7e7
6 changed files with 920 additions and 7 deletions
354
test/unit/security-master-security-type.test.ts
Normal file
354
test/unit/security-master-security-type.test.ts
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
buildSecurityTypeByIsin,
|
||||
classifyEodSecurityType,
|
||||
compareAscii,
|
||||
DEFAULT_MAX_SECURITY_TYPE_CONFLICTS,
|
||||
EOD_SECURITY_TYPE_MAP,
|
||||
SECURITY_TYPES,
|
||||
type SecurityType,
|
||||
type SecurityTypeClassificationStats,
|
||||
type SecurityTypeInputRecord,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
function mulberry32(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) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function shuffleWithSeed<T>(items: readonly T[], seed: number): T[] {
|
||||
const copy = items.slice();
|
||||
const rand = mulberry32(seed);
|
||||
for (let i = copy.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rand() * (i + 1));
|
||||
const tmp = copy[i]!;
|
||||
copy[i] = copy[j]!;
|
||||
copy[j] = tmp;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
function assertStatsReconcile(
|
||||
stats: SecurityTypeClassificationStats,
|
||||
mappedSize: number,
|
||||
conflictsLength: number,
|
||||
unknownTotal: number
|
||||
): void {
|
||||
expect(stats.recordsIn).toBe(
|
||||
stats.classified + stats.missingIsin + stats.missingType + stats.unknownType
|
||||
);
|
||||
expect(stats.isinsMapped).toBe(mappedSize);
|
||||
expect(stats.isinsMapped + stats.isinsConflicting).toBe(stats.distinctClassifiedIsins);
|
||||
expect(stats.isinsConflicting).toBe(conflictsLength + stats.conflictsTruncated);
|
||||
expect(unknownTotal).toBe(stats.unknownType);
|
||||
}
|
||||
|
||||
describe('security-master security-type classifier', () => {
|
||||
test('zero-I/O static proof: security-type.ts has no DB, fs, or network imports', () => {
|
||||
const sourcePath = resolve(
|
||||
import.meta.dir,
|
||||
'../../apps/stock/data-pipeline/src/security-master/security-type.ts'
|
||||
);
|
||||
const sourceText = readFileSync(sourcePath, 'utf8');
|
||||
expect(sourceText).not.toMatch(
|
||||
/from\s+['"](?:node:fs|node:net|node:http|node:https|mongodb|pg|@stock-bot\/mongodb|@stock-bot\/postgres)['"]/
|
||||
);
|
||||
});
|
||||
|
||||
test('classifyEodSecurityType maps every EOD_SECURITY_TYPE_MAP entry and case/whitespace variants into SECURITY_TYPES', () => {
|
||||
expect(Object.isFrozen(EOD_SECURITY_TYPE_MAP)).toBe(true);
|
||||
expect(DEFAULT_MAX_SECURITY_TYPE_CONFLICTS).toBe(200);
|
||||
|
||||
const validSecurityTypes = new Set<string>(SECURITY_TYPES);
|
||||
const observedOutputs = new Set<SecurityType>();
|
||||
|
||||
for (const [rawKey, expectedType] of Object.entries(EOD_SECURITY_TYPE_MAP)) {
|
||||
expect(validSecurityTypes.has(expectedType)).toBe(true);
|
||||
observedOutputs.add(expectedType);
|
||||
|
||||
// Exact, lowercase, mixed-case, leading/trailing spaces, and collapsed internal whitespace.
|
||||
expect(classifyEodSecurityType(rawKey)).toBe(expectedType);
|
||||
expect(classifyEodSecurityType(rawKey.toLowerCase())).toBe(expectedType);
|
||||
expect(classifyEodSecurityType(` ${rawKey.toLowerCase()} `)).toBe(expectedType);
|
||||
expect(classifyEodSecurityType(`\t${rawKey.replace(/ /g, ' \t\n ')}\n`)).toBe(
|
||||
expectedType
|
||||
);
|
||||
}
|
||||
|
||||
// All 8 canonical SecurityType values are reachable from EOD_SECURITY_TYPE_MAP.
|
||||
expect([...observedOutputs].sort(compareAscii)).toEqual([...SECURITY_TYPES].sort(compareAscii));
|
||||
|
||||
// Spot-check realistic provider spellings.
|
||||
expect(classifyEodSecurityType('Common Stock')).toBe('common');
|
||||
expect(classifyEodSecurityType('Preferred Stock')).toBe('preferred');
|
||||
expect(classifyEodSecurityType('ETF')).toBe('etf');
|
||||
expect(classifyEodSecurityType('Unit')).toBe('unit');
|
||||
expect(classifyEodSecurityType('Units')).toBe('unit');
|
||||
expect(classifyEodSecurityType('Warrant')).toBe('warrant');
|
||||
expect(classifyEodSecurityType('Warrants')).toBe('warrant');
|
||||
expect(classifyEodSecurityType('Right')).toBe('right');
|
||||
expect(classifyEodSecurityType('Rights')).toBe('right');
|
||||
expect(classifyEodSecurityType('CDR')).toBe('cdr');
|
||||
expect(classifyEodSecurityType('Currency')).toBe('fx');
|
||||
expect(classifyEodSecurityType('Forex')).toBe('fx');
|
||||
expect(classifyEodSecurityType('FX')).toBe('fx');
|
||||
});
|
||||
|
||||
test('classifyEodSecurityType returns null for non-equity values, blanks, unknowns, non-strings, and prototype keys', () => {
|
||||
const nullInputs: unknown[] = [
|
||||
// Documented non-equity EODHD values (must never be guessed)
|
||||
'FUND',
|
||||
'Mutual Fund',
|
||||
'Bond',
|
||||
'Notes',
|
||||
'INDEX',
|
||||
'Index',
|
||||
'ETC',
|
||||
'Closed-End Fund',
|
||||
'Trust',
|
||||
// Blanks and whitespace
|
||||
'',
|
||||
' ',
|
||||
' \t\n\r ',
|
||||
// Unknown values
|
||||
'Cryptocurrency',
|
||||
'ADR',
|
||||
'Depositary Receipt',
|
||||
// Non-strings
|
||||
null,
|
||||
undefined,
|
||||
0,
|
||||
42,
|
||||
true,
|
||||
false,
|
||||
{},
|
||||
['Common Stock'],
|
||||
Symbol('ETF'),
|
||||
// Prototype keys (must never match Object.prototype properties)
|
||||
'toString',
|
||||
'constructor',
|
||||
'__proto__',
|
||||
'valueOf',
|
||||
'hasOwnProperty',
|
||||
'TOSTRING',
|
||||
'CONSTRUCTOR',
|
||||
];
|
||||
|
||||
for (const input of nullInputs) {
|
||||
expect(classifyEodSecurityType(input)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
test('buildSecurityTypeByIsin omits conflicts, collapses duplicates, handles mixed missing/unknown on same ISIN, and sorts unknowns', () => {
|
||||
const records: SecurityTypeInputRecord[] = [
|
||||
// Identical duplicates collapse into one mapped ISIN
|
||||
{ isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'AAPL.US' },
|
||||
{ isin: 'US0378331005', rawType: ' common stock ', sourceId: 'AAPL.NEO' },
|
||||
// Classified + missingType + unknownType on same ISIN -> still maps cleanly without conflict
|
||||
{ isin: 'CA82509L1076', rawType: 'Common Stock', sourceId: 'SHOP.TO' },
|
||||
{ isin: 'CA82509L1076', rawType: null, sourceId: 'SHOP.US' },
|
||||
{ isin: 'CA82509L1076', rawType: 'Unknown Variant', sourceId: 'SHOP.NEO' },
|
||||
// Conflicting types on one ISIN -> omitted from map, emitted in conflicts
|
||||
{ isin: 'US1111111111', rawType: 'ETF', sourceId: 'CONF.US' },
|
||||
{ isin: 'US1111111111', rawType: 'Common Stock', sourceId: 'CONF.TO' },
|
||||
{ isin: 'US1111111111', rawType: 'Preferred Stock', sourceId: 'CONF.V' },
|
||||
// Second conflict to verify ASCII ordering and capping
|
||||
{ isin: 'CA2222222222', rawType: 'Unit', sourceId: 'UNIT.TO' },
|
||||
{ isin: 'CA2222222222', rawType: 'Warrant', sourceId: 'UNIT.V' },
|
||||
// Missing ISIN (counts as missingIsin even if rawType is also missing or unknown)
|
||||
{ isin: null, rawType: 'Common Stock', sourceId: 'NOISIN1.US' },
|
||||
{ isin: ' ', rawType: undefined, sourceId: 'NOISIN2.US' },
|
||||
// Missing/non-string/blank type on valid ISIN
|
||||
{ isin: 'US3333333333', rawType: undefined, sourceId: 'NOTYPE1.US' },
|
||||
{ isin: 'US3333333333', rawType: 123, sourceId: 'NOTYPE2.US' },
|
||||
{ isin: 'US3333333333', rawType: ' \t ', sourceId: 'NOTYPE3.US' },
|
||||
// Unknown raw types with ties to verify count desc then ASCII tie-breaking
|
||||
{ isin: 'US4444444444', rawType: 'FUND', sourceId: 'F1.US' },
|
||||
{ isin: 'US4444444445', rawType: ' FUND ', sourceId: 'F2.US' },
|
||||
{ isin: 'US4444444446', rawType: 'FUND', sourceId: 'F3.US' },
|
||||
{ isin: 'US5555555555', rawType: 'Mutual Fund', sourceId: 'MF1.US' },
|
||||
{ isin: 'US5555555556', rawType: 'Mutual Fund', sourceId: 'MF2.US' },
|
||||
{ isin: 'US6666666666', rawType: 'Bond', sourceId: 'B1.US' },
|
||||
{ isin: 'US6666666667', rawType: 'Bond', sourceId: 'B2.US' },
|
||||
{ isin: 'US7777777777', rawType: 'INDEX', sourceId: 'IDX1.US' },
|
||||
];
|
||||
|
||||
const result = buildSecurityTypeByIsin(records);
|
||||
|
||||
// Mapped ISINs in ASCII order, excluding conflicting ISINs
|
||||
expect([...result.securityTypeByIsin.entries()]).toEqual([
|
||||
['CA82509L1076', 'common'],
|
||||
['US0378331005', 'common'],
|
||||
]);
|
||||
|
||||
// Conflicts in ASCII order by ISIN, with sorted types and sourceIds
|
||||
expect(result.conflicts).toEqual([
|
||||
{
|
||||
isin: 'CA2222222222',
|
||||
types: ['unit', 'warrant'],
|
||||
sourceIds: ['UNIT.TO', 'UNIT.V'],
|
||||
recordCount: 2,
|
||||
},
|
||||
{
|
||||
isin: 'US1111111111',
|
||||
types: ['common', 'etf', 'preferred'],
|
||||
sourceIds: ['CONF.TO', 'CONF.US', 'CONF.V'],
|
||||
recordCount: 3,
|
||||
},
|
||||
]);
|
||||
|
||||
// Unknown raw types sorted by count desc, then ASCII (Bond before Mutual Fund at count 2)
|
||||
expect(result.unknownRawTypes).toEqual([
|
||||
{ rawType: 'FUND', count: 3 },
|
||||
{ rawType: 'Bond', count: 2 },
|
||||
{ rawType: 'Mutual Fund', count: 2 },
|
||||
{ rawType: 'INDEX', count: 1 },
|
||||
{ rawType: 'Unknown Variant', count: 1 },
|
||||
]);
|
||||
|
||||
const unknownSum = result.unknownRawTypes.reduce((acc, row) => acc + row.count, 0);
|
||||
assertStatsReconcile(
|
||||
result.stats,
|
||||
result.securityTypeByIsin.size,
|
||||
result.conflicts.length,
|
||||
unknownSum
|
||||
);
|
||||
expect(result.stats).toEqual({
|
||||
recordsIn: 23,
|
||||
classified: 8,
|
||||
missingIsin: 2,
|
||||
missingType: 4,
|
||||
unknownType: 9,
|
||||
distinctClassifiedIsins: 4,
|
||||
isinsMapped: 2,
|
||||
isinsConflicting: 2,
|
||||
conflictsTruncated: 0,
|
||||
});
|
||||
|
||||
// Capping conflicts preserves total count and reports conflictsTruncated
|
||||
const capped = buildSecurityTypeByIsin(records, { maxConflicts: 1 });
|
||||
expect(capped.conflicts.map(c => c.isin)).toEqual(['CA2222222222']);
|
||||
expect(capped.stats.isinsConflicting).toBe(2);
|
||||
expect(capped.stats.conflictsTruncated).toBe(1);
|
||||
assertStatsReconcile(
|
||||
capped.stats,
|
||||
capped.securityTypeByIsin.size,
|
||||
capped.conflicts.length,
|
||||
unknownSum
|
||||
);
|
||||
|
||||
const zeroCapped = buildSecurityTypeByIsin(records, { maxConflicts: 0 });
|
||||
expect(zeroCapped.conflicts).toEqual([]);
|
||||
expect(zeroCapped.stats.isinsConflicting).toBe(2);
|
||||
expect(zeroCapped.stats.conflictsTruncated).toBe(2);
|
||||
|
||||
// Invalid maxConflicts rejected
|
||||
expect(() => buildSecurityTypeByIsin(records, { maxConflicts: -1 })).toThrow(RangeError);
|
||||
expect(() => buildSecurityTypeByIsin(records, { maxConflicts: 1.5 })).toThrow(RangeError);
|
||||
expect(() => buildSecurityTypeByIsin(records, { maxConflicts: Number.NaN })).toThrow(
|
||||
RangeError
|
||||
);
|
||||
});
|
||||
|
||||
test('determinism: output is identical across input permutations', () => {
|
||||
const records: SecurityTypeInputRecord[] = [
|
||||
{ isin: 'US98954M1018', rawType: 'Common Stock', sourceId: 'Z.US' },
|
||||
{ isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'AAPL.US' },
|
||||
{ isin: 'CA7800871021', rawType: 'Preferred Stock', sourceId: 'RY-PA.TO' },
|
||||
{ isin: 'CA82509L1076', rawType: 'ETF', sourceId: 'SHOP.TO' },
|
||||
{ isin: 'CA82509L1076', rawType: 'Common Stock', sourceId: 'SHOP.US' },
|
||||
{ isin: 'CA82509L1076', rawType: 'Unit', sourceId: 'SHOP.NEO' },
|
||||
{ isin: 'US1234567890', rawType: 'CDR', sourceId: 'CDR1.NEO' },
|
||||
{ isin: 'US1234567890', rawType: 'CDR', sourceId: 'CDR2.NEO' },
|
||||
{ isin: 'US0000000001', rawType: 'FUND', sourceId: 'F1.US' },
|
||||
{ isin: 'US0000000002', rawType: 'Bond', sourceId: 'B1.US' },
|
||||
{ isin: 'US0000000003', rawType: 'FUND', sourceId: 'F2.US' },
|
||||
{ isin: null, rawType: 'Warrant', sourceId: 'W1.TO' },
|
||||
{ isin: 'US0000000004', rawType: null, sourceId: 'M1.US' },
|
||||
];
|
||||
|
||||
const serialize = (res: ReturnType<typeof buildSecurityTypeByIsin>) =>
|
||||
JSON.stringify({
|
||||
entries: [...res.securityTypeByIsin.entries()],
|
||||
stats: res.stats,
|
||||
unknownRawTypes: res.unknownRawTypes,
|
||||
conflicts: res.conflicts,
|
||||
});
|
||||
|
||||
const baseline = serialize(buildSecurityTypeByIsin(records));
|
||||
|
||||
for (const seed of [7, 42, 1337, 20261128, 999999]) {
|
||||
const shuffled = shuffleWithSeed(records, seed);
|
||||
expect(serialize(buildSecurityTypeByIsin(shuffled))).toBe(baseline);
|
||||
}
|
||||
});
|
||||
|
||||
test('local benchmark: >= 300,000 synthetic EOD records classify at >= 100,000 records/s with zero DB connections', () => {
|
||||
const RECORD_COUNT = 300_000;
|
||||
const rand = mulberry32(20261128);
|
||||
const vocabulary: readonly unknown[] = [
|
||||
'Common Stock',
|
||||
'Preferred Stock',
|
||||
'ETF',
|
||||
'Unit',
|
||||
'Warrant',
|
||||
'Right',
|
||||
'CDR',
|
||||
'Currency',
|
||||
'FUND',
|
||||
'Mutual Fund',
|
||||
'Bond',
|
||||
null,
|
||||
];
|
||||
|
||||
// Pre-build 300k deterministic records (100k distinct ISINs, ~3 records/ISIN, small conflict rate).
|
||||
const records: SecurityTypeInputRecord[] = new Array(RECORD_COUNT);
|
||||
for (let i = 0; i < RECORD_COUNT; i++) {
|
||||
const bucket = i % 100_000;
|
||||
const missingIsin = i % 50 === 0;
|
||||
const isin = missingIsin ? null : `US${String(bucket).padStart(10, '0')}`;
|
||||
// Every 5,000th bucket (offset +1 so it is not also a missingIsin bucket) introduces a conflict.
|
||||
let rawType: unknown;
|
||||
if (!missingIsin && bucket % 5_000 === 1 && i >= 100_000) {
|
||||
rawType = 'ETF';
|
||||
} else if (i % 20 === 0) {
|
||||
rawType = vocabulary[8 + Math.floor(rand() * 4)];
|
||||
} else {
|
||||
rawType = vocabulary[bucket % 8];
|
||||
}
|
||||
records[i] = {
|
||||
isin,
|
||||
rawType,
|
||||
sourceId: `SYM${i}.US`,
|
||||
};
|
||||
}
|
||||
|
||||
const started = performance.now();
|
||||
const result = buildSecurityTypeByIsin(records);
|
||||
const elapsedMs = performance.now() - started;
|
||||
const recordsPerSec = Math.round(RECORD_COUNT / (elapsedMs / 1000));
|
||||
|
||||
process.stdout.write(
|
||||
`[security-type benchmark] ${RECORD_COUNT.toLocaleString('en-US')} records in ${elapsedMs.toFixed(1)} ms (${recordsPerSec.toLocaleString('en-US')} records/s, mapped=${result.stats.isinsMapped}, conflicts=${result.stats.isinsConflicting})\n`
|
||||
);
|
||||
|
||||
const unknownSum = result.unknownRawTypes.reduce((acc, row) => acc + row.count, 0);
|
||||
assertStatsReconcile(
|
||||
result.stats,
|
||||
result.securityTypeByIsin.size,
|
||||
result.conflicts.length,
|
||||
unknownSum
|
||||
);
|
||||
expect(result.stats.recordsIn).toBe(RECORD_COUNT);
|
||||
expect(result.stats.isinsMapped).toBeGreaterThan(80_000);
|
||||
expect(result.stats.isinsConflicting).toBeGreaterThan(0);
|
||||
expect(recordsPerSec).toBeGreaterThanOrEqual(100_000);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
|
|||
import { resolve } from 'node:path';
|
||||
import type { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { BarSpanIndex } from '../../apps/stock/data-pipeline/src/normalization/bar-spans';
|
||||
import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers';
|
||||
import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker';
|
||||
import {
|
||||
CEO_SYMBOLS_PROJECTION,
|
||||
|
|
@ -339,6 +340,8 @@ describe('security-master source-symbol-readers', () => {
|
|||
expect('profile' in QM_SYMBOLS_PROJECTION).toBe(false);
|
||||
expect('symbolInfo' in QM_SYMBOLS_PROJECTION).toBe(false);
|
||||
expect(EOD_SYMBOLS_PROJECTION._id).toBe(0);
|
||||
expect(EOD_SYMBOLS_PROJECTION.Type).toBe(1);
|
||||
expect(EOD_SYMBOLS_PROJECTION.type).toBe(1);
|
||||
expect(IB_SYMBOLS_PROJECTION._id).toBe(0);
|
||||
expect(CEO_SYMBOLS_PROJECTION._id).toBe(0);
|
||||
expect(EOD_SYMBOL_CHANGE_PROJECTION._id).toBe(0);
|
||||
|
|
@ -1366,12 +1369,12 @@ describe('security-master source-symbol-readers', () => {
|
|||
|
||||
const baseCollections = {
|
||||
eodSymbols: [
|
||||
{ eodSearchCode: 'Z.US', Code: 'Z', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US98954M1018', Name: 'Zillow' },
|
||||
{ eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple' },
|
||||
{ eodSearchCode: 'Z.US', Code: 'Z', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US98954M1018', Name: 'Zillow', Type: 'Common Stock' },
|
||||
{ eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' },
|
||||
// Duplicate sourceId with different names to test full tie-breaker determinism
|
||||
{ eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup B' },
|
||||
{ eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup A' },
|
||||
{ eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA7800871021', Name: 'RBC' },
|
||||
{ eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup B', Type: 'ETF' },
|
||||
{ eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup A', Type: 'ETF' },
|
||||
{ eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA7800871021', Name: 'RBC', type: 'Common Stock' },
|
||||
],
|
||||
ibSymbols: [
|
||||
{ conid: 900, symbol: 'Z', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US98954M1018' },
|
||||
|
|
@ -1399,6 +1402,12 @@ describe('security-master source-symbol-readers', () => {
|
|||
exchangeLookup,
|
||||
});
|
||||
const baselineJson = JSON.stringify(baseline);
|
||||
const baselineTypeEntries = [...baseline.securityTypeByIsin.entries()];
|
||||
expect(baselineTypeEntries).toEqual([
|
||||
['CA7800871021', 'common'],
|
||||
['US0378331005', 'common'],
|
||||
['US98954M1018', 'common'],
|
||||
]);
|
||||
|
||||
// Verify (source, sourceId) compareAscii sort order.
|
||||
for (let i = 1; i < baseline.stageARecords.length; i++) {
|
||||
|
|
@ -1426,9 +1435,171 @@ describe('security-master source-symbol-readers', () => {
|
|||
exchangeLookup,
|
||||
});
|
||||
expect(JSON.stringify(candidate)).toBe(baselineJson);
|
||||
expect([...candidate.securityTypeByIsin.entries()]).toEqual(baselineTypeEntries);
|
||||
}
|
||||
});
|
||||
|
||||
test('security-type wiring & Stage A integration: maps typed EOD docs (including lowercase type and CUSIP-derived ISIN), keeps non-string Type docs, and reports conflicts/unknowns', async () => {
|
||||
const exchangeLookup = createPass1ExchangeLookup();
|
||||
const expectedDerivedCaIsin = cusipToIsin('813137106', 'CA');
|
||||
expect(expectedDerivedCaIsin).not.toBeNull();
|
||||
|
||||
const reader = new FakeSourceSymbolReader(
|
||||
{
|
||||
eodSymbols: [
|
||||
// Standard Type: 'Common Stock'
|
||||
{
|
||||
eodSearchCode: 'AAPL.US',
|
||||
Code: 'AAPL',
|
||||
Exchange: 'NASDAQ',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'US0378331005',
|
||||
Name: 'Apple Inc.',
|
||||
Type: 'Common Stock',
|
||||
},
|
||||
// Lowercase `type` fallback
|
||||
{
|
||||
eodSearchCode: 'SPY.US',
|
||||
Code: 'SPY',
|
||||
Exchange: 'NYSE',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'US78462F1030',
|
||||
Name: 'SPDR S&P 500 ETF',
|
||||
type: 'etf',
|
||||
},
|
||||
// CUSIP-derived ISIN: bad ISIN check digit with CA prefix + valid CUSIP 813137106
|
||||
{
|
||||
eodSearchCode: 'SCU-UN.TO',
|
||||
Code: 'SCU-UN',
|
||||
Exchange: 'TO',
|
||||
Country: 'Canada',
|
||||
Currency: 'CAD',
|
||||
Isin: 'CA8131391062',
|
||||
Cusip: '813137106',
|
||||
Name: 'Second Cup Income Fund',
|
||||
Type: 'Unit',
|
||||
},
|
||||
// Non-string Type must NOT skip the doc (emitted to Stage A/B, counted in missingType)
|
||||
{
|
||||
eodSearchCode: 'RY.TO',
|
||||
Code: 'RY',
|
||||
Exchange: 'TO',
|
||||
Country: 'Canada',
|
||||
Currency: 'CAD',
|
||||
Isin: 'CA7800871021',
|
||||
Name: 'Royal Bank of Canada',
|
||||
Type: 42 as unknown as string,
|
||||
},
|
||||
// Unknown Type ('Mutual Fund') emitted to Stage A/B, omitted from securityTypeByIsin
|
||||
{
|
||||
eodSearchCode: 'META.US',
|
||||
Code: 'META',
|
||||
Exchange: 'NASDAQ',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'US30303M1027',
|
||||
Name: 'Meta Platforms Inc.',
|
||||
Type: 'Mutual Fund',
|
||||
},
|
||||
// Conflicting types across two EOD docs sharing the same ISIN (SHOP)
|
||||
{
|
||||
eodSearchCode: 'SHOP.TO',
|
||||
Code: 'SHOP',
|
||||
Exchange: 'TO',
|
||||
Country: 'Canada',
|
||||
Currency: 'CAD',
|
||||
Isin: 'CA82509L1076',
|
||||
Name: 'Shopify Inc.',
|
||||
Type: 'Common Stock',
|
||||
},
|
||||
{
|
||||
eodSearchCode: 'SHOP.US',
|
||||
Code: 'SHOP',
|
||||
Exchange: 'NYSE',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'CA82509L1076',
|
||||
Name: 'Shopify Inc.',
|
||||
Type: 'ETF',
|
||||
},
|
||||
],
|
||||
ibSymbols: [],
|
||||
qmSymbols: [],
|
||||
ceoSymbols: [],
|
||||
eodSymbolChange: [],
|
||||
},
|
||||
{ readOnly: true, applyFilterAndProjection: true }
|
||||
);
|
||||
|
||||
const sources = await readSecurityMasterSources(reader, { exchangeLookup });
|
||||
|
||||
// All 7 EOD docs emitted (non-string Type did NOT trigger invalidFieldType skip).
|
||||
expect(sources.stats.eodSymbols.docsRead).toBe(7);
|
||||
expect(sources.stats.eodSymbols.emitted).toBe(7);
|
||||
expect(sources.stats.eodSymbols.skips.invalidFieldType).toBe(0);
|
||||
assertStatsConservation(sources.stats.eodSymbols);
|
||||
|
||||
// Check securityTypeByIsin contents and stats.
|
||||
expect([...sources.securityTypeByIsin.entries()]).toEqual([
|
||||
[expectedDerivedCaIsin!, 'unit'],
|
||||
['US0378331005', 'common'],
|
||||
['US78462F1030', 'etf'],
|
||||
]);
|
||||
expect(sources.unknownSecurityTypes).toEqual([{ rawType: 'Mutual Fund', count: 1 }]);
|
||||
expect(sources.securityTypeConflicts).toEqual([
|
||||
{
|
||||
isin: 'CA82509L1076',
|
||||
types: ['common', 'etf'],
|
||||
sourceIds: ['SHOP.TO', 'SHOP.US'],
|
||||
recordCount: 2,
|
||||
},
|
||||
]);
|
||||
expect(sources.securityTypeStats).toEqual({
|
||||
recordsIn: 7,
|
||||
classified: 5,
|
||||
missingIsin: 0,
|
||||
missingType: 1,
|
||||
unknownType: 1,
|
||||
distinctClassifiedIsins: 4,
|
||||
isinsMapped: 3,
|
||||
isinsConflicting: 1,
|
||||
conflictsTruncated: 0,
|
||||
});
|
||||
|
||||
// Feed reader output directly into Stage A and verify every typed non-conflicting EOD instrument
|
||||
// resolves to an ISIN present in securityTypeByIsin (zero missing_security_type skips in persistSecurityMaster).
|
||||
const stageA = matchInstrumentsStageA(sources.stageARecords);
|
||||
expect(stageA.conflicts).toEqual([]);
|
||||
expect(stageA.unresolved).toEqual([]);
|
||||
|
||||
const stageAIsins = new Set(stageA.instruments.map(i => i.primaryIsin));
|
||||
expect(stageAIsins).toEqual(
|
||||
new Set([
|
||||
'US0378331005',
|
||||
'US78462F1030',
|
||||
expectedDerivedCaIsin!,
|
||||
'CA7800871021',
|
||||
'US30303M1027',
|
||||
'CA82509L1076',
|
||||
])
|
||||
);
|
||||
|
||||
const typedNonConflictingIsins = ['US0378331005', 'US78462F1030', expectedDerivedCaIsin!];
|
||||
const missingForTyped = stageA.instruments.filter(
|
||||
inst =>
|
||||
typedNonConflictingIsins.includes(inst.primaryIsin) &&
|
||||
!sources.securityTypeByIsin.has(inst.primaryIsin)
|
||||
);
|
||||
expect(missingForTyped).toEqual([]);
|
||||
|
||||
// Untyped, unknown-typed, and conflicting instruments are omitted from securityTypeByIsin.
|
||||
expect(sources.securityTypeByIsin.has('CA7800871021')).toBe(false);
|
||||
expect(sources.securityTypeByIsin.has('US30303M1027')).toBe(false);
|
||||
expect(sources.securityTypeByIsin.has('CA82509L1076')).toBe(false);
|
||||
});
|
||||
|
||||
test('local benchmark: >= 368k synthetic docs (300k eod + 50k qm + 18k ib) sustain >= 25,000 docs/s', async () => {
|
||||
const EOD_COUNT = 300_000;
|
||||
const QM_COUNT = 50_000;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue