422 lines
16 KiB
TypeScript
422 lines
16 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { readFileSync } from 'node:fs';
|
|
import { resolve } from 'node:path';
|
|
import {
|
|
buildSecurityTypeByIsin,
|
|
buildSecurityTypeByIsinForStageA,
|
|
classifyEodSecurityType,
|
|
compareAscii,
|
|
DEFAULT_MAX_SECURITY_TYPE_CONFLICTS,
|
|
EOD_SECURITY_TYPE_MAP,
|
|
SECURITY_TYPES,
|
|
type SecurityType,
|
|
type SecurityTypeClassificationStats,
|
|
type SecurityTypeInputRecord,
|
|
type StageAInstrumentCandidate,
|
|
} 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('buildSecurityTypeByIsinForStageA includes only Stage A-accepted EOD members and prevents quarantined rows from supplying or vetoing types', () => {
|
|
const records: SecurityTypeInputRecord[] = [
|
|
// Accepted EOD member for US0378331005
|
|
{ isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'AAPL.US' },
|
|
// Quarantined EOD row (not in instruments) sharing US0378331005 with conflicting Type
|
|
{ isin: 'US0378331005', rawType: 'ETF', sourceId: 'AAPL_STALE.US' },
|
|
// Quarantined EOD row that is the only row for US30303M1027
|
|
{ isin: 'US30303M1027', rawType: 'ETF', sourceId: 'META_BAD.US' },
|
|
// Accepted EOD member whose raw record had null isin (Stage A primaryIsin is authoritative)
|
|
{ isin: null, rawType: 'Unit', sourceId: 'SCU-UN.TO' },
|
|
];
|
|
|
|
const instruments: StageAInstrumentCandidate[] = [
|
|
{
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [
|
|
{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' },
|
|
{ source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' },
|
|
],
|
|
},
|
|
{
|
|
primaryIsin: 'CA8131371066',
|
|
primaryCusip: '813137106',
|
|
issuerCountry: 'CA',
|
|
canonicalName: 'Second Cup Income Fund',
|
|
members: [{ source: 'eod', sourceId: 'SCU-UN.TO', currency: 'CAD', method: 'tier2_cusip' }],
|
|
},
|
|
// IB-only instrument (no EOD members)
|
|
{
|
|
primaryIsin: 'CA7800871021',
|
|
primaryCusip: '780087102',
|
|
issuerCountry: 'CA',
|
|
canonicalName: 'Royal Bank of Canada',
|
|
members: [{ source: 'ib', sourceId: '100001', currency: 'CAD', method: 'tier1_isin' }],
|
|
},
|
|
];
|
|
|
|
const result = buildSecurityTypeByIsinForStageA(records, instruments);
|
|
expect([...result.securityTypeByIsin.entries()]).toEqual([
|
|
['CA8131371066', 'unit'],
|
|
['US0378331005', 'common'],
|
|
]);
|
|
expect(result.conflicts).toEqual([]);
|
|
expect(result.unknownRawTypes).toEqual([]);
|
|
assertStatsReconcile(
|
|
result.stats,
|
|
result.securityTypeByIsin.size,
|
|
result.conflicts.length,
|
|
0
|
|
);
|
|
expect(result.stats).toEqual({
|
|
recordsIn: 2,
|
|
classified: 2,
|
|
missingIsin: 0,
|
|
missingType: 0,
|
|
unknownType: 0,
|
|
distinctClassifiedIsins: 2,
|
|
isinsMapped: 2,
|
|
isinsConflicting: 0,
|
|
conflictsTruncated: 0,
|
|
});
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|