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
|
|
@ -95,3 +95,31 @@ bun test test/unit/security-master-source-symbol-readers.test.ts
|
|||
- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):**
|
||||
- Workload: `368,000` synthetic docs (`300,000` `eodSymbols`, `50,000` `qmSymbols`, `18,000` `ibSymbols`) including NMFQS exclusion, country normalization, ISIN/CUSIP check-digit validation, ticker parsing, and deterministic ASCII sorting.
|
||||
- Observed throughput: `754,047 docs/s` (`488.0 ms` wall time, floor `>= 25,000 docs/s`).
|
||||
|
||||
## EOD Security-Type Classifier (`security-type.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/security-type.ts` maps raw EODHD `Type` strings into the canonical PostgreSQL `instrument.security_type` enum (`SecurityType`) and builds the `securityTypeByIsin` map required by `persistSecurityMaster` (wired automatically through `readEodSymbols` and `readSecurityMasterSources`).
|
||||
|
||||
- **Mapping table (`EOD_SECURITY_TYPE_MAP`, trimmed, whitespace-collapsed, case-insensitive):**
|
||||
|
||||
| EODHD `Type` | Canonical `SecurityType` |
|
||||
| --- | --- |
|
||||
| `Common Stock` | `common` |
|
||||
| `Preferred Stock` | `preferred` |
|
||||
| `ETF` | `etf` |
|
||||
| `Unit`, `Units` | `unit` |
|
||||
| `Warrant`, `Warrants` | `warrant` |
|
||||
| `Right`, `Rights` | `right` |
|
||||
| `CDR` | `cdr` |
|
||||
| `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`).
|
||||
- **Local synthetic benchmark:** Run the unit suite and fixed-seed 300,000-record synthetic benchmark (zero DB connections) with:
|
||||
|
||||
```bash
|
||||
bun test test/unit/security-master-security-type.test.ts
|
||||
```
|
||||
|
||||
- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):**
|
||||
- Workload: `300,000` synthetic EOD records (`100,000` distinct ISIN buckets, mixed mapped/unknown/missing types, and `20` conflicting ISINs exercising Pass 2 conflict collection).
|
||||
- Observed throughput: `4,277,092 records/s` (`70.1 ms` wall time, floor `>= 100,000 records/s`).
|
||||
|
|
|
|||
|
|
@ -191,6 +191,19 @@ export {
|
|||
type SelectSampleDatesOptions,
|
||||
} from './price-cross-check';
|
||||
|
||||
export {
|
||||
buildSecurityTypeByIsin,
|
||||
classifyEodSecurityType,
|
||||
DEFAULT_MAX_SECURITY_TYPE_CONFLICTS,
|
||||
EOD_SECURITY_TYPE_MAP,
|
||||
type BuildSecurityTypeByIsinOptions,
|
||||
type BuildSecurityTypeByIsinResult,
|
||||
type SecurityTypeClassificationStats,
|
||||
type SecurityTypeConflict,
|
||||
type SecurityTypeInputRecord,
|
||||
type UnknownSecurityTypeCount,
|
||||
} from './security-type';
|
||||
|
||||
export {
|
||||
adaptCeoSymbolDoc,
|
||||
adaptEodSymbolChangeDoc,
|
||||
|
|
|
|||
278
apps/stock/data-pipeline/src/security-master/security-type.ts
Normal file
278
apps/stock/data-pipeline/src/security-master/security-type.ts
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
/**
|
||||
* Pure, deterministic EODHD `Type` -> `SecurityType` classifier for the security-master loader.
|
||||
*
|
||||
* Vocabulary note: QA MongoDB (`eodSymbols`) is unreachable from the sandbox, so
|
||||
* `EOD_SECURITY_TYPE_MAP` reflects the published EODHD `Type` vocabulary. Non-equity-like values
|
||||
* (`FUND`, `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.) and any unmapped provider strings
|
||||
* return `null` and are surfaced in `unknownRawTypes` for review rather than guessed from ticker
|
||||
* suffixes or company names.
|
||||
*/
|
||||
import { compareAscii } from './exchange-pass1';
|
||||
import type { SecurityType } from './persist';
|
||||
|
||||
export const DEFAULT_MAX_SECURITY_TYPE_CONFLICTS = 200;
|
||||
|
||||
/**
|
||||
* Published EODHD `Type` vocabulary mapped to the canonical PostgreSQL `instrument.security_type`
|
||||
* enum (`SecurityType`). Keys are trimmed, whitespace-collapsed uppercase strings.
|
||||
*/
|
||||
export const EOD_SECURITY_TYPE_MAP: Readonly<Record<string, SecurityType>> = Object.freeze({
|
||||
'COMMON STOCK': 'common',
|
||||
'PREFERRED STOCK': 'preferred',
|
||||
ETF: 'etf',
|
||||
UNIT: 'unit',
|
||||
UNITS: 'unit',
|
||||
WARRANT: 'warrant',
|
||||
WARRANTS: 'warrant',
|
||||
RIGHT: 'right',
|
||||
RIGHTS: 'right',
|
||||
CDR: 'cdr',
|
||||
CURRENCY: 'fx',
|
||||
FOREX: 'fx',
|
||||
FX: 'fx',
|
||||
});
|
||||
|
||||
// Backing Map avoids prototype-chain lookups (e.g. `toString`, `constructor`, `__proto__`).
|
||||
const EOD_SECURITY_TYPE_LOOKUP: ReadonlyMap<string, SecurityType> = new Map<string, SecurityType>(
|
||||
Object.entries(EOD_SECURITY_TYPE_MAP)
|
||||
);
|
||||
|
||||
const WHITESPACE_RUN_PATTERN = /\s+/g;
|
||||
|
||||
export interface SecurityTypeInputRecord {
|
||||
readonly isin: string | null;
|
||||
readonly rawType: unknown;
|
||||
readonly sourceId: string;
|
||||
}
|
||||
|
||||
export interface UnknownSecurityTypeCount {
|
||||
readonly rawType: string;
|
||||
readonly count: number;
|
||||
}
|
||||
|
||||
export interface SecurityTypeConflict {
|
||||
readonly isin: string;
|
||||
readonly types: readonly SecurityType[];
|
||||
readonly sourceIds: readonly string[];
|
||||
readonly recordCount: number;
|
||||
}
|
||||
|
||||
export interface SecurityTypeClassificationStats {
|
||||
recordsIn: number;
|
||||
classified: number;
|
||||
missingIsin: number;
|
||||
missingType: number;
|
||||
unknownType: number;
|
||||
distinctClassifiedIsins: number;
|
||||
isinsMapped: number;
|
||||
isinsConflicting: number;
|
||||
conflictsTruncated: number;
|
||||
}
|
||||
|
||||
export interface BuildSecurityTypeByIsinOptions {
|
||||
readonly maxConflicts?: number;
|
||||
}
|
||||
|
||||
export interface BuildSecurityTypeByIsinResult {
|
||||
securityTypeByIsin: Map<string, SecurityType>;
|
||||
stats: SecurityTypeClassificationStats;
|
||||
unknownRawTypes: UnknownSecurityTypeCount[];
|
||||
conflicts: SecurityTypeConflict[];
|
||||
}
|
||||
|
||||
function normalizeRawTypeString(rawType: string): string {
|
||||
const trimmed = rawType.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return '';
|
||||
}
|
||||
return trimmed.replace(WHITESPACE_RUN_PATTERN, ' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps an EODHD `Type` value (trimmed, case-insensitive, whitespace-collapsed) to the canonical
|
||||
* `SecurityType` union. Returns `null` for non-strings, blanks, non-equity values (`FUND`,
|
||||
* `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.), and unmapped strings. Never guesses from
|
||||
* ticker suffixes or names.
|
||||
*/
|
||||
export function classifyEodSecurityType(rawType: unknown): SecurityType | null {
|
||||
if (typeof rawType !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const normalized = normalizeRawTypeString(rawType);
|
||||
if (normalized.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return EOD_SECURITY_TYPE_LOOKUP.get(normalized.toUpperCase()) ?? null;
|
||||
}
|
||||
|
||||
interface ConflictAccumulator {
|
||||
readonly types: Set<SecurityType>;
|
||||
readonly sourceIds: Set<string>;
|
||||
recordCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregates EODHD security-type records by ISIN into a deterministic `securityTypeByIsin` map
|
||||
* for `persistSecurityMaster`, omitting any ISIN whose classified records disagree and reporting
|
||||
* conflicts and unmapped raw `Type` values in deterministic order.
|
||||
*/
|
||||
export function buildSecurityTypeByIsin(
|
||||
records: readonly SecurityTypeInputRecord[],
|
||||
options: BuildSecurityTypeByIsinOptions = {}
|
||||
): BuildSecurityTypeByIsinResult {
|
||||
const maxConflicts = options.maxConflicts ?? DEFAULT_MAX_SECURITY_TYPE_CONFLICTS;
|
||||
if (!Number.isInteger(maxConflicts) || maxConflicts < 0) {
|
||||
throw new RangeError(
|
||||
`buildSecurityTypeByIsin: maxConflicts must be a non-negative integer (received ${String(maxConflicts)})`
|
||||
);
|
||||
}
|
||||
|
||||
let classified = 0;
|
||||
let missingIsin = 0;
|
||||
let missingType = 0;
|
||||
let unknownType = 0;
|
||||
|
||||
const rawByIsin = new Map<string, SecurityType>();
|
||||
const conflictingIsins = new Set<string>();
|
||||
const unknownCounts = new Map<string, number>();
|
||||
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
const record = records[i];
|
||||
if (record === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof record.isin !== 'string') {
|
||||
missingIsin += 1;
|
||||
continue;
|
||||
}
|
||||
const isin = record.isin.trim();
|
||||
if (isin.length === 0) {
|
||||
missingIsin += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof record.rawType !== 'string') {
|
||||
missingType += 1;
|
||||
continue;
|
||||
}
|
||||
const displayRawType = normalizeRawTypeString(record.rawType);
|
||||
if (displayRawType.length === 0) {
|
||||
missingType += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const mapped = EOD_SECURITY_TYPE_LOOKUP.get(displayRawType.toUpperCase());
|
||||
if (mapped === undefined) {
|
||||
unknownType += 1;
|
||||
unknownCounts.set(displayRawType, (unknownCounts.get(displayRawType) ?? 0) + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
classified += 1;
|
||||
|
||||
if (conflictingIsins.has(isin)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = rawByIsin.get(isin);
|
||||
if (existing === undefined) {
|
||||
rawByIsin.set(isin, mapped);
|
||||
} else if (existing !== mapped) {
|
||||
rawByIsin.delete(isin);
|
||||
conflictingIsins.add(isin);
|
||||
}
|
||||
}
|
||||
|
||||
const conflicts: SecurityTypeConflict[] = [];
|
||||
if (conflictingIsins.size > 0 && maxConflicts > 0) {
|
||||
const sortedConflictingIsins = [...conflictingIsins].sort(compareAscii);
|
||||
const sampleLimit = Math.min(sortedConflictingIsins.length, maxConflicts);
|
||||
const accumulators = new Map<string, ConflictAccumulator>();
|
||||
|
||||
for (let i = 0; i < sampleLimit; i++) {
|
||||
const isin = sortedConflictingIsins[i];
|
||||
if (isin !== undefined) {
|
||||
accumulators.set(isin, {
|
||||
types: new Set<SecurityType>(),
|
||||
sourceIds: new Set<string>(),
|
||||
recordCount: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2 runs only when conflicts exist so the non-conflicting fast path allocates no wrappers.
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
const record = records[i];
|
||||
if (record === undefined || typeof record.isin !== 'string') {
|
||||
continue;
|
||||
}
|
||||
const isin = record.isin.trim();
|
||||
const acc = accumulators.get(isin);
|
||||
if (acc === undefined) {
|
||||
continue;
|
||||
}
|
||||
const mapped = classifyEodSecurityType(record.rawType);
|
||||
if (mapped === null) {
|
||||
continue;
|
||||
}
|
||||
acc.types.add(mapped);
|
||||
acc.sourceIds.add(record.sourceId);
|
||||
acc.recordCount += 1;
|
||||
}
|
||||
|
||||
for (let i = 0; i < sampleLimit; i++) {
|
||||
const isin = sortedConflictingIsins[i];
|
||||
if (isin === undefined) {
|
||||
continue;
|
||||
}
|
||||
const acc = accumulators.get(isin);
|
||||
if (acc !== undefined) {
|
||||
conflicts.push({
|
||||
isin,
|
||||
types: [...acc.types].sort(compareAscii),
|
||||
sourceIds: [...acc.sourceIds].sort(compareAscii),
|
||||
recordCount: acc.recordCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const securityTypeByIsin = new Map<string, SecurityType>();
|
||||
const sortedMappedIsins = [...rawByIsin.keys()].sort(compareAscii);
|
||||
for (let i = 0; i < sortedMappedIsins.length; i++) {
|
||||
const isin = sortedMappedIsins[i];
|
||||
if (isin !== undefined) {
|
||||
const securityType = rawByIsin.get(isin);
|
||||
if (securityType !== undefined) {
|
||||
securityTypeByIsin.set(isin, securityType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const unknownRawTypes: UnknownSecurityTypeCount[] = [];
|
||||
for (const [rawType, count] of unknownCounts.entries()) {
|
||||
unknownRawTypes.push({ rawType, count });
|
||||
}
|
||||
unknownRawTypes.sort((a, b) => b.count - a.count || compareAscii(a.rawType, b.rawType));
|
||||
|
||||
const isinsMapped = securityTypeByIsin.size;
|
||||
const isinsConflicting = conflictingIsins.size;
|
||||
|
||||
return {
|
||||
securityTypeByIsin,
|
||||
stats: {
|
||||
recordsIn: records.length,
|
||||
classified,
|
||||
missingIsin,
|
||||
missingType,
|
||||
unknownType,
|
||||
distinctClassifiedIsins: isinsMapped + isinsConflicting,
|
||||
isinsMapped,
|
||||
isinsConflicting,
|
||||
conflictsTruncated: isinsConflicting - conflicts.length,
|
||||
},
|
||||
unknownRawTypes,
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ import {
|
|||
type BarSpanIndex,
|
||||
type SpanDateRange,
|
||||
} from '../normalization/bar-spans';
|
||||
import { isValidCusip, isValidIsin } from '../normalization/identifiers';
|
||||
import { cusipToIsin, isValidCusip, isValidIsin } from '../normalization/identifiers';
|
||||
import { normalizeProviderSymbol } from '../normalization/provider-symbol';
|
||||
import { parseTickerDetailed } from '../normalization/ticker';
|
||||
import {
|
||||
|
|
@ -26,6 +26,14 @@ import {
|
|||
type StageBSymbolChangeInput,
|
||||
type StageBTickerSourceInput,
|
||||
} from './listing-stage-b';
|
||||
import type { SecurityType } from './persist';
|
||||
import {
|
||||
buildSecurityTypeByIsin,
|
||||
type SecurityTypeClassificationStats,
|
||||
type SecurityTypeConflict,
|
||||
type SecurityTypeInputRecord,
|
||||
type UnknownSecurityTypeCount,
|
||||
} from './security-type';
|
||||
|
||||
export const SOURCE_SYMBOL_COLLECTIONS = Object.freeze({
|
||||
eod: 'eodSymbols',
|
||||
|
|
@ -151,6 +159,7 @@ export interface ReadSourceCollectionOptions {
|
|||
readonly countries?: readonly string[] | null;
|
||||
readonly knownExchanges?: readonly ExchangeSeedRow[];
|
||||
readonly batchSize?: number;
|
||||
readonly maxSecurityTypeConflicts?: number;
|
||||
}
|
||||
|
||||
export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions;
|
||||
|
|
@ -191,6 +200,8 @@ export type AdaptEodSymbolResult =
|
|||
readonly ok: true;
|
||||
readonly stageARecord: StageASourceRecord;
|
||||
readonly eodListing: StageBEodListingInput;
|
||||
readonly rawType: unknown;
|
||||
readonly resolvedIsin: string | null;
|
||||
readonly invalidIdentifiersNulled: number;
|
||||
}
|
||||
| { readonly ok: false; readonly skipReason: SourceSymbolSkipReason };
|
||||
|
|
@ -221,6 +232,10 @@ export type AdaptEodSymbolChangeResult =
|
|||
export interface ReadEodSymbolsResult {
|
||||
stageARecords: StageASourceRecord[];
|
||||
eodListings: StageBEodListingInput[];
|
||||
securityTypeByIsin: Map<string, SecurityType>;
|
||||
securityTypeStats: SecurityTypeClassificationStats;
|
||||
unknownSecurityTypes: UnknownSecurityTypeCount[];
|
||||
securityTypeConflicts: SecurityTypeConflict[];
|
||||
stats: SourceCollectionReadStats;
|
||||
}
|
||||
|
||||
|
|
@ -259,6 +274,10 @@ export interface SecurityMasterSourcesStats {
|
|||
export interface SecurityMasterSourcesResult {
|
||||
stageARecords: StageASourceRecord[];
|
||||
stageBInput: SecurityMasterStageBSourceInput;
|
||||
securityTypeByIsin: Map<string, SecurityType>;
|
||||
securityTypeStats: SecurityTypeClassificationStats;
|
||||
unknownSecurityTypes: UnknownSecurityTypeCount[];
|
||||
securityTypeConflicts: SecurityTypeConflict[];
|
||||
stats: SecurityMasterSourcesStats;
|
||||
}
|
||||
|
||||
|
|
@ -359,6 +378,8 @@ export const EOD_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.fr
|
|||
Name: 1,
|
||||
name: 1,
|
||||
companyName: 1,
|
||||
Type: 1,
|
||||
type: 1,
|
||||
delisted: 1,
|
||||
});
|
||||
|
||||
|
|
@ -746,6 +767,20 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts raw EODHD `Type`/`type` without rejecting non-string values so a malformed `Type`
|
||||
* never skips the symbol document (it is counted as `missingType` by the classifier instead).
|
||||
*/
|
||||
function readRawSecurityType(doc: Record<string, unknown>): unknown {
|
||||
if (typeof doc.Type === 'string' && doc.Type.trim().length > 0) {
|
||||
return doc.Type;
|
||||
}
|
||||
if (typeof doc.type === 'string' && doc.type.trim().length > 0) {
|
||||
return doc.type;
|
||||
}
|
||||
return doc.Type !== undefined ? doc.Type : doc.type;
|
||||
}
|
||||
|
||||
function isNorthAmericaIso(code: string | null): code is 'US' | 'CA' {
|
||||
return code === 'US' || code === 'CA';
|
||||
}
|
||||
|
|
@ -1132,6 +1167,13 @@ export function adaptEodSymbolDoc(
|
|||
const name = normalized?.companyName ?? nameField.value;
|
||||
const ticker = normalized?.symbol ?? tickerField.value;
|
||||
const span = toSpanDateRange(context.barSpans?.get('eod', sourceId));
|
||||
const rawType = readRawSecurityType(doc);
|
||||
const resolvedIsin =
|
||||
validIsin !== null
|
||||
? validIsin
|
||||
: validCusip !== null && isNorthAmericaIso(issuerCountry)
|
||||
? cusipToIsin(validCusip, issuerCountry)
|
||||
: null;
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
|
|
@ -1152,6 +1194,8 @@ export function adaptEodSymbolDoc(
|
|||
currency,
|
||||
span,
|
||||
},
|
||||
rawType,
|
||||
resolvedIsin,
|
||||
invalidIdentifiersNulled,
|
||||
};
|
||||
}
|
||||
|
|
@ -1624,6 +1668,7 @@ export async function readEodSymbols(
|
|||
|
||||
const stageARecords: StageASourceRecord[] = [];
|
||||
const eodListings: StageBEodListingInput[] = [];
|
||||
const securityTypeRecords: SecurityTypeInputRecord[] = [];
|
||||
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eod);
|
||||
|
||||
const findOptions: SourceSymbolFindOptions = {
|
||||
|
|
@ -1645,6 +1690,11 @@ export async function readEodSymbols(
|
|||
}
|
||||
stageARecords.push(adapted.stageARecord);
|
||||
eodListings.push(adapted.eodListing);
|
||||
securityTypeRecords.push({
|
||||
isin: adapted.resolvedIsin,
|
||||
rawType: adapted.rawType,
|
||||
sourceId: adapted.stageARecord.sourceId,
|
||||
});
|
||||
stats.emitted += 1;
|
||||
stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled;
|
||||
}
|
||||
|
|
@ -1653,7 +1703,22 @@ export async function readEodSymbols(
|
|||
stageARecords.sort(compareStageARecords);
|
||||
eodListings.sort(compareEodListings);
|
||||
|
||||
return { stageARecords, eodListings, stats };
|
||||
const securityTypeResult = buildSecurityTypeByIsin(
|
||||
securityTypeRecords,
|
||||
options.maxSecurityTypeConflicts !== undefined
|
||||
? { maxConflicts: options.maxSecurityTypeConflicts }
|
||||
: undefined
|
||||
);
|
||||
|
||||
return {
|
||||
stageARecords,
|
||||
eodListings,
|
||||
securityTypeByIsin: securityTypeResult.securityTypeByIsin,
|
||||
securityTypeStats: securityTypeResult.stats,
|
||||
unknownSecurityTypes: securityTypeResult.unknownRawTypes,
|
||||
securityTypeConflicts: securityTypeResult.conflicts,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
/** Streams and adapts `ibSymbols` from a read-only MongoDB reader. */
|
||||
|
|
@ -1866,6 +1931,10 @@ export async function readSecurityMasterSources(
|
|||
tickerSources,
|
||||
symbolChanges: symbolChangeResult.symbolChanges,
|
||||
},
|
||||
securityTypeByIsin: eodResult.securityTypeByIsin,
|
||||
securityTypeStats: eodResult.securityTypeStats,
|
||||
unknownSecurityTypes: eodResult.unknownSecurityTypes,
|
||||
securityTypeConflicts: eodResult.securityTypeConflicts,
|
||||
stats: {
|
||||
eodSymbols: eodResult.stats,
|
||||
ibSymbols: ibResult.stats,
|
||||
|
|
|
|||
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