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
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue