diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 177a7076..febcbba3 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -61,5 +61,5 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto - **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`. +- **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside inclusive `[1 - 0.02, 1 + 0.02]`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`. - **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/price-cross-check.ts b/apps/stock/data-pipeline/src/security-master/price-cross-check.ts index f1ce01aa..e979aa68 100644 --- a/apps/stock/data-pipeline/src/security-master/price-cross-check.ts +++ b/apps/stock/data-pipeline/src/security-master/price-cross-check.ts @@ -99,6 +99,7 @@ export interface PriceCrossCheckVerdictCounts { export interface PriceCrossCheckStats { pairsIn: number; + invalidPairs: number; byVerdict: PriceCrossCheckVerdictCounts; conflictsEmitted: number; droppedInvalidCloses: number; @@ -197,6 +198,25 @@ function cloneEndpoint(endpoint: PriceSeriesEndpoint): PriceSeriesEndpoint { }; } +function sanitizeEndpoint(raw: unknown): { endpoint: PriceSeriesEndpoint; valid: boolean } { + if (raw === null || typeof raw !== 'object') { + return { + endpoint: { source: '', sourceId: '', currency: '' }, + valid: false, + }; + } + const candidate = raw as Record; + const source = typeof candidate.source === 'string' ? candidate.source : ''; + const sourceId = typeof candidate.sourceId === 'string' ? candidate.sourceId : ''; + const currency = typeof candidate.currency === 'string' ? candidate.currency : ''; + const valid = + source.length > 0 && sourceId.length > 0 && typeof candidate.currency === 'string'; + return { + endpoint: { source, sourceId, currency }, + valid, + }; +} + function compareEndpoint(a: PriceSeriesEndpoint, b: PriceSeriesEndpoint): number { return ( compareAscii(a.source, b.source) || @@ -499,20 +519,53 @@ export function crossCheckPrices( low_correlation: 0, confirmed: 0, }; + const minAllowedRatio = 1 - ratioTolerance; + const maxAllowedRatio = 1 + ratioTolerance; + let invalidPairs = 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) { + const pair = input.pairs[i] as unknown; + if (pair === null || typeof pair !== 'object') { + invalidPairs += 1; + byVerdict.unsupported_currency_pair += 1; + results.push({ + left: { source: '', sourceId: '', currency: '' }, + right: { source: '', sourceId: '', currency: '' }, + verdict: 'unsupported_currency_pair', + usableDates: 0, + medianRatio: null, + priceCorr: null, + }); continue; } - const left = cloneEndpoint(pair.left); - const right = cloneEndpoint(pair.right); + + const pairRecord = pair as Record; + const leftSanitized = sanitizeEndpoint(pairRecord.left); + const rightSanitized = sanitizeEndpoint(pairRecord.right); + const left = leftSanitized.endpoint; + const right = rightSanitized.endpoint; const mode = classifyCurrencyPair(left.currency, right.currency); + if (!leftSanitized.valid || !rightSanitized.valid) { + invalidPairs += 1; + const malformedVerdict: PriceCrossCheckVerdict = + mode === 'unsupported' ? 'unsupported_currency_pair' : 'insufficient_data'; + byVerdict[malformedVerdict] += 1; + results.push({ + left, + right, + verdict: malformedVerdict, + usableDates: 0, + medianRatio: null, + priceCorr: null, + }); + continue; + } + if (mode === 'unsupported') { byVerdict.unsupported_currency_pair += 1; results.push({ @@ -584,7 +637,7 @@ export function crossCheckPrices( !Number.isFinite(medianRatio) ) { verdict = 'insufficient_data'; - } else if (Math.abs(medianRatio - 1) > ratioTolerance) { + } else if (medianRatio < minAllowedRatio || medianRatio > maxAllowedRatio) { verdict = 'ratio_mismatch'; } else if (priceCorr < minCorrelation) { verdict = 'low_correlation'; @@ -635,6 +688,7 @@ export function crossCheckPrices( conflicts, stats: { pairsIn: input.pairs.length, + invalidPairs, byVerdict, conflictsEmitted: conflicts.length, droppedInvalidCloses, diff --git a/test/unit/security-master-price-cross-check.test.ts b/test/unit/security-master-price-cross-check.test.ts index 9d3f9803..eab54106 100644 --- a/test/unit/security-master-price-cross-check.test.ts +++ b/test/unit/security-master-price-cross-check.test.ts @@ -395,6 +395,115 @@ describe('security master Pass 4 cross-sectional price cross-check', () => { expect(result.conflicts[0]?.sourceId).toBe('OLD:US'); }); + test('treats default ratio tolerance bounds (0.98 and 1.02) as inclusive and rejects values just outside', () => { + // Exact integer multiples avoid floating-point drift on left/right so medianRatio is + // strictly 1.02, 0.98, 1.0201, and 0.9799. + const basePrices = [100, 150, 200, 125, 250, 175, 300, 225]; + const cases = [ + { id: 'AT_UPPER', factor: 1.02, expectedVerdict: 'confirmed' as const }, + { id: 'AT_LOWER', factor: 0.98, expectedVerdict: 'confirmed' as const }, + { id: 'OVER_UPPER', factor: 1.0201, expectedVerdict: 'ratio_mismatch' as const }, + { id: 'UNDER_LOWER', factor: 0.9799, expectedVerdict: 'ratio_mismatch' as const }, + ]; + + const pairs: PriceCrossCheckPair[] = []; + const closes: SampleCloseRecord[] = []; + for (const c of cases) { + pairs.push({ + left: { source: 'qm', sourceId: `${c.id}:US`, currency: 'USD' }, + right: { source: 'eod', sourceId: `${c.id}.US`, currency: 'USD' }, + }); + 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: `${c.id}:US`, date, close: p * c.factor }); + closes.push({ source: 'eod', sourceId: `${c.id}.US`, date, close: p }); + } + } + + const result = crossCheckPrices({ pairs, closes, usdCadByDate: [] }); + assertReconciliationAndContracts(result, pairs.length); + expect(result.stats.invalidPairs).toBe(0); + + const byId = new Map(result.results.map((r) => [r.left.sourceId, r])); + expect(byId.get('AT_UPPER:US')?.medianRatio).toBe(1.02); + expect(byId.get('AT_UPPER:US')?.verdict).toBe('confirmed'); + expect(byId.get('AT_LOWER:US')?.medianRatio).toBe(0.98); + expect(byId.get('AT_LOWER:US')?.verdict).toBe('confirmed'); + expect(byId.get('OVER_UPPER:US')?.verdict).toBe('ratio_mismatch'); + expect(byId.get('UNDER_LOWER:US')?.verdict).toBe('ratio_mismatch'); + + expect(result.conflicts.map((c) => c.sourceId)).toEqual(['OVER_UPPER:US', 'UNDER_LOWER:US']); + expect(result.conflicts.every((c) => c.conflictKind === 'price_ratio_mismatch')).toBe(true); + }); + + test('records deterministic non-confirming results for malformed candidates without aborting valid ones', () => { + const basePrices = [100, 112, 105, 118, 124, 119, 130, 136]; + 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: 'GOOD:US', date, close: p }); + closes.push({ source: 'eod', sourceId: 'GOOD.US', date, close: p }); + } + + const validPair: PriceCrossCheckPair = { + left: { source: 'qm', sourceId: 'GOOD:US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'GOOD.US', currency: 'USD' }, + }; + + // Include: valid pair, null pair, undefined pair, sparse array hole, null right endpoint, + // missing left endpoint, and empty/non-string source with valid USD currencies. + const malformedPairs = new Array(7); + malformedPairs[0] = validPair; + malformedPairs[1] = null as unknown as PriceCrossCheckPair; + malformedPairs[2] = undefined as unknown as PriceCrossCheckPair; + // index 3 intentionally left as a sparse hole + malformedPairs[4] = { + left: { source: 'qm', sourceId: 'NULL_RIGHT:US', currency: 'USD' }, + right: null as unknown as PriceCrossCheckPair['right'], + }; + malformedPairs[5] = { + left: undefined as unknown as PriceCrossCheckPair['left'], + right: { source: 'eod', sourceId: 'NULL_LEFT.US', currency: 'USD' }, + }; + malformedPairs[6] = { + left: { source: '', sourceId: 'EMPTY_SRC:US', currency: 'USD' }, + right: { source: 'eod', sourceId: 'EMPTY_SRC.US', currency: 'USD' }, + }; + + const result = crossCheckPrices({ + pairs: malformedPairs, + closes, + usdCadByDate: [], + }); + + assertReconciliationAndContracts(result, malformedPairs.length); + expect(result.stats.pairsIn).toBe(7); + expect(result.stats.invalidPairs).toBe(6); + expect(result.stats.byVerdict.confirmed).toBe(1); + expect(result.stats.byVerdict.unsupported_currency_pair).toBe(5); + expect(result.stats.byVerdict.insufficient_data).toBe(1); + expect(result.conflicts).toEqual([]); + + const confirmed = result.results.filter((r) => r.verdict === 'confirmed'); + expect(confirmed.length).toBe(1); + expect(confirmed[0]?.left.sourceId).toBe('GOOD:US'); + expect(confirmed[0]?.priceCorr).toBe(1); + + // Reversing the dense equivalent produces the exact same sorted output and stats. + const denseReversed = [ + malformedPairs[6], + malformedPairs[5], + malformedPairs[4], + undefined, + malformedPairs[2], + malformedPairs[1], + malformedPairs[0], + ] as unknown as PriceCrossCheckPair[]; + expect(crossCheckPrices({ pairs: denseReversed, closes, usdCadByDate: [] })).toEqual(result); + }); + 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];