Compare commits

...

2 commits

64 changed files with 10674 additions and 374 deletions

7
.gitignore vendored
View file

@ -121,3 +121,10 @@ docs/configuration-standardization.md
# Rust
target/
# Python
__pycache__/
*.py[cod]
*.egg-info/
.pytest_cache/
.venv/

1260
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

@ -6,10 +6,11 @@ import {
} from '../normalization/bar-spans';
import { parseTickerDetailed } from '../normalization/ticker';
import { compareAscii, type ExchangeRole } from './exchange-pass1';
import type {
StageAInstrumentCandidate,
StageAMatchMethod,
StageASource,
import {
isSyntheticInstrumentKey,
type StageAInstrumentCandidate,
type StageAMatchMethod,
type StageASource,
} from './instrument-stage-a';
export const MAX_TICKER_ROOT_LENGTH = 24;
@ -44,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 {
@ -54,6 +58,7 @@ export interface StageBTickerSourceInput {
role: ExchangeRole | null;
currency?: string | null;
span: SpanDateRange | null;
name?: string | null;
}
export interface StageBSymbolChangeInput {
@ -77,6 +82,8 @@ export interface StageBInput {
export interface MatchListingsStageBOptions {
readonly spanOverlapToleranceDays?: number;
readonly enableIbTickerDisambiguation?: boolean;
readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean;
}
export interface StageBListingCandidate extends ListingNaturalKey {
@ -201,7 +208,7 @@ interface StagedIbCandidate {
currency: string;
conid: number;
primaryExchange: string | null;
method: StageAMatchMethod;
method: StageBMatchMethod;
}
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
@ -216,8 +223,15 @@ function isStageASourceValue(value: unknown): value is StageASource {
return value === 'ib' || value === 'eod';
}
function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod {
return value === 'tier1_isin' || value === 'tier2_cusip';
function isStageAMatchMethodValue(
value: unknown,
allowSyntheticTier3 = false
): value is StageAMatchMethod {
return (
value === 'tier1_isin' ||
value === 'tier2_cusip' ||
(allowSyntheticTier3 && value === 'tier3_ticker_span')
);
}
function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource {
@ -658,7 +672,8 @@ export function matchListingsStageB(
`Invalid empty or non-string sourceId at instruments[${i}].members[${j}]`
);
}
if (!isStageAMatchMethodValue(member.method)) {
const isSyntheticInst = isSyntheticInstrumentKey(inst.primaryIsin);
if (!isStageAMatchMethodValue(member.method, isSyntheticInst)) {
throw new Error(
`Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]`
);
@ -865,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[] = [];
@ -1006,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) {
@ -1143,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({
@ -1190,7 +1294,7 @@ export function matchListingsStageB(
currency,
conid: contract.conid,
primaryExchange,
method: member.method,
method: matchMethod,
});
}
}
@ -1483,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,

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 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) {

View file

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

View file

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

View file

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

View file

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

View file

@ -355,6 +355,17 @@
"typescript": "^5.3.0",
},
},
"libs/data/duckdb": {
"name": "@stock-bot/duckdb",
"version": "1.0.0",
"dependencies": {
"@duckdb/node-api": "^1.4.4-r.1",
"@stock-bot/research": "workspace:*",
},
"devDependencies": {
"@types/node": "^20.11.0",
},
},
"libs/data/mongodb": {
"name": "@stock-bot/mongodb",
"version": "1.0.0",
@ -540,6 +551,22 @@
"@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="],
"@duckdb/node-api": ["@duckdb/node-api@1.4.4-r.4", "", { "dependencies": { "@duckdb/node-bindings": "1.4.4-r.4" } }, "sha512-yUotG8wPSmmEFxAODt07rXJZgV2fhvzhnZX3wrMspQNEaNVwXArzakgKyfakZkYL9me7SK9eDnXYv/XbdifWEg=="],
"@duckdb/node-bindings": ["@duckdb/node-bindings@1.4.4-r.4", "", { "optionalDependencies": { "@duckdb/node-bindings-darwin-arm64": "1.4.4-r.4", "@duckdb/node-bindings-darwin-x64": "1.4.4-r.4", "@duckdb/node-bindings-linux-arm64": "1.4.4-r.4", "@duckdb/node-bindings-linux-x64": "1.4.4-r.4", "@duckdb/node-bindings-win32-arm64": "1.4.4-r.4", "@duckdb/node-bindings-win32-x64": "1.4.4-r.4" } }, "sha512-JYjCaZmqvqrjFBjT3Q6jnb3OFz26lAUTFXUka/HQRxWRy23ZiURZwPYMLkyFBLHa696hNlC85M/EWXDRFnDIfg=="],
"@duckdb/node-bindings-darwin-arm64": ["@duckdb/node-bindings-darwin-arm64@1.4.4-r.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ozQbuBlV+01WzyXcqXjEV3TbN+qQ8UcelwPmQaqBn86pdXQHuYGuS8K9a5yATsg+JvivqHQSb95OBHdP7FYDkA=="],
"@duckdb/node-bindings-darwin-x64": ["@duckdb/node-bindings-darwin-x64@1.4.4-r.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-quoPmg26/fpLM80UNMXYSYKGnXJUiqKTSlDIgONQiMVYXJqPc2yz9qwcTuZgaQx7JhD2m1D/cc+h/4d8yVD79Q=="],
"@duckdb/node-bindings-linux-arm64": ["@duckdb/node-bindings-linux-arm64@1.4.4-r.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ve+kJ9+IqF5VBNWDzlUeg1xxKGHGqT9MJPxjRTSULgCpguL9ok13Klhw7WJQOs5ycB+osQe/40t5hOZk3cK82g=="],
"@duckdb/node-bindings-linux-x64": ["@duckdb/node-bindings-linux-x64@1.4.4-r.4", "", { "os": "linux", "cpu": "x64" }, "sha512-jBTL/WvfwxLToFa/pVHfT6elMtltJGnc3wSuxZD9OfMltit9YUdVFS37vBFQzXMT1Z8OWjtSjMh+zPKxOwHLHA=="],
"@duckdb/node-bindings-win32-arm64": ["@duckdb/node-bindings-win32-arm64@1.4.4-r.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-4tqE7r1c4wCqgm1iBfW/rP6B67nkHK1Pyj6dT8T3aqupKk2eV0QgKPBYtGOqOlE+jdhj4El9WKye7eTJ59yjZQ=="],
"@duckdb/node-bindings-win32-x64": ["@duckdb/node-bindings-win32-x64@1.4.4-r.4", "", { "os": "win32", "cpu": "x64" }, "sha512-lclo7ZibsYuCHd0ru5j9sw9x+wfXWOiNWIOjW3rcX9675xD7j4CB3RlWfZkBgdajLuXtRuo5FFfQZY249a7IlA=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="],
@ -704,6 +731,8 @@
"@stock-bot/di": ["@stock-bot/di@workspace:libs/core/di"],
"@stock-bot/duckdb": ["@stock-bot/duckdb@workspace:libs/data/duckdb"],
"@stock-bot/engine": ["@stock-bot/engine@workspace:apps/stock/engine"],
"@stock-bot/handler-registry": ["@stock-bot/handler-registry@workspace:libs/core/handler-registry"],

View file

@ -22,7 +22,7 @@ Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, D
| `eodFinancialsOLD` (`2.98M`), `eodFundamentalsOLD` (`106.6k`) | `eodFinancialsOLD` sets `filingDate == reportDate` on **`99.26%`** of rows. `eodFundamentalsOLD` has `filing_date: null`, unversioned current valuation ratios, and mislabels USD figures as `"CAD"` on NEO CDRs (`AAPL` CDR `$335B` assets). | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` from all backtests.** Use `eodFinancialsOLD` only for pre-QM historical backfill with mandatory statutory lag (ignoring its `filingDate`). |
| `qmFilings` (`30.52M`) | Has exact second-level `timefiled` (`"2025-01-31T06:01:27 EST"`) for both US EDGAR (`10-Q`, `10-K`, `8-K`, `4`, `144`) and **Canadian SEDAR+** (`Interim financial statements/report`, `Annual financial statements`, `MD&A`, `52-109`, `NI 43-101`, `45-106F1`). Metadata + external download URLs only (no parsed Form 4 share counts). | Primary `known_at` clock for `qmFinancials` and `qmEarnings`, plus standalone filing-arrival/form-type event stream. Convert `EST`/`EDT` strings cleanly using `America/New_York` rules. |
| `qmEarnings` (`444.9k`) | `66.94%` (`297,779`) have `announceTime="N/A"` (`80,481` `AMC`, `66,605` `BTO`); `consensusEps` is overwritten post-hoc. | Link to same-day `qmFilings` `8-K` / `News release` `timefiled`; if still unknown, set `known_at = reportDate 16:05 ET` (tradable `T+1` open). |
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; never rely on `eodSymbolChange` for multi-year ticker history. |
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`; empirically across `16,892/16,892` rows with numeric `forfactor`/`tofactor` (`100%`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g. `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; invert QuoteMedia `qmSplits` to canonical `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1) else `1 / splitratio`; never rely on `eodSymbolChange` for multi-year ticker history. |
| `teData` (`14.8k`), `teMarketData` (`435`), `CAD.FOREX` | `teData` has `{d, v}` final-revised values only (no release dates/vintages). `CAD.FOREX` (`eodPrices` `12,109` 1d, `eodIntraday1M` `5.20M` 1m) + `teMarketData.USDCAD` (`2,865` 1d through Apr 2026) already provide complete USD/CAD history. | Lag `teData` (`+1d` central-bank rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP) for coarse regime filters only. Curate `CAD.FOREX` + `teMarketData.USDCAD` directly into `fx_1d` and `fx_1m`. |
---
@ -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.
### 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

View file

@ -0,0 +1,78 @@
{
"summary": {
"adjustment": "total",
"ca_bars_rows": 8446226,
"ca_shorts_rows": 459930,
"ca_filings_rows": 725435,
"shorts_panel_rows": 4541173,
"vault_bar_leaks": 0
},
"shorts_trial": {
"trial_id": 1,
"created_at": "2026-11-30T15:16:14.251727+00:00",
"expression_hash": "b8d63783a3803087c922ce7fe332340264db340f8d7de1b78cfaab097c17e938",
"n_obs": 1983,
"sharpe_unann": 0.10055685659710986,
"skewness": -0.1559440430924711,
"kurtosis": 15.987384989738644
},
"shorts_dsr": {
"trial_id": 1,
"cluster_size": 1,
"effective_trials": 1.0,
"mean_correlation": null,
"pairs_used": 0,
"pairs_skipped": 0,
"sr0": 0.0,
"standard_error": 0.023055762683025283,
"dsr": 0.9999935402185955,
"passes_gate": true
},
"shorts_mean_rank_ic": 0.00694633488509233,
"shorts_rank_ic_nw_t": 2.7256714674429414,
"shorts_mean_spread": 0.010679776876364164,
"shorts_turnover": 0.40718536083796214,
"shorts_recency": {
"pass": true,
"reason": "passed",
"pre_n": 1456,
"post_n": 527,
"pre_mean": 0.006950115972062361,
"post_mean": 0.006935888466442682,
"ratio": 0.9979529110482659
},
"filings_trial": {
"trial_id": 2,
"created_at": "2026-11-30T15:16:17.977209+00:00",
"expression_hash": "c642ca87d95bb8436045ba34a231096d74df559f0e3baf91962ba0adbe3151da",
"n_obs": 885,
"sharpe_unann": -0.08030767099801248,
"skewness": -9.933468390420595,
"kurtosis": 115.43676350904063
},
"filings_dsr": {
"trial_id": 2,
"cluster_size": 2,
"effective_trials": 2.0,
"mean_correlation": null,
"pairs_used": 0,
"pairs_skipped": 1,
"sr0": 0.06647178849749248,
"standard_error": 0.02091720841503682,
"dsr": 1.1320926489926893e-12,
"passes_gate": false
},
"filings_events_used": 101522,
"filings_n_dates": 885,
"filings_car_mean": -0.022160113638103773,
"filings_car_nw_t": -1.1695875860209246,
"filings_recency": {
"pass": false,
"reason": "sign_flipped",
"pre_n": 615,
"post_n": 270,
"pre_mean": 0.002165839268979803,
"post_mean": -0.07756922859312747,
"ratio": -35.81485925761503
}
}

View file

@ -0,0 +1,117 @@
{
"host": "quant",
"curated_root": "/mnt/data/stockbot/m1-isolated/curated",
"duckdb_version": "1.5.6",
"polars_version": "1.44.2",
"duckdb_budget": {
"memory_limit": "6GB",
"threads": 4,
"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_rows_on_disk": 3363755,
"total_rows_in_scan": 78588295,
"distinct_listings_in_scan": 59096,
"scan_date_min": "2005-01-03",
"scan_date_max": "2025-02-12",
"nvda_pre_split_check": {
"listing_id": 20815,
"pre_split_2024_06_07": {
"close": 1208.88,
"raw_volume": 41238577.6,
"dollar_volume": 49852491689.088005,
"currency": "USD"
},
"post_split_2024_06_10": {
"close": 121.79,
"raw_volume": 314162688.0,
"dollar_volume": 38261873771.520004,
"currency": "USD"
},
"qm_pre_split_dollar_volume": 49852494590.4,
"rel_diff": 5.81979301196025e-08,
"within_1pct": true
},
"parquet_scan_vault_audit": {
"explain_analyze_latency_secs": 4.2861,
"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,
"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.020400683140664375,
"ratio": 1.1229725177354413
},
"sharpe_unann": 0.05117,
"sharpe_ann": 0.8123,
"newey_west_t_stat": 2.0292,
"newey_west_p_value": 0.042434,
"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

@ -0,0 +1,167 @@
# Source Field Shapes Report
- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)
- **Sample limit per collection:** 1000
- **Collections probed:** 8
- **Total documents sampled:** 7435
## `ceoShorts` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-23T03:58:26.303Z`, `2025-06-23T03:58:27.035Z`, `2025-06-23T03:58:27.655Z` |
| `id` | 100.0% (1000/1000) | int: 1000 | — | `101986246`, `101986286`, `101986333` |
| `issue_name` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 18..37) | `AAJ CAPITAL 3 CORP.`, `ABERDEEN INTERNATIONAL INC. J`, `ADDED CAPITAL INC.` |
| `market` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..2) | `TO`, `V` |
| `net_change` | 100.0% (1000/1000) | int: 1000 | — | `-10`, `-100`, `-1000` |
| `number_of_shares` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1`, `10` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..12) | `A.V`, `AA.V`, `AAA-P.V` |
| `timestamp` | 100.0% (1000/1000) | double: 1000 | — | `1492239600000`, `1493535600000`, `1494831600000` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-26T19:28:57.102Z`, `2025-06-26T19:28:57.127Z`, `2025-06-26T19:28:57.129Z` |
## `eodPrices` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `adjustedClose` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `close` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-07-11T02:13:56.412Z`, `2025-07-11T02:13:56.492Z`, `2025-07-11T02:13:56.694Z` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2020-12-19`, `2020-12-20`, `2020-12-21` |
| `eodSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 11..14) | `$ADS-USD.CC`, `$AFLOKI-USD.CC`, `$ANRX-USD.CC` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `CC` |
| `high` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `low` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `open` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 8..11) | `$ADS-USD`, `$AFLOKI-USD`, `$ANRX-USD` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-08-13T14:09:20.036Z`, `2025-08-13T14:09:20.106Z`, `2025-08-13T14:09:20.135Z` |
| `volume` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1000242`, `1006139` |
## `qmDividends` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `amount` | 100.0% (1000/1000) | int: 10, double: 990 | — | `0`, `0.01`, `0.01167` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.799Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.069Z` |
| `currency` | 92.8% (928/1000) | string: 928 | other: 928 (len 3..3) | `CAD`, `USD` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1987-03-31`, `1987-06-01`, `1987-06-25` |
| `declared` | 96.5% (965/1000) | string: 965 | ymd: 965 (len 10..10) | `1987-03-25`, `1987-05-21`, `1987-05-27` |
| `divflag` | 6.2% (62/1000) | string: 62 | other: 62 (len 2..2) | `EX`, `FI`, `SP` |
| `divtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `D`, `S` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `NGS`, `NSC`, `NSD` |
| `frequency` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `A`, `I`, `M` |
| `indicatedrate` | 66.0% (660/1000) | double: 660 | — | `0.01`, `0.01167`, `0.0125` |
| `payable` | 99.7% (997/1000) | string: 997 | ymd: 997 (len 10..10) | `1987-04-20`, `1987-07-01`, `1987-07-20` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..9) | `DBM:CA`, `DCM:CA`, `DHT.U:CA` |
| `qualified` | 22.6% (226/1000) | string: 226 | other: 226 (len 1..1) | `N`, `Q` |
| `record` | 99.6% (996/1000) | string: 996 | ymd: 996 (len 10..10) | `1987-04-06`, `1987-06-05`, `1987-07-01` |
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1987-03-31T00:00:00.000Z`, `1987-06-01T00:00:00.000Z`, `1987-06-25T00:00:00.000Z` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..8) | `DBM`, `DCM`, `DHT.U` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.080Z`, `2025-06-29T22:25:29.146Z`, `2025-06-29T22:25:29.148Z` |
| `usdFxRate` | 25.6% (256/1000) | int: 253, double: 3 | — | `0.05`, `1`, `1.39556` |
## `qmEarnings` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `actualEps` | 100.0% (1000/1000) | string: 73, int: 34, double: 893 | other: 73 (len 3..3) | `-0.01`, `-0.02`, `-0.03` |
| `announceTime` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `AMC`, `BTO`, `N/A` |
| `consensusEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.864Z`, `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z` |
| `epsSurpriseDollar` | 100.0% (1000/1000) | string: 359, int: 66, double: 575 | other: 359 (len 3..3) | `-0.0033`, `-0.005`, `-0.01` |
| `epsSurprisePercent` | 100.0% (1000/1000) | string: 366, int: 147, double: 487 | other: 366 (len 3..3) | `-0.6944`, `-0.7123`, `-0.8065` |
| `estimatedEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX`, `NGS`, `NSC` |
| `numOfEstimates` | 100.0% (1000/1000) | string: 42, int: 958 | other: 42 (len 3..3) | `0`, `1`, `10` |
| `period` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..7) | `N/A`, `Q1 1995`, `Q1 1996` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..8) | `DLCG:CA`, `DPM:CA`, `DSV:CA` |
| `quarterEnd` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1994-09-30`, `1994-12-31`, `1995-03-31` |
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1994-10-26T00:00:00.000Z`, `1994-10-27T00:00:00.000Z`, `1994-11-02T00:00:00.000Z` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..5) | `DLCG`, `DPM`, `DSV` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z`, `2025-06-29T22:25:29.167Z` |
## `qmFilings` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `acc` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 36..151) | `01521843-00000001-00002586-s@#91#91761#SEDAR#...`, `01521972-00000001-00002586-s@#91#91761#SEDAR#...`, `01523099-00000001-00002586-s@#93#93810#SEDAR#...` |
| `datefiled` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX` |
| `filingDate` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` |
| `filingId` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 24..24) | `5e6b93561f348f7b9159eb20`, `5e6b94221f348f7b9159fa0b`, `5e6b94221f348f7b9159fa0c` |
| `formdescription` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..72) | `52-109F2R - Certification of refiled interim ...`, `52-109FV1 - Certification of annual filings -...`, `52-109FV2 - Certification of interim filings ...` |
| `formgroup` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 19..38) | `Continuous Disclosure`, `Continuous disclosure`, `Exempt Market Offerings and Disclosure` |
| `formtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 21..21) | `002-001-001012-000052`, `002-001-001012-000054`, `002-001-001012-001002` |
| `htmllink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 225..312) | `https://app.quotemedia.com/datatool/downloadF...` |
| `pages` | 100.0% (1000/1000) | int: 1000 | — | `1`, `10`, `11` |
| `pdflink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 224..311) | `https://app.quotemedia.com/datatool/downloadF...` |
| `size` | 100.0% (1000/1000) | null: 1000 | — | — |
| `source` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `QM` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..6) | `AAC.P`, `ACAP.P`, `ACOP` |
| `timefiled` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 23..23) | `2010-01-06T03:00:00 EST`, `2010-01-07T03:00:00 EST`, `2010-01-12T03:00:00 EST` |
## `qmPrices` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `change` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.001851`, `-0.001877`, `-0.003661` |
| `changepercent` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.007`, `-0.008`, `-0.014` |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:05:12.787Z` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2021-07-06`, `2021-07-07`, `2021-07-08` |
| `dateTime` | 100.0% (1000/1000) | date: 1000 | — | `2021-07-06T00:00:00.000Z`, `2021-07-07T00:00:00.000Z`, `2021-07-08T00:00:00.000Z` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `TSX` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..4) | `X:CA` |
| `sharevolume` | 100.0% (1000/1000) | int: 1000 | — | `100159`, `100168`, `100494` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `X` |
| `unadjustedclose` | 100.0% (1000/1000) | int: 29, double: 971 | — | `122.8`, `123.04`, `123.11` |
| `unadjustedhigh` | 100.0% (1000/1000) | int: 30, double: 970 | — | `123.85`, `124.4`, `124.76` |
| `unadjustedlow` | 100.0% (1000/1000) | int: 29, double: 971 | — | `121.42`, `121.9`, `122.24` |
| `unadjustedopen` | 100.0% (1000/1000) | int: 38, double: 962 | — | `122.02`, `122.24`, `122.7` |
| `unadjustedvwap` | 100.0% (1000/1000) | double: 1000 | — | `122.6259`, `123.1946`, `123.6024` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:59:43.948Z` |
## `qmSplits` (1000 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.834Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z` |
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1972-06-21`, `1973-04-23`, `1976-07-26` |
| `declared` | 40.8% (408/1000) | string: 408 | ymd: 408 (len 10..10) | `1978-11-29`, `1979-03-02`, `1979-04-16` |
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..5) | `CDX`, `CNQ`, `EXPM` |
| `forfactor` | 100.0% (1000/1000) | string: 114, int: 867, double: 19 | emptyOrWhitespace: 114 (len 0..0) | <code></code>, `1`, `1.024549` |
| `payment` | 38.2% (382/1000) | string: 382 | ymd: 382 (len 10..10) | `1969-12-31`, `1979-01-05`, `1979-04-06` |
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..12) | `A`, `AAUC:CA`, `ABRA:CA` |
| `record` | 38.1% (381/1000) | string: 381 | ymd: 381 (len 10..10) | `1969-12-31`, `1978-12-12`, `1979-03-15` |
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1972-06-21T00:00:00.000Z`, `1973-04-23T00:00:00.000Z`, `1976-07-26T00:00:00.000Z` |
| `splitratio` | 100.0% (1000/1000) | int: 305, double: 695 | — | `0.005`, `0.01`, `0.029129` |
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..9) | `A`, `AAUC`, `ABRA` |
| `tofactor` | 100.0% (1000/1000) | string: 114, int: 745, double: 141 | emptyOrWhitespace: 114 (len 0..0) | <code></code>, `0.067967`, `0.3333` |
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z`, `2025-06-29T22:25:29.147Z` |
## `teMarketData` (435 docs sampled)
| Field | Presence | Types | String Patterns | Examples |
| --- | --- | --- | --- | --- |
| `_id` | 100.0% (435/435) | objectId: 435 | — | — |
| `category` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` |
| `createdAt` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
| `daily` | 100.0% (435/435) | array: 435 | — | — |
| `frequency` | 100.0% (435/435) | string: 435 | other: 435 (len 5..8) | `daily`, `intraday` |
| `fullName` | 100.0% (435/435) | string: 435 | other: 435 (len 3..48) | `Abu Dhabi General`, `Aluminum`, `Amman Stock Exchange General Index` |
| `industry` | 100.0% (435/435) | null: 435 | — | — |
| `lastUpdated` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
| `monthly` | 100.0% (435/435) | array: 435 | — | — |
| `name` | 100.0% (435/435) | string: 435 | other: 435 (len 2..28) | `ADX General`, `ASE`, `ASPI` |
| `sector` | 100.0% (435/435) | null: 435 | — | — |
| `symbolType` | 100.0% (435/435) | string: 435 | other: 435 (len 3..3) | `com`, `cur`, `gov` |
| `teSymbol` | 100.0% (435/435) | string: 435 | other: 435 (len 2..11) | `ADSMI`, `AEX`, `AS51` |
| `ticker` | 100.0% (435/435) | null: 435 | — | — |
| `type` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` |
| `unit` | 100.0% (435/435) | string: 293, null: 142 | other: 293 (len 3..19) | `AUD/100Kg`, `BRL/Kgs`, `CNY/KG` |
| `updated_at` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |

View file

@ -0,0 +1,332 @@
# Security Master Match & Conflict Report
## Exit Thresholds
| Criterion | Status | Target |
| --- | --- | --- |
| Exchanges Mapped | PASS | 100.00% |
| Equities Resolved (Eligible) | PASS | >= 95.00% |
## Exchange Coverage
| Mapped | Unresolved | Total | Mapped % |
| --- | --- | --- | --- |
| 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
| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| eod | 66258 | 65970 | 288 | 0 | 288 | 0 | 65970 | 99.57% | 100.00% |
| ib | 18402 | 16882 | 1449 | 71 | 0 | 1165 | 17237 | 91.74% | 97.94% |
| qm | 47140 | 23394 | 23724 | 22 | 11259 | 11790 | 24091 | 49.63% | 97.11% |
| 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
| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| AU | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% |
| BM | 13 | 0 | 13 | 0 | 0 | 13 | 0.00% | 0.00% |
| CA | 25221 | 18044 | 7148 | 29 | 0 | 25221 | 71.54% | 71.54% |
| IE | 2 | 0 | 1 | 1 | 0 | 2 | 0.00% | 0.00% |
| IL | 4 | 0 | 4 | 0 | 0 | 4 | 0.00% | 0.00% |
| JE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| JP | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
| KY | 51 | 0 | 34 | 17 | 0 | 51 | 0.00% | 0.00% |
| MH | 6 | 0 | 5 | 1 | 0 | 6 | 0.00% | 0.00% |
| NL | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% |
| SG | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% |
| US | 104021 | 93106 | 10861 | 54 | 6 | 104015 | 89.51% | 89.51% |
| VI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
## Unresolved by Reason
### Stage A
| Source | Reason | Count |
| --- | --- | --- |
| ib | missing_identifiers | 4 |
### Stage B
| Source | Reason | Count |
| --- | --- | --- |
| ceo | invalid_ticker | 17 |
| ceo | no_matching_listing | 4141 |
| eod | composite_venue | 288 |
| ib | invalid_currency | 24 |
| ib | no_listing_for_currency | 1421 |
| qm | ats_routing_venue | 8283 |
| qm | composite_venue | 2976 |
| qm | invalid_ticker | 1 |
| qm | missing_span | 10221 |
| qm | no_matching_listing | 2204 |
| qm | no_span_overlap | 39 |
## Conflicts by Pass & Kind
| Pass | Conflict Kind | Count |
| --- | --- | --- |
| pass4 | price_low_correlation | 197 |
| pass4 | price_ratio_mismatch | 312 |
| stage_a | isin_cusip_mismatch | 1 |
| stage_b | ambiguous_ib_listing | 30 |
| stage_b | ambiguous_ticker_span | 22 |
| stage_b | competing_ib_conid | 40 |
| stage_b | duplicate_source_id | 10 |
## Pass 4 Price Cross-Check Verdicts
- Pairs In: 65231
- Invalid Pairs: 0
- Conflicts Emitted: 509
| Verdict | Count |
| --- | --- |
| unsupported_currency_pair | 0 |
| insufficient_data | 60599 |
| ratio_mismatch | 312 |
| low_correlation | 197 |
| confirmed | 4123 |
## Pass 6 Delisting Chain Outcomes
- Total Input Listings: 65970
- Processed Listings: 65970
- Continuities Created: 95
- Conflicts Detected: 0
| Outcome | Count |
| --- | --- |
| active | 25956 |
| moved_to_otc | 95 |
| bankruptcy_cancelled | 590 |
| unknown_involuntary | 39329 |
## Conflict Sample
| Pass | Source | Source ID | Conflict Kind | Detail |
| --- | --- | --- | --- | --- |
| pass4 | eod | AAPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AAPL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4923,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AAPL"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | ABLT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABLT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9623,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABLT"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | ABM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2871,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABM"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | ABR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6267,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABR"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | ABT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABT.US"},"medianRatio":1.0000009402030838,"minCorrelation":0.9,"priceCorr":0.653,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABT"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ACD.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ACD.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.768,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ACD:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | ADM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8875,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADM"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ADX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6527,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADX"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | AFG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AFG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8974,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AFG"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | AG.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AG.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8279,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AG:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | AGFXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AGFXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3573,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AGFXF"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | ALXN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ALXN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4186,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ALXN"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | AMAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6599,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMAT"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | AMGN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMGN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8658,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMGN"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | APD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"APD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7669,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"APD"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ARX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ARX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8297,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ARX:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | ASG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ASG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8475,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ASG"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | AUQ.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AUQ.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5609,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AUQ:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | AVU.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AVU.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.415,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AVU:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | AVY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AVY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.888,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AVY"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | B.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"B.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8517,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"B"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BCE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BCE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2712,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BCE:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | BEN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BEN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8754,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BEN"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BKH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.829,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKH"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5579,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | BKTI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKTI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8971,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKTI"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BLM.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BLM.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BLM:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | BMGP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BMGP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BMGP"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | BN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BN.TO"},"medianRatio":0.9924867905232657,"minCorrelation":0.9,"priceCorr":0.7976,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BN:CA"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | BN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BN.US"},"medianRatio":0.9930629800660156,"minCorrelation":0.9,"priceCorr":0.8718,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BN"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | BNSOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BNSOF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BNSOF"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | BOH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BOH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8681,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BOH"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | BTO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BTO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7832,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BTO"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | BYDDY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BYDDY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BYDDY"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | CAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8615,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CAT"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | CCK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CCK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8453,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CCK"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | CFW.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CFW.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7823,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CFW:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | CGNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CGNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8472,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CGNX"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | CINF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CINF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5966,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CINF"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | CIX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CIX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7309,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CIX:CA"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | CL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7174,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CL"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | CMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8188,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CMT"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | COV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"COV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2511,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"COV:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | CRRX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CRRX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7485,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CRRX:CA"},"usableDates":8,"verdict":"low_correlation"} |
| pass4 | eod | CSCO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CSCO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5838,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CSCO"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | CTAS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CTAS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.833,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CTAS"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | DF.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DF.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8822,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DF:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | DGICB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DGICB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7254,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DGICB"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | DHR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DHR.US"},"medianRatio":1.0000008038585209,"minCorrelation":0.9,"priceCorr":0.7251,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DHR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | DIS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DIS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6493,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DIS"},"usableDates":23,"verdict":"low_correlation"} |
| pass4 | eod | DMI.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DMI.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7968,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DMI:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | DOC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DOC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5946,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DOC"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | DS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4049,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DS:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | DTE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7957,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTE"},"usableDates":20,"verdict":"low_correlation"} |
| pass4 | eod | DTRK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTRK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7845,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTRK"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | EA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8582,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EA"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | EAPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EAPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EAPH"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | EBIXQ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EBIXQ.US"},"medianRatio":0.9984378853901176,"minCorrelation":0.9,"priceCorr":0.8049,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EBIXQ"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | EEA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EEA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8994,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EEA"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | EIT-UN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EIT-UN.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2739,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EIT.UN:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | EIX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EIX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8568,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EIX"},"usableDates":19,"verdict":"low_correlation"} |
| pass4 | eod | EKG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EKG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EKG:CA"},"usableDates":8,"verdict":"low_correlation"} |
| pass4 | eod | EMR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EMR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8167,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EMR"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | ENS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ENS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2394,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ENS"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | ERIC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ERIC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ERIC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | ETR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ETR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8864,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ETR"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | EXC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EXC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6761,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EXC"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | EXG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EXG.V"},"medianRatio":1.0128205128205128,"minCorrelation":0.9,"priceCorr":0.8849,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EXG:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | FAST.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FAST.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FAST"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | FE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FE"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | FI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5734,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FI"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | FLO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FLO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6659,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FLO"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | FTFT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FTFT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FTFT"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | FTU.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"FTU.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7131,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"FTU:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | GAB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GAB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GAB"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | GLW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GLW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5909,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GLW"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | GMGI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GMGI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GMGI"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | GPC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GPC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.893,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GPC"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | GR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0751,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GR:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | GSY.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GSY.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.821,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GSY:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | GWO.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GWO.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4038,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GWO:CA"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | GWW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GWW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8347,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GWW"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | HD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3437,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HD"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | HE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8973,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HE"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | HERC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HERC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9709,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HERC"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | HMSY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HMSY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8013,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HMSY"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | HON.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HON.US"},"medianRatio":0.9985665897393179,"minCorrelation":0.9,"priceCorr":0.7848,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HON"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | HRB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HRB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7753,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HRB"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | IAF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IAF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8914,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IAF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | IBM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IBM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8969,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IBM"},"usableDates":23,"verdict":"low_correlation"} |
| pass4 | eod | IDXX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IDXX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7758,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IDXX"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | INVI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"INVI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8356,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"INVI"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | INX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"INX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1372,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"INX:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | IP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IP.US"},"medianRatio":1.0000015837820717,"minCorrelation":0.9,"priceCorr":0.8714,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IP"},"usableDates":20,"verdict":"low_correlation"} |
| pass4 | eod | IPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8854,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IPG"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | J.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"J.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"J"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | JHI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2883,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHI"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | JHS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5039,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHS"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | JNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JNJ"},"usableDates":20,"verdict":"low_correlation"} |
| pass4 | eod | JPM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JPM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6225,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JPM"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | K.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"K.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"K"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | KNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3071,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KNX"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | KO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KO"},"usableDates":23,"verdict":"low_correlation"} |
| pass4 | eod | KTN.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"KTN.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1622,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"KTN:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | LB.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"LB.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7835,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"LB:CA"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | LIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8716,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LIN"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | LOW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LOW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.692,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LOW"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | LTTC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LTTC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7122,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LTTC"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | MAG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5247,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAG"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | MAH.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"MAH.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8872,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"MAH:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | MAKOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAKOF.US"},"medianRatio":1.0010373443983402,"minCorrelation":0.9,"priceCorr":-0.3094,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAKOF"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | MAR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAR.US"},"medianRatio":1.0000850013709899,"minCorrelation":0.9,"priceCorr":0.878,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAR"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | MAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAT"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | MCD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8111,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCD"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | MCHP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCHP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7736,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCHP"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | MG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8326,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MG"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | MGF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3548,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | MGRC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGRC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8632,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGRC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | MIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2315,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MIN"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | MMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0508,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MMT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | MRNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MRNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4307,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MRNJ"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | MU.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MU.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.887,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MU"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NCA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NCA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6143,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NCA"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | NDSN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NDSN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8823,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NDSN"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NEV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NEV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4241,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NEV:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | NEWH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NEWH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3492,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NEWH"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | NGG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NGG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NGG"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | NHC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NHC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7198,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NHC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NJR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NJR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7038,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NJR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | NSC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NSC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8787,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NSC"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | NTRS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NTRS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8915,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NTRS"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NUV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NUV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6387,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NUV"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | NVO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NVO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8002,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NVO"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | NWX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NWX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8847,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NWX:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | NZP.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NZP.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8469,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NZP:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | ODX-H.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ODX-H.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7014,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ODX.H:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | OMVKY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"OMVKY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"OMVKY"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | ORCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8616,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORCL"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | ORI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8524,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORI"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | ORN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0519,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORN"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | PAYX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PAYX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8645,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PAYX"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PBI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PBI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8444,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PBI"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5439,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PCH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCH"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | PDLI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PDLI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PDLI"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | PDV.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PDV.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PDV:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | PEG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.852,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEG"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | PEO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8323,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEO"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PFE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PFE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8302,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PFE"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.841,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PG"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PGR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PGR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7961,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PGR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4549,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PIM"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PNC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PNC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7715,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PNC"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPG"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PPL.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PPL.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6331,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PPL:CA"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | PPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPL.US"},"medianRatio":0.9962860635696822,"minCorrelation":0.9,"priceCorr":0.7763,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPL"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | PPT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5062,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | PSHG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSHG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.897,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSHG"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | PSYC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSYC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0099,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSYC"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | PTE.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PTE.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7833,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PTE:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | PTVCB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PTVCB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4213,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PTVCB"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | QNC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"QNC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"QNC:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | RDI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RDI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8088,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RDI"},"usableDates":8,"verdict":"low_correlation"} |
| pass4 | eod | RJF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RJF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4954,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RJF"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | ROG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ROG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8908,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ROG"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SABA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SABA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5922,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SABA"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | SBR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SBR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4564,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SBR"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | SCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6328,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SCL"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SDR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SDR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8406,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SDR:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | SGC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SGC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5532,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SGC"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SHW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SHW.US"},"medianRatio":1.0000010134792743,"minCorrelation":0.9,"priceCorr":0.7152,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SHW"},"usableDates":15,"verdict":"low_correlation"} |
| pass4 | eod | SIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SIM"},"usableDates":9,"verdict":"low_correlation"} |
| pass4 | eod | SKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8894,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SKT"},"usableDates":12,"verdict":"low_correlation"} |
| pass4 | eod | SO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7559,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SO"},"usableDates":16,"verdict":"low_correlation"} |
| pass4 | eod | SPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0746,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SPH"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | SR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5368,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SR"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | SR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SR.V"},"medianRatio":1.0121951219512195,"minCorrelation":0.9,"priceCorr":0.4701,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SR:CA"},"usableDates":6,"verdict":"low_correlation"} |
| pass4 | eod | SRC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1692,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRC:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | SRG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7455,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRG:CA"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | SSV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SSV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6213,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SSV:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | SWZ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SWZ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7802,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SWZ"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | SYY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SYY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SYY"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | T.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"T.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7822,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"T"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | TCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.836,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCF"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | TCI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2847,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCI"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | TFX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TFX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TFX"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | TIGO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TIGO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3913,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TIGO"},"usableDates":11,"verdict":"low_correlation"} |
| pass4 | eod | TJX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TJX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8876,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TJX"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | TLGPY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TLGPY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6001,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TLGPY"},"usableDates":10,"verdict":"low_correlation"} |
| pass4 | eod | TMBXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TMBXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7082,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TMBXF"},"usableDates":5,"verdict":"low_correlation"} |
| pass4 | eod | UHT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UHT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UHT"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | UNM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8065,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNM"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | UNP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7949,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNP"},"usableDates":17,"verdict":"low_correlation"} |
| pass4 | eod | URE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"URE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8376,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"URE:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | UVV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UVV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8327,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UVV"},"usableDates":14,"verdict":"low_correlation"} |
| pass4 | eod | VQS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"VQS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7545,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"VQS:CA"},"usableDates":7,"verdict":"low_correlation"} |
| pass4 | eod | WAFD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"WAFD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8958,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"WAFD"},"usableDates":13,"verdict":"low_correlation"} |
| pass4 | eod | ABBNY.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ABBNY.US"},"medianRatio":0.9512875068194219,"minCorrelation":0.9,"priceCorr":0.9996,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABBNY"},"usableDates":9,"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"} |
Showing 200 of 612 conflicts (412 more in CSV).

View file

@ -247,3 +247,48 @@ The following items were **not measured** in this docs-only spike and can only b
5. **Unverified live provider field shapes:** Exact field names and BSON types on live QA MongoDB for `ceoShorts` (`--shares-short-field`, `timestamp` unit), `qmFilings` (`--filings-form-type-field`, `symbol` vs `qmSearchCode`), `qmEarnings` optional fields, `qmDividends` (`amount`/`currency`), `teMarketData` (`t` epoch unit), and `qmPrices.date` string vs `DateTime` format remain pending the first host run of `probe-source-field-shapes.ts`.
6. **QuestDB `10.2.0` ILP v2 throughput (M2):** Multi-socket Rust ILP v2 ingestion rate into `bars_1m` (`PARTITION BY MONTH`, `DEDUP UPSERT KEYS(ts, listing_id)`) on `quant` has not been benchmarked.
7. **Rust `mongodb` crate compile time and transitive crate count:** Exact transitive dependency footprint and offline build time for `mongodb` (`bson-3`) + `tokio` inside this workspace have not been measured because this spike adds no crates.
---
## 8. M1 Live Verification & Final Option B Record (`2026-11-30`)
During Milestone `M1` closure on branch `m1-close-evidence`, the Option B Rust MongoDB driver and CLI wiring (`tools/curate-etl`) were implemented, compiled offline, unit/integration-tested, and executed end-to-end against live read-only QA MongoDB (`studio_stock_bot_read@stock`) on `quant` (`10.0.0.51`) into isolated output directory `/mnt/data/stockbot/m1-isolated/curated`. Every Section 7 unknown applicable to `M1` is now resolved empirically (item 6 — QuestDB `10.2.0` ILP v2 — remains scoped strictly to `M2`):
### 8.1 Dependency Footprint & Offline Build/Test Verification (Resolves §7.7)
- **Driver pin (`tools/curate-etl/Cargo.toml`):** `mongodb = "=3.10.2"` (`default-features = false`, features `compat-3-3-0`, `bson-3`, `sync`, `rustls-tls`, `dns-resolver`).
- **Transitive crate delta:** `123` transitive crates added to `Cargo.lock` (all vendored/cached for `--offline` builds; zero OpenSSL system dependency).
- **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 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).
### 8.2 Live Provider Field Shapes & Empirical Findings (Resolves §7.5)
Measured by `apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts` (`7,435` docs across all `8` M1 collections in `0.7 s`, recorded in `design/data-pipeline/m1-source-field-shapes.md`) plus live curation verification:
- **`qmSplits` sign convention (critical empirical catch):** Across all `16,892 / 16,892` (`100.00%`) `qmSplits` documents with numeric `forfactor`/`tofactor` (out of `18,751` total), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `tools/curate-etl/src/bson_qm_actions.rs` now converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` (avoiding 6-decimal truncation like `0.142857` for 7:1) or `1.0 / splitratio` when `forfactor`/`tofactor` are blank.
- **`ceoShorts` mapping key:** `ceoShorts.symbol` uses exchange-suffixed tickers (`"A.V"`, `"ACB.TO"`) matching `provider_mapping(source='eod')`, with fields `number_of_shares` and `net_change`.
- **`qmFilings` Canadian keys:** `qmFilings` omits `:CA` on Canadian `symbol` rows (`symbol: "RY", exchange: "TSX"`); `bson_qm_events.rs` qualifies Canadian exchanges to `"{symbol}:CA"` during `provider_mapping(source='qm')` resolution.
- **`qmDividends`:** Confirmed `amount` (`100%` numeric) and `currency` (`92.8%` present; missing-currency rows cleanly counted as decode rejects).
### 8.3 Live `quant` Curation & Security-Master Timings (Resolves §7.1–§7.4)
| 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,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-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-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, 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`)** |
*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`.
### 8.4 Final Recommendation (Confirmed)
**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.
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`.

View file

@ -0,0 +1,23 @@
{
"name": "@stock-bot/duckdb",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Server-side DuckDB executor and MarketDataStore wiring for curated Hive Parquet datasets",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"build": "tsc",
"test": "bun test"
},
"dependencies": {
"@duckdb/node-api": "^1.4.4-r.1",
"@stock-bot/research": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.11.0"
}
}

View file

@ -0,0 +1,266 @@
/**
* Concrete server-side DuckDB executor and `MarketDataStore` wiring over
* curated Hive-partitioned Parquet datasets (`design/DATA-CONTRACTS.md` §3.A & §4).
*
* Uses `@duckdb/node-api` (native N-API bindings, works in both Bun and Node)
* while keeping `@stock-bot/research` browser-safe and dependency-free.
*/
import { copyFile, link, mkdir, mkdtemp, open, rm, type FileHandle } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DuckDBInstance, type DuckDBConnection, type DuckDBValue } from '@duckdb/node-api';
import type { MarketDataStore, TableCell, TableRow } from '@stock-bot/research/market-data-store';
import {
createDuckDbMarketDataStore,
type AdjFactorsArtifactPinner,
type DuckDbExecutor,
type DuckDbMarketDataStoreOptions,
type DuckDbParam,
type PinnedAdjFactorsArtifact,
} from '@stock-bot/research/market-data-store-duckdb';
const UTF8_DECODER = new TextDecoder('utf-8', { fatal: false });
const MS_PER_DAY = 86_400_000;
export interface CreateNodeDuckDbExecutorOptions {
/** Optional DuckDB file path; defaults to `':memory:'` for read-only Parquet scans. */
readonly databasePath?: string;
}
export interface ClosableDuckDbExecutor extends DuckDbExecutor {
close(): Promise<void>;
}
export interface OpenDuckDbMarketDataStoreOptions
extends Omit<DuckDbMarketDataStoreOptions, 'executor'> {
/** Optional DuckDB database path; defaults to `':memory:'`. */
readonly databasePath?: string;
}
export interface OpenedDuckDbMarketDataStore {
readonly store: MarketDataStore;
readonly executor: ClosableDuckDbExecutor;
close(): Promise<void>;
}
function formatEpochDaysIso(days: number): string {
const date = new Date(days * MS_PER_DAY);
const y = String(date.getUTCFullYear()).padStart(4, '0');
const m = String(date.getUTCMonth() + 1).padStart(2, '0');
const d = String(date.getUTCDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object';
}
/**
* Normalizes a `@duckdb/node-api` cell value into `@stock-bot/research`'s
* strict `TableCell` (`string | number | boolean | null`) contract.
*/
export function normalizeDuckDbCell(value: unknown): TableCell {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'string' || typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return Object.is(value, -0) ? 0 : value;
}
if (typeof value === 'bigint') {
const asNumber = Number(value);
if (!Number.isSafeInteger(asNumber)) {
throw new RangeError(
`DuckDB BIGINT value ${value.toString()} exceeds JavaScript safe integer range.`
);
}
return asNumber;
}
if (value instanceof Uint8Array) {
return UTF8_DECODER.decode(value);
}
if (value instanceof Date) {
return value.getTime();
}
if (isRecord(value)) {
// DuckDBBlobValue / DuckDBBitValue expose `{ bytes: Uint8Array }` (e.g. parquet_kv_metadata)
if (value.bytes instanceof Uint8Array) {
return UTF8_DECODER.decode(value.bytes);
}
// DuckDBDateValue exposes `{ days: number }`
if (typeof value.days === 'number' && Number.isFinite(value.days)) {
return formatEpochDaysIso(value.days);
}
// DuckDBTimestampValue / DuckDBTimestampTZValue expose `{ micros: bigint }`
if (typeof value.micros === 'bigint') {
const ms = Number(value.micros / 1000n);
if (!Number.isSafeInteger(ms)) {
throw new RangeError(
`DuckDB timestamp micros ${value.micros.toString()} exceeds safe millisecond range.`
);
}
return ms;
}
// DuckDBDecimalValue exposes `{ value: bigint, scale: number }`
if (typeof value.value === 'bigint' && typeof value.scale === 'number') {
return Number(value.value) / 10 ** value.scale;
}
}
return String(value);
}
/**
* Opens an in-process `@duckdb/node-api` connection and adapts it to
* {@link DuckDbExecutor}.
*/
export async function createNodeDuckDbExecutor(
options: CreateNodeDuckDbExecutorOptions = {}
): Promise<ClosableDuckDbExecutor> {
const databasePath = options.databasePath ?? ':memory:';
const instance = await DuckDBInstance.create(databasePath);
const connection: DuckDBConnection = await instance.connect();
let closed = false;
const assertOpen = (): void => {
if (closed) {
throw new Error('DuckDbExecutor connection has already been closed.');
}
};
return {
async run(sql: string): Promise<void> {
assertOpen();
await connection.run(sql);
},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
assertOpen();
const values: DuckDBValue[] = params.map(param => param as DuckDBValue);
const reader =
values.length > 0
? await connection.runAndReadAll(sql, values)
: await connection.runAndReadAll(sql);
const rawRows = reader.getRowObjects();
const rows: TableRow[] = new Array(rawRows.length);
for (let i = 0; i < rawRows.length; i += 1) {
const raw = rawRows[i];
const clean: Record<string, TableCell> = {};
if (raw !== undefined) {
for (const [col, cell] of Object.entries(raw)) {
clean[col] = normalizeDuckDbCell(cell);
}
}
rows[i] = clean;
}
return rows;
},
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
connection.closeSync();
instance.closeSync();
},
};
}
/**
* Pins a mutable `<curatedRoot>/adj_factors/part.parquet` path to a single
* inode/snapshot across footer verification and factor scan so concurrent
* atomic replacements by `curate-etl` cannot introduce TOCTOU drift.
*
* On Linux, opens a read-only file descriptor and exposes `/proc/self/fd/<fd>`.
* On platforms without `/proc/self/fd`, falls back to a private hardlink (or
* copy across filesystems) inside a temporary directory cleaned up in `release()`.
*/
export function createFsAdjFactorsPinner(): AdjFactorsArtifactPinner {
return async (sourcePath: string): Promise<PinnedAdjFactorsArtifact> => {
if (process.platform === 'linux') {
const handle: FileHandle = await open(sourcePath, 'r');
let released = false;
return {
pinnedPath: `/proc/self/fd/${handle.fd}`,
async release(): Promise<void> {
if (released) {
return;
}
released = true;
await handle.close();
},
};
}
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-adj-pin-'));
const pinnedPath = join(tempDir, 'adj_factors.parquet');
try {
await link(sourcePath, pinnedPath);
} catch {
await copyFile(sourcePath, pinnedPath);
}
let released = false;
return {
pinnedPath,
async release(): Promise<void> {
if (released) {
return;
}
released = true;
await rm(tempDir, { recursive: true, force: true });
},
};
};
}
/**
* Opens a ready-to-use DuckDB-backed {@link MarketDataStore} wired with
* `@duckdb/node-api` and a filesystem `adj_factors` artifact pinner.
*/
export async function openDuckDbMarketDataStore(
options: OpenDuckDbMarketDataStoreOptions
): Promise<OpenedDuckDbMarketDataStore> {
const tempDir = options.env?.STOCK_BOT_DUCKDB_TEMP_DIR;
if (typeof tempDir === 'string' && tempDir.trim().length > 0) {
await mkdir(tempDir, { recursive: true });
}
const executor = await createNodeDuckDbExecutor({
databasePath: options.databasePath,
});
const pinAdjFactorsArtifact =
options.pinAdjFactorsArtifact ??
(options.immutableAdjFactorsPath === undefined ? createFsAdjFactorsPinner() : undefined);
try {
const store = createDuckDbMarketDataStore({
...options,
executor,
...(pinAdjFactorsArtifact !== undefined ? { pinAdjFactorsArtifact } : {}),
});
return {
store,
executor,
async close(): Promise<void> {
await executor.close();
},
};
} catch (err) {
await executor.close();
throw err;
}
}
export {
createDuckDbMarketDataStore,
type AdjFactorsArtifactPinner,
type DuckDbExecutor,
type DuckDbMarketDataStoreOptions,
type DuckDbParam,
type PinnedAdjFactorsArtifact,
};

View file

@ -0,0 +1,250 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
computeVaultCutoffTs,
VaultHoldoutFenceError,
type BarRecord,
} from '@stock-bot/research/market-data-store';
import {
createNodeDuckDbExecutor,
openDuckDbMarketDataStore,
} from '../src/index';
const tempDirs: string[] = [];
afterEach(async () => {
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir !== undefined) {
await rm(dir, { recursive: true, force: true });
}
}
});
async function buildCuratedFixture(): Promise<{
curatedRoot: string;
duckTempDir: string;
vaultCutoffTs: number;
}> {
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-mds-'));
tempDirs.push(root);
const curatedRoot = join(root, 'curated');
const duckTempDir = join(root, 'duckdb-tmp');
await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
await mkdir(join(curatedRoot, 'adj_factors'), { recursive: true });
await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true });
await mkdir(join(curatedRoot, 'shorts'), { recursive: true });
await mkdir(join(curatedRoot, 'fx_1d'), { recursive: true });
await mkdir(duckTempDir, { recursive: true });
// Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
const vaultCutoffMicros = vaultCutoffTs * 1000;
const asOfMicros = vaultCutoffMicros - 1;
const writer = await createNodeDuckDbExecutor();
try {
// 2024 bars (pre-Vault): listing 101 (USD, NVDA 10:1 split on 2024-06-10) + listing 202 (CAD)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2024-06-07', TIMESTAMPTZ '2024-06-07 20:00:00+00', 1200.0::DOUBLE, 1220.0::DOUBLE, 1190.0::DOUBLE, 1208.88::DOUBLE, 41238600.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-07 20:00:00+00'),
(101::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 120.37::DOUBLE, 123.10::DOUBLE, 117.01::DOUBLE, 121.79::DOUBLE, 314162700.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00'),
(202::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 140.0::DOUBLE, 142.0::DOUBLE, 139.0::DOUBLE, 141.5::DOUBLE, 1200000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00')
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// 2025 bars: one pre-Vault bar (2025-02-12) and one Vault bar (2025-02-14)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2025-02-12', TIMESTAMPTZ '2025-02-12 20:00:00+00', 130.0::DOUBLE, 132.0::DOUBLE, 129.0::DOUBLE, 131.0::DOUBLE, 200000000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-12 20:00:00+00'),
(101::INTEGER, DATE '2025-02-14', TIMESTAMPTZ '2025-02-14 20:00:00+00', 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 1.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-14 20:00:00+00')
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
`);
// Point-in-time fenced adj_factors snapshot (10:1 split on 2024-06-10)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(101::INTEGER, DATE '2024-06-10', 10.0::DOUBLE, 10.05::DOUBLE, TIMESTAMPTZ '2024-06-10 00:00:00+00')
) AS t(listing_id, ex_date, cum_split_factor, cum_total_factor, known_at)
) TO '${join(curatedRoot, 'adj_factors', 'part.parquet')}' (
FORMAT PARQUET,
KV_METADATA {
'stock_bot.adj_factors.format_version': '1',
'stock_bot.adj_factors.snapshot_kind': 'point_in_time_fenced',
'stock_bot.adj_factors.as_of_micros': '${asOfMicros}',
'stock_bot.adj_factors.vault_cutoff_micros': '${vaultCutoffMicros}',
'stock_bot.adj_factors.rows_written': '1',
'stock_bot.adj_factors.snapshot_checksum': '0x0123456789abcdef'
}
)
`);
// Events (2024 filing)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'MD&A'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR)
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
`);
// Canadian shorts (+4 biz day known_at)
await writer.run(`
COPY (
SELECT * FROM (VALUES
(202::INTEGER, DATE '2024-06-15', TIMESTAMPTZ '2024-06-21 21:00:00+00', 500000.0::DOUBLE, 25000.0::DOUBLE, NULL::DOUBLE, 'ceo_shorts'::VARCHAR)
) AS t(listing_id, report_date, known_at, shares_short, net_change, pct_float, source)
) TO '${join(curatedRoot, 'shorts', 'part.parquet')}' (FORMAT PARQUET)
`);
// FX 1d (USDCAD)
await writer.run(`
COPY (
SELECT * FROM (VALUES
('USDCAD'::VARCHAR, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 23:59:59.999999+00', 1.375::DOUBLE, 1.378::DOUBLE, 1.372::DOUBLE, 1.376::DOUBLE, 'eod_forex'::VARCHAR, TIMESTAMPTZ '2024-06-10 23:59:59.999999+00')
) AS t(pair, session_date, ts, open, high, low, close, source, known_at)
) TO '${join(curatedRoot, 'fx_1d', 'part.parquet')}' (FORMAT PARQUET)
`);
} finally {
await writer.close();
}
return { curatedRoot, duckTempDir, vaultCutoffTs };
}
describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => {
test('reads real Parquet bars (raw, split, total), events, shorts, fx, universe and enforces Vault fence', async () => {
const { curatedRoot, duckTempDir, vaultCutoffTs } = await buildCuratedFixture();
const opened = await openDuckDbMarketDataStore({
curatedRoot,
vaultCutoffTs,
env: {
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
STOCK_BOT_DUCKDB_THREADS: '2',
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
},
});
try {
// 1. Raw bars: request through 2025-12-31 must clamp before Vault cutoff (2025-02-13) and never return 2025-02-14!
const rawBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2025-12-31',
adjustment: 'raw',
})) {
rawBars.push(...batch.rows);
}
expect(rawBars.length).toBe(3);
expect(rawBars.every(r => r.ts < vaultCutoffTs)).toBe(true);
expect(rawBars[0]!.close).toBeCloseTo(1208.88, 6);
expect(rawBars[0]!.volume).toBeCloseTo(41_238_600, 1);
// 2. Vault rejection when from >= vaultCutoffTs
let rejected = false;
try {
for await (const _batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2025-02-13',
to: '2025-08-01',
adjustment: 'raw',
})) {
// should not yield
}
} catch (err) {
rejected = err instanceof VaultHoldoutFenceError;
}
expect(rejected).toBe(true);
// 3. Split-adjusted bars via pinned point_in_time_fenced adj_factors snapshot
const splitBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'split',
})) {
splitBars.push(...batch.rows);
}
expect(splitBars.length).toBe(2);
expect(splitBars[0]!.close).toBeCloseTo(120.888, 6);
expect(splitBars[0]!.volume).toBeCloseTo(412_386_000, 1);
expect(splitBars[1]!.close).toBeCloseTo(121.79, 6);
// 4. Total-return-adjusted bars (price divided by cum_total_factor, volume scaled by cum_split_factor)
const totalBars: BarRecord[] = [];
for await (const batch of opened.store.bars({
listingIds: [101],
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-15',
adjustment: 'total',
})) {
totalBars.push(...batch.rows);
}
expect(totalBars.length).toBe(2);
expect(totalBars[0]!.close).toBeCloseTo(1208.88 / 10.05, 6);
expect(totalBars[0]!.volume).toBeCloseTo(412_386_000, 1);
// 5. Events
const events = await opened.store.events({
kinds: ['filing'],
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
});
expect(events.rows.length).toBe(1);
expect(events.rows[0]!.subtype).toBe('MD&A');
// 6. Shorts (known_at fence)
const shortsBeforeKnown = await opened.store.shortsAsOf({
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
asOf: '2024-06-18',
});
expect(shortsBeforeKnown.rows.length).toBe(0);
const shortsAfterKnown = await opened.store.shortsAsOf({
listingIds: [202],
from: '2024-06-01',
to: '2024-06-30',
asOf: '2024-06-25',
});
expect(shortsAfterKnown.rows.length).toBe(1);
expect(shortsAfterKnown.rows[0]!.shares_short).toBe(500_000);
// 7. FX
const fx = await opened.store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2024-06-01',
to: '2024-06-30',
});
expect(fx.rows.length).toBe(1);
expect(fx.rows[0]!.close).toBeCloseTo(1.376, 6);
// 8. Universe
expect(await opened.store.universe({ ref: 'US_EQ', date: '2024-06-10' })).toEqual([101]);
expect(await opened.store.universe({ ref: 'CA_EQ', date: '2024-06-10' })).toEqual([202]);
expect(await opened.store.universe({ ref: 'US_CA_EQ', date: '2024-06-10' })).toEqual([
101, 202,
]);
} finally {
await opened.close();
}
});
});

