From e2e2bfdd6d543fa482ee5d774fdd8e43d672ee9b Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 20:57:00 -0500 Subject: [PATCH] T-73: tests --- ...ty-master-price-cross-check-t73-qa.test.ts | 367 ++++++++++++++++++ 1 file changed, 367 insertions(+) create mode 100644 test/unit/security-master-price-cross-check-t73-qa.test.ts diff --git a/test/unit/security-master-price-cross-check-t73-qa.test.ts b/test/unit/security-master-price-cross-check-t73-qa.test.ts new file mode 100644 index 00000000..24f54a55 --- /dev/null +++ b/test/unit/security-master-price-cross-check-t73-qa.test.ts @@ -0,0 +1,367 @@ +import { describe, expect, test } from 'bun:test'; +import { + crossCheckPrices, + selectSampleDates, + type FxRateByDateRecord, + type PriceCrossCheckPair, + type PriceCrossCheckResult, + type SampleCloseRecord, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA coverage for T-73 (Pass 4 price cross-check). Complements +// security-master-price-cross-check.test.ts with an independent readable reference loop for +// medianRatio / priceCorr, hand-computed ledgers, odd-size stratification, currency +// normalization, FX scoping to cross-currency pairs only, and per-pair counter accumulation. + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state / 4294967296; + }; +} + +function ymd(dayIndex: number): string { + // Deterministic synthetic calendar: 2021-01..2021-12, day 01..28 (always valid). + const month = Math.floor(dayIndex / 28) + 1; + const day = (dayIndex % 28) + 1; + return `2021-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; +} + +/** Readable reference: median and Pearson of log returns in USD, no shortcuts. */ +function referenceCheck( + left: number[], + right: number[], + fx: number[], + mode: 'same' | 'cad_vs_usd' | 'usd_vs_cad' +): { medianRatio: number; priceCorr: number | null } { + const ratios = left.map((l, i) => { + const r = right[i] as number; + const f = fx[i] as number; + const expected = mode === 'same' ? 1 : mode === 'cad_vs_usd' ? f : 1 / f; + return l / r / expected; + }); + const sorted = [...ratios].sort((a, b) => a - b); + const n = sorted.length; + const medianRatio = + n % 2 === 1 + ? (sorted[(n - 1) / 2] as number) + : ((sorted[n / 2 - 1] as number) + (sorted[n / 2] as number)) / 2; + + const lUsd = left.map((v, i) => (mode === 'cad_vs_usd' ? v / (fx[i] as number) : v)); + const rUsd = right.map((v, i) => (mode === 'usd_vs_cad' ? v / (fx[i] as number) : v)); + const xs: number[] = []; + const ys: number[] = []; + for (let i = 1; i < n; i++) { + xs.push(Math.log((lUsd[i] as number) / (lUsd[i - 1] as number))); + ys.push(Math.log((rUsd[i] as number) / (rUsd[i - 1] as number))); + } + if (xs.length < 3) { + return { medianRatio, priceCorr: null }; + } + const mx = xs.reduce((a, b) => a + b, 0) / xs.length; + const my = ys.reduce((a, b) => a + b, 0) / ys.length; + let sxy = 0; + let sxx = 0; + let syy = 0; + for (let i = 0; i < xs.length; i++) { + sxy += ((xs[i] as number) - mx) * ((ys[i] as number) - my); + sxx += ((xs[i] as number) - mx) ** 2; + syy += ((ys[i] as number) - my) ** 2; + } + const r = sxy / Math.sqrt(sxx * syy); + return { medianRatio, priceCorr: Math.round(r * 10_000) / 10_000 || 0 }; +} + +function assertReconciles(result: PriceCrossCheckResult, pairs: number): void { + const v = result.stats.byVerdict; + expect( + v.unsupported_currency_pair + + v.insufficient_data + + v.ratio_mismatch + + v.low_correlation + + v.confirmed + ).toBe(pairs); + expect(result.results.length).toBe(pairs); + expect(result.stats.pairsIn).toBe(pairs); + expect(result.conflicts.length).toBe(v.ratio_mismatch + v.low_correlation); + expect(result.stats.conflictsEmitted).toBe(result.conflicts.length); +} + +describe('T-73 QA: Pass 4 price cross-check edge cases', () => { + describe('selectSampleDates', () => { + test('picks the hand-computed middle of each stratum for 10 dates into 3 strata', () => { + // n=10, count=3 -> strata [0,3) [3,6) [6,10) -> mids 1, 4, 7 + const dates = Array.from({ length: 10 }, (_, i) => ymd(i)); + expect(selectSampleDates(dates, { count: 3 })).toEqual([ymd(1), ymd(4), ymd(7)]); + }); + + test('count=1 returns the single median-ish date and dedupe happens before stratifying', () => { + const dates = Array.from({ length: 5 }, (_, i) => ymd(i)); + // Heavy duplication of the first date must not shift strata. + const skewed = [...dates, ...Array.from({ length: 50 }, () => ymd(0))]; + expect(selectSampleDates(skewed, { count: 1 })).toEqual([ymd(2)]); + expect(selectSampleDates(skewed, { count: 2 })).toEqual([ymd(0), ymd(3)]); + }); + + test('does not mutate its input array', () => { + const dates = [ymd(5), ymd(1), ymd(3)]; + const copy = [...dates]; + selectSampleDates(dates, { count: 2 }); + expect(dates).toEqual(copy); + }); + }); + + describe('crossCheckPrices vs independent reference loop', () => { + test('matches reference medianRatio and priceCorr on seeded same/CAD-USD/USD-CAD fixtures', () => { + const rng = makeRng(20261127); + const modes = ['same', 'cad_vs_usd', 'usd_vs_cad'] as const; + for (let fixture = 0; fixture < 30; fixture++) { + const mode = modes[fixture % 3] as (typeof modes)[number]; + const n = 5 + (fixture % 21); // 5..25 sample dates; mixes odd and even medians + const usd: number[] = []; + const noise: number[] = []; + const fx: number[] = []; + let level = 20 + rng() * 80; + for (let i = 0; i < n; i++) { + level *= Math.exp((rng() - 0.5) * 0.2); + usd.push(level); + noise.push(1 + (rng() - 0.5) * 0.06); + fx.push(1.2 + rng() * 0.25); + } + // Left series: USD price with independent basis noise; converted to left currency. + const leftCcy = mode === 'cad_vs_usd' ? 'CAD' : 'USD'; + const rightCcy = mode === 'usd_vs_cad' ? 'CAD' : 'USD'; + const left = usd.map( + (p, i) => (leftCcy === 'CAD' ? p * (fx[i] as number) : p) * (noise[i] as number) + ); + const right = usd.map((p, i) => (rightCcy === 'CAD' ? p * (fx[i] as number) : p)); + + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + for (let i = 0; i < n; i++) { + closes.push({ source: 'L', sourceId: 'X', date: ymd(i * 3), close: left[i] as number }); + closes.push({ source: 'R', sourceId: 'Y', date: ymd(i * 3), close: right[i] as number }); + usdCadByDate.push({ date: ymd(i * 3), usdCad: fx[i] as number }); + } + const pair: PriceCrossCheckPair = { + left: { source: 'L', sourceId: 'X', currency: leftCcy }, + right: { source: 'R', sourceId: 'Y', currency: rightCcy }, + }; + + const result = crossCheckPrices({ pairs: [pair], closes, usdCadByDate }); + const ref = referenceCheck(left, right, fx, mode); + const row = result.results[0]; + + assertReconciles(result, 1); + expect(row?.usableDates).toBe(n); + expect(row?.medianRatio).toBeCloseTo(ref.medianRatio, 12); + expect(row?.priceCorr).toBe(ref.priceCorr); + } + }); + + test('hand ledger: even-count median averages the two middle normalized ratios', () => { + // Ratios left/right: 1.00, 1.01, 1.03, 1.05, 0.99, 1.02 -> sorted mid pair 1.01, 1.02 -> 1.015 + const right = [100, 110, 105, 120, 115, 125]; + const factors = [1.0, 1.01, 1.03, 1.05, 0.99, 1.02]; + const closes: SampleCloseRecord[] = right.flatMap((r, i) => [ + { source: 'L', sourceId: 'A', date: ymd(i), close: r * (factors[i] as number) }, + { source: 'R', sourceId: 'B', date: ymd(i), close: r }, + ]); + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'L', sourceId: 'A', currency: 'USD' }, + right: { source: 'R', sourceId: 'B', currency: 'USD' }, + }, + ], + closes, + usdCadByDate: [], + }); + expect(result.results[0]?.medianRatio).toBeCloseTo(1.015, 12); + expect(result.results[0]?.verdict).toBe('confirmed'); + }); + }); + + describe('currency handling', () => { + test('normalizes lower-case / padded currency codes but echoes the caller endpoint unchanged', () => { + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + const usd = [30, 33, 31, 36, 35, 39]; + for (let i = 0; i < usd.length; i++) { + const fx = 1.3 + i * 0.01; + closes.push({ source: 'tsx', sourceId: 'Q', date: ymd(i), close: (usd[i] as number) * fx }); + closes.push({ source: 'nyse', sourceId: 'Q', date: ymd(i), close: usd[i] as number }); + usdCadByDate.push({ date: ymd(i), usdCad: fx }); + } + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'tsx', sourceId: 'Q', currency: ' cad' }, + right: { source: 'nyse', sourceId: 'Q', currency: 'Usd ' }, + }, + ], + closes, + usdCadByDate, + }); + expect(result.results[0]?.verdict).toBe('confirmed'); + expect(result.results[0]?.left.currency).toBe(' cad'); + expect(result.results[0]?.right.currency).toBe('Usd '); + }); + + test('same-currency pairs ignore FX entirely (no skip, no counter) even when FX is empty', () => { + const prices = [10, 11, 10.5, 12, 11.4, 13]; + const closes: SampleCloseRecord[] = prices.flatMap((p, i) => [ + { source: 'ceo', sourceId: 'V1', date: ymd(i), close: p }, + { source: 'eod', sourceId: 'V1.V', date: ymd(i), close: p }, + ]); + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'ceo', sourceId: 'V1', currency: 'CAD' }, + right: { source: 'eod', sourceId: 'V1.V', currency: 'CAD' }, + }, + ], + closes, + usdCadByDate: [], + }); + expect(result.results[0]?.verdict).toBe('confirmed'); + expect(result.results[0]?.usableDates).toBe(6); + expect(result.stats.skippedMissingFxDates).toBe(0); + }); + + test('a CAD/USD pair quoted at parity (no FX premium) is a ratio_mismatch, not confirmed', () => { + // Guards against the expected-ratio direction being dropped: CAD close == USD close is wrong. + const prices = [50, 55, 52, 60, 58, 63]; + const closes: SampleCloseRecord[] = prices.flatMap((p, i) => [ + { source: 'tsx', sourceId: 'P', date: ymd(i), close: p }, + { source: 'nyse', sourceId: 'P', date: ymd(i), close: p }, + ]); + const usdCadByDate = prices.map((_, i) => ({ date: ymd(i), usdCad: 1.35 })); + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'tsx', sourceId: 'P', currency: 'CAD' }, + right: { source: 'nyse', sourceId: 'P', currency: 'USD' }, + }, + { + left: { source: 'nyse', sourceId: 'P', currency: 'USD' }, + right: { source: 'tsx', sourceId: 'P', currency: 'CAD' }, + }, + ], + closes, + usdCadByDate, + }); + assertReconciles(result, 2); + const byLeft = new Map(result.results.map(r => [r.left.source, r])); + expect(byLeft.get('tsx')?.verdict).toBe('ratio_mismatch'); + expect(byLeft.get('tsx')?.medianRatio).toBeCloseTo(1 / 1.35, 12); + expect(byLeft.get('nyse')?.verdict).toBe('ratio_mismatch'); + expect(byLeft.get('nyse')?.medianRatio).toBeCloseTo(1.35, 12); + expect(result.conflicts.map(c => c.source)).toEqual(['nyse', 'tsx']); + }); + }); + + describe('counters and isolation', () => { + test('skippedMissingFxDates accumulates per cross-currency pair and closes are shared, not consumed', () => { + const usd = [20, 22, 21, 24, 23, 26, 25]; + const closes: SampleCloseRecord[] = []; + const usdCadByDate: FxRateByDateRecord[] = []; + for (let i = 0; i < usd.length; i++) { + const fx = 1.3 + i * 0.005; + closes.push({ source: 'tsx', sourceId: 'S', date: ymd(i), close: (usd[i] as number) * fx }); + closes.push({ source: 'nyse', sourceId: 'S', date: ymd(i), close: usd[i] as number }); + if (i !== 3) { + usdCadByDate.push({ date: ymd(i), usdCad: fx }); + } + } + const cadLeft: PriceCrossCheckPair = { + left: { source: 'tsx', sourceId: 'S', currency: 'CAD' }, + right: { source: 'nyse', sourceId: 'S', currency: 'USD' }, + }; + const usdLeft: PriceCrossCheckPair = { + left: { source: 'nyse', sourceId: 'S', currency: 'USD' }, + right: { source: 'tsx', sourceId: 'S', currency: 'CAD' }, + }; + const result = crossCheckPrices({ pairs: [cadLeft, usdLeft], closes, usdCadByDate }); + assertReconciles(result, 2); + expect(result.stats.skippedMissingFxDates).toBe(2); + for (const row of result.results) { + expect(row.usableDates).toBe(6); + expect(row.verdict).toBe('confirmed'); + } + expect(result.results[0]?.priceCorr).toBe(result.results[1]?.priceCorr); + }); + + test('pair with no closes for either side is insufficient_data with zero usable dates and null metrics', () => { + const result = crossCheckPrices({ + pairs: [ + { + left: { source: 'qm', sourceId: 'GHOST', currency: 'USD' }, + right: { source: 'eod', sourceId: 'GHOST.US', currency: 'USD' }, + }, + ], + closes: [{ source: 'qm', sourceId: 'GHOST', date: ymd(0), close: 1 }], + usdCadByDate: [], + }); + assertReconciles(result, 1); + expect(result.results[0]).toMatchObject({ + verdict: 'insufficient_data', + usableDates: 0, + medianRatio: null, + priceCorr: null, + }); + expect(result.stats.invalidPairs).toBe(0); + }); + + test('does not mutate input arrays or endpoint objects; result endpoints are copies', () => { + const pair: PriceCrossCheckPair = { + left: { source: 'L', sourceId: 'A', currency: 'USD' }, + right: { source: 'R', sourceId: 'B', currency: 'USD' }, + }; + const prices = [10, 12, 11, 13, 12.5, 14]; + const closes: SampleCloseRecord[] = prices.flatMap((p, i) => [ + { source: 'L', sourceId: 'A', date: ymd(5 - i), close: p }, + { source: 'R', sourceId: 'B', date: ymd(5 - i), close: p * 2 }, + ]); + const input = { pairs: [pair], closes, usdCadByDate: [] as FxRateByDateRecord[] }; + const snapshot = JSON.stringify(input); + const result = crossCheckPrices(input); + expect(JSON.stringify(input)).toBe(snapshot); + expect(result.results[0]?.left).not.toBe(pair.left); + expect(result.conflicts[0]?.detail.left).not.toBe(pair.left); + expect(result.results[0]?.verdict).toBe('ratio_mismatch'); + }); + + test('custom thresholds flip verdicts at the configured boundaries', () => { + const left = [100, 101.2, 99.1, 101.5, 98.8, 101.4]; + const right = [100, 98.8, 100.9, 98.6, 101.2, 98.7]; + const closes: SampleCloseRecord[] = left.flatMap((l, i) => [ + { source: 'L', sourceId: 'A', date: ymd(i), close: l }, + { source: 'R', sourceId: 'B', date: ymd(i), close: right[i] as number }, + ]); + const pairs: PriceCrossCheckPair[] = [ + { + left: { source: 'L', sourceId: 'A', currency: 'USD' }, + right: { source: 'R', sourceId: 'B', currency: 'USD' }, + }, + ]; + const base = crossCheckPrices({ pairs, closes, usdCadByDate: [] }); + expect(base.results[0]?.verdict).toBe('low_correlation'); + // minCorrelation = -1 accepts any correlation. + const loose = crossCheckPrices({ pairs, closes, usdCadByDate: [] }, { minCorrelation: -1 }); + expect(loose.results[0]?.verdict).toBe('confirmed'); + expect(loose.conflicts).toEqual([]); + // ratioTolerance = 0 rejects any non-unit median. + const strict = crossCheckPrices( + { pairs, closes, usdCadByDate: [] }, + { minCorrelation: -1, ratioTolerance: 0 } + ); + expect(strict.results[0]?.verdict).toBe('ratio_mismatch'); + // Raising minCommonDates above the 6 usable dates yields insufficient_data. + const many = crossCheckPrices({ pairs, closes, usdCadByDate: [] }, { minCommonDates: 7 }); + expect(many.results[0]?.verdict).toBe('insufficient_data'); + expect(many.conflicts).toEqual([]); + }); + }); +});