Compare commits
3 commits
f518c86380
...
e2e2bfdd6d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2e2bfdd6d | ||
|
|
db284d7760 | ||
|
|
8f76d99046 |
5 changed files with 2026 additions and 0 deletions
|
|
@ -54,3 +54,12 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@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` 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.
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,701 @@
|
|||
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;
|
||||
invalidPairs: 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 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<string, unknown>;
|
||||
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) ||
|
||||
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<CurrencyPairMode, 'unsupported'>
|
||||
): number | null {
|
||||
if (points.length < MIN_CORRELATION_RETURNS + 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const returnCount = points.length - 1;
|
||||
const rx = new Array<number>(returnCount);
|
||||
const ry = new Array<number>(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<string>();
|
||||
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<string, Map<string, number | null>>();
|
||||
|
||||
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<string, number | null>();
|
||||
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<string, number | null>();
|
||||
|
||||
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,
|
||||
};
|
||||
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] 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 pairRecord = pair as Record<string, unknown>;
|
||||
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({
|
||||
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<number>(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 (medianRatio < minAllowedRatio || medianRatio > maxAllowedRatio) {
|
||||
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,
|
||||
invalidPairs,
|
||||
byVerdict,
|
||||
conflictsEmitted: conflicts.length,
|
||||
droppedInvalidCloses,
|
||||
droppedConflictingCloses,
|
||||
droppedInvalidFxRates,
|
||||
droppedConflictingFxRates,
|
||||
skippedMissingFxDates,
|
||||
},
|
||||
};
|
||||
}
|
||||
367
test/unit/security-master-price-cross-check-t73-qa.test.ts
Normal file
367
test/unit/security-master-price-cross-check-t73-qa.test.ts
Normal file
|
|
@ -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([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
921
test/unit/security-master-price-cross-check.test.ts
Normal file
921
test/unit/security-master-price-cross-check.test.ts
Normal file
|
|
@ -0,0 +1,921 @@
|
|||
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('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<PriceCrossCheckPair>(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];
|
||||
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