View file

@ -0,0 +1,14 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true
},
"include": ["src/**/*"],
"references": [
{
"path": "../../research"
}
]
}

View file

@ -0,0 +1,599 @@
"""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
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
DuckDB + Polars over curated Hive-partitioned Parquet (`bars_1d/year=*/part.parquet`),
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
import argparse
import json
import math
import os
import shutil
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import duckdb
import numpy as np
import polars as pl
from stockbot.calculations import (
deflated_sharpe_ratio,
evaluate_recency_gate,
newey_west_mean_test,
trial_moments,
)
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(
curated_root: Path,
temp_dir: Path,
max_ingested_date: str = "2025-08-13",
start_date: str = "2005-01-01",
nvda_listing_id: int | None = None,
qm_nvda_dollar_vol: float | None = None,
) -> dict[str, object]:
temp_dir.mkdir(parents=True, exist_ok=True)
vault_cutoff_ms = compute_vault_cutoff_ts(max_ingested_date)
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_ts = vault_cutoff_dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
bars_glob = str(curated_root / "bars_1d" / "year=*" / "part.parquet")
# 1. Run 1 on a fresh DuckDB connection (before any warmup query on bars_1d)
con_cold = _open_duckdb(temp_dir)
try:
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,
)
# NVDA pre-split 2024-06-07 dollar volume verification
nvda_check: dict[str, object] | None = None
if nvda_listing_id is not None:
nvda_row = con_cold.execute(
f"""
SELECT session_date::VARCHAR, open, high, low, close, volume, close * volume AS dollar_volume, currency
FROM read_parquet('{bars_glob}', hive_partitioning = true)
WHERE listing_id = ? AND session_date IN (DATE '2024-06-07', DATE '2024-06-10')
ORDER BY session_date
""",
[nvda_listing_id],
).fetchall()
pre_split = next((r for r in nvda_row if r[0] == "2024-06-07"), None)
post_split = next((r for r in nvda_row if r[0] == "2024-06-10"), None)
rel_diff: float | None = None
if pre_split is not None and qm_nvda_dollar_vol is not None and qm_nvda_dollar_vol > 0:
rel_diff = abs(float(pre_split[6]) - qm_nvda_dollar_vol) / qm_nvda_dollar_vol
nvda_check = {
"listing_id": nvda_listing_id,
"pre_split_2024_06_07": (
{
"close": float(pre_split[4]),
"raw_volume": float(pre_split[5]),
"dollar_volume": float(pre_split[6]),
"currency": pre_split[7],
}
if pre_split
else None
),
"post_split_2024_06_10": (
{
"close": float(post_split[4]),
"raw_volume": float(post_split[5]),
"dollar_volume": float(post_split[6]),
"currency": post_split[7],
}
if post_split
else None
),
"qm_pre_split_dollar_volume": qm_nvda_dollar_vol,
"rel_diff": rel_diff,
"within_1pct": rel_diff is not None and rel_diff <= 0.01,
}
# Exact dataset totals on disk
vault_rows_on_disk = int(
con_cold.execute(
f"SELECT COUNT(*) FROM read_parquet('{bars_glob}', hive_partitioning = true) WHERE session_date >= CAST(? AS DATE)",
[vault_cutoff_iso_date],
).fetchone()[0]
)
scan_stats = con_cold.execute(
f"""
SELECT COUNT(*)::BIGINT, COUNT(DISTINCT listing_id)::BIGINT, MIN(session_date)::VARCHAR, MAX(session_date)::VARCHAR
FROM read_parquet('{bars_glob}', hive_partitioning = true)
WHERE session_date >= CAST(? AS DATE)
AND session_date < CAST(? AS DATE)
AND currency IN ('USD', 'CAD')
AND close > 0 AND volume > 0
""",
[start_date, vault_cutoff_iso_date],
).fetchone()
total_rows_in_scan = int(scan_stats[0])
distinct_listings_in_scan = int(scan_stats[1])
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 {
"host": os.uname().nodename,
"curated_root": str(curated_root),
"duckdb_version": duckdb.__version__,
"polars_version": pl.__version__,
"duckdb_budget": {
"memory_limit": DEFAULT_DUCKDB_MEMORY_LIMIT,
"threads": DEFAULT_DUCKDB_THREADS,
"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_rows_on_disk": vault_rows_on_disk,
"total_rows_in_scan": total_rows_in_scan,
"distinct_listings_in_scan": distinct_listings_in_scan,
"scan_date_min": scan_stats[2],
"scan_date_max": scan_stats[3],
"nvda_pre_split_check": nvda_check,
"parquet_scan_vault_audit": scan_audit,
"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"]),
}
def main() -> None:
parser = argparse.ArgumentParser(description="M1 quant 20y US/CA scan + signal benchmark")
parser.add_argument("--curated-root", type=Path, required=True)
parser.add_argument("--temp-dir", type=Path, required=True)
parser.add_argument("--max-ingested-date", default="2025-08-13")
parser.add_argument("--start-date", default="2005-01-01")
parser.add_argument("--nvda-listing-id", type=int, default=None)
parser.add_argument("--qm-nvda-dollar-vol", type=float, default=None)
parser.add_argument("--out-json", type=Path, default=None)
args = parser.parse_args()
result = run_benchmark(
curated_root=args.curated_root,
temp_dir=args.temp_dir,
max_ingested_date=args.max_ingested_date,
start_date=args.start_date,
nvda_listing_id=args.nvda_listing_id,
qm_nvda_dollar_vol=args.qm_nvda_dollar_vol,
)
rendered = json.dumps(result, indent=2)
print(rendered)
if args.out_json is not None:
args.out_json.parent.mkdir(parents=True, exist_ok=True)
args.out_json.write_text(rendered + "\n", encoding="utf-8")
if __name__ == "__main__":
main()

29
python/pyproject.toml Normal file
View file

@ -0,0 +1,29 @@
[project]
name = "stockbot"
version = "0.1.0"
description = "Stock Bot Python Research SDK (Vault-fenced DuckDB/Parquet MarketDataStore, Signal Analyzer, Event Study, trial_ledger DSR)"
requires-python = ">=3.11"
dependencies = [
"duckdb>=1.2.0,<2.0.0",
"polars>=1.20.0,<2.0.0",
"marimo>=0.11.0,<1.0.0",
"psycopg[binary]>=3.2.0,<4.0.0",
"numpy>=1.26.0,<3.0.0",
"scipy>=1.13.0,<2.0.0",
"pyarrow>=18.0.0,<22.0.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0.0,<9.0.0",
]
[build-system]
requires = ["hatchling>=1.25.0"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["stockbot"]
[tool.pytest.ini_options]
testpaths = ["tests"]

View file

@ -0,0 +1,80 @@
"""Stock Bot Python Research SDK (`stockbot`)."""
from . import data
from .calculations import (
DSR_VALIDATION_GATE,
EULER_MASCHERONI,
RECENCY_MIN_RATIO,
RECENCY_SPLIT_DATE,
DeflatedSharpeResult,
EffectiveTrialsResult,
NeweyWestResult,
TrialMoments,
analyze_signal_panel,
compute_event_study,
deflated_sharpe_ratio,
effective_independent_trials,
evaluate_recency_gate,
newey_west_mean_test,
trial_moments,
)
from .data import MarketDataStore
from .ledger import (
ClusterDsrSummary,
RecordedTrial,
TrialLedgerClient,
canonical_expression_hash,
)
from .signals import run_event_study_trial, run_signal_study
from .vault import (
DEFAULT_DUCKDB_MEMORY_LIMIT,
DEFAULT_DUCKDB_TEMP_DIRECTORY,
DEFAULT_DUCKDB_THREADS,
DuckDbConnectionBudget,
FencedTimeRange,
MarketDataStoreValidationError,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
apply_vault_fence,
compute_vault_cutoff_ts,
resolve_duckdb_budget,
vault_cutoff_date_str,
)
__all__ = [
"data",
"MarketDataStore",
"TrialLedgerClient",
"RecordedTrial",
"ClusterDsrSummary",
"canonical_expression_hash",
"run_signal_study",
"run_event_study_trial",
"analyze_signal_panel",
"compute_event_study",
"trial_moments",
"effective_independent_trials",
"deflated_sharpe_ratio",
"newey_west_mean_test",
"evaluate_recency_gate",
"TrialMoments",
"EffectiveTrialsResult",
"DeflatedSharpeResult",
"NeweyWestResult",
"DSR_VALIDATION_GATE",
"EULER_MASCHERONI",
"RECENCY_SPLIT_DATE",
"RECENCY_MIN_RATIO",
"DEFAULT_DUCKDB_MEMORY_LIMIT",
"DEFAULT_DUCKDB_THREADS",
"DEFAULT_DUCKDB_TEMP_DIRECTORY",
"DuckDbConnectionBudget",
"FencedTimeRange",
"MarketDataStoreValidationError",
"VaultHoldoutFenceError",
"VaultScopeNotAuthorizedError",
"apply_vault_fence",
"compute_vault_cutoff_ts",
"resolve_duckdb_budget",
"vault_cutoff_date_str",
]

View file

@ -0,0 +1,494 @@
"""Canonical quantitative validation metrics matching `@stock-bot/calculations`.
Exact formulas from `design/VALIDATION-AND-RIGOR.md` §1, §2.B, §2.C, §3.2:
- `trial_moments`: sample std (N - 1), plugin skewness m3/m2^(3/2), Pearson kurtosis m4/m2^2
- `effective_independent_trials`: Bailey & Lopez de Prado N-hat
- `deflated_sharpe_ratio`: non-normal DSR with Euler-Mascheroni gamma = 0.5772156649015329
- `newey_west_mean_test`: Bartlett kernel HAC t-stat and two-sided normal p-value
- `analyze_signal_panel`: fast vectorized Polars/NumPy IC, Rank-IC, quantiles, turnover, recency
- `compute_event_study`: zero-look-ahead AAR/CAAR, R-7 CAR fans, date-clustered HAC t-stat, recency
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Sequence
import numpy as np
import polars as pl
from scipy.stats import norm
EULER_MASCHERONI = 0.5772156649015329
DSR_VALIDATION_GATE = 0.95
RECENCY_SPLIT_DATE = "2023-01-01"
RECENCY_MIN_RATIO = 0.5
@dataclass(frozen=True)
class TrialMoments:
n_obs: int
sharpe_unann: float
skewness: float
kurtosis: float
@dataclass(frozen=True)
class EffectiveTrialsResult:
k: int
pairs_used: int
pairs_skipped: int
mean_correlation: float | None
n_hat: float
@dataclass(frozen=True)
class DeflatedSharpeResult:
sr0: float
standard_error: float
dsr: float
@dataclass(frozen=True)
class NeweyWestResult:
n_obs: int
lag: int
mean: float
standard_error: float
t_stat: float
p_value: float
def trial_moments(series: Sequence[float] | np.ndarray, daily_risk_free: float = 0.0) -> TrialMoments:
"""Computes canonical per-trial moments matching `trialMoments` in `@stock-bot/calculations`."""
arr = np.asarray(series, dtype=np.float64)
finite = arr[np.isfinite(arr)]
n = int(finite.size)
if n < 2:
raise ValueError(f"trial_moments requires at least 2 finite observations (got {n}).")
mean_val = float(np.mean(finite))
centered = finite - mean_val
m2 = float(np.mean(centered * centered))
if m2 <= 0.0:
raise ValueError("trial_moments requires non-zero variance.")
sample_std = math.sqrt(float(np.sum(centered * centered)) / (n - 1))
sharpe_unann = (mean_val - daily_risk_free) / sample_std
m3 = float(np.mean(centered ** 3))
m4 = float(np.mean(centered ** 4))
skewness = m3 / (m2 ** 1.5)
kurtosis = m4 / (m2 * m2)
return TrialMoments(
n_obs=n,
sharpe_unann=float(sharpe_unann),
skewness=float(skewness),
kurtosis=float(kurtosis),
)
def newey_west_mean_test(
series: Sequence[float] | np.ndarray, lag: int | None = None
) -> NeweyWestResult:
"""Bartlett-kernel Newey-West HAC test for H0: mean == 0."""
arr = np.asarray(series, dtype=np.float64)
arr = arr[np.isfinite(arr)]
n = int(arr.size)
if n < 2:
return NeweyWestResult(
n_obs=n, lag=0, mean=float("nan"), standard_error=float("nan"), t_stat=float("nan"), p_value=float("nan")
)
max_lag = lag if lag is not None else max(1, int(math.floor(4.0 * ((n / 100.0) ** (2.0 / 9.0)))))
max_lag = min(max_lag, n - 1)
mean_val = float(np.mean(arr))
u = arr - mean_val
gamma0 = float(np.dot(u, u)) / n
lrv = gamma0
for l in range(1, max_lag + 1):
weight = 1.0 - l / (max_lag + 1.0)
gamma_l = float(np.dot(u[l:], u[:-l])) / n
lrv += 2.0 * weight * gamma_l
lrv = max(lrv, 0.0)
se = math.sqrt(lrv / n) if lrv > 0.0 else 0.0
if se == 0.0:
t_stat = 0.0 if mean_val == 0.0 else math.copysign(float("inf"), mean_val)
p_val = 1.0 if mean_val == 0.0 else 0.0
else:
t_stat = mean_val / se
p_val = float(2.0 * (1.0 - norm.cdf(abs(t_stat))))
return NeweyWestResult(
n_obs=n, lag=max_lag, mean=mean_val, standard_error=se, t_stat=float(t_stat), p_value=p_val
)
def effective_independent_trials(
aligned_series_by_id: Sequence[tuple[int, dict[str, float]]]
) -> EffectiveTrialsResult:
"""Computes Bailey & Lopez de Prado effective independent trials N-hat."""
k = len(aligned_series_by_id)
if k <= 1:
return EffectiveTrialsResult(k=k, pairs_used=0, pairs_skipped=0, mean_correlation=None, n_hat=1.0)
corr_sum = 0.0
pairs_used = 0
pairs_skipped = 0
for i in range(k):
_, map_i = aligned_series_by_id[i]
keys_i = set(map_i.keys())
for j in range(i + 1, k):
_, map_j = aligned_series_by_id[j]
common = sorted(keys_i.intersection(map_j.keys()))
if len(common) < 2:
pairs_skipped += 1
continue
xi = np.array([map_i[d] for d in common], dtype=np.float64)
xj = np.array([map_j[d] for d in common], dtype=np.float64)
xi -= xi.mean()
xj -= xj.mean()
denom = math.sqrt(float(np.dot(xi, xi) * np.dot(xj, xj)))
if denom <= 0.0 or not math.isfinite(denom):
pairs_skipped += 1
continue
rho = max(-1.0, min(1.0, float(np.dot(xi, xj)) / denom))
corr_sum += rho
pairs_used += 1
if pairs_used == 0:
return EffectiveTrialsResult(
k=k, pairs_used=0, pairs_skipped=pairs_skipped, mean_correlation=None, n_hat=float(k)
)
mean_corr = corr_sum / pairs_used
n_hat = max(1.0, 1.0 + (k - 1.0) * (1.0 - max(0.0, mean_corr)))
return EffectiveTrialsResult(
k=k,
pairs_used=pairs_used,
pairs_skipped=pairs_skipped,
mean_correlation=float(mean_corr),
n_hat=float(n_hat),
)
def deflated_sharpe_ratio(
*,
sharpe_unann: float,
n_obs: int,
skewness: float,
kurtosis: float,
n_hat: float,
cluster_sharpes: Sequence[float],
) -> DeflatedSharpeResult:
"""Computes non-normal Deflated Sharpe Ratio (DSR) per VALIDATION-AND-RIGOR.md §2.C."""
if n_obs < 2:
raise ValueError("n_obs must be >= 2.")
sr_arr = np.asarray(cluster_sharpes, dtype=np.float64)
sr_arr = sr_arr[np.isfinite(sr_arr)]
if n_hat <= 1.0 or sr_arr.size < 2:
sr0 = 0.0
else:
sigma_sr = float(np.std(sr_arr, ddof=1))
if sigma_sr <= 0.0:
sr0 = 0.0
else:
z1 = float(norm.ppf(1.0 - 1.0 / n_hat))
z2 = float(norm.ppf(1.0 - 1.0 / (n_hat * math.e)))
sr0 = sigma_sr * ((1.0 - EULER_MASCHERONI) * z1 + EULER_MASCHERONI * z2)
se_num = 1.0 - skewness * sharpe_unann + ((kurtosis - 1.0) / 4.0) * (sharpe_unann ** 2)
if se_num <= 0.0:
raise ValueError("Non-positive Sharpe standard-error variance term.")
se = math.sqrt(se_num / (n_obs - 1.0))
dsr = float(norm.cdf((sharpe_unann - sr0) / se))
return DeflatedSharpeResult(sr0=float(sr0), standard_error=float(se), dsr=dsr)
def evaluate_recency_gate(
dates: Sequence[str],
series: Sequence[float] | np.ndarray,
*,
split_date: str = RECENCY_SPLIT_DATE,
min_ratio: float = RECENCY_MIN_RATIO,
) -> dict[str, object]:
"""Post-2023 Recency Gate: post mean > 0 and >= min_ratio * pre mean (sign-preserving)."""
arr = np.asarray(series, dtype=np.float64)
pre_vals = np.array([v for d, v in zip(dates, arr) if d < split_date and math.isfinite(v)], dtype=np.float64)
post_vals = np.array([v for d, v in zip(dates, arr) if d >= split_date and math.isfinite(v)], dtype=np.float64)
pre_mean = float(pre_vals.mean()) if pre_vals.size > 0 else float("nan")
post_mean = float(post_vals.mean()) if post_vals.size > 0 else float("nan")
if pre_vals.size == 0:
return {"pass": False, "reason": "empty_pre_window", "pre_n": 0, "post_n": int(post_vals.size), "pre_mean": None, "post_mean": post_mean if post_vals.size else None, "ratio": None}
if post_vals.size == 0:
return {"pass": False, "reason": "empty_post_window", "pre_n": int(pre_vals.size), "post_n": 0, "pre_mean": pre_mean, "post_mean": None, "ratio": None}
if pre_mean == 0.0:
return {"pass": False, "reason": "zero_pre_mean", "pre_n": int(pre_vals.size), "post_n": int(post_vals.size), "pre_mean": pre_mean, "post_mean": post_mean, "ratio": None}
ratio = post_mean / pre_mean
same_sign = (pre_mean > 0 and post_mean > 0) or (pre_mean < 0 and post_mean < 0)
passed = same_sign and ratio >= min_ratio
reason = "passed" if passed else ("sign_flipped" if not same_sign else "post_below_ratio_threshold")
return {
"pass": passed,
"reason": reason,
"pre_n": int(pre_vals.size),
"post_n": int(post_vals.size),
"pre_mean": pre_mean,
"post_mean": post_mean,
"ratio": float(ratio),
}
def analyze_signal_panel(
panel: pl.DataFrame,
*,
vault_cutoff_date: str,
n_quantiles: int = 5,
min_cross_section: int = 10,
recency_split_date: str = RECENCY_SPLIT_DATE,
) -> dict[str, object]:
"""Vectorized Polars/NumPy cross-sectional Signal Analyzer.
Expects columns: `session_date` (str YYYY-MM-DD or Date), `listing_id` (int),
`signal` (float), `forward_return` (float).
Enforces strict Vault cutoff `session_date < vault_cutoff_date`.
"""
df = panel.with_columns(
pl.col("session_date").cast(pl.String).alias("session_date"),
pl.col("signal").cast(pl.Float64),
pl.col("forward_return").cast(pl.Float64),
).filter(
pl.col("signal").is_finite() & pl.col("forward_return").is_finite()
)
vault_excluded = int(df.filter(pl.col("session_date") >= vault_cutoff_date).height)
fenced = df.filter(pl.col("session_date") < vault_cutoff_date)
# Filter dates with enough listings and compute cross-sectional Pearson IC, Rank IC, and Q_top - Q_bot
ranked = (
fenced.with_columns(pl.len().over("session_date").alias("_n"))
.filter(pl.col("_n") >= min_cross_section)
.with_columns(
pl.col("signal").rank("average").over("session_date").alias("_sig_rank"),
pl.col("forward_return").rank("average").over("session_date").alias("_ret_rank"),
(
((pl.col("signal").rank("ordinal").over("session_date") - 1) * n_quantiles // pl.col("_n"))
.clip(0, n_quantiles - 1)
.alias("_q")
),
)
)
daily_ic = (
ranked.group_by("session_date")
.agg(
pl.len().alias("n_listings"),
pl.corr("signal", "forward_return").alias("ic"),
pl.corr("_sig_rank", "_ret_rank").alias("rank_ic"),
pl.col("forward_return").filter(pl.col("_q") == (n_quantiles - 1)).mean().alias("q_top"),
pl.col("forward_return").filter(pl.col("_q") == 0).mean().alias("q_bot"),
)
.with_columns((pl.col("q_top") - pl.col("q_bot")).alias("spread"))
.filter(pl.col("rank_ic").is_finite() & pl.col("spread").is_finite())
.sort("session_date")
)
# Top-quantile membership turnover across consecutive dates
top_members = (
ranked.filter(pl.col("_q") == (n_quantiles - 1))
.group_by("session_date")
.agg(pl.col("listing_id").implode().alias("ids"))
.sort("session_date")
)
prev_set: set[int] | None = None
turnovers: list[float] = []
for row in top_members.iter_rows():
cur_set = set(row[1])
if prev_set is not None and len(cur_set) > 0 and len(prev_set) > 0:
overlap = len(cur_set.intersection(prev_set))
turnovers.append(1.0 - overlap / max(len(cur_set), len(prev_set)))
prev_set = cur_set
dates = daily_ic["session_date"].to_list()
rank_ic_series = daily_ic["rank_ic"].to_numpy()
ic_series = daily_ic["ic"].to_numpy()
spread_series = daily_ic["spread"].to_numpy()
rank_ic_nw = newey_west_mean_test(rank_ic_series)
spread_nw = newey_west_mean_test(spread_series)
recency_ic = evaluate_recency_gate(dates, rank_ic_series, split_date=recency_split_date)
recency_spread = evaluate_recency_gate(dates, spread_series, split_date=recency_split_date)
return {
"n_dates": len(dates),
"total_observations": int(ranked.height),
"vault_excluded_rows": vault_excluded,
"dates": dates,
"ic_series": ic_series.tolist(),
"rank_ic_series": rank_ic_series.tolist(),
"spread_series": spread_series.tolist(),
"mean_ic": float(np.nanmean(ic_series)) if len(dates) else float("nan"),
"mean_rank_ic": rank_ic_nw.mean,
"rank_ic_nw_t": rank_ic_nw.t_stat,
"rank_ic_nw_p": rank_ic_nw.p_value,
"mean_quantile_spread": spread_nw.mean,
"spread_nw_t": spread_nw.t_stat,
"mean_top_quantile_turnover": float(np.mean(turnovers)) if turnovers else float("nan"),
"recency_rank_ic": recency_ic,
"recency_spread": recency_spread,
}
def compute_event_study(
bars_df: pl.DataFrame,
events_df: pl.DataFrame,
*,
vault_cutoff_date: str,
pre_days: int = 5,
post_days: int = 10,
min_events: int = 5,
recency_split_date: str = RECENCY_SPLIT_DATE,
) -> dict[str, object]:
"""Zero-look-ahead Event Study over curated daily bars and point-in-time events.
Events anchor to the first trading session with `bar.ts >= event.known_at`.
All events whose event session or `event + post_days` session >= `vault_cutoff_date`
are strictly excluded before computing returns.
"""
bars = (
bars_df.select(["listing_id", "session_date", "ts", "close"])
.with_columns(
pl.col("session_date").cast(pl.String),
pl.col("close").cast(pl.Float64),
)
.filter((pl.col("session_date") < vault_cutoff_date) & (pl.col("close") > 0))
.sort(["listing_id", "session_date"])
)
# Build shared session calendar and per-listing daily returns
session_dates = bars["session_date"].unique().sort().to_list()
date_to_idx = {d: i for i, d in enumerate(session_dates)}
n_sessions = len(session_dates)
# Compute close-to-close simple returns per listing and equal-weight market benchmark
ret_df = (
bars.with_columns(
(pl.col("close") / pl.col("close").shift(1).over("listing_id") - 1.0).alias("ret")
)
.filter(pl.col("ret").is_finite())
)
bench_df = (
ret_df.group_by("session_date")
.agg(pl.col("ret").mean().alias("bench_ret"))
)
abn_df = (
ret_df.join(bench_df, on="session_date", how="left")
.with_columns((pl.col("ret") - pl.col("bench_ret")).alias("abn_ret"))
)
# Index returns per listing into dense arrays for fast window slicing
listing_abn: dict[int, dict[int, float]] = {}
listing_close_ts: dict[int, tuple[np.ndarray, np.ndarray]] = {}
for lid, grp in bars.group_by("listing_id", maintain_order=False):
lid_int = int(lid[0])
ts_arr = grp["ts"].cast(pl.Int64).to_numpy()
idx_arr = np.array([date_to_idx[d] for d in grp["session_date"].to_list()], dtype=np.int32)
listing_close_ts[lid_int] = (ts_arr, idx_arr)
for lid, grp in abn_df.group_by("listing_id", maintain_order=False):
lid_int = int(lid[0])
d_map: dict[int, float] = {}
for s_date, abn in zip(grp["session_date"].to_list(), grp["abn_ret"].to_list()):
d_map[date_to_idx[s_date]] = float(abn)
listing_abn[lid_int] = d_map
ev_ts_col = events_df.select(["listing_id", "known_at"]).with_columns(
pl.col("known_at").cast(pl.Int64)
)
seen_pairs: set[tuple[int, int]] = set()
cars_by_date: dict[str, list[float]] = {}
window_matrix: list[list[float]] = []
vault_excluded_events = 0
cutoff_ts_micros = int(
datetime_from_ymd(vault_cutoff_date)
)
for lid_raw, known_at_us in ev_ts_col.iter_rows():
if known_at_us >= cutoff_ts_micros:
vault_excluded_events += 1
continue
lid = int(lid_raw)
if lid not in listing_close_ts or lid not in listing_abn:
continue
ts_arr, idx_arr = listing_close_ts[lid]
pos = int(np.searchsorted(ts_arr, known_at_us, side="left"))
if pos >= ts_arr.size:
continue
day_idx = int(idx_arr[pos])
if day_idx - pre_days < 0 or day_idx + post_days >= n_sessions:
continue
key = (lid, day_idx)
if key in seen_pairs:
continue
seen_pairs.add(key)
abn_map = listing_abn[lid]
window_vals: list[float] = []
complete = True
for offset in range(-pre_days, post_days + 1):
val = abn_map.get(day_idx + offset)
if val is None or not math.isfinite(val):
complete = False
break
window_vals.append(val)
if not complete:
continue
window_matrix.append(window_vals)
post_car = float(sum(window_vals[pre_days:]))
cars_by_date.setdefault(session_dates[day_idx], []).append(post_car)
events_used = len(window_matrix)
if events_used < min_events or len(cars_by_date) < 2:
return {
"status": "insufficient_data",
"events_used": events_used,
"n_dates": len(cars_by_date),
"vault_excluded_events": vault_excluded_events,
}
mat = np.asarray(window_matrix, dtype=np.float64)
aar = mat.mean(axis=0)
caar = np.cumsum(aar)
clustered_dates = sorted(cars_by_date.keys())
mean_cars = np.array([float(np.mean(cars_by_date[d])) for d in clustered_dates], dtype=np.float64)
nw = newey_west_mean_test(mean_cars)
recency = evaluate_recency_gate(clustered_dates, mean_cars, split_date=recency_split_date)
return {
"status": "ok",
"pre_days": pre_days,
"post_days": post_days,
"events_used": events_used,
"n_dates": len(clustered_dates),
"vault_excluded_events": vault_excluded_events,
"clustered_dates": clustered_dates,
"mean_cars": mean_cars.tolist(),
"car_mean": nw.mean,
"car_nw_t": nw.t_stat,
"car_nw_p": nw.p_value,
"aar": aar.tolist(),
"caar": caar.tolist(),
"recency": recency,
}
def datetime_from_ymd(ymd: str) -> int:
from datetime import datetime, timezone
dt = datetime.strptime(ymd, "%Y-%m-%d").replace(tzinfo=timezone.utc)
return int(dt.timestamp() * 1_000_000)

295
python/stockbot/data.py Normal file
View file

@ -0,0 +1,295 @@
"""Vault-fenced DuckDB + Polars `MarketDataStore` for curated Hive Parquet."""
from __future__ import annotations
import os
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Literal, Sequence
import duckdb
import polars as pl
from .vault import (
DataScope,
DuckDbConnectionBudget,
MarketDataStoreValidationError,
apply_vault_fence,
resolve_duckdb_budget,
)
EventKind = Literal["filing", "earnings", "ceo_post", "corporate_action"]
AdjustmentMode = Literal["raw", "split", "total"]
UniverseRef = Literal["US_EQ", "CA_EQ", "US_CA_EQ"]
_UNIVERSE_CURRENCIES: dict[str, tuple[str, ...]] = {
"US_EQ": ("USD",),
"CA_EQ": ("CAD",),
"US_CA_EQ": ("USD", "CAD"),
}
class MarketDataStore:
"""Vault-fenced DuckDB + Parquet reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`."""
def __init__(
self,
curated_root: str | Path,
*,
vault_cutoff_ts: int,
vault_operator_authorized: bool = False,
budget: DuckDbConnectionBudget | None = None,
adj_factors_path: str | Path | None = None,
) -> None:
self.curated_root = str(Path(curated_root).resolve())
self.vault_cutoff_ts = vault_cutoff_ts
self.vault_operator_authorized = vault_operator_authorized
self.budget = budget or resolve_duckdb_budget()
self.adj_factors_path = (
str(Path(adj_factors_path).resolve())
if adj_factors_path is not None
else str(Path(self.curated_root) / "adj_factors" / "part.parquet")
)
os.makedirs(self.budget.temp_directory, exist_ok=True)
self._con = duckdb.connect(":memory:")
for stmt in self.budget.statements:
self._con.execute(stmt)
def close(self) -> None:
self._con.close()
def __enter__(self) -> "MarketDataStore":
return self
def __exit__(self, *_: object) -> None:
self.close()
def _bars_glob(self) -> str:
return f"{self.curated_root}/bars_1d/year=*/part.parquet"
def _events_glob(self) -> str:
return f"{self.curated_root}/events/year=*/part.parquet"
def _shorts_path(self) -> str:
return f"{self.curated_root}/shorts/part.parquet"
def _fx_path(self) -> str:
return f"{self.curated_root}/fx_1d/part.parquet"
def _verify_fenced_adj_factors(self, as_of_micros: int, scope: DataScope) -> str:
rows = self._con.execute(
f"SELECT key::VARCHAR AS k, value::VARCHAR AS v FROM parquet_kv_metadata('{self.adj_factors_path}')"
).fetchall()
kv = {str(k): str(v) for k, v in rows if str(k).startswith("stock_bot.adj_factors.")}
kind = kv.get("stock_bot.adj_factors.snapshot_kind")
if kind != "point_in_time_fenced":
raise MarketDataStoreValidationError(
f"Adjusted bars require point_in_time_fenced adj_factors snapshot (got {kind!r} at {self.adj_factors_path})."
)
if scope == "vault_fenced":
raw_vc = kv.get("stock_bot.adj_factors.vault_cutoff_micros")
expected_vc = self.vault_cutoff_ts * 1000
if raw_vc is None or raw_vc == "none" or int(raw_vc) > expected_vc:
raise MarketDataStoreValidationError(
f"adj_factors vault_cutoff_micros ({raw_vc}) incompatible with store cutoff ({expected_vc})."
)
raw_as_of = kv.get("stock_bot.adj_factors.as_of_micros")
if raw_as_of is not None and raw_as_of != "none" and int(raw_as_of) > as_of_micros:
raise MarketDataStoreValidationError(
f"adj_factors as_of_micros ({raw_as_of}) exceeds query as_of_micros ({as_of_micros})."
)
return self.adj_factors_path
def bars(
self,
*,
listing_ids: Sequence[int] | None = None,
currencies: Sequence[str] | None = None,
timeframe: str = "1d",
from_date: str,
to_date: str,
adjustment: AdjustmentMode = "raw",
as_of: str | None = None,
scope: DataScope = "vault_fenced",
) -> pl.DataFrame:
if timeframe != "1d":
raise NotImplementedError(f"Timeframe {timeframe!r} is reserved for QuestDB (M2).")
fenced = apply_vault_fence(
from_date,
to_date,
self.vault_cutoff_ts,
as_of=as_of,
scope=scope,
vault_operator_authorized=self.vault_operator_authorized,
)
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
where = ["b.ts >= ?", "b.ts <= ?", "b.known_at <= ?"]
params: list[object] = [from_ts, to_ts, as_of_ts]
if listing_ids is not None:
if len(listing_ids) == 0:
return pl.DataFrame()
placeholders = ", ".join(["?"] * len(listing_ids))
where.append(f"b.listing_id IN ({placeholders})")
params.extend(int(x) for x in listing_ids)
if currencies is not None:
placeholders = ", ".join(["?"] * len(currencies))
where.append(f"b.currency IN ({placeholders})")
params.extend(str(c) for c in currencies)
where_sql = " AND ".join(where)
if adjustment == "raw":
sql = f"""
SELECT
b.listing_id,
b.session_date,
b.ts,
b.open,
b.high,
b.low,
b.close,
b.volume,
b.vwap,
b.currency,
b.source,
b.known_at
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b
WHERE {where_sql}
ORDER BY b.listing_id ASC, b.session_date ASC
"""
return self._con.execute(sql, params).pl()
adj_path = self._verify_fenced_adj_factors(fenced.as_of_micros, fenced.scope)
price_col = "cum_split_factor" if adjustment == "split" else "cum_total_factor"
sql = f"""
WITH adj AS (
SELECT listing_id, ex_date, cum_split_factor, cum_total_factor
FROM read_parquet('{adj_path}')
WHERE known_at <= ?
)
SELECT
b.listing_id,
b.session_date,
b.ts,
b.open / COALESCE(a.{price_col}, 1.0) AS open,
b.high / COALESCE(a.{price_col}, 1.0) AS high,
b.low / COALESCE(a.{price_col}, 1.0) AS low,
b.close / COALESCE(a.{price_col}, 1.0) AS close,
b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume,
CASE WHEN b.vwap IS NULL THEN NULL ELSE b.vwap / COALESCE(a.{price_col}, 1.0) END AS vwap,
b.currency,
b.source,
b.known_at
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b
ASOF LEFT JOIN adj a
ON b.listing_id = a.listing_id AND b.session_date < a.ex_date
WHERE {where_sql}
ORDER BY b.listing_id ASC, b.session_date ASC
"""
return self._con.execute(sql, [as_of_ts, *params]).pl()
def shorts_as_of(
self,
*,
listing_ids: Sequence[int] | None = None,
from_date: str,
to_date: str,
as_of: str | None = None,
) -> pl.DataFrame:
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced")
from_d = datetime.fromtimestamp(fenced.from_ms / 1000.0, tz=timezone.utc).date()
to_d = datetime.fromtimestamp(fenced.to_ms / 1000.0, tz=timezone.utc).date()
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
where = ["report_date >= ?", "report_date <= ?", "known_at <= ?"]
params: list[object] = [from_d, to_d, as_of_ts]
if listing_ids is not None:
if len(listing_ids) == 0:
return pl.DataFrame()
placeholders = ", ".join(["?"] * len(listing_ids))
where.append(f"listing_id IN ({placeholders})")
params.extend(int(x) for x in listing_ids)
sql = f"""
SELECT listing_id, report_date, known_at, shares_short, net_change, pct_float, source
FROM read_parquet('{self._shorts_path()}')
WHERE {' AND '.join(where)}
ORDER BY listing_id ASC, report_date ASC
"""
return self._con.execute(sql, params).pl()
def events(
self,
*,
kinds: Sequence[EventKind],
listing_ids: Sequence[int] | None = None,
from_date: str,
to_date: str,
as_of: str | None = None,
) -> pl.DataFrame:
if not kinds:
raise MarketDataStoreValidationError("events requires at least one kind.")
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced")
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
kind_ph = ", ".join(["?"] * len(kinds))
where = [f"kind IN ({kind_ph})", "ts >= ?", "ts <= ?", "known_at <= ?"]
params: list[object] = [*kinds, from_ts, to_ts, as_of_ts]
if listing_ids is not None:
if len(listing_ids) == 0:
return pl.DataFrame()
lid_ph = ", ".join(["?"] * len(listing_ids))
where.append(f"listing_id IN ({lid_ph})")
params.extend(int(x) for x in listing_ids)
sql = f"""
SELECT listing_id, ts, known_at, known_at_source, kind, subtype, payload_json
FROM read_parquet('{self._events_glob()}', hive_partitioning = true)
WHERE {' AND '.join(where)}
ORDER BY listing_id ASC, ts ASC
"""
return self._con.execute(sql, params).pl()
def fx(self, *, pair: str = "USD.CAD", timeframe: str = "1d", from_date: str, to_date: str) -> pl.DataFrame:
if timeframe != "1d":
raise NotImplementedError("FX intraday 1m is reserved for QuestDB (M2).")
if pair != "USD.CAD":
raise MarketDataStoreValidationError(f"Unsupported FX pair: {pair!r}")
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, scope="vault_fenced")
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
sql = f"""
SELECT pair, session_date, ts, open, high, low, close, source, known_at
FROM read_parquet('{self._fx_path()}')
WHERE pair = 'USDCAD' AND ts >= ? AND ts <= ? AND known_at <= ?
ORDER BY session_date ASC
"""
return self._con.execute(sql, [from_ts, to_ts, as_of_ts]).pl()
def universe(self, *, ref: UniverseRef, on_date: str, lookback_days: int = 7) -> list[int]:
if ref not in _UNIVERSE_CURRENCIES:
raise MarketDataStoreValidationError(f"Unsupported universe ref: {ref!r}")
fenced = apply_vault_fence(on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced")
end_d = date.fromisoformat(on_date)
start_d = end_d - timedelta(days=lookback_days)
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
currencies = _UNIVERSE_CURRENCIES[ref]
ph = ", ".join(["?"] * len(currencies))
sql = f"""
SELECT DISTINCT listing_id
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true)
WHERE currency IN ({ph})
AND session_date >= ?
AND session_date <= ?
AND ts <= ?
AND known_at <= ?
ORDER BY listing_id ASC
"""
rows = self._con.execute(sql, [*currencies, start_d, end_d, to_ts, as_of_ts]).fetchall()
return [int(r[0]) for r in rows]

269
python/stockbot/ledger.py Normal file
View file

@ -0,0 +1,269 @@
"""Append-only PostgreSQL `trial_ledger` client and cluster N-hat DSR evaluator."""
from __future__ import annotations
import hashlib
import json
import math
import struct
from dataclasses import dataclass
from typing import Any, Literal, Mapping, Sequence
import numpy as np
import psycopg
from .calculations import (
DSR_VALIDATION_GATE,
DeflatedSharpeResult,
EffectiveTrialsResult,
deflated_sharpe_ratio,
effective_independent_trials,
trial_moments,
)
from .vault import VaultHoldoutFenceError, parse_timestamp_ms
TrialStage = Literal["signal_ic", "event_study", "screen", "engine_backtest"]
UniverseMarket = Literal["US_EQ", "CA_EQ", "US_CA_EQ", "FX"]
HorizonBucket = Literal["intraday", "swing_1_10d", "position_10d_plus"]
def _normalize_json_value(value: Any) -> Any:
if value is None or isinstance(value, (bool, str)):
return value
if isinstance(value, (int, float)):
if isinstance(value, float):
if not math.isfinite(value):
raise ValueError(f"Non-finite number forbidden in expression hash: {value!r}")
if value == 0.0:
return 0
return value
if isinstance(value, Mapping):
out: dict[str, Any] = {}
for k in sorted(value.keys()):
v = value[k]
if v is not None:
out[str(k)] = _normalize_json_value(v)
return out
if isinstance(value, (list, tuple)):
return [_normalize_json_value(v) for v in value]
raise TypeError(f"Unsupported value type for canonical_expression_hash: {type(value)!r}")
def canonical_expression_hash(
*,
expression: str,
params: Mapping[str, Any],
universe: str,
sample_start: str,
sample_end: str,
horizon: str,
) -> str:
"""64-hex SHA-256 over canonical ASCII-sorted JSON matching `@stock-bot/research`."""
collapsed_expr = " ".join(expression.strip().split())
payload = _normalize_json_value(
{
"expression": collapsed_expr,
"horizon": horizon,
"params": params,
"sampleEnd": sample_end,
"sampleStart": sample_start,
"universe": universe,
}
)
encoded = json.dumps(payload, separators=(",", ":"), sort_keys=True, ensure_ascii=False).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
@dataclass(frozen=True)
class RecordedTrial:
trial_id: int
created_at: str
expression_hash: str
n_obs: int
sharpe_unann: float
skewness: float
kurtosis: float
@dataclass(frozen=True)
class ClusterDsrSummary:
trial_id: int
cluster_size: int
effective_trials: float
mean_correlation: float | None
pairs_used: int
pairs_skipped: int
sr0: float
standard_error: float
dsr: float
passes_gate: bool
class TrialLedgerClient:
"""Append-only writer and cluster DSR reader for PostgreSQL `trial_ledger`."""
def __init__(self, dsn: str) -> None:
self._dsn = dsn
def record_trial(
self,
*,
principal_id: str,
stage: TrialStage,
universe_market: UniverseMarket,
horizon_bucket: HorizonBucket,
expression_hash: str,
sample_start: str,
sample_end: str,
vault_cutoff_date: str,
daily_series: Sequence[float],
campaign_id: str | None = None,
hypothesis_id: str | None = None,
) -> RecordedTrial:
"""Validates Vault fence + float32 precision and inserts into `trial_ledger`."""
start_ms = parse_timestamp_ms(sample_start, "start", "sample_start")
end_ms = parse_timestamp_ms(sample_end, "end", "sample_end")
cutoff_ms = parse_timestamp_ms(vault_cutoff_date, "start", "vault_cutoff_date")
if end_ms < start_ms:
raise ValueError(f"sample_end ({sample_end}) precedes sample_start ({sample_start}).")
if start_ms >= cutoff_ms:
raise VaultHoldoutFenceError(sample_start, start_ms, cutoff_ms)
if end_ms >= cutoff_ms:
raise VaultHoldoutFenceError(sample_end, end_ms, cutoff_ms)
# Quantize to IEEE-754 REAL (float32) before moment calculation so stored values match moments
f32_values: list[float] = []
for x in daily_series:
fx = float(x)
if not math.isfinite(fx):
raise ValueError("daily_series contains non-finite value.")
packed = struct.unpack("<f", struct.pack("<f", fx))[0]
if not math.isfinite(packed):
raise ValueError(f"Value {fx} overflows float32 REAL precision.")
f32_values.append(0.0 if packed == 0.0 else float(packed))
moments = trial_moments(f32_values)
with psycopg.connect(self._dsn) as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO trial_ledger (
principal_id,
campaign_id,
stage,
universe_market,
horizon_bucket,
hypothesis_id,
expression_hash,
sample_start,
sample_end,
n_obs,
sharpe_unann,
skewness,
kurtosis,
daily_series
) VALUES (
%s, %s, %s, %s, %s, %s, %s, %s::date, %s::date, %s, %s, %s, %s, %s::real[]
)
RETURNING trial_id, created_at
""",
(
principal_id,
campaign_id,
stage,
universe_market,
horizon_bucket,
hypothesis_id,
expression_hash,
sample_start,
sample_end,
moments.n_obs,
moments.sharpe_unann,
moments.skewness,
moments.kurtosis,
f32_values,
),
)
row = cur.fetchone()
assert row is not None
trial_id, created_at = int(row[0]), row[1].isoformat()
conn.commit()
return RecordedTrial(
trial_id=trial_id,
created_at=created_at,
expression_hash=expression_hash,
n_obs=moments.n_obs,
sharpe_unann=moments.sharpe_unann,
skewness=moments.skewness,
kurtosis=moments.kurtosis,
)
def cluster_deflated_sharpe(
self,
*,
trial_id: int,
observation_dates_by_trial_id: Mapping[int, Sequence[str]] | None = None,
dsr_gate: float = DSR_VALIDATION_GATE,
) -> ClusterDsrSummary:
"""Loads target trial and its `(universe_market, horizon_bucket)` cluster and computes DSR."""
with psycopg.connect(self._dsn) as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT trial_id, universe_market, horizon_bucket, n_obs,
sharpe_unann, skewness, kurtosis, daily_series
FROM trial_ledger
WHERE trial_id = %s
""",
(trial_id,),
)
target = cur.fetchone()
if target is None:
raise LookupError(f"trial_id={trial_id} not found in trial_ledger.")
_, universe_market, horizon_bucket, n_obs, sr, skew, kurt, _ = target
cur.execute(
"""
SELECT trial_id, sharpe_unann, daily_series
FROM trial_ledger
WHERE universe_market = %s AND horizon_bucket = %s
ORDER BY trial_id ASC
""",
(universe_market, horizon_bucket),
)
cluster_rows = cur.fetchall()
cluster_sharpes = [float(r[1]) for r in cluster_rows]
aligned_items: list[tuple[int, dict[str, float]]] = []
for r_id, _, r_series in cluster_rows:
tid = int(r_id)
dates = (observation_dates_by_trial_id or {}).get(tid)
if dates is not None and len(dates) == len(r_series):
aligned_items.append((tid, {d: float(v) for d, v in zip(dates, r_series)}))
else:
aligned_items.append((tid, {}))
eff: EffectiveTrialsResult = effective_independent_trials(aligned_items)
dsr_res: DeflatedSharpeResult = deflated_sharpe_ratio(
sharpe_unann=float(sr),
n_obs=int(n_obs),
skewness=float(skew),
kurtosis=float(kurt),
n_hat=eff.n_hat,
cluster_sharpes=cluster_sharpes,
)
return ClusterDsrSummary(
trial_id=trial_id,
cluster_size=eff.k,
effective_trials=eff.n_hat,
mean_correlation=eff.mean_correlation,
pairs_used=eff.pairs_used,
pairs_skipped=eff.pairs_skipped,
sr0=dsr_res.sr0,
standard_error=dsr_res.standard_error,
dsr=dsr_res.dsr,
passes_gate=dsr_res.dsr >= dsr_gate,
)

137
python/stockbot/signals.py Normal file
View file

@ -0,0 +1,137 @@
"""High-level Signal Analyzer & Event Study runners with write-before-return trial logging."""
from __future__ import annotations
from typing import Any, Mapping
import polars as pl
from .calculations import analyze_signal_panel, compute_event_study
from .ledger import (
ClusterDsrSummary,
HorizonBucket,
RecordedTrial,
TrialLedgerClient,
UniverseMarket,
canonical_expression_hash,
)
def run_signal_study(
*,
panel: pl.DataFrame,
ledger: TrialLedgerClient,
principal_id: str = "operator",
universe_market: UniverseMarket,
horizon_bucket: HorizonBucket,
horizon_label: str,
expression: str,
params: Mapping[str, Any],
vault_cutoff_date: str,
n_quantiles: int = 5,
min_cross_section: int = 10,
ledger_series: str = "rank_ic",
) -> dict[str, Any]:
"""Runs Signal Analyzer under the Vault fence, writes to `trial_ledger`, and computes cluster DSR."""
analysis = analyze_signal_panel(
panel,
vault_cutoff_date=vault_cutoff_date,
n_quantiles=n_quantiles,
min_cross_section=min_cross_section,
)
dates: list[str] = analysis["dates"] # type: ignore[assignment]
if len(dates) < 2:
return {"status": "insufficient_data", "analysis": analysis, "trial": None, "dsr": None}
series: list[float] = (
analysis["rank_ic_series"] if ledger_series == "rank_ic" else analysis["spread_series"]
) # type: ignore[assignment]
expr_hash = canonical_expression_hash(
expression=expression,
params=params,
universe=universe_market,
sample_start=dates[0],
sample_end=dates[-1],
horizon=horizon_label,
)
recorded: RecordedTrial = ledger.record_trial(
principal_id=principal_id,
stage="signal_ic",
universe_market=universe_market,
horizon_bucket=horizon_bucket,
expression_hash=expr_hash,
sample_start=dates[0],
sample_end=dates[-1],
vault_cutoff_date=vault_cutoff_date,
daily_series=series,
)
dsr: ClusterDsrSummary = ledger.cluster_deflated_sharpe(
trial_id=recorded.trial_id,
observation_dates_by_trial_id={recorded.trial_id: dates},
)
return {
"status": "ok",
"analysis": analysis,
"trial": recorded,
"dsr": dsr,
}
def run_event_study_trial(
*,
bars_df: pl.DataFrame,
events_df: pl.DataFrame,
ledger: TrialLedgerClient,
principal_id: str = "operator",
universe_market: UniverseMarket,
horizon_bucket: HorizonBucket,
expression: str,
params: Mapping[str, Any],
vault_cutoff_date: str,
pre_days: int = 5,
post_days: int = 10,
min_events: int = 5,
) -> dict[str, Any]:
"""Runs Event Study under the Vault fence, writes to `trial_ledger`, and computes cluster DSR."""
study = compute_event_study(
bars_df,
events_df,
vault_cutoff_date=vault_cutoff_date,
pre_days=pre_days,
post_days=post_days,
min_events=min_events,
)
if study.get("status") != "ok":
return {"status": "insufficient_data", "study": study, "trial": None, "dsr": None}
dates: list[str] = study["clustered_dates"] # type: ignore[assignment]
series: list[float] = study["mean_cars"] # type: ignore[assignment]
expr_hash = canonical_expression_hash(
expression=expression,
params=params,
universe=universe_market,
sample_start=dates[0],
sample_end=dates[-1],
horizon=f"event_-{pre_days}_+{post_days}d",
)
recorded = ledger.record_trial(
principal_id=principal_id,
stage="event_study",
universe_market=universe_market,
horizon_bucket=horizon_bucket,
expression_hash=expr_hash,
sample_start=dates[0],
sample_end=dates[-1],
vault_cutoff_date=vault_cutoff_date,
daily_series=series,
)
dsr = ledger.cluster_deflated_sharpe(
trial_id=recorded.trial_id,
observation_dates_by_trial_id={recorded.trial_id: dates},
)
return {
"status": "ok",
"study": study,
"trial": recorded,
"dsr": dsr,
}

