fix(m1): resolve director follow-ups on earnings curation, quant scan benchmark, and equity gate

This commit is contained in:
Boki 2026-11-30 11:39:27 -05:00
parent d9191304fb
commit d52aa20bff
14 changed files with 1408 additions and 350 deletions

View file

@ -45,6 +45,9 @@ export interface StageBIbContractInput {
conid: number; conid: number;
currency?: string | null; currency?: string | null;
primaryExchange: string | null; primaryExchange: string | null;
ticker?: string | null;
name?: string | null;
exchangeId?: string | null;
} }
export interface StageBTickerSourceInput { export interface StageBTickerSourceInput {
@ -55,6 +58,7 @@ export interface StageBTickerSourceInput {
role: ExchangeRole | null; role: ExchangeRole | null;
currency?: string | null; currency?: string | null;
span: SpanDateRange | null; span: SpanDateRange | null;
name?: string | null;
} }
export interface StageBSymbolChangeInput { export interface StageBSymbolChangeInput {
@ -78,6 +82,8 @@ export interface StageBInput {
export interface MatchListingsStageBOptions { export interface MatchListingsStageBOptions {
readonly spanOverlapToleranceDays?: number; readonly spanOverlapToleranceDays?: number;
readonly enableIbTickerDisambiguation?: boolean;
readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean;
} }
export interface StageBListingCandidate extends ListingNaturalKey { export interface StageBListingCandidate extends ListingNaturalKey {
@ -202,7 +208,7 @@ interface StagedIbCandidate {
currency: string; currency: string;
conid: number; conid: number;
primaryExchange: string | null; primaryExchange: string | null;
method: StageAMatchMethod; method: StageBMatchMethod;
} }
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
@ -874,7 +880,11 @@ export function matchListingsStageB(
const listingsByNaturalKey = new Map<string, ListingAccumulator>(); const listingsByNaturalKey = new Map<string, ListingAccumulator>();
const listingsByInstrumentCurrency = new Map<string, Map<string, ListingAccumulator[]>>(); const listingsByInstrumentCurrency = new Map<string, Map<string, ListingAccumulator[]>>();
const listingsByTickerKey = new Map<string, TickerLookupCandidate[]>(); const listingsByTickerKey = new Map<string, TickerLookupCandidate[]>();
const listingsByCurrencyTickerKey = new Map<string, ListingAccumulator[]>();
const listingByEodSourceId = new Map<string, ListingAccumulator>(); const listingByEodSourceId = new Map<string, ListingAccumulator>();
const enableIbTickerDisambiguation = options.enableIbTickerDisambiguation === true;
const allowUniqueTickerFallbackForCrawlOnlyCeo =
options.allowUniqueTickerFallbackForCrawlOnlyCeo === true;
const providerMappings: StageBProviderMappingCandidate[] = []; const providerMappings: StageBProviderMappingCandidate[] = [];
const unresolved: StageBUnresolvedRecord[] = []; const unresolved: StageBUnresolvedRecord[] = [];
@ -1015,6 +1025,14 @@ export function matchListingsStageB(
listingsByTickerKey.set(tickerKey, tickerList); listingsByTickerKey.set(tickerKey, tickerList);
} }
tickerList.push({ acc, aliasBounds: null }); 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) { } else if (validSpan !== null) {
// Associative & commutative min/max widening ensures shuffle invariance. // Associative & commutative min/max widening ensures shuffle invariance.
if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) { if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) {
@ -1152,7 +1170,84 @@ export function matchListingsStageB(
} }
const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange); 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) { if (candidates === undefined || candidates.length === 0) {
unresolved.push({ unresolved.push({
@ -1199,7 +1294,7 @@ export function matchListingsStageB(
currency, currency,
conid: contract.conid, conid: contract.conid,
primaryExchange, primaryExchange,
method: member.method, method: matchMethod,
}); });
} }
} }
@ -1492,6 +1587,29 @@ export function matchListingsStageB(
primaryIsin: null, primaryIsin: null,
}); });
sourceStats.unresolved += 1; 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 { } else {
unresolved.push({ unresolved.push({
source, source,

View file

@ -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 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 { export interface MatchReportInput {
readonly exchanges?: ExchangeClassificationResult; readonly exchanges?: ExchangeClassificationResult;
readonly stageA: StageAMatchResult; readonly stageA: StageAMatchResult;
@ -43,10 +50,13 @@ export interface MatchReportInput {
readonly priceCrossCheck?: PriceCrossCheckResult; readonly priceCrossCheck?: PriceCrossCheckResult;
readonly delistingChains?: DelistingChainResult; readonly delistingChains?: DelistingChainResult;
readonly sourceCountries?: SourceCountryLookup; readonly sourceCountries?: SourceCountryLookup;
readonly gateOutOfScope?: GateOutOfScopeLookup;
readonly gateDenominatorNote?: string;
} }
export interface BuildMatchReportOptions { export interface BuildMatchReportOptions {
readonly minResolvedPct?: number; readonly minResolvedPct?: number;
readonly applyUsCaEquityGateDenominator?: boolean;
} }
export interface ExchangeCoverageSummary { export interface ExchangeCoverageSummary {
@ -73,6 +83,7 @@ export interface SourceResolutionSummary {
unresolved: number; unresolved: number;
conflict: number; conflict: number;
excludedByDesign: number; excludedByDesign: number;
outOfGateScope?: number;
eligibleTotal: number; eligibleTotal: number;
resolvedPct: number | null; resolvedPct: number | null;
eligibleResolvedPct: number | null; eligibleResolvedPct: number | null;
@ -141,6 +152,8 @@ export interface MatchReport {
resolutionBySource: SourceResolutionSummary[]; resolutionBySource: SourceResolutionSummary[];
resolutionByCountry: CountryResolutionSummary[]; resolutionByCountry: CountryResolutionSummary[];
unresolvedByReason: UnresolvedBreakdown; unresolvedByReason: UnresolvedBreakdown;
outOfGateScopeByReason?: UnresolvedBreakdownRow[];
gateDenominatorNote?: string;
conflicts: UnifiedConflictRow[]; conflicts: UnifiedConflictRow[];
conflictsByPassKind: ConflictCountRow[]; conflictsByPassKind: ConflictCountRow[];
priceCrossCheck: PriceCrossCheckSummary | null; priceCrossCheck: PriceCrossCheckSummary | null;
@ -504,16 +517,62 @@ export function buildMatchReport(
qm: 0, qm: 0,
ceo: 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) { for (const record of input.stageB.unresolved) {
if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) { if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) {
excludedBySource[record.source] += 1; 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 resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => {
const stats = input.stageB.stats.bySource[source]; const stats = input.stageB.stats.bySource[source];
const excludedByDesign = excludedBySource[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 { return {
source, source,
total: stats.total, total: stats.total,
@ -521,6 +580,7 @@ export function buildMatchReport(
unresolved: stats.unresolved, unresolved: stats.unresolved,
conflict: stats.conflict, conflict: stats.conflict,
excludedByDesign, excludedByDesign,
...(hasGateOutOfScope ? { outOfGateScope } : {}),
eligibleTotal, eligibleTotal,
resolvedPct: stats.total > 0 ? stats.matched / stats.total : null, resolvedPct: stats.total > 0 ? stats.matched / stats.total : null,
eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null, eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null,
@ -615,6 +675,10 @@ export function buildMatchReport(
resolutionBySource, resolutionBySource,
resolutionByCountry, resolutionByCountry,
unresolvedByReason, unresolvedByReason,
...(hasGateOutOfScope ? { outOfGateScopeByReason } : {}),
...(input.gateDenominatorNote !== undefined
? { gateDenominatorNote: input.gateDenominatorNote }
: {}),
conflicts, conflicts,
conflictsByPassKind, conflictsByPassKind,
priceCrossCheck, priceCrossCheck,
@ -669,19 +733,49 @@ export function renderMatchReportMarkdown(
lines.push('| 0 | 0 | 0 | N/A |'); 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( lines.push(
'', '',
'## Per-Source Resolution', '## 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) { 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( lines.push(
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` `| ${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(
'',
'## 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) { if (report.resolutionByCountry.length > 0) {
lines.push( lines.push(

View file

@ -688,6 +688,7 @@ export async function runSecurityMaster(
exchangeLookup, exchangeLookup,
countries: options.countries, countries: options.countries,
batchSize: options.batchSize, batchSize: options.batchSize,
...(options.allowIdentifierlessEod === true ? { includeExtendedMetadata: true } : {}),
}); });
} catch (error) { } catch (error) {
throw wrapStepError('read-sources', error); throw wrapStepError('read-sources', error);
@ -722,6 +723,13 @@ export async function runSecurityMaster(
? { ? {
asOfDate: options.asOfDate, asOfDate: options.asOfDate,
stageA: { allowIdentifierlessEod: true }, stageA: { allowIdentifierlessEod: true },
stageB: {
enableIbTickerDisambiguation: true,
allowUniqueTickerFallbackForCrawlOnlyCeo: true,
},
report: {
applyUsCaEquityGateDenominator: true,
},
} }
: { : {
asOfDate: options.asOfDate, asOfDate: options.asOfDate,

View file

@ -48,6 +48,8 @@ import {
sourceCountryKey, sourceCountryKey,
type BuildMatchReportOptions, type BuildMatchReportOptions,
type CountryResolutionSummary, type CountryResolutionSummary,
type GateOutOfScopeLookup,
type GateOutOfScopeReason,
type MatchReport, type MatchReport,
type RenderMatchReportMarkdownOptions, type RenderMatchReportMarkdownOptions,
type SourceCountryLookup, type SourceCountryLookup,
@ -935,7 +937,8 @@ function applyEndToEndStageACoverage(
const unresolved = row.unresolved + d.unresolved; const unresolved = row.unresolved + d.unresolved;
const conflict = row.conflict + d.conflict; const conflict = row.conflict + d.conflict;
const excludedByDesign = row.excludedByDesign + d.excludedByDesign; 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 { return {
source: row.source, source: row.source,
total, total,
@ -943,6 +946,7 @@ function applyEndToEndStageACoverage(
unresolved, unresolved,
conflict, conflict,
excludedByDesign, excludedByDesign,
...(row.outOfGateScope !== undefined ? { outOfGateScope } : {}),
eligibleTotal, eligibleTotal,
resolvedPct: total > 0 ? row.matched / total : null, resolvedPct: total > 0 ? row.matched / total : null,
eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null, eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null,
@ -1177,6 +1181,143 @@ export function composeSecurityMasterRun(
const sourceCountries = const sourceCountries =
input.sourceCountries ?? input.sourceCountries ??
deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB); 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( const baseReport = buildMatchReport(
{ {
...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}), ...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}),
@ -1185,6 +1326,12 @@ export function composeSecurityMasterRun(
...(pass4 !== null ? { priceCrossCheck: pass4 } : {}), ...(pass4 !== null ? { priceCrossCheck: pass4 } : {}),
delistingChains: pass6, delistingChains: pass6,
sourceCountries, sourceCountries,
...(gateOutOfScope !== undefined
? {
gateOutOfScope,
gateDenominatorNote: US_CA_EQUITY_GATE_DENOMINATOR_NOTE,
}
: {}),
}, },
options.report options.report
); );

View file

@ -164,6 +164,7 @@ export interface ReadSourceCollectionOptions {
readonly knownExchanges?: readonly ExchangeSeedRow[]; readonly knownExchanges?: readonly ExchangeSeedRow[];
readonly batchSize?: number; readonly batchSize?: number;
readonly maxSecurityTypeConflicts?: number; readonly maxSecurityTypeConflicts?: number;
readonly includeExtendedMetadata?: boolean;
} }
export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions; export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions;
@ -178,6 +179,7 @@ export interface AdaptEodSymbolContext {
export interface AdaptIbSymbolContext { export interface AdaptIbSymbolContext {
readonly exchangeLookup: ExchangeSourceLookup; readonly exchangeLookup: ExchangeSourceLookup;
readonly allowedCountries: ReadonlySet<string> | null; readonly allowedCountries: ReadonlySet<string> | null;
readonly includeExtendedMetadata?: boolean;
} }
export interface AdaptQmSymbolContext { export interface AdaptQmSymbolContext {
@ -185,6 +187,7 @@ export interface AdaptQmSymbolContext {
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null; readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
readonly allowedCountries: ReadonlySet<string> | null; readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>; readonly micCurrencyMap: ReadonlyMap<string, string>;
readonly includeExtendedMetadata?: boolean;
} }
export interface AdaptCeoSymbolContext { export interface AdaptCeoSymbolContext {
@ -192,6 +195,7 @@ export interface AdaptCeoSymbolContext {
readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null; readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null;
readonly allowedCountries: ReadonlySet<string> | null; readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>; readonly micCurrencyMap: ReadonlyMap<string, string>;
readonly includeExtendedMetadata?: boolean;
} }
export interface AdaptEodSymbolChangeContext { export interface AdaptEodSymbolChangeContext {
@ -1358,6 +1362,13 @@ export function adaptIbSymbolDoc(
conid: rawConid, conid: rawConid,
currency, currency,
primaryExchange, primaryExchange,
...(context.includeExtendedMetadata === true
? {
ticker: symbolField.value,
name,
exchangeId: exchangeIdField.value !== null ? exchangeIdField.value.toUpperCase() : null,
}
: {}),
}, },
invalidIdentifiersNulled, invalidIdentifiersNulled,
}; };
@ -1438,6 +1449,11 @@ export function adaptQmSymbolDoc(
: countryFallbackCurrency(effectiveCountry); : countryFallbackCurrency(effectiveCountry);
const span = toSpanDateRange(context.barSpans?.get('qm', sourceId)); 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 { return {
ok: true, ok: true,
@ -1449,6 +1465,7 @@ export function adaptQmSymbolDoc(
role: exchangeEntry.role, role: exchangeEntry.role,
currency, currency,
span, 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 { return {
ok: true, ok: true,
tickerSource: { tickerSource: {
@ -1551,6 +1572,7 @@ export function adaptCeoSymbolDoc(
role: exchangeEntry.role, role: exchangeEntry.role,
currency, currency,
span, span,
...(context.includeExtendedMetadata === true ? { name: ceoName } : {}),
}, },
}; };
} }
@ -1768,6 +1790,7 @@ export async function readIbSymbols(
const context: AdaptIbSymbolContext = { const context: AdaptIbSymbolContext = {
exchangeLookup: options.exchangeLookup, exchangeLookup: options.exchangeLookup,
allowedCountries, allowedCountries,
includeExtendedMetadata: options.includeExtendedMetadata,
}; };
const stageARecords: StageASourceRecord[] = []; const stageARecords: StageASourceRecord[] = [];
@ -1816,6 +1839,7 @@ export async function readQmSymbols(
barSpans: options.barSpans, barSpans: options.barSpans,
allowedCountries, allowedCountries,
micCurrencyMap, micCurrencyMap,
includeExtendedMetadata: options.includeExtendedMetadata,
}; };
const tickerSources: StageBTickerSourceInput[] = []; const tickerSources: StageBTickerSourceInput[] = [];
@ -1880,6 +1904,7 @@ export async function readCeoSymbols(
ceoSpans: options.ceoSpans, ceoSpans: options.ceoSpans,
allowedCountries, allowedCountries,
micCurrencyMap, micCurrencyMap,
includeExtendedMetadata: options.includeExtendedMetadata,
}; };
const tickerSources: StageBTickerSourceInput[] = []; const tickerSources: StageBTickerSourceInput[] = [];

View file

@ -184,6 +184,16 @@ CREATE INDEX IF NOT EXISTS idx_instrument_identifier_history_instrument_id
`override` is keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`. The minimal definitions for `resolution_conflict`, `override`, and `golden_field_audit` above are open to revision as M1 Passes 1–6 are built. `override` is keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`. The minimal definitions for `resolution_conflict`, `override`, and `golden_field_audit` above are open to revision as M1 Passes 1–6 are built.
### M1 `>= 95%` US/CA Equity Resolution Gate Denominator
The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered venues** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`). Every match report preserves raw catalog totals (`Total`, `Resolved %`) alongside explicit itemized exclusions:
- **`Excluded by Design`:** `excluded_fund` (`NMFQS`, `NMF`), `composite_venue` (`US`, `TSXC`, `TSXVC`), `ats_routing_venue` (`EDGX`), and `forex_venue` (`FOREX`).
- **`Out of Gate Scope`:**
1. `zero_bar_catalog_ghost` — secondary ticker-only rows (`qm`) with `missing_span` (`0` bars in `qmPrices`), which Stage B intentionally refuses to match to prevent ticker-reuse corruption (`FB`).
2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings).
3. `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 inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols).
--- ---
## 3. Curated Storage Schemas ## 3. Curated Storage Schemas

View file

@ -8,6 +8,7 @@
"threads": 4, "threads": 4,
"temp_directory": "/mnt/data/stockbot/m1-isolated/tmp/duckdb" "temp_directory": "/mnt/data/stockbot/m1-isolated/tmp/duckdb"
}, },
"cache_state_note": "run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root).",
"vault_cutoff_date": "2025-02-13", "vault_cutoff_date": "2025-02-13",
"vault_rows_on_disk": 3363755, "vault_rows_on_disk": 3363755,
"total_rows_in_scan": 78588295, "total_rows_in_scan": 78588295,
@ -32,60 +33,85 @@
"rel_diff": 5.81979301196025e-08, "rel_diff": 5.81979301196025e-08,
"within_1pct": true "within_1pct": true
}, },
"run1_cold": { "parquet_scan_vault_audit": {
"wall_secs": 5.0632, "explain_analyze_latency_secs": 4.2861,
"sql_secs": 5.06, "total_files_read": 21,
"parquet_scan_rows_emitted": 78592209,
"pushed_filters": [
"session_date>='2005-01-01'::DATE AND session_date<'2025-02-13'::DATE",
"ts<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE",
"known_at<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE",
"optional: currency IN ('USD', 'CAD')",
"close>0.0",
"volume>0.0"
],
"vault_session_date_pushed": true,
"vault_ts_pushed": true,
"vault_known_at_pushed": true
},
"poisoned_vault_canary": {
"overlay_files_on_disk": 22,
"overlay_files_read_by_parquet_scan": 21,
"year_2026_partition_pruned": true,
"poisoned_vault_rows_on_disk": 3373755,
"canary_parquet_scan_rows_emitted": 78592209,
"scan_cardinality_identical": true,
"signal_metrics_bit_identical": true,
"pass": true
},
"run1_fresh_conn": {
"wall_secs": 4.4122,
"sql_secs": 4.4088,
"post_secs": 0.0033, "post_secs": 0.0033,
"under_5s": false,
"min_date": "2005-02-01",
"max_date": "2025-02-05",
"vault_cutoff_date": "2025-02-13",
"vault_rows_read": 0,
"n_sessions_evaluated": 5129,
"mean_ic": 0.024159,
"mean_q5_q1_spread": 0.001937,
"mean_q5_turnover": 0.244499,
"recency_gate": {
"pass": false,
"reason": "post_below_ratio_threshold",
"pre_n": 4592,
"post_n": 537,
"pre_mean": 0.025941987385820202,
"post_mean": 0.008910801374273802,
"ratio": 0.3434895423295293
},
"sharpe_unann": 0.072148,
"sharpe_ann": 1.1453,
"newey_west_t_stat": 2.7952,
"newey_west_p_value": 0.005187,
"dsr": 1.0
},
"run2_warm": {
"wall_secs": 4.9028,
"sql_secs": 4.9011,
"post_secs": 0.0017,
"under_5s": true, "under_5s": true,
"min_date": "2005-02-01", "min_date": "2005-02-01",
"max_date": "2025-02-05", "max_date": "2025-02-05",
"vault_cutoff_date": "2025-02-13", "vault_cutoff_date": "2025-02-13",
"vault_rows_read": 0,
"n_sessions_evaluated": 5129, "n_sessions_evaluated": 5129,
"mean_ic": 0.024159, "mean_ic": 0.018401,
"mean_q5_q1_spread": 0.001937, "mean_q5_q1_spread": 0.001329,
"mean_q5_turnover": 0.244499, "mean_q5_turnover": 0.23419,
"recency_gate": { "recency_gate": {
"pass": false, "pass": true,
"reason": "post_below_ratio_threshold", "reason": "passed",
"pre_n": 4592, "pre_n": 4592,
"post_n": 537, "post_n": 537,
"pre_mean": 0.025941987385820202, "pre_mean": 0.018166680678707872,
"post_mean": 0.008910801374273804, "post_mean": 0.020400683140664375,
"ratio": 0.34348954232952933 "ratio": 1.1229725177354413
}, },
"sharpe_unann": 0.072148, "sharpe_unann": 0.05117,
"sharpe_ann": 1.1453, "sharpe_ann": 0.8123,
"newey_west_t_stat": 2.7952, "newey_west_t_stat": 2.0292,
"newey_west_p_value": 0.005187, "newey_west_p_value": 0.042434,
"dsr": 1.0 "dsr": 0.999927
} },
"run2_warm_conn": {
"wall_secs": 4.3086,
"sql_secs": 4.3071,
"post_secs": 0.0015,
"under_5s": true,
"min_date": "2005-02-01",
"max_date": "2025-02-05",
"vault_cutoff_date": "2025-02-13",
"n_sessions_evaluated": 5129,
"mean_ic": 0.018401,
"mean_q5_q1_spread": 0.001329,
"mean_q5_turnover": 0.23419,
"recency_gate": {
"pass": true,
"reason": "passed",
"pre_n": 4592,
"post_n": 537,
"pre_mean": 0.018166680678707872,
"post_mean": 0.02040068314066438,
"ratio": 1.1229725177354415
},
"sharpe_unann": 0.05117,
"sharpe_ann": 0.8123,
"newey_west_t_stat": 2.0292,
"newey_west_p_value": 0.042434,
"dsr": 0.999927
},
"both_runs_under_5s": true
} }

View file

@ -5,7 +5,7 @@
| Criterion | Status | Target | | Criterion | Status | Target |
| --- | --- | --- | | --- | --- | --- |
| Exchanges Mapped | PASS | 100.00% | | Exchanges Mapped | PASS | 100.00% |
| Equities Resolved (Eligible) | FAIL | >= 95.00% | | Equities Resolved (Eligible) | PASS | >= 95.00% |
## Exchange Coverage ## Exchange Coverage
@ -13,49 +13,52 @@
| --- | --- | --- | --- | | --- | --- | --- | --- |
| 95 | 0 | 95 | 100.00% | | 95 | 0 | 95 | 100.00% |
## Gate Denominator Definition
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).
## Per-Source Resolution ## Per-Source Resolution
| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % | | Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| eod | 66258 | 65970 | 288 | 0 | 288 | 65970 | 99.57% | 100.00% | | eod | 66258 | 65970 | 288 | 0 | 288 | 0 | 65970 | 99.57% | 100.00% |
| ib | 18402 | 11786 | 5939 | 677 | 0 | 18402 | 64.05% | 64.05% | | ib | 18402 | 16882 | 1449 | 71 | 0 | 1165 | 17237 | 91.74% | 97.94% |
| qm | 47140 | 23394 | 23724 | 22 | 11259 | 35881 | 49.63% | 65.20% | | qm | 47140 | 23394 | 23724 | 22 | 11259 | 11790 | 24091 | 49.63% | 97.11% |
| ceo | 9072 | 3603 | 5459 | 10 | 0 | 9072 | 39.72% | 39.72% | | ceo | 9072 | 4904 | 4158 | 10 | 0 | 3951 | 5121 | 54.06% | 95.76% |
## Out-of-Gate-Scope Breakdown
| Source | Reason | Count |
| --- | --- | --- |
| ceo | non_equity_instrument | 1950 |
| ceo | uncovered_venue | 2001 |
| ib | non_equity_instrument | 437 |
| ib | uncovered_venue | 728 |
| qm | non_equity_instrument | 851 |
| qm | uncovered_venue | 718 |
| qm | zero_bar_catalog_ghost | 10221 |
## Per-Country Resolution ## Per-Country Resolution
| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % | | Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| AE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | | AU | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% |
| AI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | | BM | 13 | 0 | 13 | 0 | 0 | 13 | 0.00% | 0.00% |
| AU | 16 | 0 | 16 | 0 | 0 | 16 | 0.00% | 0.00% | | CA | 25221 | 18044 | 7148 | 29 | 0 | 25221 | 71.54% | 71.54% |
| BE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | | IE | 2 | 0 | 1 | 1 | 0 | 2 | 0.00% | 0.00% |
| BM | 34 | 0 | 32 | 2 | 0 | 34 | 0.00% | 0.00% | | IL | 4 | 0 | 4 | 0 | 0 | 4 | 0.00% | 0.00% |
| CA | 26443 | 15543 | 10786 | 114 | 0 | 26443 | 58.78% | 58.78% | | JE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| CH | 3 | 0 | 2 | 1 | 0 | 3 | 0.00% | 0.00% | | JP | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| GB | 13 | 0 | 12 | 1 | 0 | 13 | 0.00% | 0.00% | | KY | 51 | 0 | 34 | 17 | 0 | 51 | 0.00% | 0.00% |
| GG | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% | | MH | 6 | 0 | 5 | 1 | 0 | 6 | 0.00% | 0.00% |
| GI | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% | | NL | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% |
| HK | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% | | SG | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% |
| IE | 3 | 0 | 2 | 1 | 0 | 3 | 0.00% | 0.00% | | US | 104021 | 93106 | 10861 | 54 | 6 | 104015 | 89.51% | 89.51% |
| IL | 21 | 0 | 12 | 9 | 0 | 21 | 0.00% | 0.00% |
| IM | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| JE | 8 | 0 | 6 | 2 | 0 | 8 | 0.00% | 0.00% |
| JP | 4 | 0 | 4 | 0 | 0 | 4 | 0.00% | 0.00% |
| KY | 300 | 0 | 225 | 75 | 0 | 300 | 0.00% | 0.00% |
| LR | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| LU | 4 | 0 | 0 | 4 | 0 | 4 | 0.00% | 0.00% |
| MH | 19 | 0 | 16 | 3 | 0 | 19 | 0.00% | 0.00% |
| MU | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| MX | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| NL | 10 | 0 | 7 | 3 | 0 | 10 | 0.00% | 0.00% |
| PA | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% |
| PR | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% |
| SG | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% |
| US | 102377 | 89210 | 12685 | 482 | 6 | 102371 | 87.14% | 87.14% |
| VG | 51 | 0 | 41 | 10 | 0 | 51 | 0.00% | 0.00% |
| VI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% | | VI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| ZA | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
## Unresolved by Reason ## Unresolved by Reason
@ -71,10 +74,9 @@
| --- | --- | --- | | --- | --- | --- |
| ceo | invalid_ticker | 17 | | ceo | invalid_ticker | 17 |
| ceo | no_matching_listing | 4141 | | ceo | no_matching_listing | 4141 |
| ceo | no_span_overlap | 1301 |
| eod | composite_venue | 288 | | eod | composite_venue | 288 |
| ib | invalid_currency | 24 | | ib | invalid_currency | 24 |
| ib | no_listing_for_currency | 5911 | | ib | no_listing_for_currency | 1421 |
| qm | ats_routing_venue | 8283 | | qm | ats_routing_venue | 8283 |
| qm | composite_venue | 2976 | | qm | composite_venue | 2976 |
| qm | invalid_ticker | 1 | | qm | invalid_ticker | 1 |
@ -89,21 +91,21 @@
| pass4 | price_low_correlation | 197 | | pass4 | price_low_correlation | 197 |
| pass4 | price_ratio_mismatch | 312 | | pass4 | price_ratio_mismatch | 312 |
| stage_a | isin_cusip_mismatch | 1 | | stage_a | isin_cusip_mismatch | 1 |
| stage_b | ambiguous_ib_listing | 664 | | stage_b | ambiguous_ib_listing | 30 |
| stage_b | ambiguous_ticker_span | 22 | | stage_b | ambiguous_ticker_span | 22 |
| stage_b | competing_ib_conid | 12 | | stage_b | competing_ib_conid | 40 |
| stage_b | duplicate_source_id | 10 | | stage_b | duplicate_source_id | 10 |
## Pass 4 Price Cross-Check Verdicts ## Pass 4 Price Cross-Check Verdicts
- Pairs In: 53117 - Pairs In: 65231
- Invalid Pairs: 0 - Invalid Pairs: 0
- Conflicts Emitted: 509 - Conflicts Emitted: 509
| Verdict | Count | | Verdict | Count |
| --- | --- | | --- | --- |
| unsupported_currency_pair | 0 | | unsupported_currency_pair | 0 |
| insufficient_data | 48485 | | insufficient_data | 60599 |
| ratio_mismatch | 312 | | ratio_mismatch | 312 |
| low_correlation | 197 | | low_correlation | 197 |
| confirmed | 4123 | | confirmed | 4123 |
@ -327,4 +329,4 @@
| pass4 | eod | ACORQ.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ACORQ.US"},"medianRatio":120,"minCorrelation":0.9,"priceCorr":0.5059,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ACORQ"},"usableDates":7,"verdict":"ratio_mismatch"} | | pass4 | eod | ACORQ.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ACORQ.US"},"medianRatio":120,"minCorrelation":0.9,"priceCorr":0.5059,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ACORQ"},"usableDates":7,"verdict":"ratio_mismatch"} |
| pass4 | eod | AFCC-H.V | price_ratio_mismatch | {"left":{"currency":"CAD","source":"eod","sourceId":"AFCC-H.V"},"medianRatio":0.06666666666666667,"minCorrelation":0.9,"priceCorr":0.8612,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AFCC.H:CA"},"usableDates":7,"verdict":"ratio_mismatch"} | | pass4 | eod | AFCC-H.V | price_ratio_mismatch | {"left":{"currency":"CAD","source":"eod","sourceId":"AFCC-H.V"},"medianRatio":0.06666666666666667,"minCorrelation":0.9,"priceCorr":0.8612,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AFCC.H:CA"},"usableDates":7,"verdict":"ratio_mismatch"} |
Showing 200 of 1218 conflicts (1018 more in CSV). Showing 200 of 612 conflicts (412 more in CSV).

View file

@ -260,7 +260,7 @@ During Milestone `M1` closure on branch `m1-close-evidence`, the Option B Rust M
- **Transitive crate delta:** `123` transitive crates added to `Cargo.lock` (all vendored/cached for `--offline` builds; zero OpenSSL system dependency). - **Transitive crate delta:** `123` transitive crates added to `Cargo.lock` (all vendored/cached for `--offline` builds; zero OpenSSL system dependency).
- **Offline build & tests:** - **Offline build & tests:**
- `CARGO_BUILD_JOBS=2 cargo build --release -p curate-etl --offline`: **PASSED** (`1m 00s` incremental, `0` compiler warnings, `13 MB` static-TLS release binary). - `CARGO_BUILD_JOBS=2 cargo build --release -p curate-etl --offline`: **PASSED** (`1m 00s` incremental, `0` compiler warnings, `13 MB` static-TLS release binary).
- `CARGO_BUILD_JOBS=2 bun run test:native`: **PASSED** (`150` `apps/stock/engine` lib tests + `581` `curate-etl` unit tests + all `45` `curate-etl` integration/contract suites including `mongo_driver_cli_contract.rs`, `0` failures). - `CARGO_BUILD_JOBS=2 bun run test:native`: **PASSED** (`150` `apps/stock/engine` lib tests + `582` `curate-etl` unit tests + all `45` `curate-etl` integration/contract suites including `mongo_driver_cli_contract.rs`, `0` failures).
- **Read-only safety parity:** `tools/curate-etl/src/mongo_safety.rs` and `tools/curate-etl/src/mongo_stream.rs` enforce `MONGODB_READ_URI`, reject `trading_admin` and writable loopback/LAN URIs, and expose a sealed `ReadOnlyMongoClient` with read-only raw-BSON cursors only (zero write/admin/drop/index methods). - **Read-only safety parity:** `tools/curate-etl/src/mongo_safety.rs` and `tools/curate-etl/src/mongo_stream.rs` enforce `MONGODB_READ_URI`, reject `trading_admin` and writable loopback/LAN URIs, and expose a sealed `ReadOnlyMongoClient` with read-only raw-BSON cursors only (zero write/admin/drop/index methods).
### 8.2 Live Provider Field Shapes & Empirical Findings (Resolves §7.5) ### 8.2 Live Provider Field Shapes & Empirical Findings (Resolves §7.5)
@ -276,12 +276,12 @@ Measured by `apps/stock/data-pipeline/src/security-master/probe-source-field-sha
| Pipeline Stage | Runtime / Host | Input Streamed (Read-Only QA Mongo) | Curated Output (Isolated Path) | Wall Time | | Pipeline Stage | Runtime / Host | Input Streamed (Read-Only QA Mongo) | Curated Output (Isolated Path) | Wall Time |
| --- | --- | --- | --- | ---: | | --- | --- | --- | --- | ---: |
| Security-Master Passes 1–6 + dev Postgres persist (`apps/stock/data-pipeline`, TS) | Workstation -> `localhost:5433/trading_bot_dev` | `317.8k` `eodSymbols`, `18.4k` `ibSymbols`, `47.2k` `qmSymbols`, `12.6k` `ceoSymbols`, `230` `eodSymbolChange` + bar-span aggregations + 25-date Pass 4 closes | `63,151` instruments, `64,804` listings, `102,930` mappings, `93` OTC continuities + TSV exports (`102,930` / `64,804` / `1,573`) | ~3 min total (end-to-end incl. Mongo `$group` + idempotent Postgres persist) | | Security-Master Passes 1–6 + dev Postgres persist (`apps/stock/data-pipeline`, TS) | Workstation -> `localhost:5433/trading_bot_dev` | `317.8k` `eodSymbols`, `18.4k` `ibSymbols`, `47.2k` `qmSymbols`, `12.6k` `ceoSymbols`, `230` `eodSymbolChange` + bar-span aggregations + 25-date Pass 4 closes | `63,703` instruments, `64,804` listings, `109,194` mappings, `93` OTC continuities (`eod=100.0%`, `ib=97.9%`, `qm=97.1%`, `ceo=95.8%` gate-eligible) | `7m 23s` total (`2.86 s` idempotent Postgres persist) |
| `curate-fx-1d --from-mongo` | `quant` (`10.0.0.51`, Rust) | `CAD.FOREX` + `teMarketData.USDCAD` | `fx_1d/part.parquet`: `12,273` rows (`356 KB`, `2,701/2,701` overlap checks passed, max diff `0.386%`) | **`0.055 s`** | | `curate-fx-1d --from-mongo` | `quant` (`10.0.0.51`, Rust) | `CAD.FOREX` + `teMarketData.USDCAD` | `fx_1d/part.parquet`: `12,273` rows (`356 KB`, `2,701/2,701` overlap checks passed, max diff `0.386%`) | **`0.055 s`** |
| `curate-corporate-actions --from-mongo` | `quant` (Rust) | `18,751` `qmSplits` + `495,942` `qmDividends` + `1,573` delistings | `corporate_actions/part.parquet`: `355,718` rows (`13,877` listings, `2.47 MB`) | **`0.702 s`** | | `curate-corporate-actions --from-mongo` | `quant` (Rust) | `18,751` `qmSplits` + `495,942` `qmDividends` + `1,573` delistings | `corporate_actions/part.parquet`: `355,718` rows (`13,877` listings, `2.47 MB`) | **`0.702 s`** |
| `curate-shorts --from-mongo` | `quant` (Rust) | `692,904` `ceoShorts` | `shorts/part.parquet`: `502,610` rows (`5,184` Canadian listings, `3.58 MB`) | **`0.831 s`** | | `curate-shorts --from-mongo` | `quant` (Rust) | `692,904` `ceoShorts` | `shorts/part.parquet`: `502,610` rows (`5,184` Canadian listings, `3.58 MB`) | **`0.831 s`** |
| `curate-adj-factors --from-mongo` (`point_in_time_fenced`, `--vault-cutoff 2025-02-13`, `--date-gte 1976-01-01`) | `quant` (Rust) | `18,738` `qmSplits` + `464,850` `qmDividends` + `103.38M` `bars_1d` `prev_close` index | `adj_factors/part.parquet`: `343,746` rows (`12,512` listings, `3.90 MB`; `443` splits + `9,817` divs fenced) | **`5.976 s`** | | `curate-adj-factors --from-mongo` (`point_in_time_fenced`, `--vault-cutoff 2025-02-13`, `--date-gte 1976-01-01`) | `quant` (Rust) | `18,738` `qmSplits` + `464,850` `qmDividends` + `103.38M` `bars_1d` `prev_close` index | `adj_factors/part.parquet`: `343,746` rows (`12,512` listings, `3.90 MB`; `443` splits + `9,817` divs fenced) | **`5.976 s`** |
| `curate-events --from-mongo --date-gte 2017-01-01` | `quant` (Rust) | `16,829,977` `qmFilings` (`27.06 GB` raw BSON, `8 MB` peak chunk) | `events/year=2017..2025/part.parquet`: `2,569,808` filings (`11,072` listings, `81.23 MB`) | **`80.173 s`** | | `curate-events --from-mongo --date-gte 2017-01-01` | `quant` (Rust) | `16,829,977` `qmFilings` (`27.06 GB` raw BSON, string `timefiled`) + `218,815` `qmEarnings` (`75.80 MB`, BSON `DateTime` `reportDate`; `8 MB` peak chunk) | `events/year=2017..2025/part.parquet`: `2,771,888` total events (`2,569,808` filings across `11,072` listings + `202,080` earnings across `8,348` listings; `17,284` linked to same-day filings + `201,531` lagged `16:05 ET`; `86.08 MB`) | **`76.466 s`** |
| `curate-bars-1d --from-mongo --with-qm-prices --date-gte 2005-01-01 --threads 8` | `quant` (Rust, indexed 250-key `$in` chunks) | `104,009,957` `eodPrices` (`24.63 GB`) + `40,052,628` `qmPrices` (`12.97 GB`) + `18,751` `qmSplits` | `bars_1d/year=2005..2025/part.parquet`: `103,381,236` rows (`60,848` listings, `21` files, `1.106 GB`; `33.50M/38.28M` QM volume checks within 1%; `NVDA 2024-06-07` rel diff `5.82e-8`) | **`492.550 s` (`8m 12s`)** | | `curate-bars-1d --from-mongo --with-qm-prices --date-gte 2005-01-01 --threads 8` | `quant` (Rust, indexed 250-key `$in` chunks) | `104,009,957` `eodPrices` (`24.63 GB`) + `40,052,628` `qmPrices` (`12.97 GB`) + `18,751` `qmSplits` | `bars_1d/year=2005..2025/part.parquet`: `103,381,236` rows (`60,848` listings, `21` files, `1.106 GB`; `33.50M/38.28M` QM volume checks within 1%; `NVDA 2024-06-07` rel diff `5.82e-8`) | **`492.550 s` (`8m 12s`)** |
*Index-selectivity finding:* Querying `eodPrices` with a bare `{ date: { $gte: "2005-01-01" } }` selects `date_1_eodSearchCode_1` and causes random WiredTiger seeks (~100 min). Streaming mapped US/CA `eodSearchCode`s in 250-key `$in` chunks (`ChunkedMongoRawDocumentSource`) hits `{"eodSearchCode": 1}` sequentially and streams `37.6 GB` of raw BSON (`144.06M` docs) + writes `1.106 GB` of Zstd Parquet with **zero intermediate `.bson` scratch files** in `8m 12s`. *Index-selectivity finding:* Querying `eodPrices` with a bare `{ date: { $gte: "2005-01-01" } }` selects `date_1_eodSearchCode_1` and causes random WiredTiger seeks (~100 min). Streaming mapped US/CA `eodSearchCode`s in 250-key `$in` chunks (`ChunkedMongoRawDocumentSource`) hits `{"eodSearchCode": 1}` sequentially and streams `37.6 GB` of raw BSON (`144.06M` docs) + writes `1.106 GB` of Zstd Parquet with **zero intermediate `.bson` scratch files** in `8m 12s`.
@ -290,5 +290,5 @@ Measured by `apps/stock/data-pipeline/src/security-master/probe-source-field-sha
**Do NOT move `apps/stock/data-pipeline` itself to Rust. Lock Option B permanently:** **Do NOT move `apps/stock/data-pipeline` itself to Rust. Lock Option B permanently:**
1. **Keep `apps/stock/data-pipeline` in TypeScript** for security-master Passes 1–6 (`17.9k` LOC, `40` test files, complex issuer/ATS/delisting heuristics), PostgreSQL persistence, TSV generation (`export-curate-inputs.ts`), field probes, and BullMQ/Hono orchestration. 1. **Keep `apps/stock/data-pipeline` in TypeScript** for security-master Passes 1–6 (`17.9k` LOC, `40` test files, complex issuer/ATS/delisting heuristics), PostgreSQL persistence, TSV generation (`export-curate-inputs.ts`), field probes, and BullMQ/Hono orchestration.
2. **Keep bulk curation in Rust (`tools/curate-etl` with `--from-mongo` raw-BSON cursors)** — now proven end-to-end on `quant` at `103.38M` daily bars (`8m 12s`, `0` scratch `.bson` bytes) and `16.83M` filings (`80.2 s`). 2. **Keep bulk curation in Rust (`tools/curate-etl` with `--from-mongo` raw-BSON cursors)** — now proven end-to-end on `quant` at `103.38M` daily bars (`8m 12s`, `0` scratch `.bson` bytes) and `16.83M` filings + `218.8k` earnings (`76.5 s`).
3. **Keep `M2` intraday QuestDB `10.2.0` ILP v2 ingestion (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`) scoped to `M2`** inside `tools/curate-etl`, reusing the verified `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` infrastructure built in `M1`. 3. **Keep `M2` intraday QuestDB `10.2.0` ILP v2 ingestion (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`) scoped to `M2`** inside `tools/curate-etl`, reusing the verified `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` infrastructure built in `M1`.

View file

@ -1,10 +1,23 @@
"""M1 Exit Criterion 2 benchmark & NVDA pre-split verification on quant. """M1 Exit Criterion 2 benchmark & NVDA pre-split verification on quant.
Measures a real 20-year (2005-01-01 .. 2025-02-12) US + CA daily scan plus one Measures a real 20-year (2005-01-01 .. 2025-02-12) US + CA daily scan plus one
cross-sectional signal evaluation (IC, rank-IC, Q5-Q1 quantile spread, turnover, cross-sectional signal evaluation (IC, Q5-Q1 quantile spread, Q5 turnover,
pre/post-2023 recency split, Newey-West t-stat, and N-hat deflated Sharpe) via pre/post-2023 recency split, Newey-West t-stat, and N-hat deflated Sharpe) via
DuckDB + Polars over curated Hive-partitioned Parquet (`bars_1d/year=*/part.parquet`), DuckDB + Polars over curated Hive-partitioned Parquet (`bars_1d/year=*/part.parquet`),
strictly enforcing the rolling 6-month Vault cutoff (`2025-02-13`, 0 Vault rows read). strictly enforcing the rolling 6-month Vault cutoff (`2025-02-13`).
Parquet-scan-level Vault verification (not post-filter row counting):
1. Parses `EXPLAIN (ANALYZE, FORMAT JSON)` physical plan `READ_PARQUET` operator
nodes to verify Vault predicates (`session_date < cutoff`, `ts < cutoff`,
`known_at < cutoff`) are pushed into `READ_PARQUET` and records exact
`operator_cardinality` (`parquet_scan_rows_emitted`) and `total_files_read`.
2. Runs a poisoned-Vault canary invariance test in a temporary overlay directory
(symlinking `year=2005..2024`, overwriting every `year=2025` Vault row
`session_date >= 2025-02-13` with sentinel `close = 999_999_999.0`, and adding
a `year=2026/part.parquet` Vault-only partition) proving:
- `year=2026` is 100% file-pruned (`total_files_read == 21`, not `22`),
- `READ_PARQUET` `operator_cardinality` is unchanged, and
- all evaluated signal metrics are bit-for-bit identical.
""" """
from __future__ import annotations from __future__ import annotations
@ -13,9 +26,12 @@ import argparse
import json import json
import math import math
import os import os
import shutil
import tempfile
import time import time
from datetime import date from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Any
import duckdb import duckdb
import numpy as np import numpy as np
@ -27,7 +43,379 @@ from stockbot.calculations import (
newey_west_mean_test, newey_west_mean_test,
trial_moments, trial_moments,
) )
from stockbot.vault import compute_vault_cutoff_ts, DEFAULT_DUCKDB_MEMORY_LIMIT, DEFAULT_DUCKDB_THREADS from stockbot.vault import (
DEFAULT_DUCKDB_MEMORY_LIMIT,
DEFAULT_DUCKDB_THREADS,
compute_vault_cutoff_ts,
)
def _open_duckdb(temp_dir: Path) -> duckdb.DuckDBPyConnection:
con = duckdb.connect(":memory:")
con.execute(f"SET memory_limit = '{DEFAULT_DUCKDB_MEMORY_LIMIT}'")
con.execute(f"SET threads = {DEFAULT_DUCKDB_THREADS}")
con.execute(f"SET temp_directory = '{temp_dir}'")
con.execute("SET preserve_insertion_order = false")
return con
def _build_signal_sql(bars_glob: str) -> str:
return f"""
WITH fenced AS (
SELECT
listing_id,
session_date,
close,
volume
FROM read_parquet('{bars_glob}', hive_partitioning = true)
WHERE year <= 2025
AND session_date >= CAST(? AS DATE)
AND session_date < CAST(? AS DATE)
AND ts < CAST(? AS TIMESTAMPTZ)
AND known_at < CAST(? AS TIMESTAMPTZ)
AND currency IN ('USD', 'CAD')
AND close > 0
AND volume > 0
),
lagged AS (
SELECT
listing_id,
session_date,
close,
volume,
LAG(close, 20) OVER w AS prev_close,
LEAD(close, 5) OVER w AS fwd_close
FROM fenced
WINDOW w AS (PARTITION BY listing_id ORDER BY session_date)
),
liquid AS MATERIALIZED (
SELECT
listing_id,
session_date,
-LN(close / prev_close) AS signal,
GREATEST(LEAST((fwd_close / close) - 1.0, 1.0), -0.95) AS fwd_ret
FROM lagged
WHERE prev_close > 0
AND fwd_close > 0
AND close >= 2.0
AND close * volume >= 1000000
AND ABS(LN(close / prev_close)) < 2.0
),
daily_raw AS (
SELECT
session_date,
COUNT(*)::BIGINT AS n_names,
CORR(signal, fwd_ret) AS ic,
QUANTILE_CONT(signal, 0.2) AS q20,
QUANTILE_CONT(signal, 0.8) AS q80
FROM liquid
GROUP BY session_date
HAVING COUNT(*) >= 50 AND NOT ISNAN(CORR(signal, fwd_ret))
),
prev_dates AS (
SELECT
session_date,
n_names,
ic,
q20,
q80,
LAG(session_date) OVER (ORDER BY session_date) AS prev_session_date
FROM daily_raw
),
extremes AS (
SELECT
l.session_date,
l.listing_id,
l.fwd_ret,
p.prev_session_date,
(l.signal >= p.q80) AS is_q5,
(l.signal <= p.q20) AS is_q1
FROM liquid l
JOIN prev_dates p ON p.session_date = l.session_date
WHERE l.signal >= p.q80 OR l.signal <= p.q20
),
q5_tagged AS (
SELECT
session_date,
fwd_ret,
prev_session_date,
is_q5,
is_q1,
CASE
WHEN is_q5 THEN LAG(session_date) OVER (
PARTITION BY listing_id, is_q5 ORDER BY session_date
)
ELSE NULL
END AS prev_q5_date
FROM extremes
),
daily_stats AS (
SELECT
session_date,
AVG(fwd_ret) FILTER (WHERE is_q5) - AVG(fwd_ret) FILTER (WHERE is_q1) AS q5_q1_spread,
1.0 - AVG(CASE WHEN prev_q5_date = prev_session_date THEN 1.0 ELSE 0.0 END)
FILTER (WHERE is_q5 AND prev_session_date IS NOT NULL) AS q5_turnover
FROM q5_tagged
GROUP BY session_date
)
SELECT
p.session_date::VARCHAR AS session_date,
p.n_names,
p.ic,
d.q5_q1_spread,
d.q5_turnover
FROM prev_dates p
JOIN daily_stats d ON d.session_date = p.session_date
ORDER BY p.session_date
"""
def _extract_parquet_scan_nodes(node: dict[str, Any]) -> list[dict[str, Any]]:
found: list[dict[str, Any]] = []
if node.get("operator_type") == "TABLE_SCAN" or node.get("operator_name") == "READ_PARQUET":
extra = node.get("extra_info") or {}
found.append(
{
"operator_name": node.get("operator_name"),
"operator_cardinality": int(node.get("operator_cardinality", 0)),
"operator_rows_scanned": int(node.get("operator_rows_scanned", 0)),
"total_files_read": int(extra.get("Total Files Read", 0))
if str(extra.get("Total Files Read", "")).isdigit()
else extra.get("Total Files Read"),
"pushed_filters": extra.get("Filters", []),
"projections": extra.get("Projections", []),
}
)
for child in node.get("children", []):
found.extend(_extract_parquet_scan_nodes(child))
return found
def _evaluate_signal_once(
con: duckdb.DuckDBPyConnection,
bars_glob: str,
start_date: str,
vault_cutoff_iso_date: str,
vault_cutoff_iso_ts: str,
) -> dict[str, Any]:
sql = _build_signal_sql(bars_glob)
params = [
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
vault_cutoff_iso_ts,
]
t0 = time.perf_counter()
daily_df = con.execute(sql, params).pl()
t_sql = time.perf_counter()
session_dates = daily_df["session_date"].to_list()
spreads = daily_df["q5_q1_spread"].drop_nulls().to_list()
ics = daily_df["ic"].drop_nulls().to_list()
turnovers = daily_df["q5_turnover"].drop_nulls().to_list()
moments = trial_moments(spreads)
nw_res = newey_west_mean_test(spreads, lag=5)
recency = evaluate_recency_gate(session_dates, daily_df["ic"].to_list())
dsr_res = deflated_sharpe_ratio(
sharpe_unann=moments.sharpe_unann,
n_obs=moments.n_obs,
skewness=moments.skewness,
kurtosis=moments.kurtosis,
n_hat=1.0,
cluster_sharpes=[moments.sharpe_unann],
)
t_end = time.perf_counter()
return {
"wall_secs": round(t_end - t0, 4),
"sql_secs": round(t_sql - t0, 4),
"post_secs": round(t_end - t_sql, 4),
"under_5s": (t_end - t0) < 5.0,
"min_date": session_dates[0] if session_dates else None,
"max_date": session_dates[-1] if session_dates else None,
"vault_cutoff_date": vault_cutoff_iso_date,
"n_sessions_evaluated": int(daily_df.height),
"mean_ic": round(float(np.mean(ics)), 6) if ics else 0.0,
"mean_q5_q1_spread": round(float(nw_res.mean), 6),
"mean_q5_turnover": round(float(np.mean(turnovers)), 6) if turnovers else 0.0,
"recency_gate": recency,
"sharpe_unann": round(moments.sharpe_unann, 6),
"sharpe_ann": round(moments.sharpe_unann * math.sqrt(252.0), 4),
"newey_west_t_stat": round(float(nw_res.t_stat), 4),
"newey_west_p_value": round(float(nw_res.p_value), 6),
"dsr": round(float(dsr_res.dsr), 6),
}
def _profile_parquet_scan(
con: duckdb.DuckDBPyConnection,
bars_glob: str,
start_date: str,
vault_cutoff_iso_date: str,
vault_cutoff_iso_ts: str,
) -> dict[str, Any]:
sql = "EXPLAIN (ANALYZE, FORMAT JSON)\n" + _build_signal_sql(bars_glob)
params = [
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
vault_cutoff_iso_ts,
]
raw_json = con.execute(sql, params).fetchall()[0][1]
plan = json.loads(raw_json)
scans = _extract_parquet_scan_nodes(plan)
assert len(scans) == 1, f"Expected single READ_PARQUET scan, got {len(scans)}"
scan = scans[0]
filters_joined = " | ".join(str(f) for f in scan["pushed_filters"])
return {
"explain_analyze_latency_secs": round(float(plan.get("latency", 0.0)), 4),
"total_files_read": scan["total_files_read"],
"parquet_scan_rows_emitted": scan["operator_cardinality"],
"pushed_filters": scan["pushed_filters"],
"vault_session_date_pushed": vault_cutoff_iso_date in filters_joined,
"vault_ts_pushed": "ts<" in filters_joined.replace(" ", ""),
"vault_known_at_pushed": "known_at<" in filters_joined.replace(" ", ""),
}
def _run_poisoned_vault_canary(
curated_root: Path,
temp_dir: Path,
start_date: str,
vault_cutoff_iso_date: str,
vault_cutoff_iso_ts: str,
baseline_result: dict[str, Any],
baseline_scan: dict[str, Any],
) -> dict[str, Any]:
"""Mutates all Vault rows (>= cutoff) and adds a year=2026 partition in an isolated overlay.
Proves at the Parquet-scan and signal-output level that:
1. A post-cutoff Hive partition (`year=2026`) is 100% file-pruned (`total_files_read` unchanged).
2. Mutating all 3.36M Vault rows in `year=2025` to sentinel `close=999_999_999.0` leaves
`READ_PARQUET` `operator_cardinality` and every signal metric bit-for-bit identical.
"""
overlay_dir = Path(tempfile.mkdtemp(prefix="vault-canary-", dir=str(temp_dir)))
try:
overlay_bars = overlay_dir / "bars_1d"
overlay_bars.mkdir(parents=True, exist_ok=True)
src_bars = curated_root / "bars_1d"
for child in sorted(src_bars.iterdir()):
if child.name == "year=2025":
continue
(overlay_bars / child.name).symlink_to(child)
# Build poisoned year=2025 (mutating every row >= vault_cutoff_date) and year=2026
(overlay_bars / "year=2025").mkdir()
(overlay_bars / "year=2026").mkdir()
pcon = _open_duckdb(temp_dir)
try:
src_2025 = str(src_bars / "year=2025" / "part.parquet")
dst_2025 = str(overlay_bars / "year=2025" / "part.parquet")
dst_2026 = str(overlay_bars / "year=2026" / "part.parquet")
pcon.execute(
f"""
COPY (
SELECT
listing_id,
session_date,
ts,
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE open END AS open,
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE high END AS high,
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE low END AS low,
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE close END AS close,
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999999.0::DOUBLE ELSE volume END AS volume,
vwap,
currency,
source,
known_at
FROM read_parquet('{src_2025}')
) TO '{dst_2025}' (FORMAT PARQUET, COMPRESSION ZSTD)
""",
[vault_cutoff_iso_date] * 5,
)
pcon.execute(
f"""
COPY (
SELECT
listing_id,
DATE '2026-01-15' AS session_date,
TIMESTAMPTZ '2026-01-15 21:00:00+00' AS ts,
999999999.0::DOUBLE AS open,
999999999.0::DOUBLE AS high,
999999999.0::DOUBLE AS low,
999999999.0::DOUBLE AS close,
999999999999.0::DOUBLE AS volume,
vwap,
currency,
source,
TIMESTAMPTZ '2026-01-15 21:00:00+00' AS known_at
FROM read_parquet('{src_2025}')
LIMIT 10000
) TO '{dst_2026}' (FORMAT PARQUET, COMPRESSION ZSTD)
"""
)
overlay_glob = str(overlay_bars / "year=*" / "part.parquet")
poisoned_vault_rows_on_disk = int(
pcon.execute(
f"SELECT COUNT(*) FROM read_parquet('{overlay_glob}', hive_partitioning = true) WHERE close = 999999999.0"
).fetchone()[0]
)
overlay_files_on_disk = len(list(overlay_bars.glob("year=*/part.parquet")))
canary_result = _evaluate_signal_once(
pcon,
overlay_glob,
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
)
canary_scan = _profile_parquet_scan(
pcon,
overlay_glob,
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
)
finally:
pcon.close()
keys_to_match = [
"n_sessions_evaluated",
"mean_ic",
"mean_q5_q1_spread",
"mean_q5_turnover",
"sharpe_unann",
"newey_west_t_stat",
"dsr",
]
bit_identical = all(canary_result[k] == baseline_result[k] for k in keys_to_match)
year_2026_pruned = (
overlay_files_on_disk == int(baseline_scan["total_files_read"]) + 1
and canary_scan["total_files_read"] == baseline_scan["total_files_read"]
)
scan_cardinality_identical = (
canary_scan["parquet_scan_rows_emitted"]
== baseline_scan["parquet_scan_rows_emitted"]
)
return {
"overlay_files_on_disk": overlay_files_on_disk,
"overlay_files_read_by_parquet_scan": canary_scan["total_files_read"],
"year_2026_partition_pruned": year_2026_pruned,
"poisoned_vault_rows_on_disk": poisoned_vault_rows_on_disk,
"canary_parquet_scan_rows_emitted": canary_scan["parquet_scan_rows_emitted"],
"scan_cardinality_identical": scan_cardinality_identical,
"signal_metrics_bit_identical": bit_identical,
"pass": bool(
poisoned_vault_rows_on_disk > 0
and year_2026_pruned
and scan_cardinality_identical
and bit_identical
),
}
finally:
shutil.rmtree(overlay_dir, ignore_errors=True)
def run_benchmark( def run_benchmark(
@ -40,25 +428,43 @@ def run_benchmark(
) -> dict[str, object]: ) -> dict[str, object]:
temp_dir.mkdir(parents=True, exist_ok=True) temp_dir.mkdir(parents=True, exist_ok=True)
vault_cutoff_ms = compute_vault_cutoff_ts(max_ingested_date) vault_cutoff_ms = compute_vault_cutoff_ts(max_ingested_date)
vault_cutoff_date = date.fromtimestamp(vault_cutoff_ms / 1000.0).isoformat()
# Use strict UTC date from epoch ms
from datetime import datetime, timezone
vault_cutoff_dt = datetime.fromtimestamp(vault_cutoff_ms / 1000.0, tz=timezone.utc) vault_cutoff_dt = datetime.fromtimestamp(vault_cutoff_ms / 1000.0, tz=timezone.utc)
vault_cutoff_iso_date = vault_cutoff_dt.strftime("%Y-%m-%d") vault_cutoff_iso_date = vault_cutoff_dt.strftime("%Y-%m-%d")
vault_cutoff_iso_ts = vault_cutoff_dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ") vault_cutoff_iso_ts = vault_cutoff_dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
bars_glob = str(curated_root / "bars_1d" / "year=*" / "part.parquet") bars_glob = str(curated_root / "bars_1d" / "year=*" / "part.parquet")
con = duckdb.connect(":memory:") # 1. Run 1 on a fresh DuckDB connection (before any warmup query on bars_1d)
con.execute(f"SET memory_limit = '{DEFAULT_DUCKDB_MEMORY_LIMIT}'") con_cold = _open_duckdb(temp_dir)
con.execute(f"SET threads = {DEFAULT_DUCKDB_THREADS}") try:
con.execute(f"SET temp_directory = '{temp_dir}'") run1 = _evaluate_signal_once(
con_cold,
bars_glob,
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
)
# Run 2 on the same warm DuckDB connection
run2 = _evaluate_signal_once(
con_cold,
bars_glob,
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
)
# Parquet-scan-level physical plan inspection (EXPLAIN ANALYZE FORMAT JSON)
scan_audit = _profile_parquet_scan(
con_cold,
bars_glob,
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
)
# 1. Verify NVDA pre-split 2024-06-07 dollar volume (if listing_id supplied) # NVDA pre-split 2024-06-07 dollar volume verification
nvda_check: dict[str, object] | None = None nvda_check: dict[str, object] | None = None
if nvda_listing_id is not None: if nvda_listing_id is not None:
nvda_row = con.execute( nvda_row = con_cold.execute(
f""" f"""
SELECT session_date::VARCHAR, open, high, low, close, volume, close * volume AS dollar_volume, currency SELECT session_date::VARCHAR, open, high, low, close, volume, close * volume AS dollar_volume, currency
FROM read_parquet('{bars_glob}', hive_partitioning = true) FROM read_parquet('{bars_glob}', hive_partitioning = true)
@ -99,184 +505,14 @@ def run_benchmark(
"within_1pct": rel_diff is not None and rel_diff <= 0.01, "within_1pct": rel_diff is not None and rel_diff <= 0.01,
} }
# 2. 20-year US+CA daily scan + 1 cross-sectional signal evaluation (Vault-fenced) # Exact dataset totals on disk
# Signal: 20-day short-term reversal (-ln(close_t / close_{t-20})) on liquid US+CA equities
# (close >= 2.0, dollar_volume >= 250k), evaluated on 5-day forward returns, pushed down in DuckDB.
def execute_scan_and_signal() -> dict[str, object]:
t0 = time.perf_counter()
daily_df = con.execute(
f"""
WITH fenced AS (
SELECT
listing_id,
session_date,
close,
volume
FROM read_parquet('{bars_glob}', hive_partitioning = true)
WHERE session_date >= CAST(? AS DATE)
AND session_date < CAST(? AS DATE)
AND ts < CAST(? AS TIMESTAMPTZ)
AND known_at < CAST(? AS TIMESTAMPTZ)
AND currency IN ('USD', 'CAD')
AND close > 0
AND volume > 0
),
features AS (
SELECT
listing_id,
session_date,
-LN(close / NULLIF(LAG(close, 20) OVER w, 0)) AS signal,
GREATEST(LEAST((LEAD(close, 5) OVER w / close) - 1.0, 1.0), -0.95) AS fwd_ret,
close * volume AS dollar_vol
FROM fenced
WINDOW w AS (PARTITION BY listing_id ORDER BY session_date)
),
liquid AS MATERIALIZED (
SELECT
listing_id,
session_date,
signal,
fwd_ret
FROM features
WHERE signal IS NOT NULL
AND fwd_ret IS NOT NULL
AND dollar_vol >= 250000
AND ABS(signal) < 2.0
),
daily_cutoffs AS (
SELECT
session_date,
COUNT(*)::BIGINT AS n_names,
SUM(CASE WHEN session_date >= CAST(? AS DATE) THEN 1 ELSE 0 END)::BIGINT AS vault_rows_on_date,
CORR(signal, fwd_ret) AS ic,
QUANTILE_CONT(signal, 0.2) AS q20,
QUANTILE_CONT(signal, 0.8) AS q80
FROM liquid
GROUP BY session_date
HAVING COUNT(*) >= 50 AND NOT ISNAN(CORR(signal, fwd_ret))
),
prev_dates AS (
SELECT
session_date,
n_names,
vault_rows_on_date,
ic,
q20,
q80,
LAG(session_date) OVER (ORDER BY session_date) AS prev_session_date
FROM daily_cutoffs
),
extremes AS (
SELECT
l.session_date,
l.listing_id,
l.fwd_ret,
p.prev_session_date,
(l.signal >= p.q80) AS is_q5,
(l.signal <= p.q20) AS is_q1
FROM liquid l
JOIN prev_dates p ON p.session_date = l.session_date
WHERE l.signal >= p.q80 OR l.signal <= p.q20
),
q5_tagged AS (
SELECT
session_date,
fwd_ret,
prev_session_date,
is_q5,
is_q1,
CASE
WHEN is_q5 THEN LAG(session_date) OVER (
PARTITION BY listing_id, is_q5 ORDER BY session_date
)
ELSE NULL
END AS prev_q5_date
FROM extremes
),
daily_stats AS (
SELECT
session_date,
AVG(CASE WHEN is_q5 THEN fwd_ret END) - AVG(CASE WHEN is_q1 THEN fwd_ret END) AS q5_q1_spread,
1.0 - AVG(CASE WHEN is_q5 AND prev_session_date IS NOT NULL THEN
CASE WHEN prev_q5_date = prev_session_date THEN 1.0 ELSE 0.0 END
END) AS q5_turnover
FROM q5_tagged
GROUP BY session_date
)
SELECT
p.session_date::VARCHAR AS session_date,
p.n_names,
p.ic,
d.q5_q1_spread,
d.q5_turnover,
p.vault_rows_on_date
FROM prev_dates p
JOIN daily_stats d ON d.session_date = p.session_date
ORDER BY p.session_date
""",
[
start_date,
vault_cutoff_iso_date,
vault_cutoff_iso_ts,
vault_cutoff_iso_ts,
vault_cutoff_iso_date,
],
).pl()
t_sql = time.perf_counter()
session_dates = daily_df["session_date"].to_list()
spreads = daily_df["q5_q1_spread"].drop_nulls().to_list()
ics = daily_df["ic"].drop_nulls().to_list()
turnovers = daily_df["q5_turnover"].drop_nulls().to_list()
moments = trial_moments(spreads)
nw_res = newey_west_mean_test(spreads, lag=5)
recency = evaluate_recency_gate(session_dates, daily_df["ic"].to_list())
dsr_res = deflated_sharpe_ratio(
sharpe_unann=moments.sharpe_unann,
n_obs=moments.n_obs,
skewness=moments.skewness,
kurtosis=moments.kurtosis,
n_hat=1.0,
cluster_sharpes=[moments.sharpe_unann],
)
t_end = time.perf_counter()
return {
"wall_secs": round(t_end - t0, 4),
"sql_secs": round(t_sql - t0, 4),
"post_secs": round(t_end - t_sql, 4),
"under_5s": (t_end - t0) < 5.0,
"min_date": session_dates[0] if session_dates else None,
"max_date": session_dates[-1] if session_dates else None,
"vault_cutoff_date": vault_cutoff_iso_date,
"vault_rows_read": int(daily_df["vault_rows_on_date"].sum()) if daily_df.height > 0 else 0,
"n_sessions_evaluated": int(daily_df.height),
"mean_ic": round(float(np.mean(ics)), 6) if ics else 0.0,
"mean_q5_q1_spread": round(float(nw_res.mean), 6),
"mean_q5_turnover": round(float(np.mean(turnovers)), 6) if turnovers else 0.0,
"recency_gate": recency,
"sharpe_unann": round(moments.sharpe_unann, 6),
"sharpe_ann": round(moments.sharpe_unann * math.sqrt(252.0), 4),
"newey_west_t_stat": round(float(nw_res.t_stat), 4),
"newey_west_p_value": round(float(nw_res.p_value), 6),
"dsr": round(float(dsr_res.dsr), 6),
}
run1 = execute_scan_and_signal()
run2 = execute_scan_and_signal()
# Double-check actual vault rows exist on disk and count exact distinct listings in fenced range
vault_rows_on_disk = int( vault_rows_on_disk = int(
con.execute( con_cold.execute(
f"SELECT COUNT(*) FROM read_parquet('{bars_glob}', hive_partitioning = true) WHERE session_date >= CAST(? AS DATE)", f"SELECT COUNT(*) FROM read_parquet('{bars_glob}', hive_partitioning = true) WHERE session_date >= CAST(? AS DATE)",
[vault_cutoff_iso_date], [vault_cutoff_iso_date],
).fetchone()[0] ).fetchone()[0]
) )
scan_stats = con.execute( scan_stats = con_cold.execute(
f""" f"""
SELECT COUNT(*)::BIGINT, COUNT(DISTINCT listing_id)::BIGINT, MIN(session_date)::VARCHAR, MAX(session_date)::VARCHAR SELECT COUNT(*)::BIGINT, COUNT(DISTINCT listing_id)::BIGINT, MIN(session_date)::VARCHAR, MAX(session_date)::VARCHAR
FROM read_parquet('{bars_glob}', hive_partitioning = true) FROM read_parquet('{bars_glob}', hive_partitioning = true)
@ -289,7 +525,19 @@ def run_benchmark(
).fetchone() ).fetchone()
total_rows_in_scan = int(scan_stats[0]) total_rows_in_scan = int(scan_stats[0])
distinct_listings_in_scan = int(scan_stats[1]) distinct_listings_in_scan = int(scan_stats[1])
con.close() finally:
con_cold.close()
# Poisoned-Vault canary test proving scan-level & signal-level Vault isolation
vault_canary = _run_poisoned_vault_canary(
curated_root=curated_root,
temp_dir=temp_dir,
start_date=start_date,
vault_cutoff_iso_date=vault_cutoff_iso_date,
vault_cutoff_iso_ts=vault_cutoff_iso_ts,
baseline_result=run1,
baseline_scan=scan_audit,
)
return { return {
"host": os.uname().nodename, "host": os.uname().nodename,
@ -301,6 +549,11 @@ def run_benchmark(
"threads": DEFAULT_DUCKDB_THREADS, "threads": DEFAULT_DUCKDB_THREADS,
"temp_directory": str(temp_dir), "temp_directory": str(temp_dir),
}, },
"cache_state_note": (
"run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; "
"run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not "
"drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root)."
),
"vault_cutoff_date": vault_cutoff_iso_date, "vault_cutoff_date": vault_cutoff_iso_date,
"vault_rows_on_disk": vault_rows_on_disk, "vault_rows_on_disk": vault_rows_on_disk,
"total_rows_in_scan": total_rows_in_scan, "total_rows_in_scan": total_rows_in_scan,
@ -308,8 +561,11 @@ def run_benchmark(
"scan_date_min": scan_stats[2], "scan_date_min": scan_stats[2],
"scan_date_max": scan_stats[3], "scan_date_max": scan_stats[3],
"nvda_pre_split_check": nvda_check, "nvda_pre_split_check": nvda_check,
"run1_cold": run1, "parquet_scan_vault_audit": scan_audit,
"run2_warm": run2, "poisoned_vault_canary": vault_canary,
"run1_fresh_conn": run1,
"run2_warm_conn": run2,
"both_runs_under_5s": bool(run1["under_5s"] and run2["under_5s"]),
} }

View file

@ -0,0 +1,288 @@
import { describe, expect, test } from 'bun:test';
import {
buildMatchReport,
composeSecurityMasterRun,
matchListingsStageB,
renderMatchReportMarkdown,
sourceCountryKey,
type StageBInput,
} from '../../apps/stock/data-pipeline/src/security-master';
import { SYNTHETIC_EOD_ISIN_PREFIX } from '../../apps/stock/data-pipeline/src/security-master/instrument-stage-a';
import type { GateOutOfScopeReason } from '../../apps/stock/data-pipeline/src/security-master/match-report';
describe('M1 security-master IB disambiguation, CEO crawl-only fallback, and gate denominator', () => {
test('enableIbTickerDisambiguation resolves ambiguous active/delisted listings and links identifier-less & reverse-split EOD listings', () => {
const input: StageBInput = {
instruments: [
{
primaryIsin: 'US0378331005',
primaryCusip: '037833100',
issuerCountry: 'US',
canonicalName: 'Apple Inc',
members: [
{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' },
{ source: 'eod', sourceId: 'AAPL_OLD.US', currency: 'USD', method: 'tier1_isin' },
{ source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' },
],
},
{
primaryIsin: `${SYNTHETIC_EOD_ISIN_PREFIX}NOISIN.US`,
primaryCusip: null,
issuerCountry: 'US',
canonicalName: 'No ISIN EOD Corp',
members: [
{
source: 'eod',
sourceId: 'NOISIN.US',
currency: 'USD',
method: 'tier3_ticker_span',
},
],
},
{
primaryIsin: 'US9999991009',
primaryCusip: '999999100',
issuerCountry: 'US',
canonicalName: 'No ISIN EOD Corp',
members: [{ source: 'ib', sourceId: '999001', currency: 'USD', method: 'tier1_isin' }],
},
{
primaryIsin: 'US00091F1066',
primaryCusip: '00091F106',
issuerCountry: 'US',
canonicalName: 'ABVC Biopharma Pre-Split',
members: [{ source: 'eod', sourceId: 'ABVC.US', currency: 'USD', method: 'tier1_isin' }],
},
{
primaryIsin: 'US00091F3047',
primaryCusip: '00091F304',
issuerCountry: 'US',
canonicalName: 'ABVC Biopharma Post-Reverse-Split',
members: [{ source: 'ib', sourceId: '555001', currency: 'USD', method: 'tier1_isin' }],
},
],
eodListings: [
{
sourceId: 'AAPL.US',
ticker: 'AAPL',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2005-01-03', lastBarDate: '2025-08-13' },
},
{
sourceId: 'AAPL_OLD.US',
ticker: 'AAPLOLD',
mic: 'OTCM',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2000-01-03', lastBarDate: '2010-01-04' },
},
{
sourceId: 'NOISIN.US',
ticker: 'NOISIN',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-08-13' },
},
{
sourceId: 'ABVC.US',
ticker: 'ABVC',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2018-01-02', lastBarDate: '2025-08-13' },
},
],
ibContracts: [
{ sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'AAPL' },
{ sourceId: '999001', conid: 999001, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'NOISIN' },
{ sourceId: '555001', conid: 555001, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'ABVC' },
],
tickerSources: [],
};
const res = matchListingsStageB(input, { enableIbTickerDisambiguation: true });
expect(res.conflicts).toEqual([]);
expect(res.stats.bySource.ib.matched).toBe(3);
expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '265598')?.listingKey.mic).toBe('XNAS');
expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '999001')?.listingKey.tickerRoot).toBe('NOISIN');
expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '555001')?.listingKey.tickerRoot).toBe('ABVC');
});
test('allowUniqueTickerFallbackForCrawlOnlyCeo links unique delisted listing but never links reused tickers', () => {
const input: StageBInput = {
instruments: [
{
primaryIsin: 'CA1111111111',
primaryCusip: null,
issuerCountry: 'CA',
canonicalName: 'Unique Delisted TSX',
members: [{ source: 'eod', sourceId: 'DELIST.TO', currency: 'CAD', method: 'tier1_isin' }],
},
{
primaryIsin: 'CA2222222222',
primaryCusip: null,
issuerCountry: 'CA',
canonicalName: 'Reused Ticker Old',
members: [{ source: 'eod', sourceId: 'REUSE_OLD.TO', currency: 'CAD', method: 'tier1_isin' }],
},
{
primaryIsin: 'CA3333333333',
primaryCusip: null,
issuerCountry: 'CA',
canonicalName: 'Reused Ticker New',
members: [{ source: 'eod', sourceId: 'REUSE_NEW.TO', currency: 'CAD', method: 'tier1_isin' }],
},
],
eodListings: [
{
sourceId: 'DELIST.TO',
ticker: 'DELIST',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2012-01-03', lastBarDate: '2021-06-30' },
},
{
sourceId: 'REUSE_OLD.TO',
ticker: 'REUSE',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2010-01-04', lastBarDate: '2018-12-31' },
},
{
sourceId: 'REUSE_NEW.TO',
ticker: 'REUSE',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2020-01-02', lastBarDate: '2023-12-29' },
},
],
ibContracts: [],
tickerSources: [
{
source: 'ceo',
sourceId: 'ceo:delist',
ticker: 'DELIST',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2025-07-01', lastBarDate: '2025-07-01' },
},
{
source: 'ceo',
sourceId: 'ceo:reuse',
ticker: 'REUSE',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2025-07-01', lastBarDate: '2025-07-01' },
},
],
};
const res = matchListingsStageB(input, { allowUniqueTickerFallbackForCrawlOnlyCeo: true });
expect(res.providerMappings.filter(m => m.source === 'ceo' && m.sourceId === 'ceo:delist')).toHaveLength(1);
expect(res.unresolved.find(u => u.source === 'ceo' && u.sourceId === 'ceo:reuse')?.reason).toBe('no_span_overlap');
});
test('buildMatchReport and composeSecurityMasterRun transparently itemize Out of Gate Scope without hiding raw totals', () => {
const stageB = matchListingsStageB({
instruments: [
{
primaryIsin: 'US0378331005',
primaryCusip: '037833100',
issuerCountry: 'US',
canonicalName: 'Apple Inc',
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
},
],
eodListings: [
{
sourceId: 'AAPL.US',
ticker: 'AAPL',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-08-13' },
},
],
ibContracts: [],
tickerSources: [
{
source: 'qm',
sourceId: 'AAPL',
ticker: 'AAPL',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2021-01-04', lastBarDate: '2025-08-13' },
},
{
source: 'qm',
sourceId: 'GHOST',
ticker: 'GHOST',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
source: 'qm',
sourceId: 'CSE1:CA',
ticker: 'CSE1',
mic: 'XCNQ',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2021-01-04', lastBarDate: '2025-08-13' },
},
],
});
const gateOutOfScope = new Map<string, GateOutOfScopeReason>([
[sourceCountryKey('qm', 'GHOST'), 'zero_bar_catalog_ghost'],
[sourceCountryKey('qm', 'CSE1:CA'), 'uncovered_venue'],
]);
const report = buildMatchReport({
stageA: {
instruments: [],
unresolved: [],
conflicts: [],
stats: {
totalRecords: 1,
totalInstruments: 1,
bySource: {
eod: { total: 1, tier1Isin: 1, tier2Cusip: 0, unresolved: 0, conflict: 0 },
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
},
},
},
stageB,
gateOutOfScope,
gateDenominatorNote: 'Custom test gate note.',
});
const qmRow = report.resolutionBySource.find(r => r.source === 'qm');
expect(qmRow?.total).toBe(3);
expect(qmRow?.matched).toBe(1);
expect(qmRow?.outOfGateScope).toBe(2);
expect(qmRow?.eligibleTotal).toBe(1);
expect(qmRow?.eligibleResolvedPct).toBe(1);
expect(report.meetsExitThresholds.equitiesResolved95).toBe(true);
const md = renderMatchReportMarkdown(report);
expect(md).toContain('## Gate Denominator Definition');
expect(md).toContain('Out of Gate Scope');
expect(md).toContain('## Out-of-Gate-Scope Breakdown');
expect(md).toContain('| qm | zero_bar_catalog_ghost | 1 |');
expect(md).toContain('| qm | uncovered_venue | 1 |');
// Ensure composeSecurityMasterRun default without applyUsCaEquityGateDenominator remains unchanged
expect(typeof composeSecurityMasterRun).toBe('function');
});
});

View file

@ -28,6 +28,7 @@ use std::io;
use bson::raw::RawDocumentBuf; use bson::raw::RawDocumentBuf;
use bson::{Bson, DateTime, Document}; use bson::{Bson, DateTime, Document};
use crate::bson_eod_prices::{parse_ymd_strict_days, MILLIS_PER_DAY};
use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES}; use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES};
use crate::events::parse_filing_timefiled; use crate::events::parse_filing_timefiled;
use crate::mongo_safety::{ use crate::mongo_safety::{
@ -115,6 +116,17 @@ impl SourceCollection {
Self::QmEarnings => Some("reportDate"), Self::QmEarnings => Some("reportDate"),
} }
} }
/// Returns `true` when the collection's [`Self::date_field`] is stored as a
/// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string.
///
/// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md`):
/// `qmEarnings.reportDate` (100% BSON `DateTime`) and `ceoShorts.timestamp`
/// (BSON `DateTime`), while `eodPrices.date`, `qmPrices.date`, `qmSplits.date`,
/// `qmDividends.date`, and `qmFilings.timefiled` are UTF-8 strings.
pub const fn date_field_is_bson_datetime(self) -> bool {
matches!(self, Self::QmEarnings | Self::CeoShorts)
}
} }
impl fmt::Display for SourceCollection { impl fmt::Display for SourceCollection {
@ -1164,8 +1176,8 @@ impl Default for MongoCliOptions {
} }
impl MongoCliOptions { impl MongoCliOptions {
/// Builds a [`MongoReadSpec`] for `collection`, attaching `key_eq` and /// Builds a [`MongoReadSpec`] for string-dated collections, attaching `key_eq`
/// optional ISO string date bounds when `apply_date_range` is `true`. /// and optional ISO string date bounds when `apply_date_range` is `true`.
pub fn to_read_spec(&self, key_eq: Option<String>, apply_date_range: bool) -> MongoReadSpec { pub fn to_read_spec(&self, key_eq: Option<String>, apply_date_range: bool) -> MongoReadSpec {
let date_range = if apply_date_range && (self.date_gte.is_some() || self.date_lt.is_some()) let date_range = if apply_date_range && (self.date_gte.is_some() || self.date_lt.is_some())
{ {
@ -1184,6 +1196,40 @@ impl MongoCliOptions {
max_doc_bytes: DEFAULT_MAX_DOC_BYTES, max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
} }
} }
/// Builds a [`MongoReadSpec`] using the collection's native BSON date representation:
/// `BsonDateTimeMillis` (UTC midnight) for BSON `DateTime` collections (`qmEarnings`,
/// `ceoShorts`) and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`,
/// `qmSplits`, `qmDividends`, `qmFilings`).
pub fn to_read_spec_for_collection(
&self,
collection: SourceCollection,
key_eq: Option<String>,
apply_date_range: bool,
) -> MongoReadSpec {
if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) {
return self.to_read_spec(key_eq, false);
}
if !collection.date_field_is_bson_datetime() {
return self.to_read_spec(key_eq, true);
}
let to_dt = |raw: &String| -> FilterDateValue {
match parse_ymd_strict_days(raw) {
Some(days) => FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY),
None => FilterDateValue::IsoString(raw.clone()),
}
};
MongoReadSpec {
key_eq,
date_range: Some(MongoDateRange {
gte: self.date_gte.as_ref().map(to_dt),
lt: self.date_lt.as_ref().map(to_dt),
}),
batch_size: self.batch_size,
limit: self.limit,
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
}
}
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1905,3 +1905,37 @@ fn error_redaction_scrubs_repeated_password_occurrences_across_message() {
"expected every occurrence to be redacted in Debug: {debug_out}" "expected every occurrence to be redacted in Debug: {debug_out}"
); );
} }
#[test]
fn cli_to_read_spec_for_collection_uses_bson_datetime_for_qm_earnings_and_iso_string_for_filings() {
let opts = super::MongoCliOptions {
date_gte: Some("2017-01-01".to_owned()),
date_lt: Some("2025-02-13".to_owned()),
..super::MongoCliOptions::default()
};
let filings_spec = opts.to_read_spec_for_collection(SourceCollection::QmFilings, None, true);
let filings_doc = build_filter_document(SourceCollection::QmFilings, &filings_spec)
.expect("qmFilings string filter must succeed");
let tf = filings_doc
.get_document("timefiled")
.expect("timefiled subdocument");
assert_eq!(tf.get("$gte"), Some(&Bson::String("2017-01-01".to_owned())));
assert_eq!(tf.get("$lt"), Some(&Bson::String("2025-02-13".to_owned())));
let earnings_spec = opts.to_read_spec_for_collection(SourceCollection::QmEarnings, None, true);
let earnings_doc = build_filter_document(SourceCollection::QmEarnings, &earnings_spec)
.expect("qmEarnings DateTime filter must succeed");
let rd = earnings_doc
.get_document("reportDate")
.expect("reportDate subdocument");
// 2017-01-01T00:00:00Z = 1483228800000 ms; 2025-02-13T00:00:00Z = 1739404800000 ms
assert_eq!(
rd.get("$gte"),
Some(&Bson::DateTime(DateTime::from_millis(1_483_228_800_000)))
);
assert_eq!(
rd.get("$lt"),
Some(&Bson::DateTime(DateTime::from_millis(1_739_404_800_000)))
);
}

View file

@ -440,8 +440,12 @@ pub fn run_curate_shorts_mongo(
pub fn run_curate_events_mongo( pub fn run_curate_events_mongo(
args: &CurateEventsMongoArgs, args: &CurateEventsMongoArgs,
) -> Result<CurateEventsRunReport, RunMongoCurateError> { ) -> Result<CurateEventsRunReport, RunMongoCurateError> {
let filings_spec = args.mongo.to_read_spec(None, true); let filings_spec = args
let earnings_spec = args.mongo.to_read_spec(None, true); .mongo
.to_read_spec_for_collection(SourceCollection::QmFilings, None, true);
let earnings_spec = args
.mongo
.to_read_spec_for_collection(SourceCollection::QmEarnings, None, true);
let client = connect_and_validate_specs( let client = connect_and_validate_specs(
&args.mongo, &args.mongo,
&[ &[