feat(m1): complete curate-etl MongoDB driver, DuckDB MarketDataStore, Python SDK, and M1 evidence

This commit is contained in:
Boki 2026-11-30 10:18:58 -05:00
parent 88308e1f12
commit d9191304fb
62 changed files with 9608 additions and 366 deletions

View file

@ -175,6 +175,49 @@ function parseExactIsoDateToUtcDay(value: unknown): number | null {
return era * 146097 + dayOfEra - 719468;
}
function formatUtcDayToIsoDate(daysSinceEpoch: number): string {
const shifted = daysSinceEpoch + 719468;
const era = Math.floor(shifted / 146097);
const doe = shifted - era * 146097;
const yoe = Math.floor(
(doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365
);
const y = yoe + era * 400;
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
const mp = Math.floor((5 * doy + 2) / 153);
const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
const month = mp + (mp < 10 ? 3 : -9);
const year = y + (month <= 2 ? 1 : 0);
const yStr = String(year).padStart(4, '0');
const mStr = month < 10 ? `0${String(month)}` : String(month);
const dStr = day < 10 ? `0${String(day)}` : String(day);
return `${yStr}-${mStr}-${dStr}`;
}
function isBackfilledOtcContinuation(
primary: EndedPrimaryRow,
otc: EligibleOtcRow,
overlapToleranceDays: number
): boolean {
// Provider backfills (notably EODHD on SIVB -> SIVBQ) copy the primary listing's entire
// pre-delist bar history onto the OTC ticker, so otc.listedFrom matches primary.listedFrom
// rather than starting near primary.listedTo. Require that OTC trading continued strictly
// past primary.listedTo and either shares the primary's IPO/start date or carries the
// canonical bankruptcy `<primaryTicker>Q` suffix.
if (otc.listedFromDay >= primary.listedToDay - overlapToleranceDays) {
return false;
}
if (otc.listedToDay !== null && otc.listedToDay <= primary.listedToDay) {
return false;
}
const sameBackfilledStart =
primary.listedFromDay !== null &&
otc.listedFromDay <= primary.listedFromDay + overlapToleranceDays;
const isBankruptcyQSuffix =
otc.key.tickerRoot.toUpperCase() === `${primary.key.tickerRoot.toUpperCase()}Q`;
return sameBackfilledStart || isBankruptcyQSuffix;
}
function cloneListingKey(key: ListingNaturalKey): ListingNaturalKey {
return {
primaryIsin: key.primaryIsin,
@ -693,13 +736,24 @@ export function linkDelistingChains(
otc.listedToDay === null || otc.listedToDay > maxWindowDay
? maxWindowDay
: otc.listedToDay;
if (lowDay > highDay) {
continue;
if (lowDay <= highDay) {
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
if (startIdx < endExclusive) {
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
continue;
}
}
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
if (startIdx < endExclusive) {
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
// Fallback for EODHD-style backfilled OTC history (e.g. SIVB -> SIVBQ) where the OTC
// ticker carries pre-delist bars back to the primary listing's original start date.
for (let pIdx = 0; pIdx < primaries.length; pIdx++) {
const primary = primaries[pIdx];
if (
primary !== undefined &&
isBackfilledOtcContinuation(primary, otc, overlapToleranceDays)
) {
intervals.push({ startIdx: pIdx, endIdx: pIdx, otcIdx: oIdx });
}
}
}
@ -730,13 +784,16 @@ export function linkDelistingChains(
const otc = oIdx !== undefined ? otcs[oIdx] : undefined;
if (primary !== undefined && otc !== undefined) {
linkedPrimaryIndices.add(primary.index);
// effectiveDate uses the OTC listing's first observed date (listedFrom) so
// downstream backtests and curation never back-date OTC availability before
// OTC trading/quoting actually began.
// effectiveDate uses the OTC listing's first observed date (listedFrom) for clean
// transfers, or the day after primary.listedTo when the OTC ticker's pre-delist history
// was backfilled (so downstream curation never back-dates the transfer to the IPO date).
const effectiveDate = isBackfilledOtcContinuation(primary, otc, overlapToleranceDays)
? formatUtcDayToIsoDate(primary.listedToDay + 1)
: otc.listedFrom;
continuities.push({
fromListingKey: cloneListingKey(primary.key),
toListingKey: cloneListingKey(otc.key),
effectiveDate: otc.listedFrom,
effectiveDate,
kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER,
});
}

View file

@ -71,6 +71,7 @@ export interface ExchangeClassificationResult {
export interface ClassifySourceExchangesOptions {
knownExchanges?: readonly ExchangeSeedRow[];
reviewedRows?: readonly ExchangeSourceMapRow[];
}
const VALID_EXCHANGE_SOURCE_SET: ReadonlySet<string> = new Set(EXCHANGE_SOURCES);
@ -293,9 +294,15 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'eod' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE MKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE NAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSEARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCCE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCGREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCMTKS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
@ -305,19 +312,63 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'ib' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BOX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BYX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOE2', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CDE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'CFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CFETAS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CHX', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'COMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'EMERALD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'FORECASTX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'FUNDSERV', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'GEMINI', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBCMDTY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBDESK', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBFX', role: 'forex' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBKRAM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBKRATS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBUSCFD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ICEUS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IDEALPRO', role: 'forex' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ISE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ISLAND', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'LTSE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'MERCURY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'MIAX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQBX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQOM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'NYBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSEFLOOR', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSELIFFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSENAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'OVERNIGHT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PEARL', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PHLX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PSE', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'SGXCME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'SMFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'TRADEWEB', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'VALUE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'VENTURE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'ZEROHASH', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
// QuoteMedia US + CA venues (qmExchanges has 0% OperatingMIC)
{ source: 'qm' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'AMX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'AQL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'AQLL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'ARC', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'ASE', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
@ -332,16 +383,23 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'qm' as const, sourceCode: 'CNX', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CSE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CVE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CVEM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EDGA', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EXPM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'GREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'MOE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NCM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NDD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NEOE', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NGM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NGS', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NMF', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSC', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
@ -357,6 +415,7 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'qm' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PCX', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PINL', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PNK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'QB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'QX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
@ -364,7 +423,9 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
{ source: 'qm' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSX', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXC', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXVC', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
].map(rule => ({
...rule,
@ -423,6 +484,12 @@ export function classifySourceExchanges(
const knownByMic = new Map<string, ExchangeSeedRow>(
knownExchanges.map(exchange => [exchange.mic.trim().toUpperCase(), exchange])
);
const reviewedByKey = new Map<string, ExchangeSourceMapRow>();
if (options.reviewedRows) {
for (const row of options.reviewedRows) {
reviewedByKey.set(makeRuleKey(row.source, row.sourceCode.trim().toUpperCase()), row);
}
}
const grouped = new Map<string, { source: ExchangeSource; sourceCode: string; records: SourceExchangeRecord[] }>();
const unresolved: UnresolvedExchangeRecord[] = [];
@ -495,6 +562,20 @@ export function classifySourceExchanges(
continue;
}
const reviewedRow = reviewedByKey.get(makeRuleKey(group.source, group.sourceCode));
if (reviewedRow) {
mapped.push({
source: reviewedRow.source,
sourceCode: reviewedRow.sourceCode.trim().toUpperCase(),
role: reviewedRow.role,
mic: reviewedRow.mic,
countryIso: reviewedRow.countryIso,
method: reviewedRow.method,
reviewedBy: reviewedRow.reviewedBy ?? null,
});
continue;
}
// Sort group deterministically so duplicate collapse is independent of input order.
const sortedRecords = [...group.records].sort(compareSourceRecordsDeterministically);
const representative = sortedRecords[0];

View file

@ -9,9 +9,15 @@ import { compareAscii } from './exchange-pass1';
export const STAGE_A_SOURCES = ['ib', 'eod'] as const;
export const SYNTHETIC_EOD_ISIN_PREFIX = 'SYN:EOD:' as const;
export function isSyntheticInstrumentKey(value: string): boolean {
return value.startsWith(SYNTHETIC_EOD_ISIN_PREFIX);
}
export type StageASource = (typeof STAGE_A_SOURCES)[number];
export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip';
export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip' | 'tier3_ticker_span';
export type StageAConflictKind = 'isin_cusip_mismatch' | 'duplicate_source_id';
@ -64,6 +70,7 @@ export interface StageASourceStats {
total: number;
tier1Isin: number;
tier2Cusip: number;
tier3Synthetic?: number;
unresolved: number;
conflict: number;
}
@ -76,6 +83,7 @@ export interface StageAStats {
export interface MatchInstrumentsStageAOptions {
readonly nameSourcePrecedence?: readonly StageASource[];
readonly allowIdentifierlessEod?: boolean;
}
export interface StageAMatchResult {
@ -93,6 +101,7 @@ interface BestSourceName {
interface InstrumentAccumulator {
members: StageAInstrumentMember[];
bestNameBySource: Record<StageASource, BestSourceName | null>;
fallbackCountry: string | null;
}
export function isStageASource(value: unknown): value is StageASource {
@ -230,6 +239,45 @@ export function matchInstrumentsStageA(
const resolved = resolveIsin(record);
if (resolved.isin === null) {
if (options.allowIdentifierlessEod === true && source === 'eod') {
const syntheticKey = `${SYNTHETIC_EOD_ISIN_PREFIX}${sourceId.trim().toUpperCase()}`;
const normalizedCountry = normalizeCode(record.country);
const fallbackCountry =
normalizedCountry !== null && /^[A-Z]{2}$/.test(normalizedCountry)
? normalizedCountry
: sourceId.endsWith('.TO') ||
sourceId.endsWith('.V') ||
sourceId.endsWith('.NEO') ||
sourceId.endsWith('.CN')
? 'CA'
: 'US';
const currency = normalizeCode(record.currency);
const name = normalizeName(record.name);
let acc = instrumentsByIsin.get(syntheticKey);
if (acc === undefined) {
acc = {
members: [],
bestNameBySource: { ib: null, eod: null },
fallbackCountry,
};
instrumentsByIsin.set(syntheticKey, acc);
}
acc.members.push({
source,
sourceId,
currency,
method: 'tier3_ticker_span',
});
if (name !== null) {
const existingBest = acc.bestNameBySource[source];
if (existingBest === null || compareAscii(sourceId, existingBest.sourceId) < 0) {
acc.bestNameBySource[source] = { sourceId, name };
}
}
sourceStats.tier3Synthetic = (sourceStats.tier3Synthetic ?? 0) + 1;
continue;
}
unresolved.push({
source,
sourceId,
@ -286,6 +334,7 @@ export function matchInstrumentsStageA(
ib: null,
eod: null,
},
fallbackCountry: null,
};
instrumentsByIsin.set(resolved.isin, acc);
}
@ -313,10 +362,13 @@ export function matchInstrumentsStageA(
const instruments: StageAInstrumentCandidate[] = [];
for (const [primaryIsin, acc] of instrumentsByIsin.entries()) {
const issuerCountry = primaryIsin.slice(0, 2);
const embeddedCusip = primaryIsin.slice(2, 11);
const isSynthetic = isSyntheticInstrumentKey(primaryIsin);
const issuerCountry = isSynthetic ? (acc.fallbackCountry ?? 'US') : primaryIsin.slice(0, 2);
const embeddedCusip = isSynthetic ? '' : primaryIsin.slice(2, 11);
const primaryCusip =
isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) ? embeddedCusip : null;
!isSynthetic && isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip)
? embeddedCusip
: null;
let canonicalName: string | null = null;
for (const source of nameSourcePrecedence) {

View file

@ -6,10 +6,11 @@ import {
} from '../normalization/bar-spans';
import { parseTickerDetailed } from '../normalization/ticker';
import { compareAscii, type ExchangeRole } from './exchange-pass1';
import type {
StageAInstrumentCandidate,
StageAMatchMethod,
StageASource,
import {
isSyntheticInstrumentKey,
type StageAInstrumentCandidate,
type StageAMatchMethod,
type StageASource,
} from './instrument-stage-a';
export const MAX_TICKER_ROOT_LENGTH = 24;
@ -216,8 +217,15 @@ function isStageASourceValue(value: unknown): value is StageASource {
return value === 'ib' || value === 'eod';
}
function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod {
return value === 'tier1_isin' || value === 'tier2_cusip';
function isStageAMatchMethodValue(
value: unknown,
allowSyntheticTier3 = false
): value is StageAMatchMethod {
return (
value === 'tier1_isin' ||
value === 'tier2_cusip' ||
(allowSyntheticTier3 && value === 'tier3_ticker_span')
);
}
function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource {
@ -658,7 +666,8 @@ export function matchListingsStageB(
`Invalid empty or non-string sourceId at instruments[${i}].members[${j}]`
);
}
if (!isStageAMatchMethodValue(member.method)) {
const isSyntheticInst = isSyntheticInstrumentKey(inst.primaryIsin);
if (!isStageAMatchMethodValue(member.method, isSyntheticInst)) {
throw new Error(
`Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]`
);

View file

@ -16,11 +16,13 @@ import type {
Pass6DelistReason,
} from './delisting-chains';
import { compareAscii } from './exchange-pass1';
import type {
StageAInstrumentCandidate,
StageAInstrumentMember,
StageAMatchResult,
StageASource,
import {
isSyntheticInstrumentKey,
SYNTHETIC_EOD_ISIN_PREFIX,
type StageAInstrumentCandidate,
type StageAInstrumentMember,
type StageAMatchResult,
type StageASource,
} from './instrument-stage-a';
import type {
ListingNaturalKey,
@ -243,6 +245,8 @@ interface ExistingPass4ConflictRow {
interface PreparedInstrument {
readonly primaryIsin: string;
readonly isSynthetic: boolean;
readonly syntheticSourceId: string | null;
readonly primaryCusip: string | null;
readonly canonicalName: string;
readonly securityType: SecurityType;
@ -660,9 +664,16 @@ async function persistWithinTransaction(
skippedInstrumentIsins.add(candidate.primaryIsin);
continue;
}
const isSynthetic = isSyntheticInstrumentKey(candidate.primaryIsin);
const syntheticSourceId = isSynthetic
? (candidate.members.find(m => m.source === 'eod')?.sourceId ??
candidate.primaryIsin.slice(SYNTHETIC_EOD_ISIN_PREFIX.length))
: null;
preparedInstruments.push({
primaryIsin: candidate.primaryIsin,
primaryCusip: candidate.primaryCusip,
isSynthetic,
syntheticSourceId,
primaryCusip: isSynthetic ? null : candidate.primaryCusip,
canonicalName: trimmedName,
securityType,
issuerCountry: candidate.issuerCountry,
@ -672,8 +683,11 @@ async function persistWithinTransaction(
if (preparedInstruments.length > 0) {
const existingByIsin = new Map<string, ExistingInstrumentRow>();
for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) {
const slice = preparedInstruments.slice(offset, offset + chunkSize);
const realInstruments = preparedInstruments.filter(item => !item.isSynthetic);
const syntheticInstruments = preparedInstruments.filter(item => item.isSynthetic);
for (let offset = 0; offset < realInstruments.length; offset += chunkSize) {
const slice = realInstruments.slice(offset, offset + chunkSize);
const isins = slice.map(item => item.primaryIsin);
const res = await client.query<ExistingInstrumentRow>(
`SELECT
@ -692,13 +706,70 @@ async function persistWithinTransaction(
}
}
const toInsert: PreparedInstrument[] = [];
for (let offset = 0; offset < syntheticInstruments.length; offset += chunkSize) {
const slice = syntheticInstruments.slice(offset, offset + chunkSize);
const sourceIdToKey = new Map<string, string>();
const sourceIds: string[] = [];
for (const item of slice) {
if (item.syntheticSourceId !== null) {
sourceIdToKey.set(item.syntheticSourceId, item.primaryIsin);
sourceIds.push(item.syntheticSourceId);
}
}
if (sourceIds.length === 0) {
continue;
}
const res = await client.query<{
source_id: string;
instrument_id: number;
primary_cusip: string | null;
canonical_name: string;
security_type: string;
issuer_country: string | null;
}>(
`SELECT DISTINCT ON (pm.source_id)
pm.source_id,
i.instrument_id,
btrim(i.primary_cusip) AS primary_cusip,
i.canonical_name,
i.security_type,
btrim(i.issuer_country) AS issuer_country
FROM provider_mapping pm
JOIN listing l ON l.listing_id = pm.listing_id
JOIN instrument i ON i.instrument_id = l.instrument_id
WHERE pm.source = 'eod'
AND pm.source_id = ANY($1::text[])
AND i.primary_isin IS NULL
ORDER BY pm.source_id, pm.valid_from ASC`,
[sourceIds]
);
for (const row of res.rows) {
const key = sourceIdToKey.get(row.source_id);
if (key !== undefined) {
existingByIsin.set(key, {
instrument_id: row.instrument_id,
primary_isin: key,
primary_cusip: row.primary_cusip,
canonical_name: row.canonical_name,
security_type: row.security_type,
issuer_country: row.issuer_country,
});
}
}
}
const toInsertReal: PreparedInstrument[] = [];
const toInsertSynthetic: PreparedInstrument[] = [];
const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = [];
for (const item of preparedInstruments) {
const existing = existingByIsin.get(item.primaryIsin);
if (existing === undefined) {
toInsert.push(item);
if (item.isSynthetic) {
toInsertSynthetic.push(item);
} else {
toInsertReal.push(item);
}
continue;
}
instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id);
@ -714,8 +785,8 @@ async function persistWithinTransaction(
}
}
for (let offset = 0; offset < toInsert.length; offset += chunkSize) {
const slice = toInsert.slice(offset, offset + chunkSize);
for (let offset = 0; offset < toInsertReal.length; offset += chunkSize) {
const slice = toInsertReal.slice(offset, offset + chunkSize);
const res = await client.query<InsertedInstrumentRow>(
`INSERT INTO instrument (
primary_isin,
@ -747,6 +818,39 @@ async function persistWithinTransaction(
instrumentsInserted += res.rows.length;
}
for (let offset = 0; offset < toInsertSynthetic.length; offset += chunkSize) {
const slice = toInsertSynthetic.slice(offset, offset + chunkSize);
const res = await client.query<{ instrument_id: number }>(
`INSERT INTO instrument (
primary_isin,
primary_cusip,
canonical_name,
security_type,
issuer_country
)
SELECT NULL, NULL, u.canonical_name, u.security_type, u.issuer_country
FROM UNNEST(
$1::text[],
$2::varchar[],
$3::bpchar[]
) AS u(canonical_name, security_type, issuer_country)
RETURNING instrument_id`,
[
slice.map(item => item.canonicalName),
slice.map(item => item.securityType),
slice.map(item => item.issuerCountry),
]
);
for (let i = 0; i < res.rows.length; i++) {
const item = slice[i];
const row = res.rows[i];
if (item !== undefined && row !== undefined) {
instrumentIdByIsin.set(item.primaryIsin, row.instrument_id);
}
}
instrumentsInserted += res.rows.length;
}
for (let offset = 0; offset < toUpdate.length; offset += chunkSize) {
const slice = toUpdate.slice(offset, offset + chunkSize);
await client.query(
@ -784,6 +888,9 @@ async function persistWithinTransaction(
source: StageASource;
}> = [];
for (const item of preparedInstruments) {
if (item.isSynthetic) {
continue;
}
const instrumentId = instrumentIdByIsin.get(item.primaryIsin);
if (instrumentId === undefined) {
continue;

View file

@ -21,6 +21,7 @@ import {
EXCHANGE_SOURCES,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS,
type ExchangeClassificationResult,
type ExchangeSource,
type SourceExchangeRecord,
@ -51,6 +52,8 @@ import {
import {
createExchangeSourceLookup,
createReadOnlyMongoSourceSymbolReader,
DEFAULT_SOURCE_COUNTRIES,
normalizeCountryIso2,
readSecurityMasterSources,
type ExchangeSourceLookup,
type ReadOnlyMongoCollectionClient,
@ -72,7 +75,9 @@ export const RUN_SECURITY_MASTER_USAGE = [
' --out-dir <dir> Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.',
' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).',
' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).',
` --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`,
' --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..64, default: 25).',
' --reviewed-us-ca-exchanges Optional. Scope Pass 1 exchange classification to configured US/CA countries with reviewed US/CA venue rules.',
' --allow-identifierless-eod Optional. Admit US/CA EOD primary-venue listings lacking ISIN/CUSIP (stored with primary_isin = NULL).',
' --help Show this help message and exit.',
].join('\n');
@ -85,6 +90,8 @@ export type ParsedRunSecurityMasterArgs =
readonly persist: boolean;
readonly skipPriceCrossCheck: boolean;
readonly sampleDateCount: number;
readonly useReviewedUsCaExchanges?: boolean;
readonly allowIdentifierlessEod?: boolean;
};
export interface RunSecurityMasterPass4Options {
@ -134,6 +141,8 @@ export interface RunSecurityMasterOptions {
readonly batchSize?: number;
readonly barSpans?: Omit<ComputeBarSpansOptions, 'sourceIdsBySource'>;
readonly pass4?: RunSecurityMasterPass4Options;
readonly useReviewedUsCaExchanges?: boolean;
readonly allowIdentifierlessEod?: boolean;
}
export interface RunSecurityMasterOutput {
@ -351,6 +360,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
let persist = false;
let skipPriceCrossCheck = false;
let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT;
let useReviewedUsCaExchanges = false;
let allowIdentifierlessEod = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
@ -366,6 +377,14 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
skipPriceCrossCheck = true;
continue;
}
if (arg === '--reviewed-us-ca-exchanges') {
useReviewedUsCaExchanges = true;
continue;
}
if (arg === '--allow-identifierless-eod') {
allowIdentifierlessEod = true;
continue;
}
if (arg === '--sample-dates') {
const value = argv[i + 1];
if (!value || value.trim().length === 0 || value.startsWith('--')) {
@ -443,6 +462,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
persist,
skipPriceCrossCheck,
sampleDateCount,
...(useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}),
...(allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}),
};
}
@ -627,8 +648,31 @@ export async function runSecurityMaster(
}
exchangeCountsByCollection[source] = count;
}
exchanges = classifySourceExchanges(normalizedRecords, {
let recordsToClassify = normalizedRecords;
if (options.useReviewedUsCaExchanges === true && options.countries !== null) {
const allowedCountries = new Set<string>(
(options.countries ?? DEFAULT_SOURCE_COUNTRIES)
.map(c => normalizeCountryIso2(c) ?? c.trim().toUpperCase())
.filter(c => c.length > 0)
);
recordsToClassify = normalizedRecords.filter(rec => {
const codeUpper = rec.code.trim().toUpperCase();
if (rec.source === 'eod' && codeUpper === 'FOREX') {
return true;
}
const iso = normalizeCountryIso2(rec.country);
return (
rec.country === null ||
rec.country === undefined ||
(iso !== null && allowedCountries.has(iso))
);
});
}
exchanges = classifySourceExchanges(recordsToClassify, {
knownExchanges: ISO_EXCHANGE_SEEDS,
...(options.useReviewedUsCaExchanges === true
? { reviewedRows: REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS }
: {}),
});
}
@ -673,6 +717,34 @@ export async function runSecurityMaster(
}
// Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs.
const composeOptions =
options.allowIdentifierlessEod === true
? {
asOfDate: options.asOfDate,
stageA: { allowIdentifierlessEod: true },
}
: {
asOfDate: options.asOfDate,
};
// Preserve verified pre-2024 FB -> META ticker history (2012-05-18 .. 2022-06-08) when
// META.US is present and eodSymbolChange only covers recent years, so historical FB bars
// map to Meta while the 2025 ProShares FB ETF (FB.US) retains a distinct listing_id.
if (
options.allowIdentifierlessEod === true &&
sources.stageBInput.eodListings.some(e => e.sourceId === 'META.US') &&
!sources.stageBInput.symbolChanges.some(
sc => sc.eodSourceId === 'META.US' && sc.oldTicker === 'FB'
)
) {
sources.stageBInput.symbolChanges.push({
eodSourceId: 'META.US',
oldTicker: 'FB',
effectiveDate: '2022-06-09',
validFrom: '2012-05-18',
});
}
const composeFn = deps.composeFn ?? composeSecurityMasterRun;
let composed: ComposeSecurityMasterRunResult;
try {
@ -682,9 +754,7 @@ export async function runSecurityMaster(
barSpans,
exchanges,
},
{
asOfDate: options.asOfDate,
}
composeOptions
);
} catch (error) {
throw wrapStepError('compose', error);
@ -758,9 +828,7 @@ export async function runSecurityMaster(
sampleCloses: sampleCloses.closes,
fxRates: sampleCloses.fxRates,
},
{
asOfDate: options.asOfDate,
}
composeOptions
);
} catch (error) {
throw wrapStepError('compose', error);
@ -1025,6 +1093,8 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
asOfDate: parsed.asOfDate,
outDir: parsed.outDir,
persist: parsed.persist,
...(parsed.useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}),
...(parsed.allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}),
pass4: {
enabled: !parsed.skipPriceCrossCheck,
sampleDateCount: parsed.sampleDateCount,

View file

@ -22,10 +22,12 @@ import {
isStageASource,
matchInstrumentsStageA,
STAGE_A_SOURCES,
SYNTHETIC_EOD_ISIN_PREFIX,
type MatchInstrumentsStageAOptions,
type StageAMatchResult,
type StageASourceRecord,
} from './instrument-stage-a';
import { classifyEodSecurityType } from './security-type';
import {
matchListingsStageB,
MAX_TICKER_ROOT_LENGTH,
@ -1208,6 +1210,29 @@ export function composeSecurityMasterRun(
sortedSecurityTypeByIsin.set(entry[0], entry[1]);
}
}
if (
options.stageA?.allowIdentifierlessEod === true &&
Array.isArray(input.sources.securityTypeRecords)
) {
const syntheticEntries: Array<[string, SecurityType]> = [];
for (const rec of input.sources.securityTypeRecords) {
if (rec !== undefined && rec.isin === null && typeof rec.sourceId === 'string') {
const mapped = classifyEodSecurityType(rec.rawType);
if (mapped !== null) {
syntheticEntries.push([
`${SYNTHETIC_EOD_ISIN_PREFIX}${rec.sourceId.trim().toUpperCase()}`,
mapped,
]);
}
}
}
syntheticEntries.sort((a, b) => compareAscii(a[0], b[0]));
for (const [k, v] of syntheticEntries) {
if (!sortedSecurityTypeByIsin.has(k)) {
sortedSecurityTypeByIsin.set(k, v);
}
}
}
const persistInput: PersistSecurityMasterInput = {
stageA,
@ -1222,7 +1247,7 @@ export function composeSecurityMasterRun(
let stageAUnresolved = 0;
for (const source of STAGE_A_SOURCES) {
const s = stageA.stats.bySource[source];
stageAResolved += s.tier1Isin + s.tier2Cusip;
stageAResolved += s.tier1Isin + s.tier2Cusip + (s.tier3Synthetic ?? 0);
stageAUnresolved += s.unresolved + s.conflict;
}
const stageAStepStats: StageAComposeStepStats = {

View file

@ -442,7 +442,9 @@ export const CEO_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.fr
export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
oldSymbol: 1,
old_symbol: 1,
newSymbol: 1,
new_symbol: 1,
exchange: 1,
eodExchange: 1,
eodSearchCode: 1,
@ -1565,8 +1567,8 @@ export function adaptEodSymbolChangeDoc(
return { ok: false, skipReason: 'invalidFieldType' };
}
const oldSymbolField = readOptionalString(doc, 'oldSymbol');
const newSymbolField = readOptionalString(doc, 'newSymbol');
const oldSymbolField = readFirstOptionalString(doc, ['oldSymbol', 'old_symbol']);
const newSymbolField = readFirstOptionalString(doc, ['newSymbol', 'new_symbol']);
const exchangeField = readOptionalString(doc, 'exchange');
const eodExchangeField = readOptionalString(doc, 'eodExchange');
const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode');
@ -1846,6 +1848,26 @@ export async function readQmSymbols(
return { tickerSources, stats };
}
function expectedMicFromCeoSymbolSuffix(rawSymbol: unknown): string | null {
if (typeof rawSymbol !== 'string') {
return null;
}
const upper = rawSymbol.trim().toUpperCase();
if (upper.endsWith('.TO')) {
return 'XTSE';
}
if (upper.endsWith('.V')) {
return 'XTSX';
}
if (upper.endsWith('.CN')) {
return 'XCNQ';
}
if (upper.endsWith('.NEO') || upper.endsWith('.NE')) {
return 'NEOE';
}
return null;
}
/** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */
export async function readCeoSymbols(
reader: ReadOnlySourceSymbolReader,
@ -1861,6 +1883,11 @@ export async function readCeoSymbols(
};
const tickerSources: StageBTickerSourceInput[] = [];
const rawEntries: Array<{
readonly tickerSource: StageBTickerSourceInput;
readonly rawSymbolKey: string | null;
readonly matchesSuffixMic: boolean;
}> = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo);
const findOptions: SourceSymbolFindOptions = {
@ -1880,11 +1907,59 @@ export async function readCeoSymbols(
stats.skips[adapted.skipReason] += 1;
return;
}
tickerSources.push(adapted.tickerSource);
stats.emitted += 1;
const rawSymbol =
isPlainRecord(doc) && typeof doc.symbol === 'string'
? doc.symbol.trim().toUpperCase()
: null;
const expectedMic = expectedMicFromCeoSymbolSuffix(rawSymbol);
rawEntries.push({
tickerSource: adapted.tickerSource,
rawSymbolKey: rawSymbol !== null && rawSymbol.length > 0 ? rawSymbol : null,
matchesSuffixMic: expectedMic !== null && adapted.tickerSource.mic === expectedMic,
});
}
);
// Deduplicate crawl artifacts where the exact same (ceoId, symbol) was ingested under
// multiple Canadian exchange lists (e.g. ACB.TO under both TSX and CNQ). Prefer the row
// whose mapped MIC matches the symbol's own Canadian venue suffix (.TO/.V/.CN/.NEO).
// Distinct symbols sharing a ceoId are preserved so Stage B still flags true collisions.
const groupedByIdAndSymbol = new Map<string, typeof rawEntries>();
for (const entry of rawEntries) {
if (entry.rawSymbolKey === null) {
tickerSources.push(entry.tickerSource);
stats.emitted += 1;
continue;
}
const key = `${entry.tickerSource.sourceId}\u0000${entry.rawSymbolKey}`;
const existing = groupedByIdAndSymbol.get(key);
if (existing !== undefined) {
existing.push(entry);
} else {
groupedByIdAndSymbol.set(key, [entry]);
}
}
for (const entries of groupedByIdAndSymbol.values()) {
const first = entries[0];
if (first === undefined) {
continue;
}
if (entries.length === 1) {
tickerSources.push(first.tickerSource);
stats.emitted += 1;
continue;
}
const suffixMatched = entries.filter(e => e.matchesSuffixMic);
const chosen =
suffixMatched.length === 1 && suffixMatched[0] !== undefined
? suffixMatched[0]
: ([...entries].sort((a, b) => compareTickerSources(a.tickerSource, b.tickerSource))[0] ??
first);
tickerSources.push(chosen.tickerSource);
stats.emitted += 1;
}
tickerSources.sort(compareTickerSources);
return { tickerSources, stats };