226
python/stockbot/vault.py Normal file
View file

@ -0,0 +1,226 @@
"""Rolling 6-month UTC Vault holdout fence & DuckDB connection budget."""
from __future__ import annotations
import calendar
import os
import re
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Literal, Mapping
DataScope = Literal["vault_fenced", "vault_evaluation_only"]
DEFAULT_DUCKDB_MEMORY_LIMIT = "6GB"
DEFAULT_DUCKDB_THREADS = 4
DEFAULT_DUCKDB_TEMP_DIRECTORY = "/mnt/data/stockbot/tmp/duckdb"
_DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
_MEM_LIMIT_RE = re.compile(r"^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$")
class MarketDataStoreValidationError(ValueError):
"""Raised when market-data query bounds, timestamps, or budgets are invalid."""
class VaultHoldoutFenceError(PermissionError):
"""Raised when a fenced query reaches or exceeds the rolling 6-month Vault cutoff."""
def __init__(self, from_bound: str, from_ms: int, vault_cutoff_ts: int) -> None:
super().__init__(
f'Query start "{from_bound}" ({from_ms}) reaches or exceeds Vault cutoff ({vault_cutoff_ts}).'
)
self.from_bound = from_bound
self.from_ms = from_ms
self.vault_cutoff_ts = vault_cutoff_ts
class VaultScopeNotAuthorizedError(PermissionError):
"""Raised when vault_evaluation_only is requested without operator authorization."""
@dataclass(frozen=True)
class FencedTimeRange:
from_ms: int
to_ms: int
as_of_ms: int
scope: DataScope
clamped_to: bool
clamped_as_of: bool
@property
def from_micros(self) -> int:
return self.from_ms * 1000
@property
def to_micros(self) -> int:
# Expand end-of-ms inclusive boundary to last microsecond (.999999) when ms ends in 999
return self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0)
@property
def as_of_micros(self) -> int:
return self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0)
@dataclass(frozen=True)
class DuckDbConnectionBudget:
memory_limit: str
threads: int
temp_directory: str
@property
def statements(self) -> tuple[str, str, str]:
escaped = self.temp_directory.replace("'", "''")
return (
f"SET memory_limit = '{self.memory_limit}';",
f"SET threads = {self.threads};",
f"SET temp_directory = '{escaped}';",
)
def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
if not isinstance(raw, str) or not raw:
raise MarketDataStoreValidationError(f'Expected non-empty ISO-8601 string for "{field}".')
m = _DATE_ONLY_RE.match(raw)
if m:
year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
if bound_kind == "start":
dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc)
else:
dt = datetime(year, month, day, 23, 59, 59, 999000, tzinfo=timezone.utc)
return int(dt.timestamp() * 1000)
try:
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
except ValueError as exc:
raise MarketDataStoreValidationError(
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
) from exc
if dt.tzinfo is None:
raise MarketDataStoreValidationError(
f'Naive timestamp without timezone offset is forbidden for "{field}": "{raw}".'
)
dt_utc = dt.astimezone(timezone.utc)
return int(dt_utc.timestamp() * 1000)
def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int:
"""Computes rolling 6-month Vault cutoff (`max_ingested_ts - 6 calendar months` UTC)."""
if isinstance(max_ingested_ts, int) and not isinstance(max_ingested_ts, bool):
epoch_ms = max_ingested_ts
elif isinstance(max_ingested_ts, str):
epoch_ms = parse_timestamp_ms(max_ingested_ts, "start", "max_ingested_ts")
elif isinstance(max_ingested_ts, datetime):
if max_ingested_ts.tzinfo is None:
raise MarketDataStoreValidationError("max_ingested_ts datetime must be timezone-aware.")
epoch_ms = int(max_ingested_ts.astimezone(timezone.utc).timestamp() * 1000)
else:
raise MarketDataStoreValidationError("Invalid max_ingested_ts type.")
dt = datetime.fromtimestamp(epoch_ms / 1000.0, tz=timezone.utc)
total_months = dt.year * 12 + (dt.month - 1) - 6
target_year, target_month_zero = divmod(total_months, 12)
target_month = target_month_zero + 1
max_day = calendar.monthrange(target_year, target_month)[1]
target_day = min(dt.day, max_day)
cutoff_dt = datetime(
target_year,
target_month,
target_day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
tzinfo=timezone.utc,
)
return int(cutoff_dt.timestamp() * 1000)
def vault_cutoff_date_str(vault_cutoff_ts: int) -> str:
return datetime.fromtimestamp(vault_cutoff_ts / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d")
def apply_vault_fence(
from_bound: str,
to_bound: str,
vault_cutoff_ts: int,
as_of: str | None = None,
scope: DataScope = "vault_fenced",
vault_operator_authorized: bool = False,
) -> FencedTimeRange:
from_ms = parse_timestamp_ms(from_bound, "start", "from")
to_ms = parse_timestamp_ms(to_bound, "end", "to")
if to_ms < from_ms:
raise MarketDataStoreValidationError(
f'Query end "{to_bound}" ({to_ms}) precedes start "{from_bound}" ({from_ms}).'
)
if scope == "vault_evaluation_only":
if not vault_operator_authorized:
raise VaultScopeNotAuthorizedError(
"Data scope 'vault_evaluation_only' requires explicit human operator authorization."
)
as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of is not None else to_ms
return FencedTimeRange(
from_ms=from_ms,
to_ms=to_ms,
as_of_ms=as_of_ms,
scope=scope,
clamped_to=False,
clamped_as_of=False,
)
if scope != "vault_fenced":
raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}")
if from_ms >= vault_cutoff_ts:
raise VaultHoldoutFenceError(from_bound, from_ms, vault_cutoff_ts)
clamped_to = False
if to_ms >= vault_cutoff_ts:
to_ms = vault_cutoff_ts - 1
clamped_to = True
clamped_as_of = False
if as_of is None:
as_of_ms = vault_cutoff_ts - 1
else:
as_of_ms = parse_timestamp_ms(as_of, "end", "as_of")
if as_of_ms >= vault_cutoff_ts:
as_of_ms = vault_cutoff_ts - 1
clamped_as_of = True
return FencedTimeRange(
from_ms=from_ms,
to_ms=to_ms,
as_of_ms=as_of_ms,
scope="vault_fenced",
clamped_to=clamped_to,
clamped_as_of=clamped_as_of,
)
def resolve_duckdb_budget(
env: Mapping[str, str] | None = None,
*,
memory_limit: str | None = None,
threads: int | None = None,
temp_directory: str | None = None,
) -> DuckDbConnectionBudget:
source = env if env is not None else os.environ
mem = memory_limit or source.get("STOCK_BOT_DUCKDB_MEMORY_LIMIT") or DEFAULT_DUCKDB_MEMORY_LIMIT
if not _MEM_LIMIT_RE.match(mem):
raise MarketDataStoreValidationError(f"Invalid DuckDB memory_limit: {mem!r}")
raw_threads = threads if threads is not None else int(
source.get("STOCK_BOT_DUCKDB_THREADS", str(DEFAULT_DUCKDB_THREADS))
)
if not isinstance(raw_threads, int) or raw_threads < 1 or raw_threads > 64:
raise MarketDataStoreValidationError(f"Invalid DuckDB threads: {raw_threads!r}")
tmp_dir = (
temp_directory
or source.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY")
or DEFAULT_DUCKDB_TEMP_DIRECTORY
)
if not tmp_dir or not tmp_dir.startswith("/"):
raise MarketDataStoreValidationError(f"Invalid DuckDB temp_directory: {tmp_dir!r}")
return DuckDbConnectionBudget(memory_limit=mem, threads=raw_threads, temp_directory=tmp_dir)

View file

@ -0,0 +1,153 @@
"""Unit tests for the `stockbot` Python SDK (Vault fence, DSR parity, DuckDB/Parquet store)."""
from __future__ import annotations
import math
from datetime import date, datetime, timezone
from pathlib import Path
import polars as pl
import pytest
from stockbot import (
MarketDataStore,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
analyze_signal_panel,
apply_vault_fence,
canonical_expression_hash,
compute_vault_cutoff_ts,
deflated_sharpe_ratio,
effective_independent_trials,
resolve_duckdb_budget,
trial_moments,
)
def test_vault_cutoff_and_fencing_rules() -> None:
cutoff = compute_vault_cutoff_ts("2025-08-13")
expected = int(datetime(2025, 2, 13, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000)
assert cutoff == expected
# Clamps to and as_of strictly below cutoff
fenced = apply_vault_fence("2020-01-01", "2025-08-13", cutoff)
assert fenced.clamped_to is True
assert fenced.to_ms == cutoff - 1
assert fenced.as_of_ms == cutoff - 1
# Rejects start >= cutoff
with pytest.raises(VaultHoldoutFenceError):
apply_vault_fence("2025-02-13", "2025-05-01", cutoff)
# Rejects unauthorized vault_evaluation_only
with pytest.raises(VaultScopeNotAuthorizedError):
apply_vault_fence("2025-02-13", "2025-05-01", cutoff, scope="vault_evaluation_only")
def test_trial_moments_and_dsr_match_canonical_math() -> None:
series = [0.01, 0.02, -0.005, 0.015, 0.008, -0.002, 0.012, 0.004]
m = trial_moments(series)
assert m.n_obs == 8
assert m.sharpe_unann > 0.0
assert m.kurtosis >= m.skewness ** 2 + 1.0
# Identical series -> rho = 1.0 -> N_hat = 1.0
dates = [f"2024-01-0{i+1}" for i in range(len(series))]
eff_dup = effective_independent_trials(
[(1, dict(zip(dates, series))), (2, dict(zip(dates, series)))]
)
assert math.isclose(eff_dup.mean_correlation or 0.0, 1.0, rel_tol=1e-9)
assert math.isclose(eff_dup.n_hat, 1.0, rel_tol=1e-9)
dsr = deflated_sharpe_ratio(
sharpe_unann=m.sharpe_unann,
n_obs=m.n_obs,
skewness=m.skewness,
kurtosis=m.kurtosis,
n_hat=2.0,
cluster_sharpes=[m.sharpe_unann, 0.1],
)
assert 0.0 <= dsr.dsr <= 1.0
assert dsr.standard_error > 0.0
def test_canonical_expression_hash_is_deterministic() -> None:
h1 = canonical_expression_hash(
expression=" ca_shorts neg_shares_short ",
params={"b": 2, "a": 1, "skip": None},
universe="CA_EQ",
sample_start="2018-01-01",
sample_end="2025-01-31",
horizon="5d",
)
h2 = canonical_expression_hash(
expression="ca_shorts neg_shares_short",
params={"a": 1, "b": 2},
universe="CA_EQ",
sample_start="2018-01-01",
sample_end="2025-01-31",
horizon="5d",
)
assert len(h1) == 64
assert h1 == h2
def test_duckdb_market_data_store_enforces_vault_fence(tmp_path: Path) -> None:
bars_dir = tmp_path / "bars_1d" / "year=2025"
bars_dir.mkdir(parents=True)
df = pl.DataFrame(
{
"listing_id": pl.Series([1, 1], dtype=pl.Int32),
"ts": pl.Series(
[
datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc),
datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc),
],
dtype=pl.Datetime("us", "UTC"),
),
"session_date": pl.Series([date(2025, 2, 10), date(2025, 2, 20)], dtype=pl.Date),
"open": [10.0, 11.0],
"high": [10.5, 11.5],
"low": [9.8, 10.8],
"close": [10.2, 11.2],
"volume": [1000.0, 2000.0],
"vwap": [None, None],
"currency": ["CAD", "CAD"],
"source": ["eod", "eod"],
"known_at": pl.Series(
[
datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc),
datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc),
],
dtype=pl.Datetime("us", "UTC"),
),
}
)
df.write_parquet(bars_dir / "part.parquet")
cutoff = compute_vault_cutoff_ts("2025-08-13") # 2025-02-13
budget = resolve_duckdb_budget(memory_limit="1GB", threads=2, temp_directory=str(tmp_path / "tmp"))
with MarketDataStore(tmp_path, vault_cutoff_ts=cutoff, budget=budget) as store:
out = store.bars(from_date="2025-01-01", to_date="2025-08-13", adjustment="raw")
assert out.height == 1
assert str(out["session_date"][0]) == "2025-02-10"
def test_signal_panel_analyzer_excludes_vault_rows() -> None:
rows = []
for day_idx in range(1, 20):
d = f"2025-02-{day_idx:02d}"
for lid in range(1, 15):
rows.append(
{
"session_date": d,
"listing_id": lid,
"signal": float(lid),
"forward_return": 0.001 * lid + (0.0001 * day_idx),
}
)
panel = pl.DataFrame(rows)
res = analyze_signal_panel(panel, vault_cutoff_date="2025-02-13", min_cross_section=10)
assert res["vault_excluded_rows"] > 0
assert all(d < "2025-02-13" for d in res["dates"]) # type: ignore[union-attr]
assert res["mean_rank_ic"] > 0.9 # type: ignore[operator]

1308
python/uv.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,251 @@
import marimo
__generated_with = "0.26.0"
app = marimo.App(width="medium")
@app.cell
def _():
import os
from pathlib import Path
import marimo as mo
import polars as pl
from stockbot import (
MarketDataStore,
TrialLedgerClient,
compute_vault_cutoff_ts,
resolve_duckdb_budget,
run_event_study_trial,
run_signal_study,
vault_cutoff_date_str,
)
curated_root = Path(os.environ.get("STOCK_BOT_CURATED_ROOT", "/mnt/data/stockbot/m1-curated"))
max_ingested_date = os.environ.get("STOCK_BOT_MAX_INGESTED_DATE", "2025-08-13")
vault_cutoff_ts = compute_vault_cutoff_ts(max_ingested_date)
vault_cutoff_date = vault_cutoff_date_str(vault_cutoff_ts)
trial_ledger_dsn = os.environ.get("STOCK_BOT_TRIAL_LEDGER_DSN", "")
temp_dir = os.environ.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY", "/tmp/stockbot-duckdb")
mo.md(
f"""
# Canadian `ceoShorts` & `qmFilings` Signal Lab Study (M1)
- **Curated Root:** `{curated_root}`
- **Max Ingested Date:** `{max_ingested_date}`
- **Rolling 6-Month Vault Cutoff (exclusive):** `{vault_cutoff_date}`
- **Trial Ledger Configured:** `{"yes" if bool(trial_ledger_dsn) else "no"}`
"""
)
return (
MarketDataStore,
TrialLedgerClient,
curated_root,
mo,
pl,
resolve_duckdb_budget,
run_event_study_trial,
run_signal_study,
temp_dir,
trial_ledger_dsn,
vault_cutoff_date,
vault_cutoff_ts,
)
@app.cell
def _(
MarketDataStore,
curated_root,
mo,
pl,
resolve_duckdb_budget,
temp_dir,
vault_cutoff_date,
vault_cutoff_ts,
):
_budget = resolve_duckdb_budget(
memory_limit="4GB",
threads=4,
temp_directory=temp_dir,
)
_adj_fenced = curated_root / "adj_factors_fenced" / "part.parquet"
if not _adj_fenced.exists():
_adj_fenced = curated_root / "adj_factors" / "part.parquet"
_adj_mode = "total" if _adj_fenced.exists() else "raw"
with MarketDataStore(
curated_root,
vault_cutoff_ts=vault_cutoff_ts,
budget=_budget,
adj_factors_path=_adj_fenced if _adj_fenced.exists() else None,
) as _store:
_ca_bars = _store.bars(
currencies=["CAD"],
from_date="2017-01-01",
to_date=vault_cutoff_date,
adjustment=_adj_mode,
)
_ca_shorts = _store.shorts_as_of(
from_date="2017-01-01",
to_date=vault_cutoff_date,
)
_ca_events = _store.events(
kinds=["filing"],
from_date="2017-01-01",
to_date=vault_cutoff_date,
)
_ca_listing_ids = _ca_bars.select("listing_id").unique()
_ca_events = _ca_events.join(_ca_listing_ids, on="listing_id", how="semi")
_ca_shorts = _ca_shorts.join(_ca_listing_ids, on="listing_id", how="semi")
# Confirm zero Vault rows leaked into any frame
_vault_bar_leaks = int(
_ca_bars.filter(pl.col("session_date").cast(pl.String) >= vault_cutoff_date).height
)
assert _vault_bar_leaks == 0, f"Vault fence breach: {_vault_bar_leaks} bars >= {vault_cutoff_date}"
# Build strict PIT ceoShorts signal panel (join_asof known_at <= bar.ts) with 5-session forward return
_bars_fwd = (
_ca_bars.sort(["listing_id", "session_date"])
.with_columns(
(pl.col("close").shift(-5).over("listing_id") / pl.col("close") - 1.0).alias(
"forward_return"
),
(pl.col("close") * pl.col("volume")).alias("dollar_vol"),
)
.filter(pl.col("forward_return").is_finite() & (pl.col("close") > 0.10))
)
_shorts_sorted = (
_ca_shorts.select(["listing_id", "known_at", "shares_short", "net_change"])
.filter(pl.col("shares_short") > 0)
.sort(["listing_id", "known_at"])
)
shorts_panel = (
_bars_fwd.sort(["listing_id", "ts"])
.join_asof(
_shorts_sorted,
left_on="ts",
right_on="known_at",
by="listing_id",
strategy="backward",
)
.filter(pl.col("shares_short").is_not_null())
.with_columns(
(-(pl.col("shares_short") / (pl.col("volume").clip(lower_bound=1.0)))).alias("signal")
)
.select(["session_date", "listing_id", "signal", "forward_return"])
)
ca_bars_summary = {
"adjustment": _adj_mode,
"ca_bars_rows": int(_ca_bars.height),
"ca_shorts_rows": int(_ca_shorts.height),
"ca_filings_rows": int(_ca_events.height),
"shorts_panel_rows": int(shorts_panel.height),
"vault_bar_leaks": _vault_bar_leaks,
}
ca_bars_slim = _ca_bars.filter(pl.col("close") >= 0.10).select(["listing_id", "session_date", "ts", "close"])
ca_filings_slim = _ca_events.select(["listing_id", "known_at", "subtype"])
mo.md(
f"""
## Loaded Curated Canadian Datasets (Zero Vault Rows)
- **Adjustment mode:** `{ca_bars_summary['adjustment']}`
- **Canadian `bars_1d` rows:** `{ca_bars_summary['ca_bars_rows']:,}` (`vault_bar_leaks = {ca_bars_summary['vault_bar_leaks']}`)
- **Canadian `shorts` (`ceoShorts`, +4bd lag) rows:** `{ca_bars_summary['ca_shorts_rows']:,}`
- **Canadian `events` (`qmFilings`) rows:** `{ca_bars_summary['ca_filings_rows']:,}`
- **Joined PIT `ceoShorts` panel rows:** `{ca_bars_summary['shorts_panel_rows']:,}`
"""
)
return ca_bars_slim, ca_bars_summary, ca_filings_slim, shorts_panel
@app.cell
def _(
TrialLedgerClient,
ca_bars_slim,
ca_filings_slim,
mo,
run_event_study_trial,
run_signal_study,
shorts_panel,
trial_ledger_dsn,
vault_cutoff_date,
):
if not trial_ledger_dsn:
mo.stop(True, mo.md("Set `STOCK_BOT_TRIAL_LEDGER_DSN` to write trials to `trial_ledger`."))
_ledger = TrialLedgerClient(trial_ledger_dsn)
shorts_study = run_signal_study(
panel=shorts_panel,
ledger=_ledger,
principal_id="operator",
universe_market="CA_EQ",
horizon_bucket="swing_1_10d",
horizon_label="5d",
expression="neg_ciro_short_interest_to_volume_5d",
params={"lag_bd": 4, "horizon_sessions": 5, "min_price_cad": 0.10, "n_quantiles": 5},
vault_cutoff_date=vault_cutoff_date,
n_quantiles=5,
min_cross_section=10,
ledger_series="rank_ic",
)
filings_study = run_event_study_trial(
bars_df=ca_bars_slim,
events_df=ca_filings_slim,
ledger=_ledger,
principal_id="operator",
universe_market="CA_EQ",
horizon_bucket="swing_1_10d",
expression="ca_qm_filings_abnormal_return_event_study",
params={"pre_days": 5, "post_days": 10, "benchmark": "equal_weight"},
vault_cutoff_date=vault_cutoff_date,
pre_days=5,
post_days=10,
min_events=5,
)
_s_trial = shorts_study["trial"]
_s_dsr = shorts_study["dsr"]
_s_ana = shorts_study["analysis"]
_f_trial = filings_study["trial"]
_f_dsr = filings_study["dsr"]
_f_stu = filings_study["study"]
mo.md(
f"""
## Study Results & `trial_ledger` Deflated Sharpe
### 1. Canadian `ceoShorts` 5-Day Forward Return Signal
- **Status:** `{shorts_study['status']}`
- **Trial ID:** `{_s_trial.trial_id if _s_trial else None}` | **n_obs:** `{_s_trial.n_obs if _s_trial else 0}`
- **Mean Rank-IC:** `{_s_ana['mean_rank_ic']:.6f}` (Newey-West t = `{_s_ana['rank_ic_nw_t']:.3f}`)
- **Mean Q5-Q1 Spread:** `{_s_ana['mean_quantile_spread']:.6f}` (Turnover = `{_s_ana['mean_top_quantile_turnover']:.3f}`)
- **Recency Gate (Post-2023):** `{_s_ana['recency_rank_ic']}`
- **Unannualized Sharpe:** `{_s_trial.sharpe_unann if _s_trial else float('nan'):.6f}`
- **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_s_dsr.cluster_size if _s_dsr else 0}` / `{_s_dsr.effective_trials if _s_dsr else 0.0:.4f}`
- **Deflated Sharpe Ratio (DSR):** `{_s_dsr.dsr if _s_dsr else float('nan'):.6f}` (`passes_gate = {_s_dsr.passes_gate if _s_dsr else False}`)
### 2. Canadian `qmFilings` Event Study (`[-5, +10]` sessions)
- **Status:** `{filings_study['status']}`
- **Trial ID:** `{_f_trial.trial_id if _f_trial else None}` | **Events Used:** `{_f_stu.get('events_used', 0)}` | **Event Dates:** `{_f_stu.get('n_dates', 0)}`
- **Mean Post-Event CAR:** `{_f_stu.get('car_mean', float('nan')):.6f}` (Newey-West t = `{_f_stu.get('car_nw_t', float('nan')):.3f}`)
- **Recency Gate (Post-2023):** `{_f_stu.get('recency')}`
- **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_f_dsr.cluster_size if _f_dsr else 0}` / `{_f_dsr.effective_trials if _f_dsr else 0.0:.4f}`
- **Deflated Sharpe Ratio (DSR):** `{_f_dsr.dsr if _f_dsr else float('nan'):.6f}` (`passes_gate = {_f_dsr.passes_gate if _f_dsr else False}`)
"""
)
return filings_study, shorts_study
if __name__ == "__main__":
app.run()

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

@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] }
mongodb = { version = "=3.10.2", default-features = false, features = ["compat-3-3-0", "bson-3", "sync", "rustls-tls", "dns-resolver"] }
parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] }
rayon = "=1.12.0"

View file

@ -467,7 +467,7 @@ Rules:
- `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`.
- `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25).
- `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
- `splitratio` (`FIELD_SPLIT_RATIO`): BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `splitratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
- `splitratio` (`FIELD_SPLIT_RATIO`), `forfactor` (`FIELD_FOR_FACTOR`), `tofactor` (`FIELD_TO_FACTOR`): BSON `Double`, `Int32`, or `Int64`; `splitratio` must be finite and `> 0.0`. Empirically across all `18,751` live `qmSplits` documents (`16,892/16,892` with numeric `forfactor`/`tofactor`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `0.1` for NVDA's `2024-06-10` 10:1 forward split; `8` for GE's `2021-08-02` 1:8 reverse split). `decode_qm_split_doc` converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1), or `1.0 / splitratio` otherwise. `ratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
- `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding.
- `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below.
- `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below.

View file

@ -5416,7 +5416,9 @@ fn run_curate_bars_cmd_benchmark_tracked(
let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()];
doc.append(cstr!("qmSearchCode"), qm_code.as_str());
doc.append(cstr!("date"), date_str.as_str());
doc.append(cstr!("splitratio"), ratio);
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
let in_reuse_gap = k % 50 == 1 && (gap_start..=gap_end).contains(&ex_date);
if !in_reuse_gap {
@ -5442,7 +5444,9 @@ fn run_curate_bars_cmd_benchmark_tracked(
doc.append(cstr!("_id"), ObjectId::from_bytes(alias_oid));
doc.append(cstr!("qmSearchCode"), alias_qm_code.as_str());
doc.append(cstr!("date"), date_str.as_str());
doc.append(cstr!("splitratio"), ratio);
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
}
}
splits_w

View file

@ -57,7 +57,18 @@ pub const FIELD_DATE: &str = "date";
/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`).
pub const FIELD_DECLARED: &str = "declared";
/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`).
///
/// Empirically verified across all `18,751` documents in `qmSplits` (`16,892/16,892` with numeric
/// `forfactor`/`tofactor`): QuoteMedia stores `splitratio = forfactor / tofactor = old_shares /
/// new_shares` (e.g. `0.1` for a 10:1 forward split such as `NVDA 2024-06-10`, `8.0` for a 1:8
/// reverse split such as `GE 2021-08-02`). [`decode_qm_split_doc`] converts this to canonical
/// `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding
/// QuoteMedia's 6-decimal truncation such as `0.142857` for 7:1), or `1.0 / splitratio` otherwise.
pub const FIELD_SPLIT_RATIO: &str = "splitratio";
/// MongoDB field name for QuoteMedia's `old_shares` factor (`forfactor`).
pub const FIELD_FOR_FACTOR: &str = "forfactor";
/// MongoDB field name for QuoteMedia's `new_shares` factor (`tofactor`).
pub const FIELD_TO_FACTOR: &str = "tofactor";
/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`).
pub const FIELD_USD_FX_RATE: &str = "usdFxRate";
/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention).
@ -573,13 +584,25 @@ fn decode_non_negative_number(
}
}
#[inline]
fn decode_optional_positive_factor(val: RawBsonRef<'_>) -> Option<f64> {
match val {
RawBsonRef::Double(v) if v.is_finite() && v > 0.0 => Some(v),
RawBsonRef::Int32(v) if v > 0 => Some(f64::from(v)),
RawBsonRef::Int64(v) if v > 0 => Some(v as f64),
_ => None,
}
}
fn decode_qm_split_doc_at<'a>(
doc: &'a RawDocument,
offset: usize,
) -> Result<RawQmSplit<'a>, BsonQmActionError> {
let mut qm_search_code: Option<&'a str> = None;
let mut ex_date: Option<i32> = None;
let mut ratio: Option<f64> = None;
let mut raw_split_ratio: Option<f64> = None;
let mut for_factor: Option<f64> = None;
let mut to_factor: Option<f64> = None;
let mut declared_date: Option<i32> = None;
for elem_res in doc.iter_elements() {
@ -597,7 +620,13 @@ fn decode_qm_split_doc_at<'a>(
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
} else if key == FIELD_SPLIT_RATIO {
let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?;
ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?);
raw_split_ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?);
} else if key == FIELD_FOR_FACTOR {
let val = decode_element_value(FIELD_FOR_FACTOR, elem, offset)?;
for_factor = decode_optional_positive_factor(val);
} else if key == FIELD_TO_FACTOR {
let val = decode_element_value(FIELD_TO_FACTOR, elem, offset)?;
to_factor = decode_optional_positive_factor(val);
} else if key == FIELD_DECLARED {
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
@ -613,12 +642,33 @@ fn decode_qm_split_doc_at<'a>(
let Some(ex_date) = ex_date else {
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
};
let Some(ratio) = ratio else {
let Some(raw_split_ratio) = raw_split_ratio else {
return Err(BsonQmActionError::MissingField {
field: FIELD_SPLIT_RATIO,
});
};
// QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares`.
// Convert to canonical `new_shares / old_shares`, preferring exact `tofactor / forfactor`
// when both are present and positive.
let ratio = match (for_factor, to_factor) {
(Some(f), Some(t)) => {
let exact = t / f;
if exact.is_finite() && exact > 0.0 {
exact
} else {
1.0 / raw_split_ratio
}
}
_ => 1.0 / raw_split_ratio,
};
if !ratio.is_finite() || ratio <= 0.0 {
return Err(BsonQmActionError::InvalidNumber {
field: FIELD_SPLIT_RATIO,
value: raw_split_ratio,
});
}
Ok(RawQmSplit {
qm_search_code,
ex_date,

View file

@ -17,7 +17,13 @@ fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) ->
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
if let Some(decl) = declared {
doc.append(cstr!("declared"), decl);
}
@ -63,7 +69,9 @@ fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rat
split_doc.append(cstr!("qmSearchCode"), "NVDA");
split_doc.append(cstr!("date"), "2024-06-10");
split_doc.append(cstr!("declared"), "2024-05-22");
split_doc.append(cstr!("splitratio"), 10.0_f64);
split_doc.append(cstr!("forfactor"), 1_i32);
split_doc.append(cstr!("tofactor"), 10_i32);
split_doc.append(cstr!("splitratio"), 0.1_f64);
split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type");
split_doc.append(
cstr!("reportDate"),
@ -121,7 +129,7 @@ fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_
split_dt.append(cstr!("qmSearchCode"), "IBM");
split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms));
split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms));
split_dt.append(cstr!("splitratio"), 2_i32);
split_dt.append(cstr!("splitratio"), 0.5_f64);
let split = decode_qm_split_doc(&split_dt).unwrap();
assert_eq!(split.ex_date, -1);
@ -146,11 +154,11 @@ fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_
#[test]
fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() {
// Splits: Double, Int32, Int64.
// Splits: Double, Int32, Int64 (QuoteMedia stores old_shares / new_shares, inverted to new/old).
for (val, expected) in [
(RawBsonRef::Double(0.05), 0.05_f64),
(RawBsonRef::Int32(4), 4.0_f64),
(RawBsonRef::Int64(10), 10.0_f64),
(RawBsonRef::Double(20.0), 0.05_f64),
(RawBsonRef::Int32(4), 0.25_f64),
(RawBsonRef::Int64(10), 0.1_f64),
] {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), "TEST");
@ -160,6 +168,33 @@ fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() {
assert_eq!(decoded.ratio.to_bits(), expected.to_bits());
}
// Exact forfactor / tofactor precedence over truncated splitratio (e.g. AAPL 7:1, GE 1:8, NVDA 2:1 empty).
{
let mut aapl = RawDocumentBuf::new();
aapl.append(cstr!("qmSearchCode"), "AAPL");
aapl.append(cstr!("date"), "2014-06-09");
aapl.append(cstr!("forfactor"), 1_i32);
aapl.append(cstr!("tofactor"), 7_i32);
aapl.append(cstr!("splitratio"), 0.142857_f64);
assert_eq!(decode_qm_split_doc(&aapl).unwrap().ratio, 7.0);
let mut ge = RawDocumentBuf::new();
ge.append(cstr!("qmSearchCode"), "GE");
ge.append(cstr!("date"), "2021-08-02");
ge.append(cstr!("forfactor"), 8_i32);
ge.append(cstr!("tofactor"), 1_i32);
ge.append(cstr!("splitratio"), 8_i32);
assert_eq!(decode_qm_split_doc(&ge).unwrap().ratio, 0.125);
let mut nvda_legacy = RawDocumentBuf::new();
nvda_legacy.append(cstr!("qmSearchCode"), "NVDA");
nvda_legacy.append(cstr!("date"), "2000-06-27");
nvda_legacy.append(cstr!("forfactor"), "");
nvda_legacy.append(cstr!("tofactor"), "");
nvda_legacy.append(cstr!("splitratio"), 0.5_f64);
assert_eq!(decode_qm_split_doc(&nvda_legacy).unwrap().ratio, 2.0);
}
// Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0.
for (val, expected) in [
(RawBsonRef::Double(0.25), 0.25_f64),
@ -233,7 +268,7 @@ fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() {
RawBsonRef::Double(1.0),
RawBsonRef::Int32(1),
RawBsonRef::Int64(1),
RawBsonRef::Double(2.0),
RawBsonRef::Double(0.5),
] {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), "NOOP");

View file

