T-87: M1.1l — Security-type classifier: eodSymbols.Type → securityTypeByIsin for the security-master loader (no new dependencies)
This commit is contained in:
parent
2f5ac2e7e7
commit
a368e8a47a
6 changed files with 285 additions and 4 deletions
|
|
@ -113,7 +113,8 @@ bun test test/unit/security-master-source-symbol-readers.test.ts
|
|||
| `Currency`, `Forex`, `FX` | `fx` |
|
||||
|
||||
- **Published-vocabulary & no-guess rule:** Because QA MongoDB is unreachable from the agent sandbox, the table is based on the published EODHD `Type` vocabulary. Non-equity-like values (`FUND`, `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.), blanks, non-strings, and unmapped strings return `null` and are never guessed from ticker suffixes or company names. A non-string `Type` on an `eodSymbols` document does not skip the document from Stage A/B — it is counted under `securityTypeStats.missingType`.
|
||||
- **Reviewing unmapped values & conflicts:** After a real security-master run, inspect `unknownSecurityTypes` (sorted by count descending, then ASCII) for any newly observed provider strings that should be added to `EOD_SECURITY_TYPE_MAP`, and inspect `securityTypeConflicts` (ISINs omitted from `securityTypeByIsin` because multiple EOD documents disagreed on their classified type; capped by `maxSecurityTypeConflicts`, default `200`, with total counts in `securityTypeStats.isinsConflicting` and `conflictsTruncated`).
|
||||
- **Stage A membership & raw vocabulary diagnostics:** `readEodSymbols` / `readSecurityMasterSources` build the loader-facing `securityTypeByIsin` map strictly from EOD rows accepted as Stage A instrument members (`buildSecurityTypeByIsinForStageA`), so rows quarantined by Stage A (`isin_cusip_mismatch`, `duplicate_source_id`) can neither supply nor veto a valid instrument's security type. All emitted EOD rows remain available in `securityTypeRecords` for raw vocabulary diagnostics (`buildSecurityTypeByIsin(sources.securityTypeRecords)`).
|
||||
- **Reviewing unmapped values & conflicts:** After a real security-master run, inspect `unknownSecurityTypes` (sorted by count descending, then ASCII) for any newly observed provider strings that should be added to `EOD_SECURITY_TYPE_MAP`, and inspect `securityTypeConflicts` (ISINs omitted from `securityTypeByIsin` because multiple Stage A-accepted EOD documents disagreed on their classified type; capped by `maxSecurityTypeConflicts`, default `200`, with total counts in `securityTypeStats.isinsConflicting` and `conflictsTruncated`).
|
||||
- **Local synthetic benchmark:** Run the unit suite and fixed-seed 300,000-record synthetic benchmark (zero DB connections) with:
|
||||
|
||||
```bash
|
||||
|
|
|
|||
|
|
@ -193,6 +193,7 @@ export {
|
|||
|
||||
export {
|
||||
buildSecurityTypeByIsin,
|
||||
buildSecurityTypeByIsinForStageA,
|
||||
classifyEodSecurityType,
|
||||
DEFAULT_MAX_SECURITY_TYPE_CONFLICTS,
|
||||
EOD_SECURITY_TYPE_MAP,
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
* suffixes or company names.
|
||||
*/
|
||||
import { compareAscii } from './exchange-pass1';
|
||||
import type { StageAInstrumentCandidate } from './instrument-stage-a';
|
||||
import type { SecurityType } from './persist';
|
||||
|
||||
export const DEFAULT_MAX_SECURITY_TYPE_CONFLICTS = 200;
|
||||
|
|
@ -276,3 +277,49 @@ export function buildSecurityTypeByIsin(
|
|||
conflicts,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the loader-facing `securityTypeByIsin` map strictly from EOD rows accepted as Stage A
|
||||
* instrument members (`member.source === 'eod'`), keyed by each instrument's `primaryIsin`.
|
||||
* Stage A-quarantined rows (e.g. `isin_cusip_mismatch`, `duplicate_source_id`) and unresolved
|
||||
* rows are excluded so they can neither supply nor veto a valid instrument's security type.
|
||||
*/
|
||||
export function buildSecurityTypeByIsinForStageA(
|
||||
records: readonly SecurityTypeInputRecord[],
|
||||
instruments: readonly StageAInstrumentCandidate[],
|
||||
options: BuildSecurityTypeByIsinOptions = {}
|
||||
): BuildSecurityTypeByIsinResult {
|
||||
const acceptedIsinByEodSourceId = new Map<string, string>();
|
||||
for (let i = 0; i < instruments.length; i++) {
|
||||
const instrument = instruments[i];
|
||||
if (instrument === undefined) {
|
||||
continue;
|
||||
}
|
||||
const members = instrument.members;
|
||||
for (let j = 0; j < members.length; j++) {
|
||||
const member = members[j];
|
||||
if (member !== undefined && member.source === 'eod') {
|
||||
acceptedIsinByEodSourceId.set(member.sourceId, instrument.primaryIsin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const acceptedRecords: SecurityTypeInputRecord[] = [];
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
const record = records[i];
|
||||
if (record === undefined) {
|
||||
continue;
|
||||
}
|
||||
const primaryIsin = acceptedIsinByEodSourceId.get(record.sourceId);
|
||||
if (primaryIsin === undefined) {
|
||||
continue;
|
||||
}
|
||||
acceptedRecords.push({
|
||||
isin: primaryIsin,
|
||||
rawType: record.rawType,
|
||||
sourceId: record.sourceId,
|
||||
});
|
||||
}
|
||||
|
||||
return buildSecurityTypeByIsin(acceptedRecords, options);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import {
|
|||
type ExchangeSource,
|
||||
type ExchangeSourceMapRow,
|
||||
} from './exchange-pass1';
|
||||
import type { StageASourceRecord } from './instrument-stage-a';
|
||||
import { matchInstrumentsStageA, type StageASourceRecord } from './instrument-stage-a';
|
||||
import {
|
||||
MAX_TICKER_ROOT_LENGTH,
|
||||
type StageBEodListingInput,
|
||||
|
|
@ -28,7 +28,7 @@ import {
|
|||
} from './listing-stage-b';
|
||||
import type { SecurityType } from './persist';
|
||||
import {
|
||||
buildSecurityTypeByIsin,
|
||||
buildSecurityTypeByIsinForStageA,
|
||||
type SecurityTypeClassificationStats,
|
||||
type SecurityTypeConflict,
|
||||
type SecurityTypeInputRecord,
|
||||
|
|
@ -232,6 +232,7 @@ export type AdaptEodSymbolChangeResult =
|
|||
export interface ReadEodSymbolsResult {
|
||||
stageARecords: StageASourceRecord[];
|
||||
eodListings: StageBEodListingInput[];
|
||||
securityTypeRecords: SecurityTypeInputRecord[];
|
||||
securityTypeByIsin: Map<string, SecurityType>;
|
||||
securityTypeStats: SecurityTypeClassificationStats;
|
||||
unknownSecurityTypes: UnknownSecurityTypeCount[];
|
||||
|
|
@ -274,6 +275,7 @@ export interface SecurityMasterSourcesStats {
|
|||
export interface SecurityMasterSourcesResult {
|
||||
stageARecords: StageASourceRecord[];
|
||||
stageBInput: SecurityMasterStageBSourceInput;
|
||||
securityTypeRecords: SecurityTypeInputRecord[];
|
||||
securityTypeByIsin: Map<string, SecurityType>;
|
||||
securityTypeStats: SecurityTypeClassificationStats;
|
||||
unknownSecurityTypes: UnknownSecurityTypeCount[];
|
||||
|
|
@ -1047,6 +1049,33 @@ function compareSymbolChanges(a: StageBSymbolChangeInput, b: StageBSymbolChangeI
|
|||
);
|
||||
}
|
||||
|
||||
function rawTypeSortKey(rawType: unknown): string {
|
||||
if (typeof rawType === 'string') {
|
||||
return `s:${rawType}`;
|
||||
}
|
||||
if (rawType === null) {
|
||||
return 'n:null';
|
||||
}
|
||||
if (rawType === undefined) {
|
||||
return 'u:undefined';
|
||||
}
|
||||
if (typeof rawType === 'number' || typeof rawType === 'boolean' || typeof rawType === 'bigint') {
|
||||
return `${typeof rawType}:${String(rawType)}`;
|
||||
}
|
||||
return `o:${typeof rawType}`;
|
||||
}
|
||||
|
||||
function compareSecurityTypeRecords(
|
||||
a: SecurityTypeInputRecord,
|
||||
b: SecurityTypeInputRecord
|
||||
): number {
|
||||
return (
|
||||
compareAscii(a.sourceId, b.sourceId) ||
|
||||
compareAscii(a.isin ?? '', b.isin ?? '') ||
|
||||
compareAscii(rawTypeSortKey(a.rawType), rawTypeSortKey(b.rawType))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure adapter converting a raw `eodSymbols` document into a Stage A source record
|
||||
* and Stage B EOD listing input.
|
||||
|
|
@ -1702,9 +1731,16 @@ export async function readEodSymbols(
|
|||
|
||||
stageARecords.sort(compareStageARecords);
|
||||
eodListings.sort(compareEodListings);
|
||||
securityTypeRecords.sort(compareSecurityTypeRecords);
|
||||
|
||||
const securityTypeResult = buildSecurityTypeByIsin(
|
||||
// Build the loader-facing map strictly from EOD rows accepted as Stage A instrument members so
|
||||
// Stage A-quarantined rows (e.g. isin_cusip_mismatch, duplicate_source_id) cannot supply or veto
|
||||
// a valid instrument's type, while keeping all emitted rows in `securityTypeRecords` for raw
|
||||
// vocabulary diagnostics.
|
||||
const eodStageA = matchInstrumentsStageA(stageARecords);
|
||||
const securityTypeResult = buildSecurityTypeByIsinForStageA(
|
||||
securityTypeRecords,
|
||||
eodStageA.instruments,
|
||||
options.maxSecurityTypeConflicts !== undefined
|
||||
? { maxConflicts: options.maxSecurityTypeConflicts }
|
||||
: undefined
|
||||
|
|
@ -1713,6 +1749,7 @@ export async function readEodSymbols(
|
|||
return {
|
||||
stageARecords,
|
||||
eodListings,
|
||||
securityTypeRecords,
|
||||
securityTypeByIsin: securityTypeResult.securityTypeByIsin,
|
||||
securityTypeStats: securityTypeResult.stats,
|
||||
unknownSecurityTypes: securityTypeResult.unknownRawTypes,
|
||||
|
|
@ -1931,6 +1968,7 @@ export async function readSecurityMasterSources(
|
|||
tickerSources,
|
||||
symbolChanges: symbolChangeResult.symbolChanges,
|
||||
},
|
||||
securityTypeRecords: eodResult.securityTypeRecords,
|
||||
securityTypeByIsin: eodResult.securityTypeByIsin,
|
||||
securityTypeStats: eodResult.securityTypeStats,
|
||||
unknownSecurityTypes: eodResult.unknownSecurityTypes,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
|
|||
import { resolve } from 'node:path';
|
||||
import {
|
||||
buildSecurityTypeByIsin,
|
||||
buildSecurityTypeByIsinForStageA,
|
||||
classifyEodSecurityType,
|
||||
compareAscii,
|
||||
DEFAULT_MAX_SECURITY_TYPE_CONFLICTS,
|
||||
|
|
@ -11,6 +12,7 @@ import {
|
|||
type SecurityType,
|
||||
type SecurityTypeClassificationStats,
|
||||
type SecurityTypeInputRecord,
|
||||
type StageAInstrumentCandidate,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
function mulberry32(seed: number): () => number {
|
||||
|
|
@ -290,6 +292,72 @@ describe('security-master security-type classifier', () => {
|
|||
}
|
||||
});
|
||||
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ import { BarSpanIndex } from '../../apps/stock/data-pipeline/src/normalization/b
|
|||
import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers';
|
||||
import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker';
|
||||
import {
|
||||
buildSecurityTypeByIsin,
|
||||
buildSecurityTypeByIsinForStageA,
|
||||
CEO_SYMBOLS_PROJECTION,
|
||||
classifySourceExchanges,
|
||||
compareAscii,
|
||||
|
|
@ -1600,6 +1602,130 @@ describe('security-master source-symbol-readers', () => {
|
|||
expect(sources.securityTypeByIsin.has('CA82509L1076')).toBe(false);
|
||||
});
|
||||
|
||||
test('regression: Stage A-quarantined EOD rows cannot veto a valid member type or supply a type, while raw emitted rows remain available for vocabulary diagnostics', async () => {
|
||||
const exchangeLookup = createPass1ExchangeLookup();
|
||||
|
||||
const reader = new FakeSourceSymbolReader(
|
||||
{
|
||||
eodSymbols: [
|
||||
// Valid EOD Common Stock row for AAPL (matching ISIN + CUSIP)
|
||||
{
|
||||
eodSearchCode: 'AAPL.US',
|
||||
Code: 'AAPL',
|
||||
Exchange: 'NASDAQ',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'US0378331005',
|
||||
Cusip: '037833100',
|
||||
Name: 'Apple Inc.',
|
||||
Type: 'Common Stock',
|
||||
},
|
||||
// Stale EOD ETF row sharing AAPL's valid ISIN but carrying SPY's valid CUSIP ->
|
||||
// Stage A quarantines as `isin_cusip_mismatch`. Must NOT veto AAPL's 'common' type.
|
||||
{
|
||||
eodSearchCode: 'AAPL_STALE.US',
|
||||
Code: 'AAPL',
|
||||
Exchange: 'NYSE',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'US0378331005',
|
||||
Cusip: '78462F103',
|
||||
Name: 'Stale Apple ETF Row',
|
||||
Type: 'ETF',
|
||||
},
|
||||
// Quarantined-only EOD row with an unmapped raw Type -> must NOT supply a type,
|
||||
// but its raw Type must stay available in `securityTypeRecords` for vocabulary diagnostics.
|
||||
{
|
||||
eodSearchCode: 'BAD_ONLY.US',
|
||||
Code: 'BADO',
|
||||
Exchange: 'NASDAQ',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: 'US30303M1027',
|
||||
Cusip: '037833100',
|
||||
Name: 'Mismatched Meta Row',
|
||||
Type: 'Structured Note',
|
||||
},
|
||||
// Duplicate EOD sourceId -> Stage A quarantines both as `duplicate_source_id`.
|
||||
// Must NOT supply a type for CA7800871021.
|
||||
{
|
||||
eodSearchCode: 'DUP.TO',
|
||||
Code: 'RY',
|
||||
Exchange: 'TO',
|
||||
Country: 'Canada',
|
||||
Currency: 'CAD',
|
||||
Isin: 'CA7800871021',
|
||||
Name: 'Royal Bank Dup 1',
|
||||
Type: 'Preferred Stock',
|
||||
},
|
||||
{
|
||||
eodSearchCode: 'DUP.TO',
|
||||
Code: 'RY',
|
||||
Exchange: 'TO',
|
||||
Country: 'Canada',
|
||||
Currency: 'CAD',
|
||||
Isin: 'CA7800871021',
|
||||
Name: 'Royal Bank Dup 2',
|
||||
Type: 'Preferred Stock',
|
||||
},
|
||||
],
|
||||
ibSymbols: [],
|
||||
qmSymbols: [],
|
||||
ceoSymbols: [],
|
||||
eodSymbolChange: [],
|
||||
},
|
||||
{ readOnly: true, applyFilterAndProjection: true }
|
||||
);
|
||||
|
||||
const sources = await readSecurityMasterSources(reader, { exchangeLookup });
|
||||
assertStatsConservation(sources.stats.eodSymbols);
|
||||
expect(sources.stats.eodSymbols.docsRead).toBe(5);
|
||||
expect(sources.stats.eodSymbols.emitted).toBe(5);
|
||||
|
||||
const stageA = matchInstrumentsStageA(sources.stageARecords);
|
||||
expect(stageA.instruments.map(i => i.primaryIsin)).toEqual(['US0378331005']);
|
||||
expect(stageA.instruments[0]?.members.map(m => m.sourceId)).toEqual(['AAPL.US']);
|
||||
expect(
|
||||
stageA.conflicts.map(c => `${c.sourceId}:${c.conflictKind}`).sort(compareAscii)
|
||||
).toEqual([
|
||||
'AAPL_STALE.US:isin_cusip_mismatch',
|
||||
'BAD_ONLY.US:isin_cusip_mismatch',
|
||||
'DUP.TO:duplicate_source_id',
|
||||
'DUP.TO:duplicate_source_id',
|
||||
]);
|
||||
|
||||
// Loader-facing map contains ONLY the Stage A-accepted member's type ('common'), with zero conflicts.
|
||||
expect([...sources.securityTypeByIsin.entries()]).toEqual([['US0378331005', 'common']]);
|
||||
expect(sources.securityTypeConflicts).toEqual([]);
|
||||
expect(sources.securityTypeByIsin.has('US30303M1027')).toBe(false);
|
||||
expect(sources.securityTypeByIsin.has('CA7800871021')).toBe(false);
|
||||
expect(sources.securityTypeStats).toEqual({
|
||||
recordsIn: 1,
|
||||
classified: 1,
|
||||
missingIsin: 0,
|
||||
missingType: 0,
|
||||
unknownType: 0,
|
||||
distinctClassifiedIsins: 1,
|
||||
isinsMapped: 1,
|
||||
isinsConflicting: 0,
|
||||
conflictsTruncated: 0,
|
||||
});
|
||||
|
||||
// Helper produces the identical loader-facing map when called explicitly after Stage A.
|
||||
const explicitStageAMap = buildSecurityTypeByIsinForStageA(
|
||||
sources.securityTypeRecords,
|
||||
stageA.instruments
|
||||
);
|
||||
expect([...explicitStageAMap.securityTypeByIsin.entries()]).toEqual([
|
||||
...sources.securityTypeByIsin.entries(),
|
||||
]);
|
||||
|
||||
// All 5 emitted EOD rows remain available in `securityTypeRecords` for raw vocabulary diagnostics.
|
||||
expect(sources.securityTypeRecords.length).toBe(5);
|
||||
const rawDiagnostics = buildSecurityTypeByIsin(sources.securityTypeRecords);
|
||||
expect(rawDiagnostics.unknownRawTypes).toEqual([{ rawType: 'Structured Note', count: 1 }]);
|
||||
});
|
||||
|
||||
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