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:
Studio 2026-11-27 20:45:22 -05:00
parent f518c86380
commit 8f76d99046
4 changed files with 1496 additions and 0 deletions

View file

@ -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';

View file

@ -0,0 +1,647 @@
import { compareAscii } from './exchange-pass1';
export const DEFAULT_SAMPLE_DATE_COUNT = 25;
export const DEFAULT_MIN_COMMON_DATES = 5;
export const DEFAULT_RATIO_TOLERANCE = 0.02;
export const DEFAULT_MIN_CORRELATION = 0.9;
export const MIN_CORRELATION_RETURNS = 3;
export const PRICE_CORR_DECIMALS = 4;
export const PRICE_CROSS_CHECK_VERDICTS = [
'unsupported_currency_pair',
'insufficient_data',
'ratio_mismatch',
'low_correlation',
'confirmed',
] as const;
export const PRICE_CROSS_CHECK_CONFLICT_KINDS = [
'price_ratio_mismatch',
'price_low_correlation',
] as const;
export type PriceCrossCheckVerdict = (typeof PRICE_CROSS_CHECK_VERDICTS)[number];
export type PriceCrossCheckConflictKind = (typeof PRICE_CROSS_CHECK_CONFLICT_KINDS)[number];
export interface SelectSampleDatesOptions {
readonly count?: number;
}
export interface PriceSeriesEndpoint {
readonly source: string;
readonly sourceId: string;
readonly currency: string;
}
export interface PriceCrossCheckPair {
readonly left: PriceSeriesEndpoint;
readonly right: PriceSeriesEndpoint;
}
export interface SampleCloseRecord {
readonly source: string;
readonly sourceId: string;
readonly date: string;
readonly close: number;
}
export interface FxRateByDateRecord {
readonly date: string;
readonly usdCad: number;
}
export interface PriceCrossCheckInput {
readonly pairs: readonly PriceCrossCheckPair[];
readonly closes: readonly SampleCloseRecord[];
readonly usdCadByDate: readonly FxRateByDateRecord[];
}
export interface CrossCheckPricesOptions {
readonly minCommonDates?: number;
readonly ratioTolerance?: number;
readonly minCorrelation?: number;
}
export interface PriceCrossCheckRow {
left: PriceSeriesEndpoint;
right: PriceSeriesEndpoint;
verdict: PriceCrossCheckVerdict;
usableDates: number;
medianRatio: number | null;
priceCorr: number | null;
}
export interface PriceCrossCheckConflictDetail {
left: PriceSeriesEndpoint;
right: PriceSeriesEndpoint;
verdict: 'ratio_mismatch' | 'low_correlation';
usableDates: number;
medianRatio: number;
priceCorr: number;
ratioTolerance: number;
minCorrelation: number;
}
export interface PriceCrossCheckConflictRecord {
source: string;
sourceId: string;
conflictKind: PriceCrossCheckConflictKind;
detail: PriceCrossCheckConflictDetail;
}
export interface PriceCrossCheckVerdictCounts {
unsupported_currency_pair: number;
insufficient_data: number;
ratio_mismatch: number;
low_correlation: number;
confirmed: number;
}
export interface PriceCrossCheckStats {
pairsIn: number;
byVerdict: PriceCrossCheckVerdictCounts;
conflictsEmitted: number;
droppedInvalidCloses: number;
droppedConflictingCloses: number;
droppedInvalidFxRates: number;
droppedConflictingFxRates: number;
skippedMissingFxDates: number;
}
export interface PriceCrossCheckResult {
results: PriceCrossCheckRow[];
conflicts: PriceCrossCheckConflictRecord[];
stats: PriceCrossCheckStats;
}
type CurrencyPairMode = 'same' | 'cad_vs_usd' | 'usd_vs_cad' | 'unsupported';
interface AlignedClosePoint {
readonly date: string;
readonly leftClose: number;
readonly rightClose: number;
readonly fx: number;
}
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/;
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
const VARIANCE_FLOOR = 1e-24;
const PRICE_CORR_SCALE = 10 ** PRICE_CORR_DECIMALS;
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
/**
* Pure-integer exact YYYY-MM-DD validator for Gregorian years 0001..9999.
* Rejects timestamps, whitespace padding, and rollover dates (e.g. 2023-02-29)
* without allocating `Date` objects.
*/
function isValidExactYmd(value: unknown): value is string {
if (typeof value !== 'string' || !EXACT_YMD_PATTERN.test(value)) {
return false;
}
const year =
(value.charCodeAt(0) - 48) * 1000 +
(value.charCodeAt(1) - 48) * 100 +
(value.charCodeAt(2) - 48) * 10 +
(value.charCodeAt(3) - 48);
if (year < 1) {
return false;
}
const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48);
if (month < 1 || month > 12) {
return false;
}
const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48);
const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0);
return day >= 1 && day <= maxDay;
}
function makeSeriesKey(source: string, sourceId: string): string {
return `${source}\u0000${sourceId}`;
}
function normalizeIsoCurrency(value: unknown): string | null {
if (typeof value !== 'string') {
return null;
}
const normalized = value.trim().toUpperCase();
return ISO_CURRENCY_PATTERN.test(normalized) ? normalized : null;
}
function classifyCurrencyPair(leftCurrency: unknown, rightCurrency: unknown): CurrencyPairMode {
const left = normalizeIsoCurrency(leftCurrency);
const right = normalizeIsoCurrency(rightCurrency);
if (left === null || right === null) {
return 'unsupported';
}
if (left === right) {
return 'same';
}
if (left === 'CAD' && right === 'USD') {
return 'cad_vs_usd';
}
if (left === 'USD' && right === 'CAD') {
return 'usd_vs_cad';
}
return 'unsupported';
}
function cloneEndpoint(endpoint: PriceSeriesEndpoint): PriceSeriesEndpoint {
return {
source: endpoint.source,
sourceId: endpoint.sourceId,
currency: endpoint.currency,
};
}
function compareEndpoint(a: PriceSeriesEndpoint, b: PriceSeriesEndpoint): number {
return (
compareAscii(a.source, b.source) ||
compareAscii(a.sourceId, b.sourceId) ||
compareAscii(a.currency, b.currency)
);
}
function compareRows(a: PriceCrossCheckRow, b: PriceCrossCheckRow): number {
return (
compareEndpoint(a.left, b.left) ||
compareEndpoint(a.right, b.right) ||
compareAscii(a.verdict, b.verdict)
);
}
function compareConflicts(
a: PriceCrossCheckConflictRecord,
b: PriceCrossCheckConflictRecord
): number {
return (
compareAscii(a.source, b.source) ||
compareAscii(a.sourceId, b.sourceId) ||
compareAscii(a.conflictKind, b.conflictKind) ||
compareEndpoint(a.detail.right, b.detail.right) ||
compareEndpoint(a.detail.left, b.detail.left)
);
}
function computeMedian(values: readonly number[]): number | null {
const n = values.length;
if (n === 0) {
return null;
}
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(n / 2);
if (n % 2 === 1) {
return sorted[mid] ?? null;
}
const lo = sorted[mid - 1];
const hi = sorted[mid];
if (lo === undefined || hi === undefined) {
return null;
}
return (lo + hi) / 2;
}
/**
* Computes two-pass centered Pearson correlation of consecutive log returns
* in a common currency (USD for CAD/USD pairs so correlation is orientation-symmetric
* and does not manufacture spurious correlation from FX moves on flat USD prices).
*/
function computeLogReturnCorrelation(
points: readonly AlignedClosePoint[],
mode: Exclude<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,
};
let skippedMissingFxDates = 0;
const results: PriceCrossCheckRow[] = [];
const conflicts: PriceCrossCheckConflictRecord[] = [];
for (let i = 0; i < input.pairs.length; i++) {
const pair = input.pairs[i];
if (pair === undefined) {
continue;
}
const left = cloneEndpoint(pair.left);
const right = cloneEndpoint(pair.right);
const mode = classifyCurrencyPair(left.currency, right.currency);
if (mode === 'unsupported') {
byVerdict.unsupported_currency_pair += 1;
results.push({
left,
right,
verdict: 'unsupported_currency_pair',
usableDates: 0,
medianRatio: null,
priceCorr: null,
});
continue;
}
const leftMap = closesBySeries.get(makeSeriesKey(left.source, left.sourceId));
const rightMap = closesBySeries.get(makeSeriesKey(right.source, right.sourceId));
const points: AlignedClosePoint[] = [];
if (leftMap !== undefined && rightMap !== undefined) {
const iterateLeft = leftMap.size <= rightMap.size;
const primaryMap = iterateLeft ? leftMap : rightMap;
const secondaryMap = iterateLeft ? rightMap : leftMap;
for (const [date, primaryClose] of primaryMap.entries()) {
if (primaryClose === null) {
continue;
}
const secondaryClose = secondaryMap.get(date);
if (secondaryClose === undefined || secondaryClose === null) {
continue;
}
let fx = 1;
if (mode !== 'same') {
const rate = fxByDate.get(date);
if (rate === undefined || rate === null) {
skippedMissingFxDates += 1;
continue;
}
fx = rate;
}
const leftClose = iterateLeft ? primaryClose : secondaryClose;
const rightClose = iterateLeft ? secondaryClose : primaryClose;
points.push({ date, leftClose, rightClose, fx });
}
}
points.sort((a, b) => compareAscii(a.date, b.date));
const usableDates = points.length;
const normalizedRatios = new Array<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 (Math.abs(medianRatio - 1) > ratioTolerance) {
verdict = 'ratio_mismatch';
} else if (priceCorr < minCorrelation) {
verdict = 'low_correlation';
} else {
verdict = 'confirmed';
}
byVerdict[verdict] += 1;
results.push({
left,
right,
verdict,
usableDates,
medianRatio,
priceCorr,
});
if (
(verdict === 'ratio_mismatch' || verdict === 'low_correlation') &&
medianRatio !== null &&
priceCorr !== null
) {
const conflictKind: PriceCrossCheckConflictKind =
verdict === 'ratio_mismatch' ? 'price_ratio_mismatch' : 'price_low_correlation';
conflicts.push({
source: left.source,
sourceId: left.sourceId,
conflictKind,
detail: {
left: cloneEndpoint(left),
right: cloneEndpoint(right),
verdict,
usableDates,
medianRatio,
priceCorr,
ratioTolerance,
minCorrelation,
},
});
}
}
results.sort(compareRows);
conflicts.sort(compareConflicts);
return {
results,
conflicts,
stats: {
pairsIn: input.pairs.length,
byVerdict,
conflictsEmitted: conflicts.length,
droppedInvalidCloses,
droppedConflictingCloses,
droppedInvalidFxRates,
droppedConflictingFxRates,
skippedMissingFxDates,
},
};
}