diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 9f8aa718..177a7076 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -54,3 +54,12 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto - **Read-only guarantee:** The CLI initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` with `readOnly: true`, performs zero MongoDB writes, and performs zero PostgreSQL writes. - **Review and upgrade workflow:** Keep `database/postgres/init/35-security-master-exchange-seed.sql` immutable as the reproducible Pass 1 baseline—`runPostgresMigrations` records applied filenames in `migrations` and skips any file it has already run, so editing migration `35` in place would not reach databases that already applied it. Instead, inspect `./tmp/pass1-unresolved-exchanges.md` for unresolved codes (unknown MICs, multi-valued `OperatingMIC`, missing MICs), add approved additions or corrections as a **new** numbered migration under `database/postgres/init/` (for example `36-security-master-exchange-overrides.sql`, setting `reviewed_by` on director-approved rows) and register it in `MASTER_FILES` in `libs/data/postgres/src/migrations.ts` (also updating `EXPLICIT_EXCHANGE_SOURCE_RULES` if future generator runs should classify those codes explicitly). Verify the upgrade against a schema where migration `35` has already run—not only a fresh schema—confirming the new migration applies cleanly and that re-applying the baseline never overwrites rows where `reviewed_by IS NOT NULL`. + +## Pass 4 Cross-Sectional Price Cross-Check +`apps/stock/data-pipeline/src/security-master/price-cross-check.ts` provides pure, zero-I/O verification for candidate source-to-source listing pairs before persisting `provider_mapping` / `resolution_conflict` rows: + +- **Stratified date sampling (`selectSampleDates`):** Drops invalid/non-`YYYY-MM-DD` values, deduplicates, sorts ascending, and selects `count` dates (default `25`) by splitting the calendar into `count` contiguous near-equal strata and picking the middle date of each (returning all valid unique dates when `<= count`). +- **Price ratio & FX rules (`crossCheckPrices`):** Compares raw sample closes over dates where both sides have a finite `close > 0` (conflicting duplicate closes or FX rates drop that date and are counted; missing FX dates on cross-currency pairs are skipped and never forward-filled). Expected `left/right` ratio is `1.0` for matching ISO currencies, `usdCad` (CAD per 1 USD) for `CAD`/`USD`, and `1 / usdCad` for `USD`/`CAD`; any other currency combination returns `unsupported_currency_pair`. +- **Return correlation:** Computes two-pass centered Pearson correlation of consecutive log returns in a canonical common currency (converting CAD closes to USD via `cadClose / usdCad` for `CAD`/`USD` pairs so correlation is orientation-symmetric and unaffected by FX moves on flat USD prices), rounded to `4` decimal places (`provider_mapping.price_corr NUMERIC(5,4)`). Returns `null` when fewer than `3` returns exist or either series has zero variance. +- **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`|medianRatio - 1| > 0.02`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. +- **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload. diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 64d1dd2e..f47fe4bf 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -109,3 +109,31 @@ export { type StageBUnresolvedReason, type StageBUnresolvedRecord, } from './listing-stage-b'; + +export { + crossCheckPrices, + DEFAULT_MIN_COMMON_DATES, + DEFAULT_MIN_CORRELATION, + DEFAULT_RATIO_TOLERANCE, + DEFAULT_SAMPLE_DATE_COUNT, + MIN_CORRELATION_RETURNS, + PRICE_CORR_DECIMALS, + PRICE_CROSS_CHECK_CONFLICT_KINDS, + PRICE_CROSS_CHECK_VERDICTS, + selectSampleDates, + type CrossCheckPricesOptions, + type FxRateByDateRecord, + type PriceCrossCheckConflictDetail, + type PriceCrossCheckConflictKind, + type PriceCrossCheckConflictRecord, + type PriceCrossCheckInput, + type PriceCrossCheckPair, + type PriceCrossCheckResult, + type PriceCrossCheckRow, + type PriceCrossCheckStats, + type PriceCrossCheckVerdict, + type PriceCrossCheckVerdictCounts, + type PriceSeriesEndpoint, + type SampleCloseRecord, + type SelectSampleDatesOptions, +} from './price-cross-check'; diff --git a/apps/stock/data-pipeline/src/security-master/price-cross-check.ts b/apps/stock/data-pipeline/src/security-master/price-cross-check.ts new file mode 100644 index 00000000..f1ce01aa --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/price-cross-check.ts @@ -0,0 +1,647 @@ +import { compareAscii } from './exchange-pass1'; + +export const DEFAULT_SAMPLE_DATE_COUNT = 25; +export const DEFAULT_MIN_COMMON_DATES = 5; +export const DEFAULT_RATIO_TOLERANCE = 0.02; +export const DEFAULT_MIN_CORRELATION = 0.9; +export const MIN_CORRELATION_RETURNS = 3; +export const PRICE_CORR_DECIMALS = 4; + +export const PRICE_CROSS_CHECK_VERDICTS = [ + 'unsupported_currency_pair', + 'insufficient_data', + 'ratio_mismatch', + 'low_correlation', + 'confirmed', +] as const; + +export const PRICE_CROSS_CHECK_CONFLICT_KINDS = [ + 'price_ratio_mismatch', + 'price_low_correlation', +] as const; + +export type PriceCrossCheckVerdict = (typeof PRICE_CROSS_CHECK_VERDICTS)[number]; +export type PriceCrossCheckConflictKind = (typeof PRICE_CROSS_CHECK_CONFLICT_KINDS)[number]; + +export interface SelectSampleDatesOptions { + readonly count?: number; +} + +export interface PriceSeriesEndpoint { + readonly source: string; + readonly sourceId: string; + readonly currency: string; +} + +export interface PriceCrossCheckPair { + readonly left: PriceSeriesEndpoint; + readonly right: PriceSeriesEndpoint; +} + +export interface SampleCloseRecord { + readonly source: string; + readonly sourceId: string; + readonly date: string; + readonly close: number; +} + +export interface FxRateByDateRecord { + readonly date: string; + readonly usdCad: number; +} + +export interface PriceCrossCheckInput { + readonly pairs: readonly PriceCrossCheckPair[]; + readonly closes: readonly SampleCloseRecord[]; + readonly usdCadByDate: readonly FxRateByDateRecord[]; +} + +export interface CrossCheckPricesOptions { + readonly minCommonDates?: number; + readonly ratioTolerance?: number; + readonly minCorrelation?: number; +} + +export interface PriceCrossCheckRow { + left: PriceSeriesEndpoint; + right: PriceSeriesEndpoint; + verdict: PriceCrossCheckVerdict; + usableDates: number; + medianRatio: number | null; + priceCorr: number | null; +} + +export interface PriceCrossCheckConflictDetail { + left: PriceSeriesEndpoint; + right: PriceSeriesEndpoint; + verdict: 'ratio_mismatch' | 'low_correlation'; + usableDates: number; + medianRatio: number; + priceCorr: number; + ratioTolerance: number; + minCorrelation: number; +} + +export interface PriceCrossCheckConflictRecord { + source: string; + sourceId: string; + conflictKind: PriceCrossCheckConflictKind; + detail: PriceCrossCheckConflictDetail; +} + +export interface PriceCrossCheckVerdictCounts { + unsupported_currency_pair: number; + insufficient_data: number; + ratio_mismatch: number; + low_correlation: number; + confirmed: number; +} + +export interface PriceCrossCheckStats { + pairsIn: number; + byVerdict: PriceCrossCheckVerdictCounts; + conflictsEmitted: number; + droppedInvalidCloses: number; + droppedConflictingCloses: number; + droppedInvalidFxRates: number; + droppedConflictingFxRates: number; + skippedMissingFxDates: number; +} + +export interface PriceCrossCheckResult { + results: PriceCrossCheckRow[]; + conflicts: PriceCrossCheckConflictRecord[]; + stats: PriceCrossCheckStats; +} + +type CurrencyPairMode = 'same' | 'cad_vs_usd' | 'usd_vs_cad' | 'unsupported'; + +interface AlignedClosePoint { + readonly date: string; + readonly leftClose: number; + readonly rightClose: number; + readonly fx: number; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; +const VARIANCE_FLOOR = 1e-24; +const PRICE_CORR_SCALE = 10 ** PRICE_CORR_DECIMALS; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +/** + * Pure-integer exact YYYY-MM-DD validator for Gregorian years 0001..9999. + * Rejects timestamps, whitespace padding, and rollover dates (e.g. 2023-02-29) + * without allocating `Date` objects. + */ +function isValidExactYmd(value: unknown): value is string { + if (typeof value !== 'string' || !EXACT_YMD_PATTERN.test(value)) { + return false; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + if (year < 1) { + return false; + } + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + if (month < 1 || month > 12) { + return false; + } + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + return day >= 1 && day <= maxDay; +} + +function makeSeriesKey(source: string, sourceId: string): string { + return `${source}\u0000${sourceId}`; +} + +function normalizeIsoCurrency(value: unknown): string | null { + if (typeof value !== 'string') { + return null; + } + const normalized = value.trim().toUpperCase(); + return ISO_CURRENCY_PATTERN.test(normalized) ? normalized : null; +} + +function classifyCurrencyPair(leftCurrency: unknown, rightCurrency: unknown): CurrencyPairMode { + const left = normalizeIsoCurrency(leftCurrency); + const right = normalizeIsoCurrency(rightCurrency); + if (left === null || right === null) { + return 'unsupported'; + } + if (left === right) { + return 'same'; + } + if (left === 'CAD' && right === 'USD') { + return 'cad_vs_usd'; + } + if (left === 'USD' && right === 'CAD') { + return 'usd_vs_cad'; + } + return 'unsupported'; +} + +function cloneEndpoint(endpoint: PriceSeriesEndpoint): PriceSeriesEndpoint { + return { + source: endpoint.source, + sourceId: endpoint.sourceId, + currency: endpoint.currency, + }; +} + +function compareEndpoint(a: PriceSeriesEndpoint, b: PriceSeriesEndpoint): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.currency, b.currency) + ); +} + +function compareRows(a: PriceCrossCheckRow, b: PriceCrossCheckRow): number { + return ( + compareEndpoint(a.left, b.left) || + compareEndpoint(a.right, b.right) || + compareAscii(a.verdict, b.verdict) + ); +} + +function compareConflicts( + a: PriceCrossCheckConflictRecord, + b: PriceCrossCheckConflictRecord +): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.conflictKind, b.conflictKind) || + compareEndpoint(a.detail.right, b.detail.right) || + compareEndpoint(a.detail.left, b.detail.left) + ); +} + +function computeMedian(values: readonly number[]): number | null { + const n = values.length; + if (n === 0) { + return null; + } + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(n / 2); + if (n % 2 === 1) { + return sorted[mid] ?? null; + } + const lo = sorted[mid - 1]; + const hi = sorted[mid]; + if (lo === undefined || hi === undefined) { + return null; + } + return (lo + hi) / 2; +} + +/** + * Computes two-pass centered Pearson correlation of consecutive log returns + * in a common currency (USD for CAD/USD pairs so correlation is orientation-symmetric + * and does not manufacture spurious correlation from FX moves on flat USD prices). + */ +function computeLogReturnCorrelation( + points: readonly AlignedClosePoint[], + mode: Exclude +): number | null { + if (points.length < MIN_CORRELATION_RETURNS + 1) { + return null; + } + + const returnCount = points.length - 1; + const rx = new Array(returnCount); + const ry = new Array(returnCount); + + let prevLeft = 0; + let prevRight = 0; + let sumX = 0; + let sumY = 0; + + for (let i = 0; i < points.length; i++) { + const pt = points[i]; + if (pt === undefined) { + return null; + } + const leftPrice = mode === 'cad_vs_usd' ? pt.leftClose / pt.fx : pt.leftClose; + const rightPrice = mode === 'usd_vs_cad' ? pt.rightClose / pt.fx : pt.rightClose; + + if (i > 0) { + const lx = Math.log(leftPrice / prevLeft); + const ly = Math.log(rightPrice / prevRight); + if (!Number.isFinite(lx) || !Number.isFinite(ly)) { + return null; + } + rx[i - 1] = lx; + ry[i - 1] = ly; + sumX += lx; + sumY += ly; + } + prevLeft = leftPrice; + prevRight = rightPrice; + } + + const meanX = sumX / returnCount; + const meanY = sumY / returnCount; + + let sxx = 0; + let syy = 0; + let sxy = 0; + for (let i = 0; i < returnCount; i++) { + const dx = (rx[i] ?? 0) - meanX; + const dy = (ry[i] ?? 0) - meanY; + sxx += dx * dx; + syy += dy * dy; + sxy += dx * dy; + } + + if ( + !Number.isFinite(sxx) || + !Number.isFinite(syy) || + !Number.isFinite(sxy) || + sxx <= VARIANCE_FLOOR || + syy <= VARIANCE_FLOOR + ) { + return null; + } + + const rawCorr = sxy / Math.sqrt(sxx * syy); + if (!Number.isFinite(rawCorr)) { + return null; + } + const clamped = Math.max(-1, Math.min(1, rawCorr)); + const rounded = Math.round(clamped * PRICE_CORR_SCALE) / PRICE_CORR_SCALE; + return rounded === 0 ? 0 : rounded; +} + +/** + * Selects up to `count` (default 25) stratified sample dates from a trading calendar. + * Drops invalid/non-YYYY-MM-DD entries, deduplicates, sorts ascending, and picks the + * middle date of each contiguous near-equal stratum. + */ +export function selectSampleDates( + tradingDates: readonly string[], + options?: SelectSampleDatesOptions +): string[] { + if (!Array.isArray(tradingDates)) { + throw new TypeError('tradingDates must be an array'); + } + if (options !== undefined && (options === null || typeof options !== 'object')) { + throw new TypeError('options must be an object'); + } + + const count = options?.count ?? DEFAULT_SAMPLE_DATE_COUNT; + if (typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) { + throw new RangeError('options.count must be a positive safe integer'); + } + + const uniqueSet = new Set(); + for (let i = 0; i < tradingDates.length; i++) { + const entry = tradingDates[i]; + if (isValidExactYmd(entry)) { + uniqueSet.add(entry); + } + } + + const unique = Array.from(uniqueSet).sort(compareAscii); + const n = unique.length; + if (n <= count) { + return unique; + } + + const selected: string[] = []; + for (let k = 0; k < count; k++) { + const start = Math.floor((k * n) / count); + const end = Math.floor(((k + 1) * n) / count); + const mid = start + Math.floor((end - start - 1) / 2); + const picked = unique[mid]; + if (picked !== undefined) { + selected.push(picked); + } + } + return selected; +} + +/** + * Pass 4 pure in-memory cross-sectional price cross-check. + * Verifies candidate source-to-source listing pairs against raw sample closes + * and USD/CAD FX rates using normalized price ratio and common-currency log-return correlation. + */ +export function crossCheckPrices( + input: PriceCrossCheckInput, + options?: CrossCheckPricesOptions +): PriceCrossCheckResult { + if (input === null || typeof input !== 'object') { + throw new TypeError('input must be an object'); + } + if (!Array.isArray(input.pairs)) { + throw new TypeError('input.pairs must be an array'); + } + if (!Array.isArray(input.closes)) { + throw new TypeError('input.closes must be an array'); + } + if (!Array.isArray(input.usdCadByDate)) { + throw new TypeError('input.usdCadByDate must be an array'); + } + if (options !== undefined && (options === null || typeof options !== 'object')) { + throw new TypeError('options must be an object'); + } + + const minCommonDates = options?.minCommonDates ?? DEFAULT_MIN_COMMON_DATES; + if ( + typeof minCommonDates !== 'number' || + !Number.isSafeInteger(minCommonDates) || + minCommonDates < 2 + ) { + throw new RangeError('options.minCommonDates must be a safe integer >= 2'); + } + + const ratioTolerance = options?.ratioTolerance ?? DEFAULT_RATIO_TOLERANCE; + if ( + typeof ratioTolerance !== 'number' || + !Number.isFinite(ratioTolerance) || + ratioTolerance < 0 + ) { + throw new RangeError('options.ratioTolerance must be a finite number >= 0'); + } + + const minCorrelation = options?.minCorrelation ?? DEFAULT_MIN_CORRELATION; + if ( + typeof minCorrelation !== 'number' || + !Number.isFinite(minCorrelation) || + minCorrelation < -1 || + minCorrelation > 1 + ) { + throw new RangeError('options.minCorrelation must be a finite number in [-1, 1]'); + } + + let droppedInvalidCloses = 0; + let droppedConflictingCloses = 0; + const closesBySeries = new Map>(); + + for (let i = 0; i < input.closes.length; i++) { + const row = input.closes[i]; + if ( + row === null || + typeof row !== 'object' || + typeof row.source !== 'string' || + row.source.length === 0 || + typeof row.sourceId !== 'string' || + row.sourceId.length === 0 || + !isValidExactYmd(row.date) || + typeof row.close !== 'number' || + !Number.isFinite(row.close) || + row.close <= 0 + ) { + droppedInvalidCloses += 1; + continue; + } + + const seriesKey = makeSeriesKey(row.source, row.sourceId); + let dateMap = closesBySeries.get(seriesKey); + if (dateMap === undefined) { + dateMap = new Map(); + closesBySeries.set(seriesKey, dateMap); + } + + if (!dateMap.has(row.date)) { + dateMap.set(row.date, row.close); + } else { + const existing = dateMap.get(row.date); + if (existing !== null && existing !== row.close) { + dateMap.set(row.date, null); + droppedConflictingCloses += 1; + } + } + } + + let droppedInvalidFxRates = 0; + let droppedConflictingFxRates = 0; + const fxByDate = new Map(); + + for (let i = 0; i < input.usdCadByDate.length; i++) { + const row = input.usdCadByDate[i]; + if ( + row === null || + typeof row !== 'object' || + !isValidExactYmd(row.date) || + typeof row.usdCad !== 'number' || + !Number.isFinite(row.usdCad) || + row.usdCad <= 0 + ) { + droppedInvalidFxRates += 1; + continue; + } + + if (!fxByDate.has(row.date)) { + fxByDate.set(row.date, row.usdCad); + } else { + const existing = fxByDate.get(row.date); + if (existing !== null && existing !== row.usdCad) { + fxByDate.set(row.date, null); + droppedConflictingFxRates += 1; + } + } + } + + const byVerdict: PriceCrossCheckVerdictCounts = { + unsupported_currency_pair: 0, + insufficient_data: 0, + ratio_mismatch: 0, + low_correlation: 0, + confirmed: 0, + }; + let skippedMissingFxDates = 0; + + const results: PriceCrossCheckRow[] = []; + const conflicts: PriceCrossCheckConflictRecord[] = []; + + for (let i = 0; i < input.pairs.length; i++) { + const pair = input.pairs[i]; + if (pair === undefined) { + continue; + } + const left = cloneEndpoint(pair.left); + const right = cloneEndpoint(pair.right); + const mode = classifyCurrencyPair(left.currency, right.currency); + + if (mode === 'unsupported') { + byVerdict.unsupported_currency_pair += 1; + results.push({ + left, + right, + verdict: 'unsupported_currency_pair', + usableDates: 0, + medianRatio: null, + priceCorr: null, + }); + continue; + } + + const leftMap = closesBySeries.get(makeSeriesKey(left.source, left.sourceId)); + const rightMap = closesBySeries.get(makeSeriesKey(right.source, right.sourceId)); + const points: AlignedClosePoint[] = []; + + if (leftMap !== undefined && rightMap !== undefined) { + const iterateLeft = leftMap.size <= rightMap.size; + const primaryMap = iterateLeft ? leftMap : rightMap; + const secondaryMap = iterateLeft ? rightMap : leftMap; + + for (const [date, primaryClose] of primaryMap.entries()) { + if (primaryClose === null) { + continue; + } + const secondaryClose = secondaryMap.get(date); + if (secondaryClose === undefined || secondaryClose === null) { + continue; + } + + let fx = 1; + if (mode !== 'same') { + const rate = fxByDate.get(date); + if (rate === undefined || rate === null) { + skippedMissingFxDates += 1; + continue; + } + fx = rate; + } + + const leftClose = iterateLeft ? primaryClose : secondaryClose; + const rightClose = iterateLeft ? secondaryClose : primaryClose; + points.push({ date, leftClose, rightClose, fx }); + } + } + + points.sort((a, b) => compareAscii(a.date, b.date)); + + const usableDates = points.length; + const normalizedRatios = new Array(usableDates); + for (let j = 0; j < usableDates; j++) { + const pt = points[j]; + if (pt === undefined) { + continue; + } + const expected = mode === 'same' ? 1 : mode === 'cad_vs_usd' ? pt.fx : 1 / pt.fx; + normalizedRatios[j] = pt.leftClose / pt.rightClose / expected; + } + + const medianRatio = computeMedian(normalizedRatios); + const priceCorr = computeLogReturnCorrelation(points, mode); + + let verdict: PriceCrossCheckVerdict; + if ( + usableDates < minCommonDates || + priceCorr === null || + medianRatio === null || + !Number.isFinite(medianRatio) + ) { + verdict = 'insufficient_data'; + } else if (Math.abs(medianRatio - 1) > ratioTolerance) { + verdict = 'ratio_mismatch'; + } else if (priceCorr < minCorrelation) { + verdict = 'low_correlation'; + } else { + verdict = 'confirmed'; + } + + byVerdict[verdict] += 1; + results.push({ + left, + right, + verdict, + usableDates, + medianRatio, + priceCorr, + }); + + if ( + (verdict === 'ratio_mismatch' || verdict === 'low_correlation') && + medianRatio !== null && + priceCorr !== null + ) { + const conflictKind: PriceCrossCheckConflictKind = + verdict === 'ratio_mismatch' ? 'price_ratio_mismatch' : 'price_low_correlation'; + conflicts.push({ + source: left.source, + sourceId: left.sourceId, + conflictKind, + detail: { + left: cloneEndpoint(left), + right: cloneEndpoint(right), + verdict, + usableDates, + medianRatio, + priceCorr, + ratioTolerance, + minCorrelation, + }, + }); + } + } + + results.sort(compareRows); + conflicts.sort(compareConflicts); + + return { + results, + conflicts, + stats: { + pairsIn: input.pairs.length, + byVerdict, + conflictsEmitted: conflicts.length, + droppedInvalidCloses, + droppedConflictingCloses, + droppedInvalidFxRates, + droppedConflictingFxRates, + skippedMissingFxDates, + }, + }; +} diff --git a/test/unit/security-master-price-cross-check.test.ts b/test/unit/security-master-price-cross-check.test.ts new file mode 100644 index 00000000..9d3f9803 --- /dev/null +++ b/test/unit/security-master-price-cross-check.test.ts @@ -0,0 +1,812 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + crossCheckPrices, + DEFAULT_MIN_COMMON_DATES, + DEFAULT_MIN_CORRELATION, + DEFAULT_RATIO_TOLERANCE, + DEFAULT_SAMPLE_DATE_COUNT, + MIN_CORRELATION_RETURNS, + PRICE_CORR_DECIMALS, + PRICE_CROSS_CHECK_CONFLICT_KINDS, + PRICE_CROSS_CHECK_VERDICTS, + selectSampleDates, + type FxRateByDateRecord, + type PriceCrossCheckInput, + type PriceCrossCheckPair, + type PriceCrossCheckResult, + type PriceCrossCheckVerdict, + type SampleCloseRecord, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const priceCrossCheckSourcePath = fileURLToPath( + new URL( + '../../apps/stock/data-pipeline/src/security-master/price-cross-check.ts', + import.meta.url + ) +); + +const ALLOWED_VERDICTS = new Set(PRICE_CROSS_CHECK_VERDICTS); +const ALLOWED_CONFLICT_KINDS = new Set(PRICE_CROSS_CHECK_CONFLICT_KINDS); + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = copy[i]; + const swap = copy[j]; + if (tmp !== undefined && swap !== undefined) { + copy[i] = swap; + copy[j] = tmp; + } + } + return copy; +} + +/** + * Generates deterministic weekday YYYY-MM-DD dates spanning [startYear, endYear] inclusive + * without depending on local timezone. + */ +function buildWeekdayCalendar(startYear: number, endYear: number): string[] { + const dates: string[] = []; + const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + // 2005-01-01 was a Saturday (dayOfWeek = 6 where 0=Sun..6=Sat). + let dayOfWeek = 6; + for (let year = startYear; year <= endYear; year++) { + const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + for (let month = 1; month <= 12; month++) { + const maxDay = month === 2 && leap ? 29 : (daysInMonth[month] ?? 30); + for (let day = 1; day <= maxDay; day++) { + if (dayOfWeek >= 1 && dayOfWeek <= 5) { + const y = String(year).padStart(4, '0'); + const m = String(month).padStart(2, '0'); + const d = String(day).padStart(2, '0'); + dates.push(`${y}-${m}-${d}`); + } + dayOfWeek = (dayOfWeek + 1) % 7; + } + } + } + return dates; +} + +function assertReconciliationAndContracts( + result: PriceCrossCheckResult, + expectedPairCount: number +): void { + expect(result.stats.pairsIn).toBe(expectedPairCount); + expect(result.results.length).toBe(expectedPairCount); + expect(result.stats.conflictsEmitted).toBe(result.conflicts.length); + + const counted: Record = { + unsupported_currency_pair: 0, + insufficient_data: 0, + ratio_mismatch: 0, + low_correlation: 0, + confirmed: 0, + }; + + for (const row of result.results) { + expect(ALLOWED_VERDICTS.has(row.verdict)).toBe(true); + counted[row.verdict] += 1; + if (row.priceCorr !== null) { + expect(Number.isFinite(row.priceCorr)).toBe(true); + expect(row.priceCorr).toBeGreaterThanOrEqual(-1); + expect(row.priceCorr).toBeLessThanOrEqual(1); + expect(Object.is(row.priceCorr, -0)).toBe(false); + // Fits provider_mapping.price_corr NUMERIC(5,4) + expect(Math.round(row.priceCorr * 10_000) / 10_000).toBe(row.priceCorr); + } + } + + expect(result.stats.byVerdict).toEqual(counted); + const verdictSum = + counted.unsupported_currency_pair + + counted.insufficient_data + + counted.ratio_mismatch + + counted.low_correlation + + counted.confirmed; + expect(verdictSum).toBe(result.stats.pairsIn); + + const expectedConflictCount = counted.ratio_mismatch + counted.low_correlation; + expect(result.conflicts.length).toBe(expectedConflictCount); + + for (const conflict of result.conflicts) { + expect(ALLOWED_CONFLICT_KINDS.has(conflict.conflictKind)).toBe(true); + expect(conflict.conflictKind.length).toBeLessThanOrEqual(32); + expect(conflict.source).toBe(conflict.detail.left.source); + expect(conflict.sourceId).toBe(conflict.detail.left.sourceId); + if (conflict.conflictKind === 'price_ratio_mismatch') { + expect(conflict.detail.verdict).toBe('ratio_mismatch'); + } else { + expect(conflict.detail.verdict).toBe('low_correlation'); + } + expect(JSON.parse(JSON.stringify(conflict.detail))).toEqual(conflict.detail); + } +} + +const SAMPLE_8_DATES = [ + '2022-01-10', + '2022-04-11', + '2022-07-11', + '2022-10-10', + '2023-01-09', + '2023-04-10', + '2023-07-10', + '2023-10-09', +] as const; + +describe('security master Pass 4 cross-sectional price cross-check', () => { + test('is exported from security-master barrel and performs zero I/O imports', () => { + expect(typeof selectSampleDates).toBe('function'); + expect(typeof crossCheckPrices).toBe('function'); + expect(DEFAULT_SAMPLE_DATE_COUNT).toBe(25); + expect(DEFAULT_MIN_COMMON_DATES).toBe(5); + expect(DEFAULT_RATIO_TOLERANCE).toBe(0.02); + expect(DEFAULT_MIN_CORRELATION).toBe(0.9); + expect(MIN_CORRELATION_RETURNS).toBe(3); + expect(PRICE_CORR_DECIMALS).toBe(4); + expect(PRICE_CROSS_CHECK_VERDICTS).toEqual([ + 'unsupported_currency_pair', + 'insufficient_data', + 'ratio_mismatch', + 'low_correlation', + 'confirmed', + ]); + expect(PRICE_CROSS_CHECK_CONFLICT_KINDS).toEqual([ + 'price_ratio_mismatch', + 'price_low_correlation', + ]); + + const sourceText = readFileSync(priceCrossCheckSourcePath, 'utf8'); + const forbiddenTokens = [ + '@stock-bot/mongodb', + '@stock-bot/postgres', + 'node:fs', + 'node:http', + 'node:https', + 'node:net', + 'bun:sqlite', + "'fs'", + '"fs"', + "'http'", + '"http"', + "'https'", + '"https"', + "'net'", + '"net"', + 'Date.now', + 'new Date', + ]; + for (const token of forbiddenTokens) { + expect(sourceText.includes(token)).toBe(false); + } + }); + + describe('selectSampleDates', () => { + test('returns 25 stratified dates from a 20-year daily calendar with one date per stratum', () => { + const calendar = buildWeekdayCalendar(2005, 2024); + expect(calendar.length).toBeGreaterThan(5000); + + const sampled = selectSampleDates(calendar); + expect(sampled.length).toBe(DEFAULT_SAMPLE_DATE_COUNT); + + // Strictly ascending and unique + for (let i = 1; i < sampled.length; i++) { + expect((sampled[i - 1] ?? '') < (sampled[i] ?? '')).toBe(true); + } + + // Exactly one date inside each of the 25 contiguous near-equal strata + const indexByDate = new Map(); + for (let i = 0; i < calendar.length; i++) { + const d = calendar[i]; + if (d !== undefined) { + indexByDate.set(d, i); + } + } + const n = calendar.length; + for (let k = 0; k < DEFAULT_SAMPLE_DATE_COUNT; k++) { + const start = Math.floor((k * n) / DEFAULT_SAMPLE_DATE_COUNT); + const end = Math.floor(((k + 1) * n) / DEFAULT_SAMPLE_DATE_COUNT); + const expectedMid = start + Math.floor((end - start - 1) / 2); + const pickedDate = sampled[k] ?? ''; + const pickedIndex = indexByDate.get(pickedDate); + expect(pickedIndex).toBeDefined(); + expect(pickedIndex).toBeGreaterThanOrEqual(start); + expect(pickedIndex).toBeLessThan(end); + expect(pickedIndex).toBe(expectedMid); + } + }); + + test('returns all unique sorted valid dates when input has <= 25 dates', () => { + expect(selectSampleDates([])).toEqual([]); + expect(selectSampleDates(['2024-06-03'])).toEqual(['2024-06-03']); + + const exactly25 = buildWeekdayCalendar(2024, 2024).slice(0, 25); + expect(selectSampleDates(exactly25)).toEqual(exactly25); + expect(selectSampleDates(shuffleWithSeed(exactly25, 17))).toEqual(exactly25); + }); + + test('drops invalid calendar dates and duplicates while keeping valid leap days', () => { + const dirty = [ + '2024-02-29', // valid leap day + '2023-02-29', // invalid non-leap day + '2024-02-30', // invalid Feb 30 + '2024-04-31', // invalid Apr 31 + '2024-00-10', // invalid month 00 + '2024-13-01', // invalid month 13 + '0000-01-01', // invalid year 0000 + '2024-01-02T00:00:00Z', // timestamp + ' 2024-01-02 ', // whitespace-padded + '', + 'not-a-date', + '2000-02-29', // valid century leap day + '1900-02-29', // invalid non-leap century + '2024-02-29', // duplicate + '2024-03-01', + undefined as unknown as string, + 12345 as unknown as string, + ]; + + expect(selectSampleDates(dirty)).toEqual(['2000-02-29', '2024-02-29', '2024-03-01']); + }); + + test('is deterministic for any input permutation', () => { + const calendar = buildWeekdayCalendar(2005, 2024); + const baseline = selectSampleDates(calendar); + for (const seed of [1, 42, 999, 202611]) { + const shuffled = shuffleWithSeed(calendar, seed); + expect(selectSampleDates(shuffled)).toEqual(baseline); + } + }); + + test('throws RangeError on non-positive or non-integer count and TypeError on bad containers', () => { + for (const badCount of [0, -1, -25, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => selectSampleDates(['2024-01-02'], { count: badCount })).toThrow(RangeError); + } + expect(() => selectSampleDates(null as unknown as string[])).toThrow(TypeError); + expect(() => selectSampleDates(['2024-01-02'], null as unknown as { count: number })).toThrow( + TypeError + ); + }); + }); + + describe('crossCheckPrices happy paths', () => { + test('confirms same-currency pair with matching closes and 4-dp rounded priceCorr', () => { + const basePrices = [100, 108, 95, 112, 125, 118, 134, 149]; + const closes: SampleCloseRecord[] = []; + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const p = basePrices[i] ?? 100; + closes.push({ source: 'qm', sourceId: 'AAPL:US', date, close: p * 1.001 }); + closes.push({ source: 'eod', sourceId: 'AAPL.US', date, close: p }); + } + + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'qm', sourceId: 'AAPL:US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + }, + ], + closes, + usdCadByDate: [], + }); + + assertReconciliationAndContracts(result, 1); + const row = result.results[0]; + expect(row?.verdict).toBe('confirmed'); + expect(row?.usableDates).toBe(8); + expect(row?.medianRatio).not.toBeNull(); + expect(Math.abs((row?.medianRatio ?? 0) - 1)).toBeLessThan(0.005); + expect(row?.priceCorr).toBe(1); + expect(result.conflicts).toEqual([]); + }); + + test('confirms CAD/USD interlisted SHOP-style pair in both orientations with identical priceCorr', () => { + // SHOP USD closes and varying USD/CAD FX rates (CAD per 1 USD) + const usdCloses = [52.4, 48.1, 61.8, 57.2, 74.5, 69.0, 81.3, 77.9]; + const usdCadRates = [1.26, 1.29, 1.31, 1.37, 1.34, 1.35, 1.32, 1.38]; + + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const usd = usdCloses[i] ?? 50; + const fx = usdCadRates[i] ?? 1.35; + // Slight 20 bps real-world basis jitter around parity + const jitter = i % 2 === 0 ? 1.002 : 0.998; + closes.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: usd * fx * jitter }); + closes.push({ source: 'eod', sourceId: 'SHOP.US', date, close: usd }); + usdCadByDate.push({ date, usdCad: fx }); + } + + const cadLeft: PriceCrossCheckPair = { + left: { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'SHOP.US', currency: 'USD' }, + }; + const usdLeft: PriceCrossCheckPair = { + left: { source: 'eod', sourceId: 'SHOP.US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD' }, + }; + + const resCadLeft = crossCheckPrices({ pairs: [cadLeft], closes, usdCadByDate }); + const resUsdLeft = crossCheckPrices({ pairs: [usdLeft], closes, usdCadByDate }); + + assertReconciliationAndContracts(resCadLeft, 1); + assertReconciliationAndContracts(resUsdLeft, 1); + + const rowCad = resCadLeft.results[0]; + const rowUsd = resUsdLeft.results[0]; + expect(rowCad?.verdict).toBe('confirmed'); + expect(rowUsd?.verdict).toBe('confirmed'); + expect(rowCad?.usableDates).toBe(8); + expect(rowUsd?.usableDates).toBe(8); + expect(Math.abs((rowCad?.medianRatio ?? 0) - 1)).toBeLessThan(0.01); + expect(Math.abs((rowUsd?.medianRatio ?? 0) - 1)).toBeLessThan(0.01); + expect(rowCad?.priceCorr).toBeGreaterThan(0.99); + // Canonical USD log-return normalization guarantees orientation-symmetric correlation. + expect(rowCad?.priceCorr).toBe(rowUsd?.priceCorr); + }); + }); + + describe('crossCheckPrices failure modes and financial invariants', () => { + test('flags ratio_mismatch on 10:1 level gap and emits price_ratio_mismatch conflict', () => { + const prices = [10, 12, 11, 14, 13, 16, 15, 19]; + const closes: SampleCloseRecord[] = []; + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const p = prices[i] ?? 10; + closes.push({ source: 'qm', sourceId: 'OLD:US', date, close: p * 10 }); + closes.push({ source: 'eod', sourceId: 'OLD.US', date, close: p }); + } + + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'qm', sourceId: 'OLD:US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'OLD.US', currency: 'USD' }, + }, + ], + closes, + usdCadByDate: [], + }); + + assertReconciliationAndContracts(result, 1); + expect(result.results[0]?.verdict).toBe('ratio_mismatch'); + expect(result.results[0]?.medianRatio).toBeCloseTo(10, 6); + expect(result.results[0]?.priceCorr).toBe(1); + expect(result.conflicts.length).toBe(1); + expect(result.conflicts[0]?.conflictKind).toBe('price_ratio_mismatch'); + expect(result.conflicts[0]?.source).toBe('qm'); + expect(result.conflicts[0]?.sourceId).toBe('OLD:US'); + }); + + test('flags low_correlation when median ratio ~ 1.0 but returns do not co-move', () => { + // Both hover around 100 (median ratio ~ 1.0) but move in opposite directions. + const leftPrices = [100, 101.2, 99.1, 101.5, 98.8, 101.4, 99.2, 101.1]; + const rightPrices = [100, 98.8, 100.9, 98.6, 101.2, 98.7, 100.8, 99.0]; + const closes: SampleCloseRecord[] = []; + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + closes.push({ source: 'ceo', sourceId: 'XYZ', date, close: leftPrices[i] ?? 100 }); + closes.push({ source: 'eod', sourceId: 'XYZ.V', date, close: rightPrices[i] ?? 100 }); + } + + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'ceo', sourceId: 'XYZ', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'XYZ.V', currency: 'CAD' }, + }, + ], + closes, + usdCadByDate: [], + }); + + assertReconciliationAndContracts(result, 1); + expect(result.results[0]?.verdict).toBe('low_correlation'); + expect(Math.abs((result.results[0]?.medianRatio ?? 0) - 1)).toBeLessThanOrEqual( + DEFAULT_RATIO_TOLERANCE + ); + expect(result.results[0]?.priceCorr).toBeLessThan(0); + expect(result.conflicts.length).toBe(1); + expect(result.conflicts[0]?.conflictKind).toBe('price_low_correlation'); + }); + + test('returns insufficient_data for < minCommonDates, < 3 returns, constant/constant-growth, and flat-USD-with-moving-FX', () => { + // Pair A: 4 usable dates (< default minCommonDates 5) + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + const aPrices = [10, 12, 11, 15]; + for (let i = 0; i < 4; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + closes.push({ source: 'qm', sourceId: 'FEW', date, close: aPrices[i] ?? 10 }); + closes.push({ source: 'eod', sourceId: 'FEW.US', date, close: aPrices[i] ?? 10 }); + } + + // Pair B: 3 usable dates (< 4 dates => < 3 returns => priceCorr === null even with minCommonDates=2) + for (let i = 0; i < 3; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + closes.push({ source: 'qm', sourceId: 'TINY', date, close: 20 + i * 3 }); + closes.push({ source: 'eod', sourceId: 'TINY.US', date, close: 20 + i * 3 }); + } + + // Pair C: constant prices (zero variance) + for (const date of SAMPLE_8_DATES) { + closes.push({ source: 'qm', sourceId: 'FLAT', date, close: 50 }); + closes.push({ source: 'eod', sourceId: 'FLAT.US', date, close: 50 }); + } + + // Pair D: constant-growth prices (log returns identical up to ~1e-16 floating-point noise) + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const val = 100 * 1.07 ** i; + closes.push({ source: 'qm', sourceId: 'CGROW', date, close: val }); + closes.push({ source: 'eod', sourceId: 'CGROW.US', date, close: val }); + } + + // Pair E: flat USD price ($100) with moving usdCad FX (CAD = 100 * usdCad) + // Must yield priceCorr === null rather than FX-induced spurious correlation. + const fxRates = [1.25, 1.31, 1.28, 1.36, 1.33, 1.4, 1.35, 1.42]; + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const fx = fxRates[i] ?? 1.35; + usdCadByDate.push({ date, usdCad: fx }); + closes.push({ source: 'eod', sourceId: 'FLATFX.TO', date, close: 100 * fx }); + closes.push({ source: 'eod', sourceId: 'FLATFX.US', date, close: 100 }); + } + + const pairs: PriceCrossCheckPair[] = [ + { + left: { source: 'qm', sourceId: 'FEW', currency: 'USD' }, + right: { source: 'eod', sourceId: 'FEW.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'FLAT', currency: 'USD' }, + right: { source: 'eod', sourceId: 'FLAT.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'CGROW', currency: 'USD' }, + right: { source: 'eod', sourceId: 'CGROW.US', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'FLATFX.TO', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'FLATFX.US', currency: 'USD' }, + }, + ]; + + const resDefault = crossCheckPrices({ pairs, closes, usdCadByDate }); + assertReconciliationAndContracts(resDefault, pairs.length); + expect(resDefault.conflicts).toEqual([]); + for (const row of resDefault.results) { + expect(row.verdict).toBe('insufficient_data'); + } + const byLeftId = new Map(resDefault.results.map((r) => [r.left.sourceId, r])); + expect(byLeftId.get('FEW')?.usableDates).toBe(4); + expect(byLeftId.get('FEW')?.priceCorr).toBe(1); + expect(byLeftId.get('FLAT')?.priceCorr).toBeNull(); + expect(byLeftId.get('CGROW')?.priceCorr).toBeNull(); + expect(byLeftId.get('FLATFX.TO')?.priceCorr).toBeNull(); + + // Verify < 3 returns yields priceCorr === null even when minCommonDates is lowered to 2. + const resTiny = crossCheckPrices( + { + pairs: [ + { + left: { source: 'qm', sourceId: 'TINY', currency: 'USD' }, + right: { source: 'eod', sourceId: 'TINY.US', currency: 'USD' }, + }, + ], + closes, + usdCadByDate, + }, + { minCommonDates: 2 } + ); + assertReconciliationAndContracts(resTiny, 1); + expect(resTiny.results[0]?.verdict).toBe('insufficient_data'); + expect(resTiny.results[0]?.usableDates).toBe(3); + expect(resTiny.results[0]?.priceCorr).toBeNull(); + }); + + test('returns unsupported_currency_pair for non-CAD/USD cross-currency or invalid currency', () => { + const pairs: PriceCrossCheckPair[] = [ + { + left: { source: 'eod', sourceId: 'SAP.DE', currency: 'EUR' }, + right: { source: 'eod', sourceId: 'SAP.US', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'RY.TO', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'RY.L', currency: 'GBP' }, + }, + { + left: { source: 'qm', sourceId: 'BAD1', currency: '' }, + right: { source: 'eod', sourceId: 'BAD1.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'BAD2', currency: 'USDT' }, + right: { source: 'eod', sourceId: 'BAD2.US', currency: 'USD' }, + }, + ]; + + const result = crossCheckPrices({ pairs, closes: [], usdCadByDate: [] }); + assertReconciliationAndContracts(result, 4); + expect(result.conflicts).toEqual([]); + for (const row of result.results) { + expect(row.verdict).toBe('unsupported_currency_pair'); + expect(row.usableDates).toBe(0); + expect(row.medianRatio).toBeNull(); + expect(row.priceCorr).toBeNull(); + } + }); + + test('skips missing FX dates without forward-filling and counts dropped invalid/conflicting closes & FX', () => { + const usdCloses = [20, 23, 21, 25, 27, 26, 30, 33]; + const fxRates = [1.3, 1.32, 1.31, 1.35, 1.34, 1.36, 1.38, 1.37]; + + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const usd = usdCloses[i] ?? 20; + const fx = fxRates[i] ?? 1.35; + closes.push({ source: 'eod', sourceId: 'TD.TO', date, close: usd * fx }); + closes.push({ source: 'eod', sourceId: 'TD.US', date, close: usd }); + // Omit FX on index 0 and index 1 so 2 dates are skipped for missing FX. + if (i >= 2) { + usdCadByDate.push({ date, usdCad: fx }); + } + } + + // Identical duplicate close and FX (must keep the date, not drop) + closes.push({ + source: 'eod', + sourceId: 'TD.US', + date: SAMPLE_8_DATES[2] ?? '', + close: usdCloses[2] ?? 21, + }); + usdCadByDate.push({ date: SAMPLE_8_DATES[2] ?? '', usdCad: fxRates[2] ?? 1.31 }); + + // Conflicting duplicate close on index 3 (3 values total -> counted once) + closes.push({ source: 'eod', sourceId: 'TD.US', date: SAMPLE_8_DATES[3] ?? '', close: 999 }); + closes.push({ source: 'eod', sourceId: 'TD.US', date: SAMPLE_8_DATES[3] ?? '', close: 888 }); + + // Invalid closes (5 rows) + closes.push( + { source: 'eod', sourceId: 'TD.US', date: SAMPLE_8_DATES[4] ?? '', close: 0 }, + { source: 'eod', sourceId: 'TD.US', date: SAMPLE_8_DATES[4] ?? '', close: -5 }, + { source: 'eod', sourceId: 'TD.US', date: SAMPLE_8_DATES[4] ?? '', close: Number.NaN }, + { + source: 'eod', + sourceId: 'TD.US', + date: '2023-02-29', + close: 25, + }, + { source: '', sourceId: 'TD.US', date: SAMPLE_8_DATES[4] ?? '', close: 25 } + ); + + // Invalid FX rates (3 rows) and conflicting FX rate on index 7 (counted once) + usdCadByDate.push( + { date: SAMPLE_8_DATES[5] ?? '', usdCad: 0 }, + { date: SAMPLE_8_DATES[5] ?? '', usdCad: Number.POSITIVE_INFINITY }, + { date: 'bad-date', usdCad: 1.35 }, + { date: SAMPLE_8_DATES[7] ?? '', usdCad: 1.99 } + ); + + // Remaining usable dates: indices 2, 4, 5, 6 (4 dates -> insufficient_data with default 5, + // confirmed if minCommonDates=4). Index 0,1 missing FX + index 7 conflicted FX => 3 skippedMissingFxDates. + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'eod', sourceId: 'TD.TO', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'TD.US', currency: 'USD' }, + }, + ], + closes, + usdCadByDate, + }); + + assertReconciliationAndContracts(result, 1); + expect(result.stats.droppedInvalidCloses).toBe(5); + expect(result.stats.droppedConflictingCloses).toBe(1); + expect(result.stats.droppedInvalidFxRates).toBe(3); + expect(result.stats.droppedConflictingFxRates).toBe(1); + expect(result.stats.skippedMissingFxDates).toBe(3); + expect(result.results[0]?.usableDates).toBe(4); + expect(result.results[0]?.verdict).toBe('insufficient_data'); + }); + + test('throws RangeError on invalid options and TypeError on invalid containers', () => { + const emptyInput: PriceCrossCheckInput = { pairs: [], closes: [], usdCadByDate: [] }; + + for (const badMinDates of [0, 1, -3, 2.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => crossCheckPrices(emptyInput, { minCommonDates: badMinDates })).toThrow( + RangeError + ); + } + for (const badTol of [-0.01, -1, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => crossCheckPrices(emptyInput, { ratioTolerance: badTol })).toThrow(RangeError); + } + for (const badCorr of [-1.01, 1.01, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => crossCheckPrices(emptyInput, { minCorrelation: badCorr })).toThrow(RangeError); + } + + // Boundary valid options succeed + expect(() => + crossCheckPrices(emptyInput, { minCommonDates: 2, ratioTolerance: 0, minCorrelation: -1 }) + ).not.toThrow(); + expect(() => + crossCheckPrices(emptyInput, { minCommonDates: 2, ratioTolerance: 0, minCorrelation: 1 }) + ).not.toThrow(); + + expect(() => crossCheckPrices(null as unknown as PriceCrossCheckInput)).toThrow(TypeError); + expect(() => + crossCheckPrices({ + pairs: null as unknown as PriceCrossCheckPair[], + closes: [], + usdCadByDate: [], + }) + ).toThrow(TypeError); + expect(() => + crossCheckPrices(emptyInput, null as unknown as { minCommonDates: number }) + ).toThrow(TypeError); + }); + }); + + describe('strict verdict priority with simultaneous conditions', () => { + test('enforces unsupported_currency_pair > insufficient_data > ratio_mismatch > low_correlation > confirmed', () => { + const closes: SampleCloseRecord[] = []; + + // 1) unsupported_currency_pair + 0 closes -> unsupported_currency_pair + // 2) insufficient_data (4 dates < 5) + 10:1 ratio gap + negative correlation -> insufficient_data + const shortLeft = [100, 120, 90, 130]; + const shortRight = [10, 8, 12, 7]; + for (let i = 0; i < 4; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + closes.push({ source: 'qm', sourceId: 'PRIO2', date, close: shortLeft[i] ?? 100 }); + closes.push({ source: 'eod', sourceId: 'PRIO2.US', date, close: shortRight[i] ?? 10 }); + } + + // 3) insufficient_data (zero-variance priceCorr === null on 8 dates) + 10:1 ratio gap -> insufficient_data + for (const date of SAMPLE_8_DATES) { + closes.push({ source: 'qm', sourceId: 'PRIO3', date, close: 100 }); + closes.push({ source: 'eod', sourceId: 'PRIO3.US', date, close: 10 }); + } + + // 4) ratio_mismatch (10:1 ratio gap) + low_correlation (negative corr) on 8 dates -> ratio_mismatch only + const badLeft = [100, 115, 95, 120, 90, 125, 88, 130]; + const badRight = [10, 8.5, 11, 8, 11.5, 7.8, 12, 7.5]; + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + closes.push({ source: 'qm', sourceId: 'PRIO4', date, close: badLeft[i] ?? 100 }); + closes.push({ source: 'eod', sourceId: 'PRIO4.US', date, close: badRight[i] ?? 10 }); + } + + const pairs: PriceCrossCheckPair[] = [ + { + left: { source: 'qm', sourceId: 'PRIO1', currency: 'EUR' }, + right: { source: 'eod', sourceId: 'PRIO1.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'PRIO2', currency: 'USD' }, + right: { source: 'eod', sourceId: 'PRIO2.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'PRIO3', currency: 'USD' }, + right: { source: 'eod', sourceId: 'PRIO3.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'PRIO4', currency: 'USD' }, + right: { source: 'eod', sourceId: 'PRIO4.US', currency: 'USD' }, + }, + ]; + + const result = crossCheckPrices({ pairs, closes, usdCadByDate: [] }); + assertReconciliationAndContracts(result, 4); + + const byId = new Map(result.results.map((r) => [r.left.sourceId, r])); + expect(byId.get('PRIO1')?.verdict).toBe('unsupported_currency_pair'); + expect(byId.get('PRIO2')?.verdict).toBe('insufficient_data'); + expect(byId.get('PRIO3')?.verdict).toBe('insufficient_data'); + expect(byId.get('PRIO4')?.verdict).toBe('ratio_mismatch'); + expect(byId.get('PRIO4')?.priceCorr).toBeLessThan(0); + + // Only PRIO4 emits a conflict, and strictly price_ratio_mismatch (not price_low_correlation). + expect(result.conflicts.length).toBe(1); + expect(result.conflicts[0]?.sourceId).toBe('PRIO4'); + expect(result.conflicts[0]?.conflictKind).toBe('price_ratio_mismatch'); + }); + }); + + describe('permutation determinism', () => { + test('shuffling pairs, closes, and usdCadByDate produces deep-equal results, conflicts, and stats', () => { + const pairs: PriceCrossCheckPair[] = [ + { + left: { source: 'qm', sourceId: 'CONF:US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'CONF.US', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'SHOP.US', currency: 'USD' }, + }, + { + left: { source: 'qm', sourceId: 'RATIO:US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'RATIO.US', currency: 'USD' }, + }, + { + left: { source: 'ceo', sourceId: 'LOWCORR', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'LOWCORR.V', currency: 'CAD' }, + }, + { + left: { source: 'qm', sourceId: 'UNSUP', currency: 'EUR' }, + right: { source: 'eod', sourceId: 'UNSUP.US', currency: 'USD' }, + }, + ]; + + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + const p1 = [40, 44, 41, 48, 52, 49, 55, 60]; + const pLowA = [100, 101.2, 99.1, 101.4, 98.9, 101.3, 99.0, 101.0]; + const pLowB = [100, 98.9, 101.0, 98.7, 101.1, 98.8, 100.9, 99.1]; + const fx = [1.28, 1.3, 1.33, 1.36, 1.34, 1.37, 1.35, 1.39]; + + for (let i = 0; i < SAMPLE_8_DATES.length; i++) { + const date = SAMPLE_8_DATES[i] ?? ''; + const base = p1[i] ?? 40; + const rate = fx[i] ?? 1.35; + closes.push( + { source: 'qm', sourceId: 'CONF:US', date, close: base }, + { source: 'eod', sourceId: 'CONF.US', date, close: base * 1.001 }, + { source: 'eod', sourceId: 'SHOP.TO', date, close: base * rate }, + { source: 'eod', sourceId: 'SHOP.US', date, close: base }, + { source: 'qm', sourceId: 'RATIO:US', date, close: base * 5 }, + { source: 'eod', sourceId: 'RATIO.US', date, close: base }, + { source: 'ceo', sourceId: 'LOWCORR', date, close: pLowA[i] ?? 100 }, + { source: 'eod', sourceId: 'LOWCORR.V', date, close: pLowB[i] ?? 100 } + ); + usdCadByDate.push({ date, usdCad: rate }); + } + + // Add identical duplicate, 3-way conflicting duplicate, and invalid rows to prove order-independence. + closes.push( + { source: 'qm', sourceId: 'CONF:US', date: SAMPLE_8_DATES[0] ?? '', close: p1[0] ?? 40 }, + { source: 'qm', sourceId: 'CONF:US', date: SAMPLE_8_DATES[1] ?? '', close: 777 }, + { source: 'qm', sourceId: 'CONF:US', date: SAMPLE_8_DATES[1] ?? '', close: 888 }, + { source: 'qm', sourceId: 'CONF:US', date: SAMPLE_8_DATES[2] ?? '', close: -1 }, + { source: 'qm', sourceId: 'CONF:US', date: '2023-02-29', close: 42 } + ); + usdCadByDate.push( + { date: SAMPLE_8_DATES[0] ?? '', usdCad: fx[0] ?? 1.28 }, + { date: SAMPLE_8_DATES[7] ?? '', usdCad: 2.5 }, + { date: SAMPLE_8_DATES[7] ?? '', usdCad: 2.6 }, + { date: SAMPLE_8_DATES[3] ?? '', usdCad: Number.NaN } + ); + + const baseline = crossCheckPrices({ pairs, closes, usdCadByDate }); + assertReconciliationAndContracts(baseline, pairs.length); + + for (const seed of [7, 101, 4099, 88888]) { + const shuffledResult = crossCheckPrices({ + pairs: shuffleWithSeed(pairs, seed), + closes: shuffleWithSeed(closes, seed + 1), + usdCadByDate: shuffleWithSeed(usdCadByDate, seed + 2), + }); + expect(shuffledResult).toEqual(baseline); + } + }); + }); +});