@ -187,6 +187,7 @@ fn validate_role_names(
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawQmFiling<'a> {
pub key: &'a str,
pub exchange: Option<&'a str>,
pub timefiled: &'a str,
pub form_type: &'a str,
pub filing_id: Option<&'a str>,
@ -686,6 +687,7 @@ where
};
let mut key_state = ReqStrState::Missing;
let mut exchange: Option<&'a str> = None;
let mut timefiled_state = ReqStrState::Missing;
let mut form_type_state = ReqStrState::Missing;
let mut filing_id_state = OptStrState::None;
@ -715,6 +717,13 @@ where
filing_id_state = decode_optional_str(val);
} else if fields.url == Some(name) {
url_state = decode_optional_str(val);
} else if name == "exchange" {
if let RawBsonRef::String(s) = val {
let trimmed = s.trim();
if !trimmed.is_empty() {
exchange = Some(trimmed);
}
}
}
}
@ -788,6 +797,7 @@ where
stats.rows_out += 1;
on_row(RawQmFiling {
key,
exchange,
timefiled,
form_type,
filing_id,

View file

@ -25,10 +25,16 @@ use crate::bench::{
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
};
use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD};
use crate::bson_eod_prices::parse_ymd_strict_days;
use crate::bson_qm_events::{
DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD,
DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD,
};
use crate::curate_adj::AdjPointInTimeFence;
use crate::mongo_stream::{
MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV,
MAX_MONGO_BATCH_SIZE,
};
use crate::run_curate_adj::CurateAdjFactorsArgs;
use crate::run_curate_bars::{
default_curate_bars_threads, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE,
@ -37,6 +43,10 @@ use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE};
use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL};
use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE};
use crate::run_mongo::{
CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs,
CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs,
};
/// Parsed CLI command to execute.
#[derive(Debug, Clone, PartialEq)]
@ -44,11 +54,18 @@ pub enum CliAction {
Help,
Version,
CurateBars1d(CurateBars1dArgs),
CurateBars1dMongo(CurateBars1dMongoArgs),
CurateAdjFactors(CurateAdjFactorsArgs),
CurateAdjFactorsFenced(CurateAdjFactorsArgs, AdjPointInTimeFence),
CurateAdjFactorsMongo(CurateAdjFactorsMongoArgs),
CurateCorporateActions(CurateCorporateActionsArgs),
CurateCorporateActionsMongo(CurateCorporateActionsMongoArgs),
CurateFx1d(CurateFx1dArgs),
CurateFx1dMongo(CurateFx1dMongoArgs),
CurateShorts(CurateShortsArgs),
CurateShortsMongo(CurateShortsMongoArgs),
CurateEvents(CurateEventsArgs),
CurateEventsMongo(CurateEventsMongoArgs),
BenchSplit(usize),
BenchAdj(usize),
BenchCorporateActions(usize),
@ -90,17 +107,23 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} [--help | -h]\n\
{name} [--version | -V]\n\
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> [--qm-prices <path>] (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>] [--threads <N>]\n\
Curate daily bars from BSON + TSV files into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE}, --threads: available parallelism)\n\
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
Curate retrospective adj_factors from BSON + TSV + bars_1d Parquet into adj_factors/part.parquet\n\
{name} curate-bars-1d --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--with-qm-prices] [--batch-size <N>] [--limit <N>] [--date-gte <YYYY-MM-DD>] [--date-lt <YYYY-MM-DD>] (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>] [--threads <N>]\n\
Curate daily bars from BSON + TSV files or read-only MongoDB into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE}, --threads: available parallelism)\n\
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir> [--as-of <YYYY-MM-DD>] [--vault-cutoff <YYYY-MM-DD>]\n\
{name} curate-adj-factors --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] [--date-gte <YYYY-MM-DD>] [--date-lt <YYYY-MM-DD>] --provider-mapping <path> --bars-1d <dir> --out <dir> [--as-of <YYYY-MM-DD>] [--vault-cutoff <YYYY-MM-DD>]\n\
Curate retrospective or point-in-time fenced adj_factors into adj_factors/part.parquet\n\
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> (--curate-inputs <dir> | --provider-mapping <path> [--delistings <path>]) --out <dir>\n\
Curate corporate_actions from BSON + TSV files into corporate_actions/part.parquet\n\
{name} curate-corporate-actions --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] (--curate-inputs <dir> | --provider-mapping <path> [--delistings <path>]) --out <dir>\n\
Curate corporate_actions from BSON + TSV files or read-only MongoDB into corporate_actions/part.parquet\n\
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\
{name} curate-fx-1d --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] [--te-symbol <sym>] --out <dir>\n\
Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files or read-only MongoDB into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\
{name} curate-shorts --ceo-shorts <path> --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
Curate shorts from ceoShorts BSON + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\
{name} curate-shorts --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\
{name} curate-events --qm-filings <path> --qm-earnings <path> --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
Curate events from qmFilings + qmEarnings BSON + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\
{name} curate-events --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] [--date-gte <YYYY-MM-DD>] [--date-lt <YYYY-MM-DD>] --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\
{name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
{name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\
{name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
@ -219,7 +242,149 @@ pub fn pin_curate_inputs_dir(dir: &Path) -> Result<PathBuf, String> {
Ok(canonical)
}
fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String> {
const MICROS_PER_DAY: i64 = 86_400_000_000;
#[derive(Default)]
struct MongoFlagState {
from_mongo: bool,
mongo_uri: Option<String>,
mongo_uri_env: Option<String>,
batch_size: Option<u32>,
limit: Option<u64>,
date_gte: Option<String>,
date_lt: Option<String>,
}
impl MongoFlagState {
fn has_any_mongo_option(&self) -> bool {
self.mongo_uri.is_some()
|| self.mongo_uri_env.is_some()
|| self.batch_size.is_some()
|| self.limit.is_some()
|| self.date_gte.is_some()
|| self.date_lt.is_some()
}
fn try_parse_value_flag(
&mut self,
flag: &str,
value: &str,
allow_date_range: bool,
) -> Result<bool, String> {
match flag {
"--mongo-uri" => {
if self.mongo_uri.is_some() {
return Err("duplicate flag '--mongo-uri'".to_string());
}
if value.trim().is_empty() {
return Err("empty value for flag '--mongo-uri'".to_string());
}
self.mongo_uri = Some(value.to_string());
Ok(true)
}
"--mongo-uri-env" => {
if self.mongo_uri_env.is_some() {
return Err("duplicate flag '--mongo-uri-env'".to_string());
}
if value.trim().is_empty() {
return Err("empty value for flag '--mongo-uri-env'".to_string());
}
self.mongo_uri_env = Some(value.to_string());
Ok(true)
}
"--batch-size" => {
if self.batch_size.is_some() {
return Err("duplicate flag '--batch-size'".to_string());
}
let parsed = value.parse::<u32>().map_err(|_| {
format!(
"invalid --batch-size '{value}' (expected an integer in 1..={MAX_MONGO_BATCH_SIZE})"
)
})?;
if parsed == 0 || parsed > MAX_MONGO_BATCH_SIZE {
return Err(format!(
"invalid --batch-size '{value}' (expected an integer in 1..={MAX_MONGO_BATCH_SIZE})"
));
}
self.batch_size = Some(parsed);
Ok(true)
}
"--limit" => {
if self.limit.is_some() {
return Err("duplicate flag '--limit'".to_string());
}
let parsed = value.parse::<u64>().map_err(|_| {
format!("invalid --limit '{value}' (expected a positive integer)")
})?;
if parsed == 0 || parsed > i64::MAX as u64 {
return Err(format!(
"invalid --limit '{value}' (expected a positive integer <= {})",
i64::MAX
));
}
self.limit = Some(parsed);
Ok(true)
}
"--date-gte" if allow_date_range => {
if self.date_gte.is_some() {
return Err("duplicate flag '--date-gte'".to_string());
}
if parse_ymd_strict_days(value).is_none() {
return Err(format!(
"invalid --date-gte '{value}' (expected strict YYYY-MM-DD)"
));
}
self.date_gte = Some(value.to_string());
Ok(true)
}
"--date-lt" if allow_date_range => {
if self.date_lt.is_some() {
return Err("duplicate flag '--date-lt'".to_string());
}
if parse_ymd_strict_days(value).is_none() {
return Err(format!(
"invalid --date-lt '{value}' (expected strict YYYY-MM-DD)"
));
}
self.date_lt = Some(value.to_string());
Ok(true)
}
_ => Ok(false),
}
}
fn build_options(self) -> Result<MongoCliOptions, String> {
if self.mongo_uri.is_some() && self.mongo_uri_env.is_some() {
return Err("cannot combine '--mongo-uri' with '--mongo-uri-env'".to_string());
}
if let (Some(gte), Some(lt)) = (&self.date_gte, &self.date_lt) {
if gte >= lt {
return Err(format!(
"invalid date range: --date-gte '{gte}' must be strictly less than --date-lt '{lt}'"
));
}
}
let uri_source = if let Some(uri) = self.mongo_uri {
MongoUriSource::Literal(uri)
} else {
MongoUriSource::EnvVar(
self.mongo_uri_env
.unwrap_or_else(|| DEFAULT_MONGO_URI_ENV.to_owned()),
)
};
Ok(MongoCliOptions {
uri_source,
batch_size: self.batch_size.unwrap_or(DEFAULT_MONGO_BATCH_SIZE),
limit: self.limit,
date_gte: self.date_gte,
date_lt: self.date_lt,
})
}
}
fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut with_qm_prices = false;
let mut eod_prices: Option<PathBuf> = None;
let mut qm_splits: Option<PathBuf> = None;
let mut qm_prices: Option<PathBuf> = None;
@ -239,6 +404,23 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
));
}
if token == "--from-mongo" {
if mongo.from_mongo {
return Err("duplicate flag '--from-mongo'".to_string());
}
mongo.from_mongo = true;
i += 1;
continue;
}
if token == "--with-qm-prices" {
if with_qm_prices {
return Err("duplicate flag '--with-qm-prices'".to_string());
}
with_qm_prices = true;
i += 1;
continue;
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
@ -253,6 +435,10 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
(token, v)
};
if mongo.try_parse_value_flag(flag, value, true)? {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
@ -314,6 +500,53 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
}
}
if mongo.from_mongo {
if eod_prices.is_some() || qm_splits.is_some() || qm_prices.is_some() {
return Err(
"cannot combine '--from-mongo' with '--eod-prices', '--qm-splits', or '--qm-prices'"
.to_string(),
);
}
let mongo_opts = mongo.build_options()?;
let (provider_mapping, listing_currencies) = if let Some(inputs_dir) = curate_inputs {
if provider_mapping.is_some() {
return Err(
"cannot combine '--curate-inputs' with '--provider-mapping'".to_string()
);
}
if listing_currencies.is_some() {
return Err(
"cannot combine '--curate-inputs' with '--listing-currencies'".to_string(),
);
}
let pinned = pin_curate_inputs_dir(&inputs_dir)?;
(
pinned.join("provider_mapping.tsv"),
pinned.join("listing_currencies.tsv"),
)
} else {
let provider_mapping = provider_mapping
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
let listing_currencies = listing_currencies
.ok_or_else(|| "missing required flag '--listing-currencies'".to_string())?;
(provider_mapping, listing_currencies)
};
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
return Ok(CliAction::CurateBars1dMongo(CurateBars1dMongoArgs {
mongo: mongo_opts,
with_qm_prices,
provider_mapping,
listing_currencies,
out_dir,
rel_tolerance: rel_tolerance.unwrap_or(DEFAULT_CURATE_BARS_REL_TOLERANCE),
threads: threads.unwrap_or_else(default_curate_bars_threads),
}));
}
if mongo.has_any_mongo_option() || with_qm_prices {
return Err("MongoDB streaming flags require '--from-mongo'".to_string());
}
let eod_prices =
eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?;
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
@ -340,7 +573,7 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
};
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
Ok(CurateBars1dArgs {
Ok(CliAction::CurateBars1d(CurateBars1dArgs {
eod_prices,
qm_splits,
qm_prices,
@ -349,15 +582,18 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
out_dir,
rel_tolerance: rel_tolerance.unwrap_or(DEFAULT_CURATE_BARS_REL_TOLERANCE),
threads: threads.unwrap_or_else(default_curate_bars_threads),
})
}))
}
fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CurateAdjFactorsArgs, String> {
fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut qm_splits: Option<PathBuf> = None;
let mut qm_dividends: Option<PathBuf> = None;
let mut provider_mapping: Option<PathBuf> = None;
let mut bars_1d_dir: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
let mut as_of_date: Option<i32> = None;
let mut vault_cutoff_date: Option<i32> = None;
let mut i = 0usize;
while i < args.len() {
@ -368,6 +604,15 @@ fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CurateAdjFactorsArgs,
));
}
if token == "--from-mongo" {
if mongo.from_mongo {
return Err("duplicate flag '--from-mongo'".to_string());
}
mongo.from_mongo = true;
i += 1;
continue;
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
@ -382,6 +627,10 @@ fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CurateAdjFactorsArgs,
(token, v)
};
if mongo.try_parse_value_flag(flag, value, true)? {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
@ -399,10 +648,66 @@ fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CurateAdjFactorsArgs,
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
"--bars-1d" => set_path(&mut bars_1d_dir, "--bars-1d", value)?,
"--out" => set_path(&mut out_dir, "--out", value)?,
"--as-of" => {
if as_of_date.is_some() {
return Err("duplicate flag '--as-of'".to_string());
}
let days = parse_ymd_strict_days(value).ok_or_else(|| {
format!("invalid --as-of '{value}' (expected strict YYYY-MM-DD)")
})?;
as_of_date = Some(days);
}
"--vault-cutoff" => {
if vault_cutoff_date.is_some() {
return Err("duplicate flag '--vault-cutoff'".to_string());
}
let days = parse_ymd_strict_days(value).ok_or_else(|| {
format!("invalid --vault-cutoff '{value}' (expected strict YYYY-MM-DD)")
})?;
vault_cutoff_date = Some(days);
}
other => return Err(format!("unknown flag '{other}' for curate-adj-factors")),
}
}
let fence = if as_of_date.is_some() || vault_cutoff_date.is_some() {
let as_of_micros = as_of_date.map(|d| (i64::from(d) + 1) * MICROS_PER_DAY - 1);
let vault_cutoff_micros = vault_cutoff_date.map(|d| i64::from(d) * MICROS_PER_DAY);
Some(AdjPointInTimeFence {
as_of_micros,
vault_cutoff_micros,
})
} else {
None
};
if mongo.from_mongo {
if qm_splits.is_some() || qm_dividends.is_some() {
return Err(
"cannot combine '--from-mongo' with '--qm-splits' or '--qm-dividends'".to_string(),
);
}
let mongo_opts = mongo.build_options()?;
let provider_mapping = provider_mapping
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
let bars_1d_dir =
bars_1d_dir.ok_or_else(|| "missing required flag '--bars-1d'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
return Ok(CliAction::CurateAdjFactorsMongo(
CurateAdjFactorsMongoArgs {
mongo: mongo_opts,
provider_mapping,
bars_1d_dir,
out_dir,
fence,
},
));
}
if mongo.has_any_mongo_option() {
return Err("MongoDB streaming flags require '--from-mongo'".to_string());
}
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
let qm_dividends =
qm_dividends.ok_or_else(|| "missing required flag '--qm-dividends'".to_string())?;
@ -411,18 +716,21 @@ fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CurateAdjFactorsArgs,
let bars_1d_dir = bars_1d_dir.ok_or_else(|| "missing required flag '--bars-1d'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
Ok(CurateAdjFactorsArgs {
let base = CurateAdjFactorsArgs {
qm_splits,
qm_dividends,
provider_mapping,
bars_1d_dir,
out_dir,
})
};
match fence {
Some(f) => Ok(CliAction::CurateAdjFactorsFenced(base, f)),
None => Ok(CliAction::CurateAdjFactors(base)),
}
}
fn parse_curate_corporate_actions_args(
args: &[&str],
) -> Result<CurateCorporateActionsArgs, String> {
fn parse_curate_corporate_actions_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut qm_splits: Option<PathBuf> = None;
let mut qm_dividends: Option<PathBuf> = None;
let mut curate_inputs: Option<PathBuf> = None;
@ -439,6 +747,15 @@ fn parse_curate_corporate_actions_args(
));
}
if token == "--from-mongo" {
if mongo.from_mongo {
return Err("duplicate flag '--from-mongo'".to_string());
}
mongo.from_mongo = true;
i += 1;
continue;
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
@ -453,6 +770,10 @@ fn parse_curate_corporate_actions_args(
(token, v)
};
if mongo.try_parse_value_flag(flag, value, false)? {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
@ -479,6 +800,47 @@ fn parse_curate_corporate_actions_args(
}
}
if mongo.from_mongo {
if qm_splits.is_some() || qm_dividends.is_some() {
return Err(
"cannot combine '--from-mongo' with '--qm-splits' or '--qm-dividends'".to_string(),
);
}
let mongo_opts = mongo.build_options()?;
let (provider_mapping, delistings) = if let Some(inputs_dir) = curate_inputs {
if provider_mapping.is_some() {
return Err(
"cannot combine '--curate-inputs' with '--provider-mapping'".to_string()
);
}
if delistings.is_some() {
return Err("cannot combine '--curate-inputs' with '--delistings'".to_string());
}
let pinned = pin_curate_inputs_dir(&inputs_dir)?;
(
pinned.join("provider_mapping.tsv"),
Some(pinned.join("delistings.tsv")),
)
} else {
let provider_mapping = provider_mapping
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
(provider_mapping, delistings)
};
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
return Ok(CliAction::CurateCorporateActionsMongo(
CurateCorporateActionsMongoArgs {
mongo: mongo_opts,
provider_mapping,
delistings,
out_dir,
},
));
}
if mongo.has_any_mongo_option() {
return Err("MongoDB streaming flags require '--from-mongo'".to_string());
}
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
let qm_dividends =
qm_dividends.ok_or_else(|| "missing required flag '--qm-dividends'".to_string())?;
@ -501,16 +863,19 @@ fn parse_curate_corporate_actions_args(
};
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
Ok(CurateCorporateActionsArgs {
qm_splits,
qm_dividends,
provider_mapping,
delistings,
out_dir,
})
Ok(CliAction::CurateCorporateActions(
CurateCorporateActionsArgs {
qm_splits,
qm_dividends,
provider_mapping,
delistings,
out_dir,
},
))
}
fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut eod_prices: Option<PathBuf> = None;
let mut te_market_data: Option<PathBuf> = None;
let mut te_symbol: Option<String> = None;
@ -525,6 +890,15 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
));
}
if token == "--from-mongo" {
if mongo.from_mongo {
return Err("duplicate flag '--from-mongo'".to_string());
}
mongo.from_mongo = true;
i += 1;
continue;
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
@ -539,6 +913,10 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
(token, v)
};
if mongo.try_parse_value_flag(flag, value, false)? {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
@ -569,21 +947,42 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
}
}
if mongo.from_mongo {
if eod_prices.is_some() || te_market_data.is_some() {
return Err(
"cannot combine '--from-mongo' with '--eod-prices' or '--te-market-data'"
.to_string(),
);
}
let mongo_opts = mongo.build_options()?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
return Ok(CliAction::CurateFx1dMongo(CurateFx1dMongoArgs {
mongo: mongo_opts,
te_symbol: te_symbol.unwrap_or_else(|| DEFAULT_TE_SYMBOL.to_string()),
out_dir,
}));
}
if mongo.has_any_mongo_option() {
return Err("MongoDB streaming flags require '--from-mongo'".to_string());
}
let eod_prices =
eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?;
let te_market_data =
te_market_data.ok_or_else(|| "missing required flag '--te-market-data'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
Ok(CurateFx1dArgs {
Ok(CliAction::CurateFx1d(CurateFx1dArgs {
eod_prices,
te_market_data,
te_symbol: te_symbol.unwrap_or_else(|| DEFAULT_TE_SYMBOL.to_string()),
out_dir,
})
}))
}
fn parse_curate_shorts_args(args: &[&str]) -> Result<CurateShortsArgs, String> {
fn parse_curate_shorts_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut ceo_shorts: Option<PathBuf> = None;
let mut provider_mapping: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
@ -603,6 +1002,15 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result<CurateShortsArgs, String> {
));
}
if token == "--from-mongo" {
if mongo.from_mongo {
return Err("duplicate flag '--from-mongo'".to_string());
}
mongo.from_mongo = true;
i += 1;
continue;
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
@ -617,6 +1025,10 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result<CurateShortsArgs, String> {
(token, v)
};
if mongo.try_parse_value_flag(flag, value, false)? {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
@ -657,6 +1069,50 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result<CurateShortsArgs, String> {
}
}
if mongo.from_mongo {
if ceo_shorts.is_some() {
return Err("cannot combine '--from-mongo' with '--ceo-shorts'".to_string());
}
let mongo_opts = mongo.build_options()?;
let provider_mapping = provider_mapping
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
let shares_short_field = shares_short_field
.ok_or_else(|| "missing required flag '--shares-short-field'".to_string())?;
let key_field = key_field.unwrap_or_else(|| DEFAULT_KEY_FIELD.to_string());
let report_date_field =
report_date_field.unwrap_or_else(|| DEFAULT_REPORT_DATE_FIELD.to_string());
let check = CurateShortsArgs {
ceo_shorts: PathBuf::from("mongodb://ceoShorts"),
provider_mapping: provider_mapping.clone(),
out_dir: out_dir.clone(),
key_field: key_field.clone(),
report_date_field: report_date_field.clone(),
shares_short_field: shares_short_field.clone(),
net_change_field: net_change_field.clone(),
pct_float_field: pct_float_field.clone(),
mapping_source: mapping_source
.clone()
.unwrap_or_else(|| DEFAULT_MAPPING_SOURCE.to_string()),
};
check.field_names().validate().map_err(|e| e.to_string())?;
return Ok(CliAction::CurateShortsMongo(CurateShortsMongoArgs {
mongo: mongo_opts,
provider_mapping,
out_dir,
key_field,
report_date_field,
shares_short_field,
net_change_field,
pct_float_field,
mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_MAPPING_SOURCE.to_string()),
}));
}
if mongo.has_any_mongo_option() {
return Err("MongoDB streaming flags require '--from-mongo'".to_string());
}
let ceo_shorts =
ceo_shorts.ok_or_else(|| "missing required flag '--ceo-shorts'".to_string())?;
let provider_mapping =
@ -679,10 +1135,11 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result<CurateShortsArgs, String> {
};
parsed.field_names().validate().map_err(|e| e.to_string())?;
Ok(parsed)
Ok(CliAction::CurateShorts(parsed))
}
fn parse_curate_events_args(args: &[&str]) -> Result<CurateEventsArgs, String> {
fn parse_curate_events_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default();
let mut qm_filings: Option<PathBuf> = None;
let mut qm_earnings: Option<PathBuf> = None;
let mut provider_mapping: Option<PathBuf> = None;
@ -709,6 +1166,15 @@ fn parse_curate_events_args(args: &[&str]) -> Result<CurateEventsArgs, String> {
));
}
if token == "--from-mongo" {
if mongo.from_mongo {
return Err("duplicate flag '--from-mongo'".to_string());
}
mongo.from_mongo = true;
i += 1;
continue;
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
@ -723,6 +1189,10 @@ fn parse_curate_events_args(args: &[&str]) -> Result<CurateEventsArgs, String> {
(token, v)
};
if mongo.try_parse_value_flag(flag, value, true)? {
continue;
}
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
@ -820,6 +1290,81 @@ fn parse_curate_events_args(args: &[&str]) -> Result<CurateEventsArgs, String> {
}
}
if mongo.from_mongo {
if qm_filings.is_some() || qm_earnings.is_some() {
return Err(
"cannot combine '--from-mongo' with '--qm-filings' or '--qm-earnings'".to_string(),
);
}
let mongo_opts = mongo.build_options()?;
let provider_mapping = provider_mapping
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
let filings_form_type_field = filings_form_type_field
.ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?;
let filings_key_field =
filings_key_field.unwrap_or_else(|| DEFAULT_FILINGS_KEY_FIELD.to_string());
let filings_timefiled_field =
filings_timefiled_field.unwrap_or_else(|| DEFAULT_FILINGS_TIMEFILED_FIELD.to_string());
let earnings_key_field =
earnings_key_field.unwrap_or_else(|| DEFAULT_EARNINGS_KEY_FIELD.to_string());
let earnings_report_date_field = earnings_report_date_field
.unwrap_or_else(|| DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string());
let earnings_announce_time_field = earnings_announce_time_field
.unwrap_or_else(|| DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string());
let mapping_source =
mapping_source.unwrap_or_else(|| DEFAULT_EVENTS_MAPPING_SOURCE.to_string());
let check = CurateEventsArgs {
qm_filings: PathBuf::from("mongodb://qmFilings"),
qm_earnings: PathBuf::from("mongodb://qmEarnings"),
provider_mapping: provider_mapping.clone(),
out_dir: out_dir.clone(),
filings_key_field: filings_key_field.clone(),
filings_timefiled_field: filings_timefiled_field.clone(),
filings_form_type_field: filings_form_type_field.clone(),
filings_filing_id_field: filings_filing_id_field.clone(),
filings_url_field: filings_url_field.clone(),
earnings_key_field: earnings_key_field.clone(),
earnings_report_date_field: earnings_report_date_field.clone(),
earnings_announce_time_field: earnings_announce_time_field.clone(),
earnings_fiscal_period_end_field: earnings_fiscal_period_end_field.clone(),
earnings_actual_eps_field: earnings_actual_eps_field.clone(),
earnings_revenue_field: earnings_revenue_field.clone(),
mapping_source: mapping_source.clone(),
};
check
.filings_field_names()
.validate()
.map_err(|e| e.to_string())?;
check
.earnings_field_names()
.validate()
.map_err(|e| e.to_string())?;
return Ok(CliAction::CurateEventsMongo(CurateEventsMongoArgs {
mongo: mongo_opts,
provider_mapping,
out_dir,
filings_key_field,
filings_timefiled_field,
filings_form_type_field,
filings_filing_id_field,
filings_url_field,
earnings_key_field,
earnings_report_date_field,
earnings_announce_time_field,
earnings_fiscal_period_end_field,
earnings_actual_eps_field,
earnings_revenue_field,
mapping_source,
}));
}
if mongo.has_any_mongo_option() {
return Err("MongoDB streaming flags require '--from-mongo'".to_string());
}
let qm_filings =
qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?;
let qm_earnings =
@ -863,7 +1408,7 @@ fn parse_curate_events_args(args: &[&str]) -> Result<CurateEventsArgs, String> {
.earnings_field_names()
.validate()
.map_err(|e| e.to_string())?;
Ok(parsed)
Ok(CliAction::CurateEvents(parsed))
}
/// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`].
@ -875,18 +1420,12 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
[flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => {
Err(format!("unexpected argument '{extra}' after '{flag}'"))
}
["curate-bars-1d", rest @ ..] => {
parse_curate_bars_1d_args(rest).map(CliAction::CurateBars1d)
}
["curate-adj-factors", rest @ ..] => {
parse_curate_adj_factors_args(rest).map(CliAction::CurateAdjFactors)
}
["curate-corporate-actions", rest @ ..] => {
parse_curate_corporate_actions_args(rest).map(CliAction::CurateCorporateActions)
}
["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest).map(CliAction::CurateFx1d),
["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest).map(CliAction::CurateShorts),
["curate-events", rest @ ..] => parse_curate_events_args(rest).map(CliAction::CurateEvents),
["curate-bars-1d", rest @ ..] => parse_curate_bars_1d_args(rest),
["curate-adj-factors", rest @ ..] => parse_curate_adj_factors_args(rest),
["curate-corporate-actions", rest @ ..] => parse_curate_corporate_actions_args(rest),
["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest),
["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest),
["curate-events", rest @ ..] => parse_curate_events_args(rest),
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
["bench-split", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),

View file

@ -103,9 +103,11 @@ pub use mongo_safety::{
ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT,
};
pub use mongo_stream::{
build_filter_document, FilterDateValue, MongoDateRange, MongoReadSpec, MongoStreamError,
RawBsonCursorReader, RawDocumentSource, SliceRawDocumentSource, SourceCollection,
VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE,
build_filter_document, open_read_only_mongo_from_env, open_read_only_mongo_uri,
FilterDateValue, MongoCliOptions, MongoDateRange, MongoRawDocumentSource, MongoReadSpec,
MongoStreamError, MongoUriSource, RawBsonCursorReader, RawDocumentSource, ReadOnlyMongoClient,
SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE,
DEFAULT_MONGO_URI_ENV, MAX_MONGO_BATCH_SIZE,
};
pub use parquet_adj::{
adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow,
@ -200,39 +202,50 @@ pub use curate_corporate_actions::{
pub mod run_curate_bars;
pub use run_curate_bars::{
default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv,
load_provider_mapping_tsv, run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport,
QmVolumeRekeyStats, RunCurateBarsError, SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
load_provider_mapping_tsv, run_curate_bars_1d, run_curate_bars_1d_with_readers,
CurateBars1dArgs, CurateBars1dRunReport, QmVolumeRekeyStats, RunCurateBarsError,
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
};
pub mod run_curate_adj;
pub use run_curate_adj::{
format_curate_adj_report, run_curate_adj_factors, CurateAdjFactorsArgs,
CurateAdjFactorsRunReport, RunCurateAdjError,
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
run_curate_adj_factors_with_readers, CurateAdjFactorsArgs, CurateAdjFactorsRunReport,
RunCurateAdjError,
};
pub mod run_curate_corporate_actions;
pub use run_curate_corporate_actions::{
format_curate_corporate_actions_report, load_delistings_tsv, run_curate_corporate_actions,
CurateCorporateActionsArgs, CurateCorporateActionsRunReport, RunCurateCorporateActionsError,
run_curate_corporate_actions_with_readers, CurateCorporateActionsArgs,
CurateCorporateActionsRunReport, RunCurateCorporateActionsError,
};
pub mod run_curate_fx;
pub use run_curate_fx::{
format_curate_fx_report, is_supported_te_symbol, run_curate_fx_1d, CurateFx1dArgs,
CurateFx1dRunReport, RunCurateFxError, ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL,
EOD_CAD_FOREX_CODE,
format_curate_fx_report, is_supported_te_symbol, run_curate_fx_1d,
run_curate_fx_1d_with_readers, CurateFx1dArgs, CurateFx1dRunReport, RunCurateFxError,
ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE,
};
pub mod run_curate_shorts;
pub use run_curate_shorts::{
format_curate_shorts_report, run_curate_shorts, CurateShortsArgs, CurateShortsRunReport,
RunCurateShortsError, DEFAULT_MAPPING_SOURCE,
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,
CurateShortsArgs, CurateShortsRunReport, RunCurateShortsError, DEFAULT_MAPPING_SOURCE,
};
pub mod run_curate_events;
pub use run_curate_events::{
format_curate_events_report, run_curate_events, CurateEventsArgs, CurateEventsRunReport,
RunCurateEventsError, DEFAULT_EVENTS_MAPPING_SOURCE,
format_curate_events_report, run_curate_events, run_curate_events_with_readers,
CurateEventsArgs, CurateEventsRunReport, RunCurateEventsError, DEFAULT_EVENTS_MAPPING_SOURCE,
};
pub mod run_mongo;
pub use run_mongo::{
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo,
CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs,
CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError,
};
#[cfg(test)]

View file

@ -18,7 +18,9 @@ use curate_etl::bench::{
run_shorts_benchmark, run_split_benchmark,
};
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
use curate_etl::run_curate_adj::{format_curate_adj_report, run_curate_adj_factors};
use curate_etl::run_curate_adj::{
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
};
use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d};
use curate_etl::run_curate_corporate_actions::{
format_curate_corporate_actions_report, run_curate_corporate_actions,
@ -26,6 +28,10 @@ use curate_etl::run_curate_corporate_actions::{
use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events};
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
use curate_etl::run_mongo::{
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo,
};
const NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");
@ -52,6 +58,18 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateBars1dMongo(curate_args)) => {
match run_curate_bars_1d_mongo(&curate_args) {
Ok(report) => {
println!("{}", format_curate_bars_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateAdjFactors(curate_args)) => {
match run_curate_adj_factors(&curate_args) {
Ok(report) => {
@ -64,6 +82,30 @@ fn main() -> ExitCode {
}
}
}
Ok(CliAction::CurateAdjFactorsFenced(curate_args, fence)) => {
match run_curate_adj_factors_fenced(&curate_args, Some(fence)) {
Ok(report) => {
println!("{}", format_curate_adj_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateAdjFactorsMongo(curate_args)) => {
match run_curate_adj_factors_mongo(&curate_args) {
Ok(report) => {
println!("{}", format_curate_adj_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateCorporateActions(curate_args)) => {
match run_curate_corporate_actions(&curate_args) {
Ok(report) => {
@ -76,6 +118,18 @@ fn main() -> ExitCode {
}
}
}
Ok(CliAction::CurateCorporateActionsMongo(curate_args)) => {
match run_curate_corporate_actions_mongo(&curate_args) {
Ok(report) => {
println!("{}", format_curate_corporate_actions_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateFx1d(curate_args)) => match run_curate_fx_1d(&curate_args) {
Ok(report) => {
println!("{}", format_curate_fx_report(&report));
@ -86,6 +140,18 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateFx1dMongo(curate_args)) => {
match run_curate_fx_1d_mongo(&curate_args) {
Ok(report) => {
println!("{}", format_curate_fx_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateShorts(curate_args)) => match run_curate_shorts(&curate_args) {
Ok(report) => {
println!("{}", format_curate_shorts_report(&report));
@ -96,6 +162,18 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateShortsMongo(curate_args)) => {
match run_curate_shorts_mongo(&curate_args) {
Ok(report) => {
println!("{}", format_curate_shorts_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateEvents(curate_args)) => match run_curate_events(&curate_args) {
Ok(report) => {
println!("{}", format_curate_events_report(&report));
@ -106,6 +184,18 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateEventsMongo(curate_args)) => {
match run_curate_events_mongo(&curate_args) {
Ok(report) => {
println!("{}", format_curate_events_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::BenchSplit(rows)) => {
let report = match run_split_benchmark(rows) {
Ok(report) => report,

View file

@ -1,30 +1,43 @@
//! Driver-independent read-only MongoDB raw-BSON cursor seam (`M1.2al`).
//! Sealed read-only MongoDB raw-BSON cursor adapter (`M1.2al`).
//!
//! Provides the closed [`SourceCollection`] allowlist, typed [`MongoReadSpec`]
//! filter validation/builder, driver-independent [`RawDocumentSource`] trait,
//! bounded-memory [`RawBsonCursorReader`] implementing [`std::io::Read`] for
//! the existing zero-copy [`crate::bson_stream`] decoders, and password-redacted
//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`].
//! the existing zero-copy [`crate::bson_stream`] decoders, password-redacted
//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`], and the
//! sealed [`ReadOnlyMongoClient`] / [`MongoRawDocumentSource`] driver adapter
//! backed by `mongodb::sync`.
//!
//! # Safety & Sealing Guarantees
//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in
//! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API
//! accepts a free-form collection name string.
//! - Zero MongoDB driver surface in this module yet (no `mongodb::` imports,
//! client/database/collection handles, or write/admin/aggregation calls).
//! - Sealed read-only driver surface: [`ReadOnlyMongoClient`] requires a
//! [`ValidatedReadOnlyMongoUri`] proof token and exposes strictly
//! [`ReadOnlyMongoClient::open_raw_cursor`] (`find` returning raw BSON bytes).
//! No `mongodb::sync::Client`, `Database`, `Collection`, write, index, admin,
//! or aggregation handle is ever exposed outside this module.
//! - Password redaction: [`MongoStreamError`] never stores raw URIs or
//! passwords; error text is sanitized at the boundary via
//! [`crate::mongo_safety::redact_mongo_uri_password`].
//! passwords; every driver error is sanitized at the boundary via
//! [`MongoStreamError::redacted_source`].
use std::error::Error;
use std::fmt;
use std::io;
use bson::raw::RawDocumentBuf;
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::events::parse_filing_timefiled;
use crate::mongo_safety::{redact_mongo_uri_password, ValidatedReadOnlyMongoUri};
use crate::mongo_safety::{
assert_read_only_mongo_uri, redact_mongo_uri_password, LocalHosts, ReadOnlyPolicy,
ValidatedReadOnlyMongoUri,
};
/// Default environment variable name holding the read-only MongoDB connection URI.
pub const DEFAULT_MONGO_URI_ENV: &str = "MONGODB_READ_URI";
/// Default MongoDB cursor batch size (matches `DEFAULT_RAW_BSON_BATCH_SIZE`).
pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096;
@ -103,6 +116,17 @@ impl SourceCollection {
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 {
@ -802,6 +826,412 @@ pub(crate) fn sanitize_driver_error_message(
redact_embedded_mongo_uris(&sanitized)
}
/// Sealed read-only raw-BSON document source backed by a `mongodb::sync::Cursor`.
///
/// Advances one document at a time directly over the driver's wire batch buffer
/// (`cursor.current().as_bytes()`) with zero per-document heap allocation or
/// BSON object deserialization. Exposes no write, admin, or underlying driver
/// handle.
pub struct MongoRawDocumentSource {
cursor: mongodb::sync::Cursor<RawDocumentBuf>,
uri: ValidatedReadOnlyMongoUri,
exhausted: bool,
}
impl fmt::Debug for MongoRawDocumentSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MongoRawDocumentSource")
.field("uri", &self.uri.redacted())
.field("exhausted", &self.exhausted)
.finish()
}
}
impl RawDocumentSource for MongoRawDocumentSource {
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
if self.exhausted {
return Ok(None);
}
match self.cursor.advance() {
Ok(true) => Ok(Some(self.cursor.current().as_bytes())),
Ok(false) => {
self.exhausted = true;
Ok(None)
}
Err(err) => {
self.exhausted = true;
Err(MongoStreamError::redacted_source(
&err.to_string(),
&self.uri,
))
}
}
}
}
/// Sealed read-only raw-BSON document source that streams a sequence of
/// key-partitioned `$in` queries over an allowlisted collection so indexed
/// per-symbol scans (`eodSearchCode`, `qmSearchCode`) skip out-of-scope global
/// symbols and avoid random-I/O date-index fetches.
pub struct ChunkedMongoRawDocumentSource {
coll: mongodb::sync::Collection<RawDocumentBuf>,
uri: ValidatedReadOnlyMongoUri,
key_field: &'static str,
date_filter: Option<(String, Bson)>,
batch_size: u32,
chunks: std::vec::IntoIter<Vec<Bson>>,
current: Option<mongodb::sync::Cursor<RawDocumentBuf>>,
exhausted: bool,
}
impl fmt::Debug for ChunkedMongoRawDocumentSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ChunkedMongoRawDocumentSource")
.field("uri", &self.uri.redacted())
.field("key_field", &self.key_field)
.field("exhausted", &self.exhausted)
.finish()
}
}
impl RawDocumentSource for ChunkedMongoRawDocumentSource {
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
if self.exhausted {
return Ok(None);
}
loop {
if self.current.is_some() {
let advanced = {
let cursor = self.current.as_mut().expect("checked is_some");
cursor.advance()
};
match advanced {
Ok(true) => {
let cursor = self.current.as_ref().expect("checked is_some");
return Ok(Some(cursor.current().as_bytes()));
}
Ok(false) => {
self.current = None;
}
Err(err) => {
self.exhausted = true;
self.current = None;
return Err(MongoStreamError::redacted_source(
&err.to_string(),
&self.uri,
));
}
}
}
let Some(chunk) = self.chunks.next() else {
self.exhausted = true;
return Ok(None);
};
let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2);
entries.push((
self.key_field.to_owned(),
Bson::Document(Document::from_iter([("$in".to_owned(), Bson::Array(chunk))])),
));
if let Some((df, dv)) = &self.date_filter {
entries.push((df.clone(), dv.clone()));
}
let filter = Document::from_iter(entries);
let cursor = self
.coll
.find(filter)
.batch_size(self.batch_size)
.run()
.map_err(|err| {
self.exhausted = true;
MongoStreamError::redacted_source(&err.to_string(), &self.uri)
})?;
self.current = Some(cursor);
}
}
}
/// Sealed read-only MongoDB client constructed exclusively from a
/// [`ValidatedReadOnlyMongoUri`] proof token.
///
/// Intentionally exposes **only** allowlisted raw-BSON `find` cursor opening
/// via [`Self::open_raw_cursor`] and clean shutdown via [`Self::shutdown`].
/// No `mongodb::sync::Client`, `Database`, `Collection`, write, index, admin,
/// or aggregation surface is accessible outside this module.
pub struct ReadOnlyMongoClient {
client: mongodb::sync::Client,
uri: ValidatedReadOnlyMongoUri,
database_name: String,
}
impl fmt::Debug for ReadOnlyMongoClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReadOnlyMongoClient")
.field("uri", &self.uri.redacted())
.field("database", &self.database_name)
.finish()
}
}
impl ReadOnlyMongoClient {
/// Connects a sealed read-only MongoDB client using a pre-validated
/// [`ValidatedReadOnlyMongoUri`] proof token.
///
/// Fails closed if the URI omits a database name in its path.
pub fn connect(uri: ValidatedReadOnlyMongoUri) -> Result<Self, MongoStreamError> {
let Some(database_name) = uri.target().database.clone() else {
return Err(MongoStreamError::Source {
detail: "validated MongoDB URI must specify a database name in its path (e.g. /stock)"
.to_owned(),
});
};
let client = mongodb::sync::Client::with_uri_str(uri.as_str())
.map_err(|err| MongoStreamError::redacted_source(&err.to_string(), &uri))?;
Ok(Self {
client,
uri,
database_name,
})
}
/// Returns the target database name parsed from the validated URI.
#[inline]
pub fn database_name(&self) -> &str {
&self.database_name
}
/// Returns the validated URI with its password replaced by `[REDACTED]`.
#[inline]
pub fn redacted_uri(&self) -> String {
self.uri.redacted()
}
/// Opens a read-only raw-BSON `find` cursor over an allowlisted
/// [`SourceCollection`] and wraps it in a bounded-memory
/// [`RawBsonCursorReader`] implementing [`io::Read`].
pub fn open_raw_cursor(
&self,
collection: SourceCollection,
spec: &MongoReadSpec,
) -> Result<RawBsonCursorReader<MongoRawDocumentSource>, MongoStreamError> {
let filter = build_filter_document(collection, spec)?;
let coll = self
.client
.database(&self.database_name)
.collection::<RawDocumentBuf>(collection.as_str());
let mut find = coll.find(filter).batch_size(spec.batch_size);
if let Some(limit) = spec.limit {
find = find.limit(limit as i64);
}
let cursor = find
.run()
.map_err(|err| MongoStreamError::redacted_source(&err.to_string(), &self.uri))?;
let source = MongoRawDocumentSource {
cursor,
uri: self.uri.clone(),
exhausted: false,
};
RawBsonCursorReader::with_max_doc_bytes(source, spec.max_doc_bytes)
}
/// Opens a read-only raw-BSON stream partitioned into `$in` chunks over
/// `keys` on `collection.key_field()`, avoiding random-I/O date-index
/// scans when reading a known security-master key universe (e.g. US+CA
/// `eodPrices` / `qmPrices`).
pub fn open_raw_cursor_for_keys(
&self,
collection: SourceCollection,
spec: &MongoReadSpec,
keys: &[String],
chunk_size: usize,
) -> Result<RawBsonCursorReader<ChunkedMongoRawDocumentSource>, MongoStreamError> {
spec.validate(collection)?;
let effective_chunk = chunk_size.clamp(1, 2000);
let date_filter = if let (Some(range), Some(date_field)) =
(&spec.date_range, collection.date_field())
{
let mut range_entries: Vec<(String, Bson)> = Vec::with_capacity(2);
if let Some(gte) = &range.gte {
range_entries.push(("$gte".to_owned(), gte.to_bson()));
}
if let Some(lt) = &range.lt {
range_entries.push(("$lt".to_owned(), lt.to_bson()));
}
if range_entries.is_empty() {
None
} else {
Some((
date_field.to_owned(),
Bson::Document(Document::from_iter(range_entries)),
))
}
} else {
None
};
let chunks: Vec<Vec<Bson>> = keys
.chunks(effective_chunk)
.map(|c| c.iter().cloned().map(Bson::String).collect())
.collect();
let coll = self
.client
.database(&self.database_name)
.collection::<RawDocumentBuf>(collection.as_str());
let source = ChunkedMongoRawDocumentSource {
coll,
uri: self.uri.clone(),
key_field: collection.key_field(),
date_filter,
batch_size: spec.batch_size,
chunks: chunks.into_iter(),
current: None,
exhausted: false,
};
RawBsonCursorReader::with_max_doc_bytes(source, spec.max_doc_bytes)
}
/// Cleanly terminates background driver tasks once all open cursors have
/// been dropped.
pub fn shutdown(self) {
self.client.shutdown().run();
}
}
/// Validates `raw_uri` against [`ReadOnlyPolicy::default`] and `local_hosts`
/// and opens a sealed [`ReadOnlyMongoClient`].
pub fn open_read_only_mongo_uri(
raw_uri: &str,
local_hosts: &LocalHosts,
) -> Result<ReadOnlyMongoClient, MongoStreamError> {
let validated = assert_read_only_mongo_uri(raw_uri, &ReadOnlyPolicy::default(), local_hosts)
.map_err(|err| MongoStreamError::Source {
detail: err.to_string(),
})?;
ReadOnlyMongoClient::connect(validated)
}
/// Reads a MongoDB URI from environment variable `env_var`, validates it
/// against [`ReadOnlyPolicy::default`] and `local_hosts`, and opens a sealed
/// [`ReadOnlyMongoClient`].
pub fn open_read_only_mongo_from_env(
env_var: &str,
local_hosts: &LocalHosts,
) -> Result<ReadOnlyMongoClient, MongoStreamError> {
if env_var.trim().is_empty() {
return Err(MongoStreamError::Source {
detail: "MongoDB URI environment variable name must not be empty".to_owned(),
});
}
let raw_uri = std::env::var(env_var).map_err(|_| MongoStreamError::Source {
detail: format!("environment variable '{env_var}' is not set or not valid UTF-8"),
})?;
open_read_only_mongo_uri(&raw_uri, local_hosts)
}
/// Configured source for a read-only MongoDB URI in CLI invocations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MongoUriSource {
/// Read URI from an environment variable (default [`DEFAULT_MONGO_URI_ENV`]).
EnvVar(String),
/// Explicit URI passed via `--mongo-uri`.
Literal(String),
}
impl MongoUriSource {
/// Validates and connects a sealed [`ReadOnlyMongoClient`] using
/// [`LocalHosts::detect`].
pub fn connect(&self) -> Result<ReadOnlyMongoClient, MongoStreamError> {
let local_hosts = LocalHosts::detect();
match self {
Self::EnvVar(var) => open_read_only_mongo_from_env(var, &local_hosts),
Self::Literal(raw) => open_read_only_mongo_uri(raw, &local_hosts),
}
}
}
/// Shared MongoDB streaming options parsed by `--from-mongo` CLI commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MongoCliOptions {
pub uri_source: MongoUriSource,
pub batch_size: u32,
pub limit: Option<u64>,
pub date_gte: Option<String>,
pub date_lt: Option<String>,
}
impl Default for MongoCliOptions {
fn default() -> Self {
Self {
uri_source: MongoUriSource::EnvVar(DEFAULT_MONGO_URI_ENV.to_owned()),
batch_size: DEFAULT_MONGO_BATCH_SIZE,
limit: None,
date_gte: None,
date_lt: None,
}
}
}
impl MongoCliOptions {
/// Builds a [`MongoReadSpec`] for string-dated collections, attaching `key_eq`
/// 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 {
let date_range = if apply_date_range && (self.date_gte.is_some() || self.date_lt.is_some())
{
Some(MongoDateRange {
gte: self.date_gte.clone().map(FilterDateValue::IsoString),
lt: self.date_lt.clone().map(FilterDateValue::IsoString),
})
} else {
None
};
MongoReadSpec {
key_eq,
date_range,
batch_size: self.batch_size,
limit: self.limit,
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)]
#[path = "mongo_stream_tests.rs"]
mod tests;

View file

@ -1234,9 +1234,10 @@ fn sealed_surface_source_scan() {
.collect::<Vec<_>>()
.join("\n");
// Driver usage in `mongo_stream.rs` is sealed to `mongodb::sync::` read-only cursor operations.
assert!(
!code_only.contains("mongodb::"),
"mongo_stream.rs must not contain any `mongodb::` driver path yet"
code_only.contains("mongodb::sync::Client") && code_only.contains("mongodb::sync::Cursor"),
"mongo_stream.rs must wire the sealed mongodb::sync driver adapter"
);
let forbidden_calls = [
@ -1904,3 +1905,37 @@ fn error_redaction_scrubs_repeated_password_occurrences_across_message() {
"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

@ -53,8 +53,9 @@ use crate::bson_stream::{
RawBsonChunkReader,
};
use crate::curate_adj::{
curate_adj_factors, curate_and_write_adj_factors, write_adj_factors_snapshot_parquet,
CurateAdjError, CurateAdjFactorsStats, CurateAdjWriteError,
curate_adj_factors, curate_and_write_adj_factors, curate_and_write_adj_factors_as_of,
write_adj_factors_snapshot_parquet, AdjPointInTimeFence, CurateAdjError,
CurateAdjFactorsStats, CurateAdjWriteError,
};
use crate::parquet_adj::{AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats};
use crate::parquet_bars::bars_1d_parquet_schema;
@ -677,21 +678,52 @@ fn decode_mapping_and_bson_inputs(
args: &CurateAdjFactorsArgs,
prev_close_index: &PrevCloseIndex,
) -> Result<DecodedAdjInputs, RunCurateAdjError> {
let mapping = load_provider_mapping_table(&args.provider_mapping)?;
decode_mapping_and_bson_from_openers(
&args.provider_mapping,
&args.qm_splits,
|| {
File::open(&args.qm_splits).map_err(|source| RunCurateAdjError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
})
},
&args.qm_dividends,
|| {
File::open(&args.qm_dividends).map_err(|source| RunCurateAdjError::OpenInput {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
})
},
prev_close_index,
)
}
fn decode_mapping_and_bson_from_openers<RS, FS, RD, FD>(
provider_mapping_path: &Path,
qm_splits_path: &Path,
open_splits: FS,
qm_dividends_path: &Path,
open_dividends: FD,
prev_close_index: &PrevCloseIndex,
) -> Result<DecodedAdjInputs, RunCurateAdjError>
where
RS: io::Read,
FS: FnOnce() -> Result<RS, RunCurateAdjError>,
RD: io::Read,
FD: FnOnce() -> Result<RD, RunCurateAdjError>,
{
let mapping = load_provider_mapping_table(provider_mapping_path)?;
let mut qm_keys: HashSet<Arc<str>> = HashSet::new();
// Stream `qmSplits`.
let splits_file =
File::open(&args.qm_splits).map_err(|source| RunCurateAdjError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
})?;
let splits_stream = open_splits()?;
let mut splits_reader =
RawBsonChunkReader::with_options(splits_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(splits_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateAdjError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
source,
},
)?;
@ -706,24 +738,19 @@ fn decode_mapping_and_bson_inputs(
)
.map_err(|source| RunCurateAdjError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
source,
})?;
let splits_docs_framed = splits_reader.docs_framed();
let splits_bytes_read = splits_reader.bytes_read();
// Stream `qmDividends` and attach strict pre-ex-date `prev_close` from `bars_1d`.
let dividends_file =
File::open(&args.qm_dividends).map_err(|source| RunCurateAdjError::OpenInput {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
})?;
let dividends_stream = open_dividends()?;
let mut dividends_reader =
RawBsonChunkReader::with_options(dividends_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(dividends_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateAdjError::BsonStream {
label: "qm-dividends",
path: args.qm_dividends.clone(),
path: qm_dividends_path.to_path_buf(),
source,
},
)?;
@ -754,7 +781,7 @@ fn decode_mapping_and_bson_inputs(
)
.map_err(|source| RunCurateAdjError::BsonStream {
label: "qm-dividends",
path: args.qm_dividends.clone(),
path: qm_dividends_path.to_path_buf(),
source,
})?;
let dividends_docs_framed = dividends_reader.docs_framed();
@ -775,21 +802,23 @@ fn decode_mapping_and_bson_inputs(
})
}
fn map_curate_write_error(
args: &CurateAdjFactorsArgs,
fn map_curate_write_error_paths(
out_dir: &Path,
qm_splits_path: &Path,
qm_dividends_path: &Path,
source: CurateAdjWriteError,
) -> RunCurateAdjError {
let input_path = match &source {
CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeySplit { .. }) => {
Some(args.qm_splits.clone())
Some(qm_splits_path.to_path_buf())
}
CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeyDividend { .. }) => {
Some(args.qm_dividends.clone())
Some(qm_dividends_path.to_path_buf())
}
_ => None,
};
RunCurateAdjError::CurateWrite {
out_dir: args.out_dir.clone(),
out_dir: out_dir.to_path_buf(),
input_path,
source,
}
@ -802,6 +831,15 @@ fn map_curate_write_error(
/// leaving any pre-existing `<out_dir>/adj_factors/part.parquet` byte-identical.
pub fn run_curate_adj_factors(
args: &CurateAdjFactorsArgs,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
run_curate_adj_factors_fenced(args, None)
}
/// Runs the end-to-end `curate-adj-factors` file-to-Parquet pipeline with an optional
/// [`AdjPointInTimeFence`] (publishing a verified `point_in_time_fenced` snapshot when `Some`).
pub fn run_curate_adj_factors_fenced(
args: &CurateAdjFactorsArgs,
fence: Option<AdjPointInTimeFence>,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
let start = Instant::now();
validate_out_dir(&args.out_dir)?;
@ -814,15 +852,94 @@ pub fn run_curate_adj_factors(
let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?;
drop(prev_close_index);
let write_report = curate_and_write_adj_factors(
finish_curate_adj_factors(
decoded,
&args.out_dir,
&decoded.mapping,
"qm",
decoded.splits,
decoded.dividends,
AdjFactorsWriteOptions::default(),
&args.qm_splits,
&args.qm_dividends,
fence,
bars_files_read,
bars_rows_loaded,
bars_listings_indexed,
start,
)
.map_err(|source| map_curate_write_error(args, source))?;
}
/// Runs `curate-adj-factors` from arbitrary raw-BSON [`io::Read`] streams.
#[allow(clippy::too_many_arguments)]
pub fn run_curate_adj_factors_with_readers<RS: io::Read, RD: io::Read>(
provider_mapping_path: &Path,
bars_1d_dir: &Path,
qm_splits_input: (&Path, RS),
qm_dividends_input: (&Path, RD),
out_dir: &Path,
fence: Option<AdjPointInTimeFence>,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
let start = Instant::now();
validate_out_dir(out_dir)?;
let prev_close_index = load_prev_close_index(bars_1d_dir)?;
let bars_files_read = prev_close_index.files_read;
let bars_rows_loaded = prev_close_index.rows_loaded;
let bars_listings_indexed = prev_close_index.by_listing.len();
let (qm_splits_path, splits_stream) = qm_splits_input;
let (qm_dividends_path, dividends_stream) = qm_dividends_input;
let decoded = decode_mapping_and_bson_from_openers(
provider_mapping_path,
qm_splits_path,
|| Ok(splits_stream),
qm_dividends_path,
|| Ok(dividends_stream),
&prev_close_index,
)?;
drop(prev_close_index);
finish_curate_adj_factors(
decoded,
out_dir,
qm_splits_path,
qm_dividends_path,
fence,
bars_files_read,
bars_rows_loaded,
bars_listings_indexed,
start,
)
}
#[allow(clippy::too_many_arguments)]
fn finish_curate_adj_factors(
decoded: DecodedAdjInputs,
out_dir: &Path,
qm_splits_path: &Path,
qm_dividends_path: &Path,
fence: Option<AdjPointInTimeFence>,
bars_files_read: usize,
bars_rows_loaded: usize,
bars_listings_indexed: usize,
start: Instant,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
let write_report = match fence {
Some(f) => curate_and_write_adj_factors_as_of(
out_dir,
&decoded.mapping,
"qm",
decoded.splits,
decoded.dividends,
f,
AdjFactorsWriteOptions::default(),
),
None => curate_and_write_adj_factors(
out_dir,
&decoded.mapping,
"qm",
decoded.splits,
decoded.dividends,
AdjFactorsWriteOptions::default(),
),
}
.map_err(|source| map_curate_write_error_paths(out_dir, qm_splits_path, qm_dividends_path, source))?;
Ok(CurateAdjFactorsRunReport {
bars_files_read,
@ -902,7 +1019,14 @@ pub(crate) fn run_curate_adj_factors_timed(
decoded.splits,
decoded.dividends,
)
.map_err(|source| map_curate_write_error(args, CurateAdjWriteError::Curate(source)))?;
.map_err(|source| {
map_curate_write_error_paths(
&args.out_dir,
&args.qm_splits,
&args.qm_dividends,
CurateAdjWriteError::Curate(source),
)
})?;
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
let checksum = compute_rows_checksum(&curated.rows);
@ -914,7 +1038,14 @@ pub(crate) fn run_curate_adj_factors_timed(
curated.snapshot_kind,
AdjFactorsWriteOptions::default(),
)
.map_err(|source| map_curate_write_error(args, CurateAdjWriteError::Parquet(source)))?;
.map_err(|source| {
map_curate_write_error_paths(
&args.out_dir,
&args.qm_splits,
&args.qm_dividends,
CurateAdjWriteError::Parquet(source),
)
})?;
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
let report = CurateAdjFactorsRunReport {

View file

@ -55,7 +55,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -144,6 +144,7 @@ pub struct CurateBars1dRunReport {
}
/// Stage-timed run output used internally by `bench-curate-bars-cmd`.
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CurateBars1dTimedRun {
pub report: CurateBars1dRunReport,
@ -661,8 +662,61 @@ fn load_and_decode_inputs(
) -> Result<LoadedCurateBarsInputs, RunCurateBarsError> {
validate_out_dir(&args.out_dir)?;
let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping)?;
let currencies = load_listing_currencies_tsv(&args.listing_currencies)?;
let qm_prices_path = args.qm_prices.clone();
load_and_decode_from_openers(
&args.provider_mapping,
&args.listing_currencies,
&args.qm_splits,
|| {
File::open(&args.qm_splits).map_err(|source| RunCurateBarsError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
})
},
&args.eod_prices,
|| {
File::open(&args.eod_prices).map_err(|source| RunCurateBarsError::OpenInput {
label: "eod-prices",
path: args.eod_prices.clone(),
source,
})
},
qm_prices_path.as_deref(),
|| match &qm_prices_path {
Some(path) => Ok(Some(File::open(path).map_err(|source| {
RunCurateBarsError::OpenInput {
label: "qm-prices",
path: path.clone(),
source,
}
})?)),
None => Ok(None),
},
)
}
#[allow(clippy::too_many_arguments)]
fn load_and_decode_from_openers<RS, FS, RE, FE, RQ, FQ>(
provider_mapping_path: &Path,
listing_currencies_path: &Path,
qm_splits_path: &Path,
open_splits: FS,
eod_prices_path: &Path,
open_eod: FE,
qm_prices_path: Option<&Path>,
open_qm: FQ,
) -> Result<LoadedCurateBarsInputs, RunCurateBarsError>
where
RS: io::Read,
FS: FnOnce() -> Result<RS, RunCurateBarsError>,
RE: io::Read,
FE: FnOnce() -> Result<RE, RunCurateBarsError>,
RQ: io::Read,
FQ: FnOnce() -> Result<Option<RQ>, RunCurateBarsError>,
{
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)?;
let currencies = load_listing_currencies_tsv(listing_currencies_path)?;
// Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
// When `--qm-prices` is provided, also build a date-aware reverse index
@ -671,7 +725,7 @@ fn load_and_decode_inputs(
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
let track_eod_ranges = args.qm_prices.is_some();
let track_eod_ranges = qm_prices_path.is_some();
for row in &mapping_rows {
if row.source == "eod" {
let key = match eod_keys.get(row.source_id.as_str()) {
@ -710,19 +764,14 @@ fn load_and_decode_inputs(
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateBarsError::ProviderMapping {
path: args.provider_mapping.clone(),
path: provider_mapping_path.to_path_buf(),
source,
}
})?;
// Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`.
let splits_file =
File::open(&args.qm_splits).map_err(|source| RunCurateBarsError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
})?;
let mut splits_reader = RawBsonChunkReader::new(splits_file);
let splits_stream = open_splits()?;
let mut splits_reader = RawBsonChunkReader::new(splits_stream);
let mut split_rekey = SplitRekeyStats::default();
let mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
let splits_decode = decode_qm_split_chunks(
@ -755,7 +804,7 @@ fn load_and_decode_inputs(
)
.map_err(|source| RunCurateBarsError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
source,
})?;
let splits_docs_framed = splits_reader.docs_framed();
@ -764,7 +813,7 @@ fn load_and_decode_inputs(
// Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys.
let (compacted_splits, splits_collision_collapsed) =
compact_mapped_qm_splits(&args.qm_splits, mapped_splits)?;
compact_mapped_qm_splits(qm_splits_path, mapped_splits)?;
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
@ -779,19 +828,14 @@ fn load_and_decode_inputs(
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
RunCurateBarsError::SplitTable {
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
source,
}
})?;
// Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys.
let eod_file =
File::open(&args.eod_prices).map_err(|source| RunCurateBarsError::OpenInput {
label: "eod-prices",
path: args.eod_prices.clone(),
source,
})?;
let mut eod_reader = RawBsonChunkReader::new(eod_file);
let eod_stream = open_eod()?;
let mut eod_reader = RawBsonChunkReader::new(eod_stream);
let mut bars: Vec<EodDailyBar<Arc<str>>> = Vec::new();
let mut bars_unmapped_source_dropped: usize = 0;
let eod_decode = decode_eod_price_chunks(
@ -807,7 +851,7 @@ fn load_and_decode_inputs(
)
.map_err(|source| RunCurateBarsError::BsonStream {
label: "eod-prices",
path: args.eod_prices.clone(),
path: eod_prices_path.to_path_buf(),
source,
})?;
let eod_docs_framed = eod_reader.docs_framed();
@ -829,60 +873,56 @@ fn load_and_decode_inputs(
let mut qm_rekey = QmVolumeRekeyStats::default();
let mut qm_decode_rekey_elapsed_secs = 0.0f64;
if let Some(qm_prices_path) = &args.qm_prices {
qm_prices_present = true;
let qm_start = Instant::now();
let qm_file =
File::open(qm_prices_path).map_err(|source| RunCurateBarsError::OpenInput {
label: "qm-prices",
path: qm_prices_path.clone(),
source,
})?;
let mut qm_reader = RawBsonChunkReader::new(qm_file);
qm_prices_decode = decode_qm_price_chunks(
&mut qm_reader,
|raw_price| {
let Some(listing_id) =
mapping.resolve("qm", raw_price.qm_search_code, raw_price.session_date)
else {
qm_rekey.qm_unmapped_qm += 1;
return;
};
let mut matched_eod = 0usize;
if let Some(ranges) = eod_ranges_by_listing.get(&listing_id) {
for range in ranges {
if raw_price.session_date >= range.valid_from
&& range
.valid_to
.is_none_or(|to| raw_price.session_date <= to)
{
qm_volumes.push(QmRawVolume {
key: Arc::clone(&range.key),
session_date: raw_price.session_date,
share_volume: raw_price.share_volume,
});
matched_eod += 1;
if let Some(qm_prices_path) = qm_prices_path {
if let Some(qm_stream) = open_qm()? {
qm_prices_present = true;
let qm_start = Instant::now();
let mut qm_reader = RawBsonChunkReader::new(qm_stream);
qm_prices_decode = decode_qm_price_chunks(
&mut qm_reader,
|raw_price| {
let Some(listing_id) =
mapping.resolve("qm", raw_price.qm_search_code, raw_price.session_date)
else {
qm_rekey.qm_unmapped_qm += 1;
return;
};
let mut matched_eod = 0usize;
if let Some(ranges) = eod_ranges_by_listing.get(&listing_id) {
for range in ranges {
if raw_price.session_date >= range.valid_from
&& range
.valid_to
.is_none_or(|to| raw_price.session_date <= to)
{
qm_volumes.push(QmRawVolume {
key: Arc::clone(&range.key),
session_date: raw_price.session_date,
share_volume: raw_price.share_volume,
});
matched_eod += 1;
}
}
}
}
if matched_eod == 0 {
qm_rekey.qm_no_eod_partner += 1;
} else {
qm_rekey.qm_attached += 1;
qm_rekey.qm_volumes_attached += matched_eod;
}
},
|_offset, _err| {},
)
.map_err(|source| RunCurateBarsError::BsonStream {
label: "qm-prices",
path: qm_prices_path.clone(),
source,
})?;
qm_prices_docs_framed = qm_reader.docs_framed();
qm_prices_bytes_read = qm_reader.bytes_read();
qm_rekey.qm_in = qm_prices_decode.docs_in;
qm_decode_rekey_elapsed_secs = qm_start.elapsed().as_secs_f64();
if matched_eod == 0 {
qm_rekey.qm_no_eod_partner += 1;
} else {
qm_rekey.qm_attached += 1;
qm_rekey.qm_volumes_attached += matched_eod;
}
},
|_offset, _err| {},
)
.map_err(|source| RunCurateBarsError::BsonStream {
label: "qm-prices",
path: qm_prices_path.to_path_buf(),
source,
})?;
qm_prices_docs_framed = qm_reader.docs_framed();
qm_prices_bytes_read = qm_reader.bytes_read();
qm_rekey.qm_in = qm_prices_decode.docs_in;
qm_decode_rekey_elapsed_secs = qm_start.elapsed().as_secs_f64();
}
}
let buffered_qm_bytes = qm_volumes.capacity() * size_of::<QmRawVolume<Arc<str>>>();
@ -924,23 +964,72 @@ pub fn run_curate_bars_1d(
}
let start = Instant::now();
let loaded = load_and_decode_inputs(args)?;
finish_curate_bars_1d(loaded, &args.out_dir, args.rel_tolerance, args.threads, start)
}
/// Runs `curate-bars-1d` from arbitrary raw-BSON [`io::Read`] streams (such as
/// [`crate::RawBsonCursorReader`] backed by read-only MongoDB cursors).
#[allow(clippy::too_many_arguments)]
pub fn run_curate_bars_1d_with_readers<RS: io::Read, RE: io::Read, RQ: io::Read>(
provider_mapping_path: &Path,
listing_currencies_path: &Path,
qm_splits_input: (&Path, RS),
eod_prices_input: (&Path, RE),
qm_prices_input: Option<(PathBuf, RQ)>,
out_dir: &Path,
rel_tolerance: f64,
threads: usize,
) -> Result<CurateBars1dRunReport, RunCurateBarsError> {
if threads == 0 {
return Err(RunCurateBarsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads),
});
}
let start = Instant::now();
validate_out_dir(out_dir)?;
let (qm_splits_path, splits_stream) = qm_splits_input;
let (eod_prices_path, eod_stream) = eod_prices_input;
let (qm_prices_path, qm_stream) = match qm_prices_input {
Some((p, r)) => (Some(p), Some(r)),
None => (None, None),
};
let loaded = load_and_decode_from_openers(
provider_mapping_path,
listing_currencies_path,
qm_splits_path,
|| Ok(splits_stream),
eod_prices_path,
|| Ok(eod_stream),
qm_prices_path.as_deref(),
|| Ok(qm_stream),
)?;
finish_curate_bars_1d(loaded, out_dir, rel_tolerance, threads, start)
}
fn finish_curate_bars_1d(
loaded: LoadedCurateBarsInputs,
out_dir: &Path,
rel_tolerance: f64,
threads: usize,
start: Instant,
) -> Result<CurateBars1dRunReport, RunCurateBarsError> {
let write_report = curate_and_write_bars_1d(
&args.out_dir,
out_dir,
loaded.bars,
&loaded.splits,
loaded.qm_volumes,
args.rel_tolerance,
rel_tolerance,
&loaded.mapping,
"eod",
&loaded.currencies,
Bars1dWriteOptions {
threads: args.threads,
threads,
..Bars1dWriteOptions::default()
},
)
.map_err(|source| RunCurateBarsError::CurateWrite {
out_dir: args.out_dir.clone(),
out_dir: out_dir.to_path_buf(),
source,
})?;
@ -964,13 +1053,14 @@ pub fn run_curate_bars_1d(
curate_stats: write_report.curate_stats,
write_stats: write_report.write_stats,
mismatch_samples: write_report.mismatch_samples,
threads: args.threads,
threads,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
/// Stage-timed variant of [`run_curate_bars_1d`] sharing [`load_and_decode_inputs`] and calling
/// [`curate_bars_1d`] + [`write_bars_1d_dataset`] separately.
#[allow(dead_code)]
pub(crate) fn run_curate_bars_1d_timed(
args: &CurateBars1dArgs,
) -> Result<CurateBars1dTimedRun, RunCurateBarsError> {

View file

@ -63,7 +63,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -454,16 +454,56 @@ struct DecodedCorporateActionInputs {
fn decode_all_inputs(
args: &CurateCorporateActionsArgs,
) -> Result<DecodedCorporateActionInputs, RunCurateCorporateActionsError> {
let mapping = load_provider_mapping_table(&args.provider_mapping)?;
decode_inputs_from_openers(
&args.provider_mapping,
args.delistings.as_deref(),
&args.qm_splits,
|| {
File::open(&args.qm_splits).map_err(|source| {
RunCurateCorporateActionsError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
}
})
},
&args.qm_dividends,
|| {
File::open(&args.qm_dividends).map_err(|source| {
RunCurateCorporateActionsError::OpenInput {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
}
})
},
)
}
fn decode_inputs_from_openers<RS, FS, RD, FD>(
provider_mapping_path: &Path,
delistings_path: Option<&Path>,
qm_splits_path: &Path,
open_splits: FS,
qm_dividends_path: &Path,
open_dividends: FD,
) -> Result<DecodedCorporateActionInputs, RunCurateCorporateActionsError>
where
RS: io::Read,
FS: FnOnce() -> Result<RS, RunCurateCorporateActionsError>,
RD: io::Read,
FD: FnOnce() -> Result<RD, RunCurateCorporateActionsError>,
{
let mapping = load_provider_mapping_table(provider_mapping_path)?;
let mut qm_keys: HashSet<Arc<str>> = HashSet::new();
let (delistings, delistings_rows_loaded, delistings_bytes_read) = match &args.delistings {
let (delistings, delistings_rows_loaded, delistings_bytes_read) = match delistings_path {
Some(path) => {
let raw_delistings = load_delistings_tsv(path)?;
let bytes_read = fs::metadata(path)
.map_err(|source| RunCurateCorporateActionsError::ReadInput {
label: "delistings",
path: path.clone(),
path: path.to_path_buf(),
source,
})?
.len();
@ -493,18 +533,12 @@ fn decode_all_inputs(
};
// Stream `qmSplits`.
let splits_file = File::open(&args.qm_splits).map_err(|source| {
RunCurateCorporateActionsError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
}
})?;
let splits_stream = open_splits()?;
let mut splits_reader =
RawBsonChunkReader::with_options(splits_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(splits_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateCorporateActionsError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
source,
},
)?;
@ -525,7 +559,7 @@ fn decode_all_inputs(
if let Some((offset, source)) = splits_corrupt_err {
return Err(RunCurateCorporateActionsError::CorruptBson {
label: "qm-splits",
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
offset,
source,
});
@ -533,7 +567,7 @@ fn decode_all_inputs(
let splits_decode = splits_decode_res.map_err(|source| {
RunCurateCorporateActionsError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
path: qm_splits_path.to_path_buf(),
source,
}
})?;
@ -541,18 +575,12 @@ fn decode_all_inputs(
let splits_bytes_read = splits_reader.bytes_read();
// Stream `qmDividends`.
let dividends_file = File::open(&args.qm_dividends).map_err(|source| {
RunCurateCorporateActionsError::OpenInput {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
}
})?;
let dividends_stream = open_dividends()?;
let mut dividends_reader =
RawBsonChunkReader::with_options(dividends_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(dividends_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateCorporateActionsError::BsonStream {
label: "qm-dividends",
path: args.qm_dividends.clone(),
path: qm_dividends_path.to_path_buf(),
source,
},
)?;
@ -573,7 +601,7 @@ fn decode_all_inputs(
if let Some((offset, source)) = dividends_corrupt_err {
return Err(RunCurateCorporateActionsError::CorruptBson {
label: "qm-dividends",
path: args.qm_dividends.clone(),
path: qm_dividends_path.to_path_buf(),
offset,
source,
});
@ -581,7 +609,7 @@ fn decode_all_inputs(
let dividends_decode = dividends_decode_res.map_err(|source| {
RunCurateCorporateActionsError::BsonStream {
label: "qm-dividends",
path: args.qm_dividends.clone(),
path: qm_dividends_path.to_path_buf(),
source,
}
})?;
@ -617,9 +645,40 @@ pub fn run_curate_corporate_actions(
validate_out_dir(&args.out_dir)?;
let decoded = decode_all_inputs(args)?;
finish_curate_corporate_actions(decoded, &args.out_dir, start)
}
/// Runs `curate-corporate-actions` from arbitrary raw-BSON [`io::Read`] streams.
pub fn run_curate_corporate_actions_with_readers<RS: io::Read, RD: io::Read>(
provider_mapping_path: &Path,
delistings_path: Option<&Path>,
qm_splits_input: (&Path, RS),
qm_dividends_input: (&Path, RD),
out_dir: &Path,
) -> Result<CurateCorporateActionsRunReport, RunCurateCorporateActionsError> {
let start = Instant::now();
validate_out_dir(out_dir)?;
let (qm_splits_path, splits_stream) = qm_splits_input;
let (qm_dividends_path, dividends_stream) = qm_dividends_input;
let decoded = decode_inputs_from_openers(
provider_mapping_path,
delistings_path,
qm_splits_path,
|| Ok(splits_stream),
qm_dividends_path,
|| Ok(dividends_stream),
)?;
finish_curate_corporate_actions(decoded, out_dir, start)
}
fn finish_curate_corporate_actions(
decoded: DecodedCorporateActionInputs,
out_dir: &Path,
start: Instant,
) -> Result<CurateCorporateActionsRunReport, RunCurateCorporateActionsError> {
let write_report = curate_and_write_corporate_actions(
&args.out_dir,
out_dir,
decoded.splits,
decoded.dividends,
decoded.delistings,
@ -628,7 +687,7 @@ pub fn run_curate_corporate_actions(
CorporateActionsWriteOptions::default(),
)
.map_err(|source| RunCurateCorporateActionsError::CurateWrite {
out_dir: args.out_dir.clone(),
out_dir: out_dir.to_path_buf(),
source,
})?;

View file

@ -50,7 +50,13 @@ fn split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> Vec<
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
if let Some(d) = declared {
doc.append(cstr!("declared"), d);
}

View file

@ -471,6 +471,26 @@ fn map_stream_error(
}
}
#[inline]
fn is_canadian_qm_exchange(exchange: &str) -> bool {
matches!(
exchange.trim().to_ascii_uppercase().as_str(),
"TSX"
| "TSXC"
| "CDX"
| "TSXVC"
| "CNQ"
| "CNX"
| "CSE"
| "CVE"
| "AQL"
| "AQLL"
| "NEO"
| "NEOE"
| "MOE"
)
}
#[inline]
fn intern_key(interner: &mut HashSet<Arc<str>>, key: &str) -> Arc<str> {
if let Some(existing) = interner.get(key) {
@ -497,25 +517,64 @@ struct DecodedEventsInputs {
}
fn decode_all_inputs(args: &CurateEventsArgs) -> Result<DecodedEventsInputs, RunCurateEventsError> {
let filings_fields = args.filings_field_names();
decode_inputs_from_openers(
&args.provider_mapping,
&args.mapping_source,
&args.filings_field_names(),
&args.earnings_field_names(),
&args.qm_filings,
|| {
File::open(&args.qm_filings).map_err(|source| RunCurateEventsError::OpenInput {
label: "qm-filings",
path: args.qm_filings.clone(),
source,
})
},
&args.qm_earnings,
|| {
File::open(&args.qm_earnings).map_err(|source| RunCurateEventsError::OpenInput {
label: "qm-earnings",
path: args.qm_earnings.clone(),
source,
})
},
)
}
#[allow(clippy::too_many_arguments)]
fn decode_inputs_from_openers<RF, FF, RE, FE>(
provider_mapping_path: &Path,
mapping_source: &str,
filings_fields: &QmFilingsFieldNames<'_>,
earnings_fields: &QmEarningsFieldNames<'_>,
qm_filings_path: &Path,
open_filings: FF,
qm_earnings_path: &Path,
open_earnings: FE,
) -> Result<DecodedEventsInputs, RunCurateEventsError>
where
RF: io::Read,
FF: FnOnce() -> Result<RF, RunCurateEventsError>,
RE: io::Read,
FE: FnOnce() -> Result<RE, RunCurateEventsError>,
{
filings_fields
.validate()
.map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?;
let earnings_fields = args.earnings_field_names();
earnings_fields
.validate()
.map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?;
if args.mapping_source.trim().is_empty() {
if mapping_source.trim().is_empty() {
return Err(RunCurateEventsError::EmptyMappingSource);
}
let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping)
.map_err(|err| map_tsv_error(&args.provider_mapping, err))?;
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)
.map_err(|err| map_tsv_error(provider_mapping_path, err))?;
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateEventsError::ProviderMapping {
path: args.provider_mapping.clone(),
path: provider_mapping_path.to_path_buf(),
source,
}
})?;
@ -523,52 +582,61 @@ fn decode_all_inputs(args: &CurateEventsArgs) -> Result<DecodedEventsInputs, Run
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
// Stream and decode qmFilings.
let filings_file =
File::open(&args.qm_filings).map_err(|source| RunCurateEventsError::OpenInput {
label: "qm-filings",
path: args.qm_filings.clone(),
source,
})?;
let filings_stream = open_filings()?;
let mut filings_reader =
RawBsonChunkReader::with_options(filings_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateEventsError::BsonStream {
label: "qm-filings",
path: args.qm_filings.clone(),
path: qm_filings_path.to_path_buf(),
source,
},
)?;
let mut filings: Vec<QmFiling<Arc<str>>> = Vec::new();
let mut ca_key_buf = String::with_capacity(32);
let filings_decode =
decode_qm_filings_chunks(&mut filings_reader, &filings_fields, |raw| {
let key = intern_key(&mut key_interner, raw.key);
decode_qm_filings_chunks(&mut filings_reader, filings_fields, |raw| {
let resolved_key_str = if !raw.key.contains(':')
&& raw.exchange.is_some_and(is_canadian_qm_exchange)
{
ca_key_buf.clear();
ca_key_buf.push_str(raw.key);
ca_key_buf.push_str(":CA");
if !mapping
.cursor_for(mapping_source, ca_key_buf.as_str())
.ranges()
.is_empty()
{
ca_key_buf.as_str()
} else {
raw.key
}
} else {
raw.key
};
let key = intern_key(&mut key_interner, resolved_key_str);
filings.push(raw.to_qm_filing(key));
})
.map_err(|err| map_stream_error("qm-filings", &args.qm_filings, err))?;
.map_err(|err| map_stream_error("qm-filings", qm_filings_path, err))?;
// Stream and decode qmEarnings (reusing the same key interner).
let earnings_file =
File::open(&args.qm_earnings).map_err(|source| RunCurateEventsError::OpenInput {
label: "qm-earnings",
path: args.qm_earnings.clone(),
source,
})?;
let earnings_stream = open_earnings()?;
let mut earnings_reader =
RawBsonChunkReader::with_options(earnings_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(earnings_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateEventsError::BsonStream {
label: "qm-earnings",
path: args.qm_earnings.clone(),
path: qm_earnings_path.to_path_buf(),
source,
},
)?;
let mut earnings: Vec<QmEarning<Arc<str>>> = Vec::new();
let earnings_decode =
decode_qm_earnings_chunks(&mut earnings_reader, &earnings_fields, |raw| {
decode_qm_earnings_chunks(&mut earnings_reader, earnings_fields, |raw| {
let key = intern_key(&mut key_interner, raw.key);
earnings.push(raw.to_qm_earning(key));
})
.map_err(|err| map_stream_error("qm-earnings", &args.qm_earnings, err))?;
.map_err(|err| map_stream_error("qm-earnings", qm_earnings_path, err))?;
Ok(DecodedEventsInputs {
mapping,
@ -635,6 +703,79 @@ pub fn run_curate_events(
})
}
/// Runs `curate-events` from arbitrary raw-BSON [`io::Read`] streams.
#[allow(clippy::too_many_arguments)]
pub fn run_curate_events_with_readers<RF: io::Read, RE: io::Read>(
provider_mapping_path: &Path,
mapping_source: &str,
filings_fields: &QmFilingsFieldNames<'_>,
earnings_fields: &QmEarningsFieldNames<'_>,
qm_filings_input: (&Path, RF),
qm_earnings_input: (&Path, RE),
out_dir: &Path,
) -> Result<CurateEventsRunReport, RunCurateEventsError> {
let start = Instant::now();
if out_dir.exists() && !out_dir.is_dir() {
return Err(RunCurateEventsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
let events_dir = out_dir.join("events");
if events_dir.exists() && !events_dir.is_dir() {
return Err(RunCurateEventsError::InvalidOutDir {
path: events_dir,
detail: "events output path exists and is not a directory".to_string(),
});
}
let (filings_path, filings_stream) = qm_filings_input;
let (earnings_path, earnings_stream) = qm_earnings_input;
let decoded = decode_inputs_from_openers(
provider_mapping_path,
mapping_source,
filings_fields,
earnings_fields,
filings_path,
|| Ok(filings_stream),
earnings_path,
|| Ok(earnings_stream),
)?;
let curated = curate_events(
decoded.filings,
decoded.earnings,
mapping_source,
&decoded.mapping,
)
.map_err(|source| RunCurateEventsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source: CurateEventsWriteError::Curate(source),
})?;
let write_stats =
write_events_dataset(out_dir, &curated.rows, EventsWriteOptions::default()).map_err(
|source| RunCurateEventsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source: CurateEventsWriteError::Parquet(source),
},
)?;
Ok(CurateEventsRunReport {
filings_docs_framed: decoded.filings_docs_framed,
filings_bytes_read: decoded.filings_bytes_read,
filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes,
filings_decode: decoded.filings_decode,
earnings_docs_framed: decoded.earnings_docs_framed,
earnings_bytes_read: decoded.earnings_bytes_read,
earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes,
earnings_decode: decoded.earnings_decode,
curate_stats: curated.stats,
write_stats,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
fn compute_rows_checksum(rows: &[EventsParquetRow]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
let mix = |mut h: u64, v: u64| -> u64 {

View file

@ -305,18 +305,48 @@ struct DecodedFxInputs {
}
fn decode_all_inputs(args: &CurateFx1dArgs) -> Result<DecodedFxInputs, RunCurateFxError> {
// 1. Stream `eodPrices` and retain exact `CAD.FOREX` bars.
let eod_file = File::open(&args.eod_prices).map_err(|source| RunCurateFxError::OpenInput {
label: "eod-prices",
path: args.eod_prices.clone(),
source,
})?;
let mut eod_reader =
RawBsonChunkReader::with_options(eod_file, BsonStreamOptions::default()).map_err(
|source| RunCurateFxError::BsonStream {
decode_inputs_from_openers(
&args.eod_prices,
|| {
File::open(&args.eod_prices).map_err(|source| RunCurateFxError::OpenInput {
label: "eod-prices",
path: args.eod_prices.clone(),
source,
})
},
&args.te_market_data,
|| {
File::open(&args.te_market_data).map_err(|source| RunCurateFxError::OpenInput {
label: "te-market-data",
path: args.te_market_data.clone(),
source,
})
},
&args.te_symbol,
)
}
fn decode_inputs_from_openers<RE, FE, RT, FT>(
eod_prices_path: &Path,
open_eod: FE,
te_market_data_path: &Path,
open_te: FT,
te_symbol: &str,
) -> Result<DecodedFxInputs, RunCurateFxError>
where
RE: io::Read,
FE: FnOnce() -> Result<RE, RunCurateFxError>,
RT: io::Read,
FT: FnOnce() -> Result<RT, RunCurateFxError>,
{
// 1. Stream `eodPrices` and retain exact `CAD.FOREX` bars.
let eod_stream = open_eod()?;
let mut eod_reader =
RawBsonChunkReader::with_options(eod_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateFxError::BsonStream {
label: "eod-prices",
path: eod_prices_path.to_path_buf(),
source,
},
)?;
let mut eod_bars: Vec<FxDailyBar> = Vec::new();
@ -348,31 +378,26 @@ fn decode_all_inputs(args: &CurateFx1dArgs) -> Result<DecodedFxInputs, RunCurate
);
if let Some((offset, source)) = eod_corrupt_err {
return Err(RunCurateFxError::CorruptEodBson {
path: args.eod_prices.clone(),
path: eod_prices_path.to_path_buf(),
offset,
source,
});
}
let eod_decode = eod_decode_res.map_err(|source| RunCurateFxError::BsonStream {
label: "eod-prices",
path: args.eod_prices.clone(),
path: eod_prices_path.to_path_buf(),
source,
})?;
let eod_docs_framed = eod_reader.docs_framed();
let eod_bytes_read = eod_reader.bytes_read();
// 2. Stream `teMarketData` and retain points for `args.te_symbol` (ASCII case-insensitive).
let te_file =
File::open(&args.te_market_data).map_err(|source| RunCurateFxError::OpenInput {
label: "te-market-data",
path: args.te_market_data.clone(),
source,
})?;
// 2. Stream `teMarketData` and retain points for `te_symbol` (ASCII case-insensitive).
let te_stream = open_te()?;
let mut te_reader =
RawBsonChunkReader::with_options(te_file, BsonStreamOptions::default()).map_err(
RawBsonChunkReader::with_options(te_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateFxError::BsonStream {
label: "te-market-data",
path: args.te_market_data.clone(),
path: te_market_data_path.to_path_buf(),
source,
},
)?;
@ -381,7 +406,7 @@ fn decode_all_inputs(args: &CurateFx1dArgs) -> Result<DecodedFxInputs, RunCurate
let te_decode_res = decode_te_market_data_chunks(
&mut te_reader,
&args.te_symbol,
te_symbol,
|bar| {
te_bars.push(bar);
},
@ -393,14 +418,14 @@ fn decode_all_inputs(args: &CurateFx1dArgs) -> Result<DecodedFxInputs, RunCurate
);
if let Some((offset, source)) = te_corrupt_err {
return Err(RunCurateFxError::CorruptTeBson {
path: args.te_market_data.clone(),
path: te_market_data_path.to_path_buf(),
offset,
source,
});
}
let te_decode = te_decode_res.map_err(|source| RunCurateFxError::BsonStream {
label: "te-market-data",
path: args.te_market_data.clone(),
path: te_market_data_path.to_path_buf(),
source,
})?;
let te_docs_framed = te_reader.docs_framed();
@ -408,9 +433,9 @@ fn decode_all_inputs(args: &CurateFx1dArgs) -> Result<DecodedFxInputs, RunCurate
if eod_bars.is_empty() && te_bars.is_empty() {
return Err(RunCurateFxError::NoDecodedBars {
eod_path: args.eod_prices.clone(),
te_path: args.te_market_data.clone(),
te_symbol: args.te_symbol.clone(),
eod_path: eod_prices_path.to_path_buf(),
te_path: te_market_data_path.to_path_buf(),
te_symbol: te_symbol.to_owned(),
});
}
@ -439,21 +464,59 @@ pub fn run_curate_fx_1d(args: &CurateFx1dArgs) -> Result<CurateFx1dRunReport, Ru
validate_te_symbol(&args.te_symbol)?;
let decoded = decode_all_inputs(args)?;
let write_report = curate_and_write_fx_1d(
finish_curate_fx_1d(
decoded,
&args.eod_prices,
&args.te_market_data,
&args.out_dir,
start,
)
}
/// Runs `curate-fx-1d` from arbitrary raw-BSON [`io::Read`] streams.
pub fn run_curate_fx_1d_with_readers<RE: io::Read, RT: io::Read>(
eod_prices_input: (&Path, RE),
te_market_data_input: (&Path, RT),
te_symbol: &str,
out_dir: &Path,
) -> Result<CurateFx1dRunReport, RunCurateFxError> {
let start = Instant::now();
validate_out_dir(out_dir)?;
validate_te_symbol(te_symbol)?;
let (eod_path, eod_stream) = eod_prices_input;
let (te_path, te_stream) = te_market_data_input;
let decoded = decode_inputs_from_openers(
eod_path,
|| Ok(eod_stream),
te_path,
|| Ok(te_stream),
te_symbol,
)?;
finish_curate_fx_1d(decoded, eod_path, te_path, out_dir, start)
}
fn finish_curate_fx_1d(
decoded: DecodedFxInputs,
eod_path: &Path,
te_path: &Path,
out_dir: &Path,
start: Instant,
) -> Result<CurateFx1dRunReport, RunCurateFxError> {
let write_report = curate_and_write_fx_1d(
out_dir,
&decoded.eod_bars,
&decoded.te_bars,
Fx1dWriteOptions::default(),
)
.map_err(|source| RunCurateFxError::CurateWrite {
out_dir: args.out_dir.clone(),
out_dir: out_dir.to_path_buf(),
source,
})?;
if write_report.curate_stats.rows_out == 0 {
return Err(RunCurateFxError::NoCuratedRows {
eod_path: args.eod_prices.clone(),
te_path: args.te_market_data.clone(),
eod_path: eod_path.to_path_buf(),
te_path: te_path.to_path_buf(),
eod_bars_in: decoded.eod_cad_forex_kept,
te_bars_in: decoded.te_decode.points_decoded,
});

View file

@ -278,40 +278,60 @@ struct DecodedShortsInputs {
}
fn decode_all_inputs(args: &CurateShortsArgs) -> Result<DecodedShortsInputs, RunCurateShortsError> {
let fields = args.field_names();
decode_inputs_from_opener(
&args.provider_mapping,
&args.mapping_source,
&args.field_names(),
&args.ceo_shorts,
|| {
File::open(&args.ceo_shorts).map_err(|source| RunCurateShortsError::OpenInput {
label: "ceo-shorts",
path: args.ceo_shorts.clone(),
source,
})
},
)
}
fn decode_inputs_from_opener<R, F>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoShortsFieldNames<'_>,
ceo_shorts_path: &Path,
open_shorts: F,
) -> Result<DecodedShortsInputs, RunCurateShortsError>
where
R: io::Read,
F: FnOnce() -> Result<R, RunCurateShortsError>,
{
fields
.validate()
.map_err(|source| RunCurateShortsError::InvalidFieldNames { source })?;
if args.mapping_source.trim().is_empty() {
if mapping_source.trim().is_empty() {
return Err(RunCurateShortsError::EmptyMappingSource);
}
let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping)
.map_err(|err| map_tsv_error(&args.provider_mapping, err))?;
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)
.map_err(|err| map_tsv_error(provider_mapping_path, err))?;
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateShortsError::ProviderMapping {
path: args.provider_mapping.clone(),
path: provider_mapping_path.to_path_buf(),
source,
}
})?;
let file = File::open(&args.ceo_shorts).map_err(|source| RunCurateShortsError::OpenInput {
label: "ceo-shorts",
path: args.ceo_shorts.clone(),
source,
})?;
let mut reader = RawBsonChunkReader::with_options(file, BsonStreamOptions::default()).map_err(
|source| RunCurateShortsError::BsonStream {
path: args.ceo_shorts.clone(),
let stream = open_shorts()?;
let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default())
.map_err(|source| RunCurateShortsError::BsonStream {
path: ceo_shorts_path.to_path_buf(),
source,
},
)?;
})?;
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
let mut reports: Vec<CeoShortReport<Arc<str>>> = Vec::new();
let decode = decode_ceo_shorts_chunks(&mut reader, &fields, |raw| {
let decode = decode_ceo_shorts_chunks(&mut reader, fields, |raw| {
let key = if let Some(existing) = key_interner.get(raw.key) {
Arc::clone(existing)
} else {
@ -329,7 +349,7 @@ fn decode_all_inputs(args: &CurateShortsArgs) -> Result<DecodedShortsInputs, Run
})
.map_err(|err| match err {
BsonCeoShortsStreamError::Stream(source) => RunCurateShortsError::BsonStream {
path: args.ceo_shorts.clone(),
path: ceo_shorts_path.to_path_buf(),
source,
},
BsonCeoShortsStreamError::Decode(source) => match &source {
@ -339,7 +359,7 @@ fn decode_all_inputs(args: &CurateShortsArgs) -> Result<DecodedShortsInputs, Run
_ => {
let offset = bson_error_offset(&source);
RunCurateShortsError::CorruptBson {
path: args.ceo_shorts.clone(),
path: ceo_shorts_path.to_path_buf(),
offset,
source,
}
@ -369,16 +389,46 @@ pub fn run_curate_shorts(
validate_out_dir(&args.out_dir)?;
let decoded = decode_all_inputs(args)?;
finish_curate_shorts(decoded, &args.mapping_source, &args.out_dir, start)
}
/// Runs `curate-shorts` from an arbitrary raw-BSON [`io::Read`] stream.
pub fn run_curate_shorts_with_reader<R: io::Read>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoShortsFieldNames<'_>,
ceo_shorts_input: (&Path, R),
out_dir: &Path,
) -> Result<CurateShortsRunReport, RunCurateShortsError> {
let start = Instant::now();
validate_out_dir(out_dir)?;
let (ceo_path, stream) = ceo_shorts_input;
let decoded = decode_inputs_from_opener(
provider_mapping_path,
mapping_source,
fields,
ceo_path,
|| Ok(stream),
)?;
finish_curate_shorts(decoded, mapping_source, out_dir, start)
}
fn finish_curate_shorts(
decoded: DecodedShortsInputs,
mapping_source: &str,
out_dir: &Path,
start: Instant,
) -> Result<CurateShortsRunReport, RunCurateShortsError> {
let write_report = curate_and_write_shorts(
&args.out_dir,
out_dir,
decoded.reports,
&args.mapping_source,
mapping_source,
&decoded.mapping,
ShortsWriteOptions::default(),
)
.map_err(|source| RunCurateShortsError::CurateWrite {
out_dir: args.out_dir.clone(),
out_dir: out_dir.to_path_buf(),
source,
})?;

View file

@ -0,0 +1,503 @@
//! Direct read-only MongoDB streaming runners for all six M1 `curate-*` CLI commands.
//!
//! Uses [`ReadOnlyMongoClient`] (constructed strictly from [`crate::ValidatedReadOnlyMongoUri`])
//! to open zero-copy raw-BSON cursors over allowlisted [`SourceCollection`]s and feeds them
//! directly into the shared `run_curate_*_with_readers` pipelines with zero intermediate `.bson`
//! scratch files.
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::path::{Path, PathBuf};
use crate::bson_ceo_shorts::CeoShortsFieldNames;
use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames};
use crate::curate_adj::AdjPointInTimeFence;
use crate::mongo_stream::{
MongoCliOptions, MongoReadSpec, MongoStreamError, ReadOnlyMongoClient, SourceCollection,
};
use crate::run_curate_adj::{
run_curate_adj_factors_with_readers, CurateAdjFactorsRunReport, RunCurateAdjError,
};
use crate::run_curate_bars::{
load_provider_mapping_tsv, run_curate_bars_1d_with_readers, CurateBars1dRunReport,
RunCurateBarsError,
};
use crate::run_curate_corporate_actions::{
run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport,
RunCurateCorporateActionsError,
};
use crate::run_curate_events::{
run_curate_events_with_readers, CurateEventsRunReport, RunCurateEventsError,
};
use crate::run_curate_fx::{
run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE,
};
use crate::run_curate_shorts::{
run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError,
};
/// Error returned by direct MongoDB streaming curation commands.
#[derive(Debug)]
pub enum RunMongoCurateError {
Mongo(MongoStreamError),
Bars(RunCurateBarsError),
Adj(RunCurateAdjError),
CorporateActions(RunCurateCorporateActionsError),
Fx(RunCurateFxError),
Shorts(RunCurateShortsError),
Events(RunCurateEventsError),
}
impl fmt::Display for RunMongoCurateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Mongo(e) => write!(f, "{e}"),
Self::Bars(e) => write!(f, "{e}"),
Self::Adj(e) => write!(f, "{e}"),
Self::CorporateActions(e) => write!(f, "{e}"),
Self::Fx(e) => write!(f, "{e}"),
Self::Shorts(e) => write!(f, "{e}"),
Self::Events(e) => write!(f, "{e}"),
}
}
}
impl Error for RunMongoCurateError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Mongo(e) => Some(e),
Self::Bars(e) => Some(e),
Self::Adj(e) => Some(e),
Self::CorporateActions(e) => Some(e),
Self::Fx(e) => Some(e),
Self::Shorts(e) => Some(e),
Self::Events(e) => Some(e),
}
}
}
/// Parsed arguments for `curate-bars-1d --from-mongo`.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateBars1dMongoArgs {
pub mongo: MongoCliOptions,
pub with_qm_prices: bool,
pub provider_mapping: PathBuf,
pub listing_currencies: PathBuf,
pub out_dir: PathBuf,
pub rel_tolerance: f64,
pub threads: usize,
}
/// Parsed arguments for `curate-adj-factors --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateAdjFactorsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub bars_1d_dir: PathBuf,
pub out_dir: PathBuf,
pub fence: Option<AdjPointInTimeFence>,
}
/// Parsed arguments for `curate-corporate-actions --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateCorporateActionsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub delistings: Option<PathBuf>,
pub out_dir: PathBuf,
}
/// Parsed arguments for `curate-fx-1d --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFx1dMongoArgs {
pub mongo: MongoCliOptions,
pub te_symbol: String,
pub out_dir: PathBuf,
}
/// Parsed arguments for `curate-shorts --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateShortsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub key_field: String,
pub report_date_field: String,
pub shares_short_field: String,
pub net_change_field: Option<String>,
pub pct_float_field: Option<String>,
pub mapping_source: String,
}
/// Parsed arguments for `curate-events --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateEventsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub filings_key_field: String,
pub filings_timefiled_field: String,
pub filings_form_type_field: String,
pub filings_filing_id_field: Option<String>,
pub filings_url_field: Option<String>,
pub earnings_key_field: String,
pub earnings_report_date_field: String,
pub earnings_announce_time_field: String,
pub earnings_fiscal_period_end_field: Option<String>,
pub earnings_actual_eps_field: Option<String>,
pub earnings_revenue_field: Option<String>,
pub mapping_source: String,
}
fn mongo_virtual_path(collection: SourceCollection) -> PathBuf {
PathBuf::from(format!("mongodb://{}", collection.as_str()))
}
fn connect_and_validate_specs(
mongo: &MongoCliOptions,
checks: &[(SourceCollection, MongoReadSpec)],
) -> Result<ReadOnlyMongoClient, RunMongoCurateError> {
for (collection, spec) in checks {
spec.validate(*collection)
.map_err(RunMongoCurateError::Mongo)?;
}
mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo)
}
fn unique_mapping_keys_for_source(
provider_mapping_path: &Path,
source: &str,
) -> Result<Vec<String>, RunCurateBarsError> {
let rows = load_provider_mapping_tsv(provider_mapping_path)?;
let mut keys = BTreeSet::new();
for row in rows {
if row.source == source {
keys.insert(row.source_id);
}
}
Ok(keys.into_iter().collect())
}
/// Streams `qmSplits`, `eodPrices`, and optional `qmPrices` directly from read-only MongoDB into
/// `bars_1d/year=YYYY/part.parquet`.
///
/// Note: `qmSplits` is always read without a date-range filter so cumulative post-bar split
/// factors remain exact even when `--date-gte` / `--date-lt` bounds `eodPrices`.
/// When `--limit` is not set, `eodPrices` and `qmPrices` are streamed in indexed `$in` key chunks
/// from `provider_mapping.tsv` so MongoDB scans only mapped US/CA symbols sequentially.
pub fn run_curate_bars_1d_mongo(
args: &CurateBars1dMongoArgs,
) -> Result<CurateBars1dRunReport, RunMongoCurateError> {
let splits_spec = MongoReadSpec {
batch_size: args.mongo.batch_size,
..MongoReadSpec::default()
};
let eod_spec = args.mongo.to_read_spec(None, true);
let qm_spec = args.mongo.to_read_spec(None, true);
let mut checks = vec![
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::EodPrices, eod_spec.clone()),
];
if args.with_qm_prices {
checks.push((SourceCollection::QmPrices, qm_spec.clone()));
}
let client = connect_and_validate_specs(&args.mongo, &checks)?;
let use_key_chunks = args.mongo.limit.is_none();
let eod_keys = if use_key_chunks {
unique_mapping_keys_for_source(&args.provider_mapping, "eod")
.map_err(RunMongoCurateError::Bars)?
} else {
Vec::new()
};
let qm_keys = if use_key_chunks && args.with_qm_prices {
unique_mapping_keys_for_source(&args.provider_mapping, "qm")
.map_err(RunMongoCurateError::Bars)?
} else {
Vec::new()
};
let result = {
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
let splits_path = mongo_virtual_path(SourceCollection::QmSplits);
let eod_path = mongo_virtual_path(SourceCollection::EodPrices);
if use_key_chunks {
let eod_reader = client
.open_raw_cursor_for_keys(SourceCollection::EodPrices, &eod_spec, &eod_keys, 250)
.map_err(RunMongoCurateError::Mongo)?;
let qm_input = if args.with_qm_prices {
let reader = client
.open_raw_cursor_for_keys(SourceCollection::QmPrices, &qm_spec, &qm_keys, 250)
.map_err(RunMongoCurateError::Mongo)?;
Some((mongo_virtual_path(SourceCollection::QmPrices), reader))
} else {
None
};
run_curate_bars_1d_with_readers(
&args.provider_mapping,
&args.listing_currencies,
(&splits_path, splits_reader),
(&eod_path, eod_reader),
qm_input,
&args.out_dir,
args.rel_tolerance,
args.threads,
)
.map_err(RunMongoCurateError::Bars)
} else {
let eod_reader = client
.open_raw_cursor(SourceCollection::EodPrices, &eod_spec)
.map_err(RunMongoCurateError::Mongo)?;
let qm_input = if args.with_qm_prices {
let reader = client
.open_raw_cursor(SourceCollection::QmPrices, &qm_spec)
.map_err(RunMongoCurateError::Mongo)?;
Some((mongo_virtual_path(SourceCollection::QmPrices), reader))
} else {
None
};
run_curate_bars_1d_with_readers(
&args.provider_mapping,
&args.listing_currencies,
(&splits_path, splits_reader),
(&eod_path, eod_reader),
qm_input,
&args.out_dir,
args.rel_tolerance,
args.threads,
)
.map_err(RunMongoCurateError::Bars)
}
};
client.shutdown();
result
}
/// Streams `qmSplits` and `qmDividends` directly from read-only MongoDB into
/// `adj_factors/part.parquet` (retrospective or point-in-time fenced).
pub fn run_curate_adj_factors_mongo(
args: &CurateAdjFactorsMongoArgs,
) -> Result<CurateAdjFactorsRunReport, RunMongoCurateError> {
let splits_spec = args.mongo.to_read_spec(None, true);
let dividends_spec = args.mongo.to_read_spec(None, true);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::QmDividends, dividends_spec.clone()),
],
)?;
let result = {
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
let dividends_reader = client
.open_raw_cursor(SourceCollection::QmDividends, &dividends_spec)
.map_err(RunMongoCurateError::Mongo)?;
let splits_path = mongo_virtual_path(SourceCollection::QmSplits);
let dividends_path = mongo_virtual_path(SourceCollection::QmDividends);
run_curate_adj_factors_with_readers(
&args.provider_mapping,
&args.bars_1d_dir,
(&splits_path, splits_reader),
(&dividends_path, dividends_reader),
&args.out_dir,
args.fence,
)
.map_err(RunMongoCurateError::Adj)
};
client.shutdown();
result
}
/// Streams `qmSplits` and `qmDividends` directly from read-only MongoDB alongside optional
/// Pass 6 `delistings.tsv` into `corporate_actions/part.parquet`.
pub fn run_curate_corporate_actions_mongo(
args: &CurateCorporateActionsMongoArgs,
) -> Result<CurateCorporateActionsRunReport, RunMongoCurateError> {
let splits_spec = args.mongo.to_read_spec(None, false);
let dividends_spec = args.mongo.to_read_spec(None, false);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::QmDividends, dividends_spec.clone()),
],
)?;
let result = {
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
let dividends_reader = client
.open_raw_cursor(SourceCollection::QmDividends, &dividends_spec)
.map_err(RunMongoCurateError::Mongo)?;
let splits_path = mongo_virtual_path(SourceCollection::QmSplits);
let dividends_path = mongo_virtual_path(SourceCollection::QmDividends);
run_curate_corporate_actions_with_readers(
&args.provider_mapping,
args.delistings.as_deref(),
(&splits_path, splits_reader),
(&dividends_path, dividends_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::CorporateActions)
};
client.shutdown();
result
}
/// Streams `eodPrices` (`eodSearchCode == "CAD.FOREX"`) and `teMarketData` (`teSymbol == te_symbol`)
/// directly from read-only MongoDB into `fx_1d/part.parquet`.
pub fn run_curate_fx_1d_mongo(
args: &CurateFx1dMongoArgs,
) -> Result<CurateFx1dRunReport, RunMongoCurateError> {
let eod_spec = args
.mongo
.to_read_spec(Some(EOD_CAD_FOREX_CODE.to_owned()), false);
let te_spec = args.mongo.to_read_spec(Some(args.te_symbol.clone()), false);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::EodPrices, eod_spec.clone()),
(SourceCollection::TeMarketData, te_spec.clone()),
],
)?;
let result = {
let eod_reader = client
.open_raw_cursor(SourceCollection::EodPrices, &eod_spec)
.map_err(RunMongoCurateError::Mongo)?;
let te_reader = client
.open_raw_cursor(SourceCollection::TeMarketData, &te_spec)
.map_err(RunMongoCurateError::Mongo)?;
let eod_path = mongo_virtual_path(SourceCollection::EodPrices);
let te_path = mongo_virtual_path(SourceCollection::TeMarketData);
run_curate_fx_1d_with_readers(
(&eod_path, eod_reader),
(&te_path, te_reader),
&args.te_symbol,
&args.out_dir,
)
.map_err(RunMongoCurateError::Fx)
};
client.shutdown();
result
}
/// Streams `ceoShorts` directly from read-only MongoDB into `shorts/part.parquet`.
pub fn run_curate_shorts_mongo(
args: &CurateShortsMongoArgs,
) -> Result<CurateShortsRunReport, RunMongoCurateError> {
let shorts_spec = args.mongo.to_read_spec(None, false);
let client = connect_and_validate_specs(
&args.mongo,
&[(SourceCollection::CeoShorts, shorts_spec.clone())],
)?;
let fields = CeoShortsFieldNames {
key: args.key_field.as_str(),
report_date: args.report_date_field.as_str(),
shares_short: args.shares_short_field.as_str(),
net_change: args.net_change_field.as_deref(),
pct_float: args.pct_float_field.as_deref(),
};
let result = {
let shorts_reader = client
.open_raw_cursor(SourceCollection::CeoShorts, &shorts_spec)
.map_err(RunMongoCurateError::Mongo)?;
let shorts_path = mongo_virtual_path(SourceCollection::CeoShorts);
run_curate_shorts_with_reader(
&args.provider_mapping,
&args.mapping_source,
&fields,
(&shorts_path, shorts_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::Shorts)
};
client.shutdown();
result
}
/// Streams `qmFilings` and `qmEarnings` directly from read-only MongoDB into
/// `events/year=YYYY/part.parquet`.
pub fn run_curate_events_mongo(
args: &CurateEventsMongoArgs,
) -> Result<CurateEventsRunReport, RunMongoCurateError> {
let filings_spec = args
.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(
&args.mongo,
&[
(SourceCollection::QmFilings, filings_spec.clone()),
(SourceCollection::QmEarnings, earnings_spec.clone()),
],
)?;
let filings_fields = QmFilingsFieldNames {
key: args.filings_key_field.as_str(),
timefiled: args.filings_timefiled_field.as_str(),
form_type: args.filings_form_type_field.as_str(),
filing_id: args.filings_filing_id_field.as_deref(),
url: args.filings_url_field.as_deref(),
};
let earnings_fields = QmEarningsFieldNames {
key: args.earnings_key_field.as_str(),
report_date: args.earnings_report_date_field.as_str(),
announce_time: args.earnings_announce_time_field.as_str(),
fiscal_period_end: args.earnings_fiscal_period_end_field.as_deref(),
actual_eps: args.earnings_actual_eps_field.as_deref(),
revenue: args.earnings_revenue_field.as_deref(),
};
let result = {
let filings_reader = client
.open_raw_cursor(SourceCollection::QmFilings, &filings_spec)
.map_err(RunMongoCurateError::Mongo)?;
let earnings_reader = client
.open_raw_cursor(SourceCollection::QmEarnings, &earnings_spec)
.map_err(RunMongoCurateError::Mongo)?;
let filings_path = mongo_virtual_path(SourceCollection::QmFilings);
let earnings_path = mongo_virtual_path(SourceCollection::QmEarnings);
run_curate_events_with_readers(
&args.provider_mapping,
&args.mapping_source,
&filings_fields,
&earnings_fields,
(&filings_path, filings_reader),
(&earnings_path, earnings_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::Events)
};
client.shutdown();
result
}
/// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly).
#[allow(dead_code)]
fn _assert_path_ref(path: &Path) -> &Path {
path
}

View file

@ -29,7 +29,9 @@ fn public_field_constants_and_single_doc_decoders_match_contract() {
split_doc.append(cstr!("qmSearchCode"), "NVDA");
split_doc.append(cstr!("date"), "2024-06-10");
split_doc.append(cstr!("declared"), "2024-05-22");
split_doc.append(cstr!("splitratio"), 10_i32);
split_doc.append(cstr!("forfactor"), 1_i32);
split_doc.append(cstr!("tofactor"), 10_i32);
split_doc.append(cstr!("splitratio"), 0.1_f64);
split_doc.append(cstr!("usdFxRate"), 1_i32);
let split = decode_qm_split_doc(&split_doc).unwrap();
@ -67,7 +69,9 @@ fn public_buffer_decoders_reconcile_and_feed_all_downstream_builders() {
s_nvda.append(cstr!("qmSearchCode"), "NVDA");
s_nvda.append(cstr!("date"), "2024-06-10");
s_nvda.append(cstr!("declared"), "2024-05-22");
s_nvda.append(cstr!("splitratio"), 10.0_f64);
s_nvda.append(cstr!("forfactor"), 1_i32);
s_nvda.append(cstr!("tofactor"), 10_i32);
s_nvda.append(cstr!("splitratio"), 0.1_f64);
split_buf.extend_from_slice(s_nvda.as_bytes());
let mut s_noop = RawDocumentBuf::new();

View file

@ -39,7 +39,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> RawDocumentBuf {
doc.append(cstr!("_id"), "ignored");
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.append(cstr!("usdFxRate"), 1_i32);
doc
}

View file

@ -303,7 +303,13 @@ fn make_split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -0,0 +1,407 @@
//! Offline contract tests for the sealed MongoDB driver adapter, CLI `--from-mongo`
//! wiring, and byte-identical file-vs-cursor Parquet parity.
use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawDocumentBuf};
use curate_etl::cli::{parse_args, CliAction};
use curate_etl::{
assert_read_only_mongo_uri, open_read_only_mongo_from_env, open_read_only_mongo_uri,
run_curate_adj_factors_fenced, run_curate_bars_1d, run_curate_bars_1d_with_readers,
run_curate_fx_1d, run_curate_fx_1d_with_readers, AdjPointInTimeFence, CurateAdjFactorsArgs,
CurateBars1dArgs, CurateFx1dArgs, LocalHosts, MongoUriSource, RawBsonCursorReader,
ReadOnlyMongoClient, ReadOnlyPolicy, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE,
DEFAULT_MONGO_URI_ENV,
};
static COUNTER: AtomicU64 = AtomicU64::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"curate-etl-mongo-cli-{tag}-{}-{id}",
std::process::id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("create temp dir");
Self(dir)
}
fn path(&self) -> &PathBuf {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn s(items: &[&str]) -> Vec<String> {
items.iter().map(|v| (*v).to_owned()).collect()
}
fn make_eod_doc(code: &str, date: &str, open: f64, high: f64, low: f64, close: f64, volume: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("eodSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("open"), open);
doc.append(cstr!("high"), high);
doc.append(cstr!("low"), low);
doc.append(cstr!("close"), close);
doc.append(cstr!("volume"), volume);
doc.into_bytes()
}
fn make_split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}
fn make_div_doc(code: &str, date: &str, amount: f64, currency: &str) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("amount"), amount);
doc.append(cstr!("currency"), currency);
doc.into_bytes()
}
#[test]
fn read_only_mongo_client_rejects_missing_database_and_unsafe_uris() {
let local = LocalHosts::empty();
let validated_no_db = assert_read_only_mongo_uri(
"mongodb://studio_stock_bot_read:SECRET_PW_99@localhost:27017",
&ReadOnlyPolicy::default(),
&local,
)
.expect("valid host/user");
let err = ReadOnlyMongoClient::connect(validated_no_db)
.expect_err("URI without database path must fail closed");
let msg = err.to_string();
assert!(msg.contains("database name"), "{msg}");
assert!(!msg.contains("SECRET_PW_99"), "password leaked: {msg}");
let admin_err = open_read_only_mongo_uri(
"mongodb://trading_admin:ADMIN_PW_99@localhost:27017/stock",
&local,
)
.expect_err("trading_admin must always be rejected");
let admin_msg = admin_err.to_string();
assert!(admin_msg.contains("trading_admin"), "{admin_msg}");
assert!(!admin_msg.contains("ADMIN_PW_99"), "password leaked: {admin_msg}");
let unauth_err = open_read_only_mongo_uri("mongodb://localhost:27017/stock", &local)
.expect_err("unauthenticated QA URI must be rejected");
assert!(
unauth_err.to_string().contains("credentials"),
"{unauth_err}"
);
let env_err = open_read_only_mongo_from_env("__STOCK_BOT_NONEXISTENT_ENV_VAR__", &local)
.expect_err("missing env var must fail closed");
assert!(env_err.to_string().contains("not set"), "{env_err}");
}
#[test]
fn cli_parses_from_mongo_for_all_six_curate_commands_and_rejects_mixing() {
let action = parse_args(&s(&[
"curate-bars-1d",
"--from-mongo",
"--with-qm-prices",
"--batch-size",
"2048",
"--limit",
"500",
"--date-gte",
"2005-01-01",
"--date-lt",
"2026-01-01",
"--provider-mapping",
"/tmp/pm.tsv",
"--listing-currencies",
"/tmp/lc.tsv",
"--out",
"/tmp/out",
"--threads",
"2",
]))
.expect("valid curate-bars-1d --from-mongo");
match action {
CliAction::CurateBars1dMongo(a) => {
assert_eq!(
a.mongo.uri_source,
MongoUriSource::EnvVar(DEFAULT_MONGO_URI_ENV.to_owned())
);
assert_eq!(a.mongo.batch_size, 2048);
assert_eq!(a.mongo.limit, Some(500));
assert_eq!(a.mongo.date_gte.as_deref(), Some("2005-01-01"));
assert_eq!(a.mongo.date_lt.as_deref(), Some("2026-01-01"));
assert!(a.with_qm_prices);
assert_eq!(a.threads, 2);
}
other => panic!("unexpected action: {other:?}"),
}
let mix_err = parse_args(&s(&[
"curate-bars-1d",
"--from-mongo",
"--eod-prices",
"/tmp/eod.bson",
"--provider-mapping",
"/tmp/pm.tsv",
"--listing-currencies",
"/tmp/lc.tsv",
"--out",
"/tmp/out",
]))
.expect_err("mixing --from-mongo with --eod-prices must fail");
assert!(mix_err.contains("cannot combine"), "{mix_err}");
let stray_mongo_flag = parse_args(&s(&[
"curate-fx-1d",
"--mongo-uri-env",
"MONGODB_READ_URI",
"--eod-prices",
"/tmp/eod.bson",
"--te-market-data",
"/tmp/te.bson",
"--out",
"/tmp/out",
]))
.expect_err("--mongo-uri-env without --from-mongo must fail");
assert!(
stray_mongo_flag.contains("require '--from-mongo'"),
"{stray_mongo_flag}"
);
let fx_action = parse_args(&s(&[
"curate-fx-1d",
"--from-mongo",
"--mongo-uri-env",
"CUSTOM_MONGO_URI",
"--out",
"/tmp/out",
]))
.expect("valid curate-fx-1d --from-mongo");
match fx_action {
CliAction::CurateFx1dMongo(a) => {
assert_eq!(
a.mongo.uri_source,
MongoUriSource::EnvVar("CUSTOM_MONGO_URI".to_owned())
);
assert_eq!(a.mongo.batch_size, DEFAULT_MONGO_BATCH_SIZE);
assert_eq!(a.te_symbol, "USDCAD");
}
other => panic!("unexpected action: {other:?}"),
}
let adj_action = parse_args(&s(&[
"curate-adj-factors",
"--from-mongo",
"--provider-mapping",
"/tmp/pm.tsv",
"--bars-1d",
"/tmp/bars_1d",
"--out",
"/tmp/out",
"--vault-cutoff",
"2025-10-01",
]))
.expect("valid curate-adj-factors --from-mongo --vault-cutoff");
match adj_action {
CliAction::CurateAdjFactorsMongo(a) => {
assert!(a.fence.is_some());
assert!(a.fence.unwrap().vault_cutoff_micros.is_some());
assert!(a.fence.unwrap().as_of_micros.is_none());
}
other => panic!("unexpected action: {other:?}"),
}
let ca_action = parse_args(&s(&[
"curate-corporate-actions",
"--from-mongo",
"--provider-mapping",
"/tmp/pm.tsv",
"--out",
"/tmp/out",
]))
.expect("valid curate-corporate-actions --from-mongo");
assert!(matches!(ca_action, CliAction::CurateCorporateActionsMongo(_)));
let shorts_action = parse_args(&s(&[
"curate-shorts",
"--from-mongo",
"--provider-mapping",
"/tmp/pm.tsv",
"--out",
"/tmp/out",
"--shares-short-field",
"number_of_shares",
"--net-change-field",
"net_change",
]))
.expect("valid curate-shorts --from-mongo");
assert!(matches!(shorts_action, CliAction::CurateShortsMongo(_)));
let events_action = parse_args(&s(&[
"curate-events",
"--from-mongo",
"--provider-mapping",
"/tmp/pm.tsv",
"--out",
"/tmp/out",
"--filings-form-type-field",
"formdescription",
"--date-gte",
"2020-01-01",
]))
.expect("valid curate-events --from-mongo");
assert!(matches!(events_action, CliAction::CurateEventsMongo(_)));
}
#[test]
fn file_mode_and_cursor_reader_mode_produce_byte_identical_parquet_outputs() {
let tmp = TempDir::new("parity");
let pm_path = tmp.path().join("provider_mapping.tsv");
let lc_path = tmp.path().join("listing_currencies.tsv");
let eod_path = tmp.path().join("eod.bson");
let splits_path = tmp.path().join("splits.bson");
let divs_path = tmp.path().join("divs.bson");
let te_path = tmp.path().join("te.bson");
fs::write(
&pm_path,
"eod\tNVDA.US\t2000-01-01\t\t101\nqm\tNVDA\t2000-01-01\t\t101\n",
)
.expect("write pm");
fs::write(&lc_path, "101\tUSD\n").expect("write lc");
let eod_docs = vec![
make_eod_doc("NVDA.US", "2024-06-07", 1200.0, 1215.0, 1190.0, 1208.88, 412_390_000.0),
make_eod_doc("NVDA.US", "2024-06-10", 120.5, 123.0, 119.0, 121.79, 314_160_000.0),
make_eod_doc("CAD.FOREX", "2024-06-07", 1.368, 1.375, 1.365, 1.374, 0.0),
];
let split_docs = vec![make_split_doc("NVDA", "2024-06-10", 10.0)];
let div_docs = vec![make_div_doc("NVDA", "2024-06-11", 0.01, "USD")];
{
let mut f = File::create(&eod_path).unwrap();
for d in &eod_docs {
f.write_all(d).unwrap();
}
let mut f = File::create(&splits_path).unwrap();
for d in &split_docs {
f.write_all(d).unwrap();
}
let mut f = File::create(&divs_path).unwrap();
for d in &div_docs {
f.write_all(d).unwrap();
}
let _ = File::create(&te_path).unwrap();
}
let out_file = tmp.path().join("out_file");
let out_cursor = tmp.path().join("out_cursor");
let file_rep = run_curate_bars_1d(&CurateBars1dArgs {
eod_prices: eod_path.clone(),
qm_splits: splits_path.clone(),
qm_prices: None,
provider_mapping: pm_path.clone(),
listing_currencies: lc_path.clone(),
out_dir: out_file.clone(),
rel_tolerance: 0.01,
threads: 1,
})
.expect("file curate-bars-1d");
let cursor_rep = run_curate_bars_1d_with_readers(
&pm_path,
&lc_path,
(
&splits_path,
RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs.clone())),
),
(
&eod_path,
RawBsonCursorReader::new(VecRawDocumentSource::new(eod_docs.clone())),
),
None::<(PathBuf, std::io::Empty)>,
&out_cursor,
0.01,
1,
)
.expect("cursor curate-bars-1d");
assert_eq!(file_rep.write_stats.rows_written, 2);
assert_eq!(cursor_rep.write_stats.rows_written, 2);
let file_bytes = fs::read(out_file.join("bars_1d/year=2024/part.parquet")).unwrap();
let cursor_bytes = fs::read(out_cursor.join("bars_1d/year=2024/part.parquet")).unwrap();
assert_eq!(
file_bytes, cursor_bytes,
"bars_1d Parquet bytes must be identical between file mode and RawBsonCursorReader mode"
);
// Verify fenced adj_factors snapshot via CLI helper
let fence = AdjPointInTimeFence {
as_of_micros: None,
vault_cutoff_micros: Some(1_759_276_800_000_000), // 2025-10-01T00:00:00Z
};
let adj_rep = run_curate_adj_factors_fenced(
&CurateAdjFactorsArgs {
qm_splits: splits_path,
qm_dividends: divs_path,
provider_mapping: pm_path,
bars_1d_dir: out_file.join("bars_1d"),
out_dir: out_file.clone(),
},
Some(fence),
)
.expect("fenced adj_factors");
assert_eq!(adj_rep.write_stats.rows_written, 2);
// Verify fx_1d byte-identical parity
let fx_file = run_curate_fx_1d(&CurateFx1dArgs {
eod_prices: eod_path.clone(),
te_market_data: te_path.clone(),
te_symbol: "USDCAD".to_owned(),
out_dir: out_file.clone(),
})
.expect("file fx_1d");
let fx_cursor = run_curate_fx_1d_with_readers(
(
&eod_path,
RawBsonCursorReader::new(VecRawDocumentSource::new(eod_docs)),
),
(
&te_path,
RawBsonCursorReader::new(VecRawDocumentSource::new(Vec::new())),
),
"USDCAD",
&out_cursor,
)
.expect("cursor fx_1d");
assert_eq!(fx_file.write_stats.rows_written, 1);
assert_eq!(fx_cursor.write_stats.rows_written, 1);
assert_eq!(
fs::read(out_file.join("fx_1d/part.parquet")).unwrap(),
fs::read(out_cursor.join("fx_1d/part.parquet")).unwrap()
);
}

View file

@ -99,7 +99,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -66,7 +66,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -117,7 +117,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -97,7 +97,13 @@ fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("date"), date);
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.into_bytes()
}

View file

@ -87,7 +87,13 @@ fn split_doc(code: &str, date: &str, declared: Option<&str>, ratio: f64) -> Vec<
if let Some(d) = declared {
doc.append(cstr!("declared"), d);
}
doc.append(cstr!("splitratio"), ratio);
if ratio.is_finite() && ratio > 0.0 {
doc.append(cstr!("splitratio"), 1.0 / ratio);
doc.append(cstr!("forfactor"), 1.0_f64);
doc.append(cstr!("tofactor"), ratio);
} else {
doc.append(cstr!("splitratio"), ratio);
}
doc.append(cstr!("usdFxRate"), 1_i32);
doc.into_bytes()
}