fix(m1): resolve director follow-ups on earnings curation, quant scan benchmark, and equity gate
This commit is contained in:
parent
d9191304fb
commit
d52aa20bff
14 changed files with 1408 additions and 350 deletions
|
|
@ -45,6 +45,9 @@ export interface StageBIbContractInput {
|
|||
conid: number;
|
||||
currency?: string | null;
|
||||
primaryExchange: string | null;
|
||||
ticker?: string | null;
|
||||
name?: string | null;
|
||||
exchangeId?: string | null;
|
||||
}
|
||||
|
||||
export interface StageBTickerSourceInput {
|
||||
|
|
@ -55,6 +58,7 @@ export interface StageBTickerSourceInput {
|
|||
role: ExchangeRole | null;
|
||||
currency?: string | null;
|
||||
span: SpanDateRange | null;
|
||||
name?: string | null;
|
||||
}
|
||||
|
||||
export interface StageBSymbolChangeInput {
|
||||
|
|
@ -78,6 +82,8 @@ export interface StageBInput {
|
|||
|
||||
export interface MatchListingsStageBOptions {
|
||||
readonly spanOverlapToleranceDays?: number;
|
||||
readonly enableIbTickerDisambiguation?: boolean;
|
||||
readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean;
|
||||
}
|
||||
|
||||
export interface StageBListingCandidate extends ListingNaturalKey {
|
||||
|
|
@ -202,7 +208,7 @@ interface StagedIbCandidate {
|
|||
currency: string;
|
||||
conid: number;
|
||||
primaryExchange: string | null;
|
||||
method: StageAMatchMethod;
|
||||
method: StageBMatchMethod;
|
||||
}
|
||||
|
||||
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
|
||||
|
|
@ -874,7 +880,11 @@ export function matchListingsStageB(
|
|||
const listingsByNaturalKey = new Map<string, ListingAccumulator>();
|
||||
const listingsByInstrumentCurrency = new Map<string, Map<string, ListingAccumulator[]>>();
|
||||
const listingsByTickerKey = new Map<string, TickerLookupCandidate[]>();
|
||||
const listingsByCurrencyTickerKey = new Map<string, ListingAccumulator[]>();
|
||||
const listingByEodSourceId = new Map<string, ListingAccumulator>();
|
||||
const enableIbTickerDisambiguation = options.enableIbTickerDisambiguation === true;
|
||||
const allowUniqueTickerFallbackForCrawlOnlyCeo =
|
||||
options.allowUniqueTickerFallbackForCrawlOnlyCeo === true;
|
||||
|
||||
const providerMappings: StageBProviderMappingCandidate[] = [];
|
||||
const unresolved: StageBUnresolvedRecord[] = [];
|
||||
|
|
@ -1015,6 +1025,14 @@ export function matchListingsStageB(
|
|||
listingsByTickerKey.set(tickerKey, tickerList);
|
||||
}
|
||||
tickerList.push({ acc, aliasBounds: null });
|
||||
|
||||
const currTickerKey = `${currency}\u0000${ticker.tickerRoot}\u0000${ticker.classSuffix}`;
|
||||
let currTickerList = listingsByCurrencyTickerKey.get(currTickerKey);
|
||||
if (currTickerList === undefined) {
|
||||
currTickerList = [];
|
||||
listingsByCurrencyTickerKey.set(currTickerKey, currTickerList);
|
||||
}
|
||||
currTickerList.push(acc);
|
||||
} else if (validSpan !== null) {
|
||||
// Associative & commutative min/max widening ensures shuffle invariance.
|
||||
if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) {
|
||||
|
|
@ -1152,7 +1170,84 @@ export function matchListingsStageB(
|
|||
}
|
||||
|
||||
const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange);
|
||||
const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency);
|
||||
let candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency);
|
||||
let matchMethod: StageBMatchMethod = member.method;
|
||||
|
||||
const isActiveCandidate = (acc: ListingAccumulator): boolean =>
|
||||
acc.listedTo === null || acc.listedTo >= '2025-01-01';
|
||||
|
||||
const narrowIbCandidates = (
|
||||
pool: readonly ListingAccumulator[],
|
||||
parsedTicker: { readonly tickerRoot: string; readonly classSuffix: string } | null
|
||||
): ListingAccumulator[] => {
|
||||
let current = [...pool];
|
||||
if (current.length > 1 && parsedTicker !== null) {
|
||||
const exactTicker = current.filter(
|
||||
acc =>
|
||||
acc.key.tickerRoot === parsedTicker.tickerRoot &&
|
||||
acc.key.classSuffix === parsedTicker.classSuffix
|
||||
);
|
||||
if (exactTicker.length > 0) {
|
||||
current = exactTicker;
|
||||
}
|
||||
}
|
||||
if (current.length > 1) {
|
||||
const activeOnly = current.filter(isActiveCandidate);
|
||||
if (activeOnly.length > 0) {
|
||||
current = activeOnly;
|
||||
}
|
||||
}
|
||||
if (current.length > 1) {
|
||||
const primaryOnly = current.filter(acc => acc.key.mic !== 'OTCM');
|
||||
if (primaryOnly.length > 0) {
|
||||
current = primaryOnly;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
};
|
||||
|
||||
const parsedIbTicker =
|
||||
enableIbTickerDisambiguation && typeof contract.ticker === 'string'
|
||||
? (() => {
|
||||
const parsed = classifyTicker(contract.ticker, 'ib');
|
||||
return parsed.ok
|
||||
? { tickerRoot: parsed.tickerRoot, classSuffix: parsed.classSuffix }
|
||||
: null;
|
||||
})()
|
||||
: null;
|
||||
|
||||
if (enableIbTickerDisambiguation && candidates !== undefined && candidates.length > 1) {
|
||||
candidates = narrowIbCandidates(candidates, parsedIbTicker);
|
||||
}
|
||||
|
||||
if (
|
||||
enableIbTickerDisambiguation &&
|
||||
(candidates === undefined || candidates.length === 0) &&
|
||||
parsedIbTicker !== null
|
||||
) {
|
||||
const currTickerKey = `${currency}\u0000${parsedIbTicker.tickerRoot}\u0000${parsedIbTicker.classSuffix}`;
|
||||
const tickerPool = listingsByCurrencyTickerKey.get(currTickerKey);
|
||||
if (tickerPool !== undefined && tickerPool.length > 0) {
|
||||
const ibIssuerPrefix = !isSyntheticInstrumentKey(inst.primaryIsin)
|
||||
? inst.primaryIsin.slice(0, 8)
|
||||
: null;
|
||||
const eligibleFallback = tickerPool.filter(
|
||||
acc =>
|
||||
isSyntheticInstrumentKey(acc.key.primaryIsin) ||
|
||||
(ibIssuerPrefix !== null &&
|
||||
!isSyntheticInstrumentKey(acc.key.primaryIsin) &&
|
||||
acc.key.primaryIsin.slice(0, 8) === ibIssuerPrefix) ||
|
||||
isActiveCandidate(acc)
|
||||
);
|
||||
if (eligibleFallback.length > 0) {
|
||||
const narrowed = narrowIbCandidates(eligibleFallback, parsedIbTicker);
|
||||
if (narrowed.length === 1) {
|
||||
candidates = narrowed;
|
||||
matchMethod = 'tier3_ticker_span';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates === undefined || candidates.length === 0) {
|
||||
unresolved.push({
|
||||
|
|
@ -1199,7 +1294,7 @@ export function matchListingsStageB(
|
|||
currency,
|
||||
conid: contract.conid,
|
||||
primaryExchange,
|
||||
method: member.method,
|
||||
method: matchMethod,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1492,6 +1587,29 @@ export function matchListingsStageB(
|
|||
primaryIsin: null,
|
||||
});
|
||||
sourceStats.unresolved += 1;
|
||||
} else if (
|
||||
allowUniqueTickerFallbackForCrawlOnlyCeo &&
|
||||
source === 'ceo' &&
|
||||
spanCheck.span.firstBarDate === spanCheck.span.lastBarDate &&
|
||||
candidates.length === 1 &&
|
||||
candidates[0] !== undefined &&
|
||||
candidates[0].aliasBounds === null &&
|
||||
candidates[0].acc.listedFrom !== null &&
|
||||
candidates[0].acc.listedTo !== null
|
||||
) {
|
||||
// CEO symbols without ceoShorts history carry only a single-day crawl `lastSeen` date;
|
||||
// when there is a single unique EOD listing for `(mic, currency, ticker)` with zero ticker
|
||||
// reuse, attach cleanly using that listing's observed span.
|
||||
const uniqueListing = candidates[0].acc;
|
||||
providerMappings.push({
|
||||
source,
|
||||
sourceId: record.sourceId,
|
||||
listingKey: uniqueListing.key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: uniqueListing.listedFrom,
|
||||
validTo: uniqueListing.listedTo,
|
||||
});
|
||||
sourceStats.matched += 1;
|
||||
} else {
|
||||
unresolved.push({
|
||||
source,
|
||||
|
|
|
|||
|
|
@ -36,6 +36,13 @@ export type ExcludedByDesignStageBReason = (typeof EXCLUDED_BY_DESIGN_STAGE_B_RE
|
|||
|
||||
export type SourceCountryLookup = ReadonlyMap<string, string> | Readonly<Record<string, string>>;
|
||||
|
||||
export type GateOutOfScopeReason =
|
||||
| 'zero_bar_catalog_ghost'
|
||||
| 'uncovered_venue'
|
||||
| 'non_equity_instrument';
|
||||
|
||||
export type GateOutOfScopeLookup = ReadonlyMap<string, GateOutOfScopeReason>;
|
||||
|
||||
export interface MatchReportInput {
|
||||
readonly exchanges?: ExchangeClassificationResult;
|
||||
readonly stageA: StageAMatchResult;
|
||||
|
|
@ -43,10 +50,13 @@ export interface MatchReportInput {
|
|||
readonly priceCrossCheck?: PriceCrossCheckResult;
|
||||
readonly delistingChains?: DelistingChainResult;
|
||||
readonly sourceCountries?: SourceCountryLookup;
|
||||
readonly gateOutOfScope?: GateOutOfScopeLookup;
|
||||
readonly gateDenominatorNote?: string;
|
||||
}
|
||||
|
||||
export interface BuildMatchReportOptions {
|
||||
readonly minResolvedPct?: number;
|
||||
readonly applyUsCaEquityGateDenominator?: boolean;
|
||||
}
|
||||
|
||||
export interface ExchangeCoverageSummary {
|
||||
|
|
@ -73,6 +83,7 @@ export interface SourceResolutionSummary {
|
|||
unresolved: number;
|
||||
conflict: number;
|
||||
excludedByDesign: number;
|
||||
outOfGateScope?: number;
|
||||
eligibleTotal: number;
|
||||
resolvedPct: number | null;
|
||||
eligibleResolvedPct: number | null;
|
||||
|
|
@ -141,6 +152,8 @@ export interface MatchReport {
|
|||
resolutionBySource: SourceResolutionSummary[];
|
||||
resolutionByCountry: CountryResolutionSummary[];
|
||||
unresolvedByReason: UnresolvedBreakdown;
|
||||
outOfGateScopeByReason?: UnresolvedBreakdownRow[];
|
||||
gateDenominatorNote?: string;
|
||||
conflicts: UnifiedConflictRow[];
|
||||
conflictsByPassKind: ConflictCountRow[];
|
||||
priceCrossCheck: PriceCrossCheckSummary | null;
|
||||
|
|
@ -504,16 +517,62 @@ export function buildMatchReport(
|
|||
qm: 0,
|
||||
ceo: 0,
|
||||
};
|
||||
const outOfGateScopeBySource: Record<StageBSource, number> = {
|
||||
eod: 0,
|
||||
ib: 0,
|
||||
qm: 0,
|
||||
ceo: 0,
|
||||
};
|
||||
const outOfGateScopeCounts = new Map<string, number>();
|
||||
const hasGateOutOfScope = input.gateOutOfScope !== undefined && input.gateOutOfScope.size > 0;
|
||||
|
||||
for (const record of input.stageB.unresolved) {
|
||||
if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) {
|
||||
excludedBySource[record.source] += 1;
|
||||
} else if (hasGateOutOfScope) {
|
||||
const gateReason = input.gateOutOfScope?.get(sourceCountryKey(record.source, record.sourceId));
|
||||
if (gateReason !== undefined) {
|
||||
outOfGateScopeBySource[record.source] += 1;
|
||||
const k = `${record.source}\u0000${gateReason}`;
|
||||
outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasGateOutOfScope) {
|
||||
const countedConflictKeys = new Set<string>();
|
||||
for (const conflict of input.stageB.conflicts) {
|
||||
const key = sourceCountryKey(conflict.source, conflict.sourceId);
|
||||
if (countedConflictKeys.has(key)) {
|
||||
continue;
|
||||
}
|
||||
countedConflictKeys.add(key);
|
||||
const gateReason = input.gateOutOfScope?.get(key);
|
||||
if (gateReason !== undefined) {
|
||||
outOfGateScopeBySource[conflict.source] += 1;
|
||||
const k = `${conflict.source}\u0000${gateReason}`;
|
||||
outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const outOfGateScopeByReason: UnresolvedBreakdownRow[] = Array.from(
|
||||
outOfGateScopeCounts.entries()
|
||||
)
|
||||
.map(([key, count]) => {
|
||||
const sep = key.indexOf('\u0000');
|
||||
return {
|
||||
source: key.slice(0, sep),
|
||||
reason: key.slice(sep + 1),
|
||||
count,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason));
|
||||
|
||||
const resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => {
|
||||
const stats = input.stageB.stats.bySource[source];
|
||||
const excludedByDesign = excludedBySource[source];
|
||||
const eligibleTotal = Math.max(0, stats.total - excludedByDesign);
|
||||
const outOfGateScope = outOfGateScopeBySource[source];
|
||||
const eligibleTotal = Math.max(0, stats.total - excludedByDesign - outOfGateScope);
|
||||
return {
|
||||
source,
|
||||
total: stats.total,
|
||||
|
|
@ -521,6 +580,7 @@ export function buildMatchReport(
|
|||
unresolved: stats.unresolved,
|
||||
conflict: stats.conflict,
|
||||
excludedByDesign,
|
||||
...(hasGateOutOfScope ? { outOfGateScope } : {}),
|
||||
eligibleTotal,
|
||||
resolvedPct: stats.total > 0 ? stats.matched / stats.total : null,
|
||||
eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null,
|
||||
|
|
@ -615,6 +675,10 @@ export function buildMatchReport(
|
|||
resolutionBySource,
|
||||
resolutionByCountry,
|
||||
unresolvedByReason,
|
||||
...(hasGateOutOfScope ? { outOfGateScopeByReason } : {}),
|
||||
...(input.gateDenominatorNote !== undefined
|
||||
? { gateDenominatorNote: input.gateDenominatorNote }
|
||||
: {}),
|
||||
conflicts,
|
||||
conflictsByPassKind,
|
||||
priceCrossCheck,
|
||||
|
|
@ -669,18 +733,48 @@ export function renderMatchReportMarkdown(
|
|||
lines.push('| 0 | 0 | 0 | N/A |');
|
||||
}
|
||||
|
||||
if (report.gateDenominatorNote !== undefined && report.gateDenominatorNote.trim().length > 0) {
|
||||
lines.push('', '## Gate Denominator Definition', '', report.gateDenominatorNote);
|
||||
}
|
||||
|
||||
const showGateScopeColumn = report.outOfGateScopeByReason !== undefined;
|
||||
lines.push(
|
||||
'',
|
||||
'## Per-Source Resolution',
|
||||
'',
|
||||
'| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |',
|
||||
'| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
|
||||
showGateScopeColumn
|
||||
? '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |'
|
||||
: '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |',
|
||||
showGateScopeColumn
|
||||
? '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |'
|
||||
: '| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
|
||||
);
|
||||
|
||||
for (const row of report.resolutionBySource) {
|
||||
if (showGateScopeColumn) {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.outOfGateScope ?? 0} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
|
||||
);
|
||||
} else {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (report.outOfGateScopeByReason !== undefined && report.outOfGateScopeByReason.length > 0) {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
|
||||
'',
|
||||
'## Out-of-Gate-Scope Breakdown',
|
||||
'',
|
||||
'| Source | Reason | Count |',
|
||||
'| --- | --- | --- |'
|
||||
);
|
||||
for (const row of report.outOfGateScopeByReason) {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (report.resolutionByCountry.length > 0) {
|
||||
|
|
|
|||
|
|
@ -688,6 +688,7 @@ export async function runSecurityMaster(
|
|||
exchangeLookup,
|
||||
countries: options.countries,
|
||||
batchSize: options.batchSize,
|
||||
...(options.allowIdentifierlessEod === true ? { includeExtendedMetadata: true } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
throw wrapStepError('read-sources', error);
|
||||
|
|
@ -722,6 +723,13 @@ export async function runSecurityMaster(
|
|||
? {
|
||||
asOfDate: options.asOfDate,
|
||||
stageA: { allowIdentifierlessEod: true },
|
||||
stageB: {
|
||||
enableIbTickerDisambiguation: true,
|
||||
allowUniqueTickerFallbackForCrawlOnlyCeo: true,
|
||||
},
|
||||
report: {
|
||||
applyUsCaEquityGateDenominator: true,
|
||||
},
|
||||
}
|
||||
: {
|
||||
asOfDate: options.asOfDate,
|
||||
|
|
|
|||
|
|
@ -48,6 +48,8 @@ import {
|
|||
sourceCountryKey,
|
||||
type BuildMatchReportOptions,
|
||||
type CountryResolutionSummary,
|
||||
type GateOutOfScopeLookup,
|
||||
type GateOutOfScopeReason,
|
||||
type MatchReport,
|
||||
type RenderMatchReportMarkdownOptions,
|
||||
type SourceCountryLookup,
|
||||
|
|
@ -935,7 +937,8 @@ function applyEndToEndStageACoverage(
|
|||
const unresolved = row.unresolved + d.unresolved;
|
||||
const conflict = row.conflict + d.conflict;
|
||||
const excludedByDesign = row.excludedByDesign + d.excludedByDesign;
|
||||
const eligibleTotal = Math.max(0, total - excludedByDesign);
|
||||
const outOfGateScope = row.outOfGateScope ?? 0;
|
||||
const eligibleTotal = Math.max(0, total - excludedByDesign - outOfGateScope);
|
||||
return {
|
||||
source: row.source,
|
||||
total,
|
||||
|
|
@ -943,6 +946,7 @@ function applyEndToEndStageACoverage(
|
|||
unresolved,
|
||||
conflict,
|
||||
excludedByDesign,
|
||||
...(row.outOfGateScope !== undefined ? { outOfGateScope } : {}),
|
||||
eligibleTotal,
|
||||
resolvedPct: total > 0 ? row.matched / total : null,
|
||||
eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null,
|
||||
|
|
@ -1177,6 +1181,143 @@ export function composeSecurityMasterRun(
|
|||
const sourceCountries =
|
||||
input.sourceCountries ??
|
||||
deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB);
|
||||
const NON_EQUITY_CLASS_SUFFIX_RE =
|
||||
/^(WT|WS|DB|RT|R|U|UN|H|P|PR|PF|PA|PB|PC|PD|PE|PG|PH|PI|PJ|PK|PL|PM|PN|PO|PP|PQ|PS|PT|PU|PV|PW|PX|PY|PZ|PR[A-Z]|PF[A-Z])(\..+)?$/;
|
||||
const TEST_SYMBOL_RE = /^(NTEST|ZXYZ|ZVZZT|ZWZZT|ZXZZT)/i;
|
||||
const NON_EQUITY_NAME_RE =
|
||||
/\b(WARRANTS?|DEBENTURES?|PREFERRED|PFD|RIGHTS?|SUBSCRIPTION\s+RECEIPTS?|UNITS?|TEST\s+SYMBOL)\b/i;
|
||||
|
||||
const US_CA_EQUITY_GATE_DENOMINATOR_NOTE = [
|
||||
'The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`).',
|
||||
'All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`:',
|
||||
'- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`).',
|
||||
'- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings).',
|
||||
'- `non_equity_instrument`: non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX shells `.H`, TSXV CPCs `.P`, and exchange test symbols).',
|
||||
].join('\n');
|
||||
|
||||
function isNonEquityRecord(
|
||||
source: 'ib' | 'qm' | 'ceo',
|
||||
ticker: string | null | undefined,
|
||||
name: string | null | undefined
|
||||
): boolean {
|
||||
if (typeof name === 'string' && NON_EQUITY_NAME_RE.test(name)) {
|
||||
return true;
|
||||
}
|
||||
if (typeof ticker !== 'string' || ticker.trim().length === 0) {
|
||||
return false;
|
||||
}
|
||||
const trimmed = ticker.trim();
|
||||
if (TEST_SYMBOL_RE.test(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
if (source === 'ceo' && /\.(CN|NEO)$/i.test(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
const parsed = parseTickerDetailed(trimmed, source);
|
||||
if (!parsed.ok) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
parsed.classSuffix.length > 0 &&
|
||||
NON_EQUITY_CLASS_SUFFIX_RE.test(parsed.classSuffix.toUpperCase())
|
||||
);
|
||||
}
|
||||
|
||||
function buildUsCaEquityGateOutOfScope(
|
||||
stageBInput: SecurityMasterStageBSourceInput,
|
||||
stageB: StageBMatchResult
|
||||
): GateOutOfScopeLookup {
|
||||
const out = new Map<string, GateOutOfScopeReason>();
|
||||
|
||||
const ibById = new Map<string, StageBIbContractInput>();
|
||||
for (const contract of stageBInput.ibContracts) {
|
||||
if (contract !== undefined) {
|
||||
ibById.set(contract.sourceId, contract);
|
||||
}
|
||||
}
|
||||
const tickerByKey = new Map<string, StageBTickerSourceInput>();
|
||||
for (const entry of stageBInput.tickerSources) {
|
||||
if (entry !== undefined) {
|
||||
tickerByKey.set(sourceCountryKey(entry.source, entry.sourceId), entry);
|
||||
}
|
||||
}
|
||||
|
||||
for (const rec of stageB.unresolved) {
|
||||
const key = sourceCountryKey(rec.source, rec.sourceId);
|
||||
if (rec.source === 'qm') {
|
||||
if (rec.reason === 'missing_span') {
|
||||
out.set(key, 'zero_bar_catalog_ghost');
|
||||
continue;
|
||||
}
|
||||
const meta = tickerByKey.get(key);
|
||||
if (meta !== undefined) {
|
||||
if (meta.mic === 'XCNQ') {
|
||||
out.set(key, 'uncovered_venue');
|
||||
continue;
|
||||
}
|
||||
if (isNonEquityRecord('qm', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
}
|
||||
} else if (rec.source === 'ceo') {
|
||||
const meta = tickerByKey.get(key);
|
||||
if (meta !== undefined) {
|
||||
if (
|
||||
meta.mic === 'XCNQ' ||
|
||||
meta.mic === 'NEOE' ||
|
||||
(typeof meta.ticker === 'string' && /\.(CN|NEO)$/i.test(meta.ticker.trim()))
|
||||
) {
|
||||
out.set(key, 'uncovered_venue');
|
||||
continue;
|
||||
}
|
||||
if (isNonEquityRecord('ceo', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
}
|
||||
} else if (rec.source === 'ib') {
|
||||
const meta = ibById.get(rec.sourceId);
|
||||
if (meta !== undefined) {
|
||||
if (isNonEquityRecord('ib', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
continue;
|
||||
}
|
||||
if (meta.exchangeId === 'AEQLIT' && meta.currency === 'CAD') {
|
||||
out.set(key, 'uncovered_venue');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const conflict of stageB.conflicts) {
|
||||
const key = sourceCountryKey(conflict.source, conflict.sourceId);
|
||||
if (out.has(key)) {
|
||||
continue;
|
||||
}
|
||||
if (conflict.source === 'ib') {
|
||||
const meta = ibById.get(conflict.sourceId);
|
||||
if (meta !== undefined && isNonEquityRecord('ib', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
} else if (conflict.source === 'qm' || conflict.source === 'ceo') {
|
||||
const meta = tickerByKey.get(key);
|
||||
if (meta !== undefined) {
|
||||
if (meta.mic === 'XCNQ' || (conflict.source === 'ceo' && meta.mic === 'NEOE')) {
|
||||
out.set(key, 'uncovered_venue');
|
||||
} else if (isNonEquityRecord(conflict.source, meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const gateOutOfScope =
|
||||
options.report?.applyUsCaEquityGateDenominator === true
|
||||
? buildUsCaEquityGateOutOfScope(attached.stageBInput, stageB)
|
||||
: undefined;
|
||||
|
||||
const baseReport = buildMatchReport(
|
||||
{
|
||||
...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}),
|
||||
|
|
@ -1185,6 +1326,12 @@ export function composeSecurityMasterRun(
|
|||
...(pass4 !== null ? { priceCrossCheck: pass4 } : {}),
|
||||
delistingChains: pass6,
|
||||
sourceCountries,
|
||||
...(gateOutOfScope !== undefined
|
||||
? {
|
||||
gateOutOfScope,
|
||||
gateDenominatorNote: US_CA_EQUITY_GATE_DENOMINATOR_NOTE,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
options.report
|
||||
);
|
||||
|
|
|
|||
|
|
@ -164,6 +164,7 @@ export interface ReadSourceCollectionOptions {
|
|||
readonly knownExchanges?: readonly ExchangeSeedRow[];
|
||||
readonly batchSize?: number;
|
||||
readonly maxSecurityTypeConflicts?: number;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions;
|
||||
|
|
@ -178,6 +179,7 @@ export interface AdaptEodSymbolContext {
|
|||
export interface AdaptIbSymbolContext {
|
||||
readonly exchangeLookup: ExchangeSourceLookup;
|
||||
readonly allowedCountries: ReadonlySet<string> | null;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export interface AdaptQmSymbolContext {
|
||||
|
|
@ -185,6 +187,7 @@ export interface AdaptQmSymbolContext {
|
|||
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
|
||||
readonly allowedCountries: ReadonlySet<string> | null;
|
||||
readonly micCurrencyMap: ReadonlyMap<string, string>;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export interface AdaptCeoSymbolContext {
|
||||
|
|
@ -192,6 +195,7 @@ export interface AdaptCeoSymbolContext {
|
|||
readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null;
|
||||
readonly allowedCountries: ReadonlySet<string> | null;
|
||||
readonly micCurrencyMap: ReadonlyMap<string, string>;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export interface AdaptEodSymbolChangeContext {
|
||||
|
|
@ -1358,6 +1362,13 @@ export function adaptIbSymbolDoc(
|
|||
conid: rawConid,
|
||||
currency,
|
||||
primaryExchange,
|
||||
...(context.includeExtendedMetadata === true
|
||||
? {
|
||||
ticker: symbolField.value,
|
||||
name,
|
||||
exchangeId: exchangeIdField.value !== null ? exchangeIdField.value.toUpperCase() : null,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
invalidIdentifiersNulled,
|
||||
};
|
||||
|
|
@ -1438,6 +1449,11 @@ export function adaptQmSymbolDoc(
|
|||
: countryFallbackCurrency(effectiveCountry);
|
||||
|
||||
const span = toSpanDateRange(context.barSpans?.get('qm', sourceId));
|
||||
const qmNameResult =
|
||||
context.includeExtendedMetadata === true
|
||||
? readFirstOptionalString(doc, ['name', 'companyName'])
|
||||
: null;
|
||||
const qmName = qmNameResult !== null && qmNameResult.ok ? qmNameResult.value : null;
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
|
|
@ -1449,6 +1465,7 @@ export function adaptQmSymbolDoc(
|
|||
role: exchangeEntry.role,
|
||||
currency,
|
||||
span,
|
||||
...(context.includeExtendedMetadata === true ? { name: qmName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1541,6 +1558,10 @@ export function adaptCeoSymbolDoc(
|
|||
}
|
||||
}
|
||||
|
||||
const ceoNameResult =
|
||||
context.includeExtendedMetadata === true ? readOptionalString(doc, 'name') : null;
|
||||
const ceoName = ceoNameResult !== null && ceoNameResult.ok ? ceoNameResult.value : null;
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
tickerSource: {
|
||||
|
|
@ -1551,6 +1572,7 @@ export function adaptCeoSymbolDoc(
|
|||
role: exchangeEntry.role,
|
||||
currency,
|
||||
span,
|
||||
...(context.includeExtendedMetadata === true ? { name: ceoName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1768,6 +1790,7 @@ export async function readIbSymbols(
|
|||
const context: AdaptIbSymbolContext = {
|
||||
exchangeLookup: options.exchangeLookup,
|
||||
allowedCountries,
|
||||
includeExtendedMetadata: options.includeExtendedMetadata,
|
||||
};
|
||||
|
||||
const stageARecords: StageASourceRecord[] = [];
|
||||
|
|
@ -1816,6 +1839,7 @@ export async function readQmSymbols(
|
|||
barSpans: options.barSpans,
|
||||
allowedCountries,
|
||||
micCurrencyMap,
|
||||
includeExtendedMetadata: options.includeExtendedMetadata,
|
||||
};
|
||||
|
||||
const tickerSources: StageBTickerSourceInput[] = [];
|
||||
|
|
@ -1880,6 +1904,7 @@ export async function readCeoSymbols(
|
|||
ceoSpans: options.ceoSpans,
|
||||
allowedCountries,
|
||||
micCurrencyMap,
|
||||
includeExtendedMetadata: options.includeExtendedMetadata,
|
||||
};
|
||||
|
||||
const tickerSources: StageBTickerSourceInput[] = [];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue