T-73: M1.1h — Pass 4: pure in-memory cross-sectional price cross-check (25 stratified sample dates, price ratio ≈ 1.0 or ≈ USD/CAD, return correlation)
This commit is contained in:
parent
f518c86380
commit
8f76d99046
4 changed files with 1496 additions and 0 deletions
812
test/unit/security-master-price-cross-check.test.ts
Normal file
812
test/unit/security-master-price-cross-check.test.ts
Normal file
|
|
@ -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<string>(PRICE_CROSS_CHECK_VERDICTS);
|
||||
const ALLOWED_CONFLICT_KINDS = new Set<string>(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<T>(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<PriceCrossCheckVerdict, number> = {
|
||||
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<string, number>();
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue