T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark)
This commit is contained in:
parent
9b57ea9677
commit
dd05e20325
4 changed files with 919 additions and 178 deletions
|
|
@ -113,6 +113,7 @@ export interface BuiltTrialRow {
|
|||
readonly sampleStart: string;
|
||||
readonly sampleEnd: string;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly dailyRiskFree?: number;
|
||||
readonly nObs: number;
|
||||
readonly sharpeUnann: number;
|
||||
readonly skewness: number;
|
||||
|
|
@ -154,6 +155,19 @@ export interface ClusterDeflatedSharpeQuery {
|
|||
readonly trialId: number | bigint | string;
|
||||
readonly asOf?: string | Date;
|
||||
readonly dsrGate?: number;
|
||||
/**
|
||||
* Optional strictly-ascending `YYYY-MM-DD` trading calendar for the cluster's market.
|
||||
* A trial without explicit observation dates is index-aligned only when its `dailySeries`
|
||||
* length exactly matches the number of sessions in `[sampleStart, sampleEnd]`.
|
||||
*/
|
||||
readonly sessionDates?: readonly string[];
|
||||
/**
|
||||
* Optional per-trial strictly-ascending `YYYY-MM-DD` observation dates for sparse series
|
||||
* (e.g. `signal_ic` or `event_study`) that may omit dates within `[sampleStart, sampleEnd]`.
|
||||
*/
|
||||
readonly observationDatesByTrialId?:
|
||||
| ReadonlyMap<number | bigint | string, readonly string[]>
|
||||
| Readonly<Record<string, readonly string[]>>;
|
||||
}
|
||||
|
||||
export interface ClusterDeflatedSharpeResult {
|
||||
|
|
@ -172,12 +186,14 @@ export interface ClusterDeflatedSharpeResult {
|
|||
}
|
||||
|
||||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const UTC_ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/;
|
||||
const ISO_OFFSET_TIMESTAMP_PATTERN =
|
||||
/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
|
||||
const AGENT_PRINCIPAL_PATTERN =
|
||||
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const EXPRESSION_HASH_PATTERN = /^[0-9a-f]{64}$/;
|
||||
const POSITIVE_INT_PATTERN = /^[1-9]\d*$/;
|
||||
const MOMENT_MATCH_REL_TOL = 1e-12;
|
||||
|
||||
const TRIAL_STAGE_SET: ReadonlySet<string> = new Set(TRIAL_STAGES);
|
||||
const UNIVERSE_MARKET_SET: ReadonlySet<string> = new Set(UNIVERSE_MARKETS);
|
||||
|
|
@ -551,7 +567,7 @@ function validateExpressionHash(value: unknown): string {
|
|||
return value;
|
||||
}
|
||||
|
||||
function validateDailySeries(value: unknown): number[] {
|
||||
function validateDailySeries(value: unknown, allowZeroVariance = false): number[] {
|
||||
const isTyped = value instanceof Float32Array || value instanceof Float64Array;
|
||||
if (!Array.isArray(value) && !isTyped) {
|
||||
throw new TrialLedgerError(
|
||||
|
|
@ -568,6 +584,8 @@ function validateDailySeries(value: unknown): number[] {
|
|||
}
|
||||
|
||||
const normalized: number[] = new Array(len);
|
||||
let firstReal = 0;
|
||||
let allEqualReal = true;
|
||||
for (let i = 0; i < len; i += 1) {
|
||||
const v: unknown = value[i];
|
||||
if (typeof v !== 'number' || !Number.isFinite(v)) {
|
||||
|
|
@ -583,8 +601,19 @@ function validateDailySeries(value: unknown): number[] {
|
|||
`dailySeries[${i}] (${v}) is outside finite PostgreSQL REAL (float32) range.`
|
||||
);
|
||||
}
|
||||
if (i === 0) {
|
||||
firstReal = asReal;
|
||||
} else if (asReal !== firstReal) {
|
||||
allEqualReal = false;
|
||||
}
|
||||
normalized[i] = Object.is(v, -0) ? 0 : v;
|
||||
}
|
||||
if (!allowZeroVariance && allEqualReal) {
|
||||
throw new TrialLedgerError(
|
||||
'ZERO_VARIANCE_SERIES',
|
||||
'dailySeries has zero variance at PostgreSQL REAL (float32) storage precision.'
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
|
|
@ -632,6 +661,15 @@ function parseTrialId(value: unknown): number {
|
|||
);
|
||||
}
|
||||
|
||||
function formatUtcInstantFromMs(epochMs: number, fractionalDigits?: string): string {
|
||||
const baseIso = new Date(epochMs).toISOString();
|
||||
if (fractionalDigits === undefined || fractionalDigits.length <= 3) {
|
||||
return baseIso;
|
||||
}
|
||||
const micros = fractionalDigits.slice(3, 6).padEnd(3, '0');
|
||||
return `${baseIso.slice(0, -1)}${micros}Z`;
|
||||
}
|
||||
|
||||
function normalizeAsOf(asOf: unknown): string | undefined {
|
||||
if (asOf === undefined) {
|
||||
return undefined;
|
||||
|
|
@ -654,8 +692,9 @@ function normalizeAsOf(asOf: unknown): string | undefined {
|
|||
{ from: '1970-01-01', to: '1970-01-01', asOf, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
if (UTC_ISO_TIMESTAMP_PATTERN.test(asOf)) {
|
||||
return asOf;
|
||||
const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(asOf);
|
||||
if (instantMatch !== null) {
|
||||
return formatUtcInstantFromMs(fenced.asOfMs, instantMatch[2]);
|
||||
}
|
||||
return new Date(fenced.asOfMs).toISOString();
|
||||
} catch (error) {
|
||||
|
|
@ -678,8 +717,9 @@ function formatUtcTimestamp(value: unknown, field: string): string {
|
|||
if (!Number.isFinite(ms)) {
|
||||
throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp string for "${field}": "${value}".`);
|
||||
}
|
||||
if (UTC_ISO_TIMESTAMP_PATTERN.test(value)) {
|
||||
return value;
|
||||
const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(value);
|
||||
if (instantMatch !== null) {
|
||||
return formatUtcInstantFromMs(ms, instantMatch[2]);
|
||||
}
|
||||
return new Date(ms).toISOString();
|
||||
}
|
||||
|
|
@ -698,10 +738,13 @@ function formatDateOnlyFromDb(value: unknown, field: string): string {
|
|||
|
||||
function parsePgRealArray(value: unknown): number[] {
|
||||
if (Array.isArray(value)) {
|
||||
return validateDailySeries(value.map(v => Number(v)));
|
||||
return validateDailySeries(
|
||||
value.map(v => Number(v)),
|
||||
true
|
||||
);
|
||||
}
|
||||
if (value instanceof Float32Array || value instanceof Float64Array) {
|
||||
return validateDailySeries(value);
|
||||
return validateDailySeries(value, true);
|
||||
}
|
||||
if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
|
||||
const inner = value.slice(1, -1).trim();
|
||||
|
|
@ -709,7 +752,7 @@ function parsePgRealArray(value: unknown): number[] {
|
|||
throw new TrialLedgerError('SERIES_TOO_SHORT', 'Empty daily_series returned from database.');
|
||||
}
|
||||
const elements = inner.split(',').map(token => Number(token));
|
||||
return validateDailySeries(elements);
|
||||
return validateDailySeries(elements, true);
|
||||
}
|
||||
throw new TrialLedgerError('INVALID_ROW', 'Unexpected daily_series value returned from database.');
|
||||
}
|
||||
|
|
@ -769,6 +812,11 @@ function isPreBuiltTrialRow(row: TrialRowInput | BuiltTrialRow): row is BuiltTri
|
|||
);
|
||||
}
|
||||
|
||||
function momentsClose(actual: number, expected: number): boolean {
|
||||
const scale = Math.max(1, Math.abs(expected));
|
||||
return Math.abs(actual - expected) <= MOMENT_MATCH_REL_TOL * scale;
|
||||
}
|
||||
|
||||
function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number): BuiltTrialRow {
|
||||
if (typeof row !== 'object' || row === null) {
|
||||
throw new TrialLedgerError('INVALID_ROW', `Row at index ${index} must be a non-null object.`);
|
||||
|
|
@ -792,6 +840,14 @@ function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number)
|
|||
);
|
||||
const dailySeries = validateDailySeries(row.dailySeries);
|
||||
|
||||
const dailyRiskFree = row.dailyRiskFree ?? 0;
|
||||
if (typeof dailyRiskFree !== 'number' || !Number.isFinite(dailyRiskFree)) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_ROW',
|
||||
`Row at index ${index} has invalid dailyRiskFree "${String(row.dailyRiskFree)}": expected a finite number.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!Number.isSafeInteger(row.nObs) || row.nObs !== dailySeries.length) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_ROW',
|
||||
|
|
@ -812,13 +868,25 @@ function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number)
|
|||
);
|
||||
}
|
||||
|
||||
// Ensure the series itself has non-zero variance so forged rows cannot bypass moment invariants.
|
||||
if (trialMoments(dailySeries) === null) {
|
||||
// Recompute moments from dailySeries and verify the pre-built row matches them so stale
|
||||
// template moments cannot be persisted alongside a different return/IC vector.
|
||||
const computed = trialMoments(dailySeries, dailyRiskFree);
|
||||
if (computed === null) {
|
||||
throw new TrialLedgerError(
|
||||
'ZERO_VARIANCE_SERIES',
|
||||
`Row at index ${index} has a zero-variance or degenerate dailySeries.`
|
||||
);
|
||||
}
|
||||
if (
|
||||
!momentsClose(row.sharpeUnann, computed.sharpeUnann) ||
|
||||
!momentsClose(row.skewness, computed.skewness) ||
|
||||
!momentsClose(row.kurtosis, computed.kurtosis)
|
||||
) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_ROW',
|
||||
`Row at index ${index} has moments (sharpeUnann, skewness, kurtosis) that do not match dailySeries.`
|
||||
);
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
principalId,
|
||||
|
|
@ -831,127 +899,504 @@ function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number)
|
|||
sampleStart,
|
||||
sampleEnd,
|
||||
vaultCutoffDate,
|
||||
nObs: row.nObs,
|
||||
sharpeUnann: row.sharpeUnann,
|
||||
skewness: row.skewness,
|
||||
kurtosis: row.kurtosis,
|
||||
dailyRiskFree,
|
||||
nObs: computed.nObs,
|
||||
sharpeUnann: computed.sharpeUnann,
|
||||
skewness: computed.skewness,
|
||||
kurtosis: computed.kurtosis,
|
||||
dailySeries: Object.freeze(dailySeries),
|
||||
});
|
||||
}
|
||||
|
||||
function buildAlignedClusterSeries(cluster: readonly TrialLedgerRow[]): readonly (readonly number[])[] {
|
||||
const count = cluster.length;
|
||||
if (count <= 1) {
|
||||
return cluster.map(trial => trial.dailySeries);
|
||||
}
|
||||
const DAYS_IN_CALENDAR_MONTH: readonly number[] = [
|
||||
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
|
||||
];
|
||||
|
||||
const first = cluster[0] as TrialLedgerRow;
|
||||
let allSameStart = true;
|
||||
let allSameEnd = true;
|
||||
for (let i = 1; i < count; i += 1) {
|
||||
const trial = cluster[i] as TrialLedgerRow;
|
||||
if (trial.sampleStart !== first.sampleStart) {
|
||||
allSameStart = false;
|
||||
function assertValidCalendarDate(raw: unknown, field: string): string {
|
||||
const dateStr = assertDateOnlyFormat(raw, field);
|
||||
const year = Number(dateStr.slice(0, 4));
|
||||
const month = Number(dateStr.slice(5, 7));
|
||||
const day = Number(dateStr.slice(8, 10));
|
||||
if (month < 1 || month > 12) {
|
||||
throw new TrialLedgerError('INVALID_DATE', `Invalid calendar month in "${field}": "${dateStr}".`);
|
||||
}
|
||||
const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
const maxDay = month === 2 && isLeap ? 29 : (DAYS_IN_CALENDAR_MONTH[month - 1] as number);
|
||||
if (day < 1 || day > maxDay) {
|
||||
throw new TrialLedgerError('INVALID_DATE', `Invalid calendar day in "${field}": "${dateStr}".`);
|
||||
}
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
function validateSortedDates(raw: unknown, field: string): readonly string[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_DATE',
|
||||
`Invalid "${field}": expected an array of strictly ascending YYYY-MM-DD dates.`
|
||||
);
|
||||
}
|
||||
const len = raw.length;
|
||||
const validated: string[] = new Array(len);
|
||||
for (let i = 0; i < len; i += 1) {
|
||||
const dateStr = assertValidCalendarDate(raw[i], `${field}[${i}]`);
|
||||
if (i > 0 && dateStr <= (validated[i - 1] as string)) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_DATE',
|
||||
`Dates in "${field}" must be strictly ascending: "${dateStr}" <= "${validated[i - 1] as string}".`
|
||||
);
|
||||
}
|
||||
if (trial.sampleEnd !== first.sampleEnd) {
|
||||
allSameEnd = false;
|
||||
validated[i] = dateStr;
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
|
||||
function normalizeObservationDatesMap(
|
||||
raw: ClusterDeflatedSharpeQuery['observationDatesByTrialId']
|
||||
): Map<number, readonly string[]> | undefined {
|
||||
if (raw === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const result = new Map<number, readonly string[]>();
|
||||
if (raw instanceof Map) {
|
||||
for (const [key, dates] of raw.entries()) {
|
||||
const id = parseTrialId(key);
|
||||
if (result.has(id)) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_ROW',
|
||||
`Duplicate trialId ${id} in observationDatesByTrialId.`
|
||||
);
|
||||
}
|
||||
result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Fast zero-copy path: all trials share sampleStart, so index t is the same trading day.
|
||||
if (allSameStart) {
|
||||
return cluster.map(trial => trial.dailySeries);
|
||||
if (!isPlainObject(raw)) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_ROW',
|
||||
'observationDatesByTrialId must be a Map or plain object mapping trialId to YYYY-MM-DD[].'
|
||||
);
|
||||
}
|
||||
|
||||
// Right-aligned leading-NaN path: all trials share sampleEnd.
|
||||
if (allSameEnd) {
|
||||
let maxLen = 0;
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const len = (cluster[i] as TrialLedgerRow).dailySeries.length;
|
||||
if (len > maxLen) {
|
||||
maxLen = len;
|
||||
}
|
||||
}
|
||||
return cluster.map(trial => {
|
||||
const series = trial.dailySeries;
|
||||
const pad = maxLen - series.length;
|
||||
if (pad === 0) {
|
||||
return series;
|
||||
}
|
||||
const padded = new Array<number>(maxLen);
|
||||
for (let t = 0; t < pad; t += 1) {
|
||||
padded[t] = Number.NaN;
|
||||
}
|
||||
for (let t = 0; t < series.length; t += 1) {
|
||||
padded[pad + t] = series[t] as number;
|
||||
}
|
||||
return padded;
|
||||
});
|
||||
for (const [key, dates] of Object.entries(raw)) {
|
||||
const id = parseTrialId(key);
|
||||
result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Mixed sampleStart and sampleEnd: only trials sharing an anchor (start or end) share index slots;
|
||||
// distinct anchors are placed in disjoint NaN-padded blocks so effectiveIndependentTrials skips
|
||||
// unalignable pairs instead of fabricating correlations.
|
||||
const byStart = new Map<string, number[]>();
|
||||
const byEnd = new Map<string, number[]>();
|
||||
let hasSharedStart = false;
|
||||
let hasSharedEnd = false;
|
||||
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const trial = cluster[i] as TrialLedgerRow;
|
||||
const startGroup = byStart.get(trial.sampleStart);
|
||||
if (startGroup !== undefined) {
|
||||
startGroup.push(i);
|
||||
hasSharedStart = true;
|
||||
function lowerBoundDate(sorted: readonly string[], target: string): number {
|
||||
let lo = 0;
|
||||
let hi = sorted.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if ((sorted[mid] as string) < target) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
byStart.set(trial.sampleStart, [i]);
|
||||
hi = mid;
|
||||
}
|
||||
const endGroup = byEnd.get(trial.sampleEnd);
|
||||
if (endGroup !== undefined) {
|
||||
endGroup.push(i);
|
||||
hasSharedEnd = true;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
function upperBoundDate(sorted: readonly string[], target: string): number {
|
||||
let lo = 0;
|
||||
let hi = sorted.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if ((sorted[mid] as string) <= target) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
byEnd.set(trial.sampleEnd, [i]);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
interface PreparedDenseSeries {
|
||||
readonly values: Float64Array;
|
||||
readonly prefixSum: Float64Array;
|
||||
}
|
||||
|
||||
function prepareDenseSeries(series: readonly number[]): PreparedDenseSeries {
|
||||
const len = series.length;
|
||||
const values = new Float64Array(len);
|
||||
const prefixSum = new Float64Array(len + 1);
|
||||
let running = 0;
|
||||
for (let t = 0; t < len; t += 1) {
|
||||
const v = series[t] as number;
|
||||
values[t] = v;
|
||||
running += v;
|
||||
prefixSum[t + 1] = running;
|
||||
}
|
||||
return { values, prefixSum };
|
||||
}
|
||||
|
||||
function pearsonSliceCorrelation(
|
||||
a: PreparedDenseSeries,
|
||||
offsetA: number,
|
||||
b: PreparedDenseSeries,
|
||||
offsetB: number,
|
||||
len: number
|
||||
): number | null {
|
||||
if (len < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meanA =
|
||||
((a.prefixSum[offsetA + len] as number) - (a.prefixSum[offsetA] as number)) / len;
|
||||
const meanB =
|
||||
((b.prefixSum[offsetB + len] as number) - (b.prefixSum[offsetB] as number)) / len;
|
||||
const aVals = a.values;
|
||||
const bVals = b.values;
|
||||
|
||||
let cov = 0;
|
||||
let varA = 0;
|
||||
let varB = 0;
|
||||
|
||||
for (let t = 0; t < len; t += 1) {
|
||||
const da = (aVals[offsetA + t] as number) - meanA;
|
||||
const db = (bVals[offsetB + t] as number) - meanB;
|
||||
cov += da * db;
|
||||
varA += da * da;
|
||||
varB += db * db;
|
||||
}
|
||||
|
||||
if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) {
|
||||
return null;
|
||||
}
|
||||
const denom = Math.sqrt(varA * varB);
|
||||
if (!Number.isFinite(denom) || denom <= 0) {
|
||||
return null;
|
||||
}
|
||||
const rawRho = cov / denom;
|
||||
if (!Number.isFinite(rawRho)) {
|
||||
return null;
|
||||
}
|
||||
return rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho;
|
||||
}
|
||||
|
||||
function pearsonDateMergedCorrelation(
|
||||
aSeries: readonly number[],
|
||||
aDates: readonly string[],
|
||||
aStart: number,
|
||||
aEnd: number,
|
||||
bSeries: readonly number[],
|
||||
bDates: readonly string[],
|
||||
bStart: number,
|
||||
bEnd: number
|
||||
): number | null {
|
||||
if (aEnd - aStart < 2 || bEnd - bStart < 2) {
|
||||
return null;
|
||||
}
|
||||
if ((aDates[aEnd - 1] as string) < (bDates[bStart] as string)) {
|
||||
return null;
|
||||
}
|
||||
if ((bDates[bEnd - 1] as string) < (aDates[aStart] as string)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let ia = aStart;
|
||||
let ib = bStart;
|
||||
let overlap = 0;
|
||||
let sumA = 0;
|
||||
let sumB = 0;
|
||||
let firstA = 0;
|
||||
let firstB = 0;
|
||||
let allEqualA = true;
|
||||
let allEqualB = true;
|
||||
|
||||
while (ia < aEnd && ib < bEnd) {
|
||||
const da = aDates[ia] as string;
|
||||
const db = bDates[ib] as string;
|
||||
if (da === db) {
|
||||
const va = aSeries[ia - aStart] as number;
|
||||
const vb = bSeries[ib - bStart] as number;
|
||||
if (Number.isFinite(va) && Number.isFinite(vb)) {
|
||||
if (overlap === 0) {
|
||||
firstA = va;
|
||||
firstB = vb;
|
||||
} else {
|
||||
if (va !== firstA) {
|
||||
allEqualA = false;
|
||||
}
|
||||
if (vb !== firstB) {
|
||||
allEqualB = false;
|
||||
}
|
||||
}
|
||||
sumA += va;
|
||||
sumB += vb;
|
||||
overlap += 1;
|
||||
}
|
||||
ia += 1;
|
||||
ib += 1;
|
||||
} else if (da < db) {
|
||||
ia += 1;
|
||||
} else {
|
||||
ib += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const alignMode: 'start' | 'end' = hasSharedStart || !hasSharedEnd ? 'start' : 'end';
|
||||
const groups = alignMode === 'start' ? byStart : byEnd;
|
||||
const aligned: (readonly number[])[] = new Array(count);
|
||||
let blockOffset = 0;
|
||||
if (overlap < 2 || allEqualA || allEqualB) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const indices of groups.values()) {
|
||||
let blockWidth = 0;
|
||||
for (let g = 0; g < indices.length; g += 1) {
|
||||
const len = (cluster[indices[g] as number] as TrialLedgerRow).dailySeries.length;
|
||||
if (len > blockWidth) {
|
||||
blockWidth = len;
|
||||
const meanA = sumA / overlap;
|
||||
const meanB = sumB / overlap;
|
||||
let cov = 0;
|
||||
let varA = 0;
|
||||
let varB = 0;
|
||||
|
||||
ia = aStart;
|
||||
ib = bStart;
|
||||
while (ia < aEnd && ib < bEnd) {
|
||||
const da = aDates[ia] as string;
|
||||
const db = bDates[ib] as string;
|
||||
if (da === db) {
|
||||
const va = aSeries[ia - aStart] as number;
|
||||
const vb = bSeries[ib - bStart] as number;
|
||||
if (Number.isFinite(va) && Number.isFinite(vb)) {
|
||||
const diffA = va - meanA;
|
||||
const diffB = vb - meanB;
|
||||
cov += diffA * diffB;
|
||||
varA += diffA * diffA;
|
||||
varB += diffB * diffB;
|
||||
}
|
||||
ia += 1;
|
||||
ib += 1;
|
||||
} else if (da < db) {
|
||||
ia += 1;
|
||||
} else {
|
||||
ib += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) {
|
||||
return null;
|
||||
}
|
||||
const denom = Math.sqrt(varA * varB);
|
||||
if (!Number.isFinite(denom) || denom <= 0) {
|
||||
return null;
|
||||
}
|
||||
const rawRho = cov / denom;
|
||||
if (!Number.isFinite(rawRho)) {
|
||||
return null;
|
||||
}
|
||||
return rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho;
|
||||
}
|
||||
|
||||
interface DenseWindowGroup {
|
||||
readonly startIdx: number;
|
||||
readonly endExclusive: number;
|
||||
readonly seriesList: (readonly number[])[];
|
||||
}
|
||||
|
||||
interface ExplicitDateTrial {
|
||||
readonly series: readonly number[];
|
||||
readonly dates: readonly string[];
|
||||
}
|
||||
|
||||
interface ClusterEffectiveTrials {
|
||||
readonly pairsUsed: number;
|
||||
readonly pairsSkipped: number;
|
||||
readonly meanCorrelation: number | null;
|
||||
readonly nHat: number;
|
||||
}
|
||||
|
||||
function computeClusterEffectiveTrials(
|
||||
cluster: readonly TrialLedgerRow[],
|
||||
sessionDates: readonly string[] | undefined,
|
||||
observationDatesMap: ReadonlyMap<number, readonly string[]> | undefined
|
||||
): ClusterEffectiveTrials {
|
||||
const k = cluster.length;
|
||||
if (k <= 1) {
|
||||
return { pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 };
|
||||
}
|
||||
|
||||
const denseGroupByKey = new Map<string, DenseWindowGroup>();
|
||||
const denseGroups: DenseWindowGroup[] = [];
|
||||
const explicitTrials: ExplicitDateTrial[] = [];
|
||||
let unalignedCount = 0;
|
||||
|
||||
for (let i = 0; i < k; i += 1) {
|
||||
const trial = cluster[i] as TrialLedgerRow;
|
||||
const explicitDates = observationDatesMap?.get(trial.trialId);
|
||||
if (explicitDates !== undefined) {
|
||||
if (explicitDates.length !== trial.dailySeries.length) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_ROW',
|
||||
`observationDatesByTrialId[${trial.trialId}] length (${explicitDates.length}) does not match dailySeries.length (${trial.dailySeries.length}).`
|
||||
);
|
||||
}
|
||||
const firstDate = explicitDates[0] as string;
|
||||
const lastDate = explicitDates[explicitDates.length - 1] as string;
|
||||
if (firstDate < trial.sampleStart || lastDate > trial.sampleEnd) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_SAMPLE_WINDOW',
|
||||
`observationDatesByTrialId[${trial.trialId}] range [${firstDate}, ${lastDate}] lies outside trial window [${trial.sampleStart}, ${trial.sampleEnd}].`
|
||||
);
|
||||
}
|
||||
explicitTrials.push({ series: trial.dailySeries, dates: explicitDates });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sessionDates !== undefined) {
|
||||
const startIdx = lowerBoundDate(sessionDates, trial.sampleStart);
|
||||
const endExclusive = upperBoundDate(sessionDates, trial.sampleEnd);
|
||||
if (endExclusive - startIdx === trial.dailySeries.length) {
|
||||
const key = `${startIdx}:${endExclusive}`;
|
||||
let group = denseGroupByKey.get(key);
|
||||
if (group === undefined) {
|
||||
group = { startIdx, endExclusive, seriesList: [] };
|
||||
denseGroupByKey.set(key, group);
|
||||
denseGroups.push(group);
|
||||
}
|
||||
group.seriesList.push(trial.dailySeries);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for (let g = 0; g < indices.length; g += 1) {
|
||||
const idx = indices[g] as number;
|
||||
const series = (cluster[idx] as TrialLedgerRow).dailySeries;
|
||||
const leadingNaNs =
|
||||
alignMode === 'start' ? blockOffset : blockOffset + (blockWidth - series.length);
|
||||
if (leadingNaNs === 0) {
|
||||
aligned[idx] = series;
|
||||
unalignedCount += 1;
|
||||
}
|
||||
|
||||
// Fast path: all K trials are proven dense on the exact same session window.
|
||||
if (denseGroups.length === 1 && (denseGroups[0] as DenseWindowGroup).seriesList.length === k) {
|
||||
const eff = effectiveIndependentTrials((denseGroups[0] as DenseWindowGroup).seriesList);
|
||||
return {
|
||||
pairsUsed: eff.pairsUsed,
|
||||
pairsSkipped: eff.pairsSkipped,
|
||||
meanCorrelation: eff.meanCorrelation,
|
||||
nHat: eff.nHat,
|
||||
};
|
||||
}
|
||||
|
||||
let rhoSum = 0;
|
||||
let pairsUsed = 0;
|
||||
let pairsSkipped = 0;
|
||||
|
||||
// 1. Within-group correlations for dense groups (uses fast unit-vector dot-product path).
|
||||
for (let g = 0; g < denseGroups.length; g += 1) {
|
||||
const group = denseGroups[g] as DenseWindowGroup;
|
||||
if (group.seriesList.length < 2) {
|
||||
continue;
|
||||
}
|
||||
const eff = effectiveIndependentTrials(group.seriesList);
|
||||
if (eff.meanCorrelation !== null) {
|
||||
rhoSum += eff.meanCorrelation * eff.pairsUsed;
|
||||
}
|
||||
pairsUsed += eff.pairsUsed;
|
||||
pairsSkipped += eff.pairsSkipped;
|
||||
}
|
||||
|
||||
// 2. Cross-group correlations between distinct dense windows (zero NaN padding).
|
||||
if (denseGroups.length > 1) {
|
||||
const preparedGroups: PreparedDenseSeries[][] = denseGroups.map(group =>
|
||||
group.seriesList.map(series => prepareDenseSeries(series))
|
||||
);
|
||||
for (let ga = 0; ga < denseGroups.length - 1; ga += 1) {
|
||||
const groupA = denseGroups[ga] as DenseWindowGroup;
|
||||
const prepA = preparedGroups[ga] as PreparedDenseSeries[];
|
||||
for (let gb = ga + 1; gb < denseGroups.length; gb += 1) {
|
||||
const groupB = denseGroups[gb] as DenseWindowGroup;
|
||||
const ovStart = groupA.startIdx > groupB.startIdx ? groupA.startIdx : groupB.startIdx;
|
||||
const ovEnd =
|
||||
groupA.endExclusive < groupB.endExclusive ? groupA.endExclusive : groupB.endExclusive;
|
||||
const ovLen = ovEnd - ovStart;
|
||||
if (ovLen < 2) {
|
||||
pairsSkipped += groupA.seriesList.length * groupB.seriesList.length;
|
||||
continue;
|
||||
}
|
||||
const offsetA = ovStart - groupA.startIdx;
|
||||
const offsetB = ovStart - groupB.startIdx;
|
||||
const prepB = preparedGroups[gb] as PreparedDenseSeries[];
|
||||
for (let ia = 0; ia < prepA.length; ia += 1) {
|
||||
const seriesA = prepA[ia] as PreparedDenseSeries;
|
||||
for (let ib = 0; ib < prepB.length; ib += 1) {
|
||||
const seriesB = prepB[ib] as PreparedDenseSeries;
|
||||
const rho = pearsonSliceCorrelation(seriesA, offsetA, seriesB, offsetB, ovLen);
|
||||
if (rho === null) {
|
||||
pairsSkipped += 1;
|
||||
} else {
|
||||
rhoSum += rho;
|
||||
pairsUsed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Explicit-date trial vs explicit-date trial (exact two-pointer date merge).
|
||||
for (let i = 0; i < explicitTrials.length - 1; i += 1) {
|
||||
const a = explicitTrials[i] as ExplicitDateTrial;
|
||||
for (let j = i + 1; j < explicitTrials.length; j += 1) {
|
||||
const b = explicitTrials[j] as ExplicitDateTrial;
|
||||
const rho = pearsonDateMergedCorrelation(
|
||||
a.series,
|
||||
a.dates,
|
||||
0,
|
||||
a.dates.length,
|
||||
b.series,
|
||||
b.dates,
|
||||
0,
|
||||
b.dates.length
|
||||
);
|
||||
if (rho === null) {
|
||||
pairsSkipped += 1;
|
||||
} else {
|
||||
const padded = new Array<number>(leadingNaNs + series.length);
|
||||
for (let t = 0; t < leadingNaNs; t += 1) {
|
||||
padded[t] = Number.NaN;
|
||||
}
|
||||
for (let t = 0; t < series.length; t += 1) {
|
||||
padded[leadingNaNs + t] = series[t] as number;
|
||||
}
|
||||
aligned[idx] = padded;
|
||||
rhoSum += rho;
|
||||
pairsUsed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
blockOffset += blockWidth;
|
||||
}
|
||||
|
||||
return aligned;
|
||||
// 4. Explicit-date trial vs dense-grid trial (zero-slice merge against sessionDates).
|
||||
if (sessionDates !== undefined && explicitTrials.length > 0 && denseGroups.length > 0) {
|
||||
for (let i = 0; i < explicitTrials.length; i += 1) {
|
||||
const exp = explicitTrials[i] as ExplicitDateTrial;
|
||||
for (let g = 0; g < denseGroups.length; g += 1) {
|
||||
const group = denseGroups[g] as DenseWindowGroup;
|
||||
if (
|
||||
(exp.dates[exp.dates.length - 1] as string) < (sessionDates[group.startIdx] as string) ||
|
||||
(sessionDates[group.endExclusive - 1] as string) < (exp.dates[0] as string)
|
||||
) {
|
||||
pairsSkipped += group.seriesList.length;
|
||||
continue;
|
||||
}
|
||||
for (let s = 0; s < group.seriesList.length; s += 1) {
|
||||
const denseSeries = group.seriesList[s] as readonly number[];
|
||||
const rho = pearsonDateMergedCorrelation(
|
||||
exp.series,
|
||||
exp.dates,
|
||||
0,
|
||||
exp.dates.length,
|
||||
denseSeries,
|
||||
sessionDates,
|
||||
group.startIdx,
|
||||
group.endExclusive
|
||||
);
|
||||
if (rho === null) {
|
||||
pairsSkipped += 1;
|
||||
} else {
|
||||
rhoSum += rho;
|
||||
pairsUsed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Pairs involving trials without proven date/grid alignment are skipped in O(1).
|
||||
if (unalignedCount > 0) {
|
||||
const alignedCount = k - unalignedCount;
|
||||
pairsSkipped += unalignedCount * alignedCount + (unalignedCount * (unalignedCount - 1)) / 2;
|
||||
}
|
||||
|
||||
if (pairsUsed === 0) {
|
||||
return { pairsUsed: 0, pairsSkipped, meanCorrelation: null, nHat: k };
|
||||
}
|
||||
|
||||
const meanCorrelation = rhoSum / pairsUsed;
|
||||
const nHat = Math.max(1, 1 + (k - 1) * (1 - Math.max(0, meanCorrelation)));
|
||||
return { pairsUsed, pairsSkipped, meanCorrelation, nHat };
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1083,6 +1528,7 @@ export function buildTrialRow(input: TrialRowInput): BuiltTrialRow {
|
|||
sampleStart,
|
||||
sampleEnd,
|
||||
vaultCutoffDate,
|
||||
dailyRiskFree,
|
||||
nObs: moments.nObs,
|
||||
sharpeUnann: moments.sharpeUnann,
|
||||
skewness: moments.skewness,
|
||||
|
|
@ -1239,6 +1685,11 @@ export async function clusterDeflatedSharpe(
|
|||
`Invalid dsrGate "${String(query.dsrGate)}": expected a finite number.`
|
||||
);
|
||||
}
|
||||
const sessionDates =
|
||||
query.sessionDates !== undefined
|
||||
? validateSortedDates(query.sessionDates, 'sessionDates')
|
||||
: undefined;
|
||||
const observationDatesMap = normalizeObservationDatesMap(query.observationDatesByTrialId);
|
||||
|
||||
const targetResult = await executor.query<Record<string, unknown>>(
|
||||
`SELECT${SELECT_TRIAL_COLUMNS}
|
||||
|
|
@ -1266,8 +1717,7 @@ WHERE trial_id = $1::bigint`,
|
|||
);
|
||||
}
|
||||
|
||||
const alignedSeries = buildAlignedClusterSeries(cluster);
|
||||
const eff = effectiveIndependentTrials(alignedSeries);
|
||||
const eff = computeClusterEffectiveTrials(cluster, sessionDates, observationDatesMap);
|
||||
const clusterSharpes = cluster.map(row => row.sharpeUnann);
|
||||
|
||||
const dsrResult = deflatedSharpeRatio({
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue