1676 lines
53 KiB
TypeScript
1676 lines
53 KiB
TypeScript
/**
|
||
* Append-only `trial_ledger` writer and relatedness-cluster N-hat-deflated Sharpe
|
||
* reader (`design/VALIDATION-AND-RIGOR.md` §2.B–§2.C, `database/postgres/init/36-trial-ledger.sql`).
|
||
*
|
||
* Browser-safe and dependency-free: zero `node:*` imports, zero `pg` dependency,
|
||
* zero bare `process` access. SQL execution is injected via {@link TrialLedgerExecutor}.
|
||
*/
|
||
|
||
import {
|
||
DSR_VALIDATION_GATE,
|
||
deflatedSharpeRatio,
|
||
effectiveIndependentTrials,
|
||
passesDsrGate,
|
||
trialMoments,
|
||
} from '@stock-bot/calculations';
|
||
import {
|
||
MarketDataStoreValidationError,
|
||
VaultHoldoutFenceError,
|
||
applyVaultFence,
|
||
} from './market-data-store';
|
||
import { sha256HexUtf8 } from './sha256';
|
||
|
||
export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const;
|
||
export type TrialStage = (typeof TRIAL_STAGES)[number];
|
||
|
||
export const UNIVERSE_MARKETS = ['US_EQ', 'CA_EQ', 'US_CA_EQ', 'FX'] as const;
|
||
export type UniverseMarket = (typeof UNIVERSE_MARKETS)[number];
|
||
|
||
export const HORIZON_BUCKETS = ['intraday', 'swing_1_10d', 'position_10d_plus'] as const;
|
||
export type HorizonBucket = (typeof HORIZON_BUCKETS)[number];
|
||
|
||
/** Maximum rows per single parameterised INSERT (`floor(65535 / 14)` PG protocol bind cap). */
|
||
export const MAX_TRIAL_BATCH_SIZE = 4681;
|
||
|
||
export type TrialLedgerErrorCode =
|
||
| 'INVALID_PRINCIPAL'
|
||
| 'INVALID_UUID'
|
||
| 'INVALID_STAGE'
|
||
| 'INVALID_UNIVERSE_MARKET'
|
||
| 'INVALID_HORIZON_BUCKET'
|
||
| 'INVALID_EXPRESSION_HASH'
|
||
| 'INVALID_EXPRESSION_INPUT'
|
||
| 'INVALID_DATE'
|
||
| 'INVALID_SAMPLE_WINDOW'
|
||
| 'VAULT_FENCE_VIOLATION'
|
||
| 'SERIES_TOO_SHORT'
|
||
| 'INVALID_SERIES_VALUE'
|
||
| 'ZERO_VARIANCE_SERIES'
|
||
| 'BATCH_TOO_LARGE'
|
||
| 'INVALID_TRIAL_ID'
|
||
| 'TRIAL_NOT_FOUND'
|
||
| 'INVALID_ROW';
|
||
|
||
/** Typed validation and lookup error thrown by `trial_ledger` helpers. */
|
||
export class TrialLedgerError extends RangeError {
|
||
readonly code: TrialLedgerErrorCode;
|
||
|
||
constructor(code: TrialLedgerErrorCode, message: string) {
|
||
super(message);
|
||
this.name = 'TrialLedgerError';
|
||
this.code = code;
|
||
Object.setPrototypeOf(this, new.target.prototype);
|
||
}
|
||
}
|
||
|
||
export interface TrialLedgerQueryResult<Row = Record<string, unknown>> {
|
||
readonly rows: readonly Row[];
|
||
readonly rowCount?: number | null;
|
||
}
|
||
|
||
/**
|
||
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
|
||
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
|
||
*/
|
||
export interface TrialLedgerExecutor {
|
||
query<Row = Record<string, unknown>>(
|
||
text: string,
|
||
params?: readonly unknown[]
|
||
): Promise<TrialLedgerQueryResult<Row>>;
|
||
}
|
||
|
||
export interface CanonicalExpressionInput {
|
||
readonly expression: string;
|
||
readonly params: unknown;
|
||
readonly universe: unknown;
|
||
readonly sampleStart: string;
|
||
readonly sampleEnd: string;
|
||
readonly horizon: string | number;
|
||
}
|
||
|
||
export interface TrialRowInput {
|
||
readonly principalId: string;
|
||
readonly campaignId?: string | null;
|
||
readonly hypothesisId?: string | null;
|
||
readonly stage: TrialStage;
|
||
readonly universeMarket: UniverseMarket;
|
||
readonly horizonBucket: HorizonBucket;
|
||
readonly expressionHash: string;
|
||
readonly sampleStart: string;
|
||
readonly sampleEnd: string;
|
||
readonly dailySeries: readonly number[] | Float32Array | Float64Array;
|
||
readonly vaultCutoffDate: string;
|
||
readonly dailyRiskFree?: number;
|
||
}
|
||
|
||
export interface BuiltTrialRow {
|
||
readonly principalId: string;
|
||
readonly campaignId: string | null;
|
||
readonly hypothesisId: string | null;
|
||
readonly stage: TrialStage;
|
||
readonly universeMarket: UniverseMarket;
|
||
readonly horizonBucket: HorizonBucket;
|
||
readonly expressionHash: string;
|
||
readonly sampleStart: string;
|
||
readonly sampleEnd: string;
|
||
readonly vaultCutoffDate: string;
|
||
readonly dailyRiskFree?: number;
|
||
readonly nObs: number;
|
||
readonly sharpeUnann: number;
|
||
readonly skewness: number;
|
||
readonly kurtosis: number;
|
||
readonly dailySeries: readonly number[];
|
||
}
|
||
|
||
export interface RecordedTrialReceipt {
|
||
readonly trialId: number;
|
||
readonly createdAt: string;
|
||
}
|
||
|
||
export interface LoadClusterTrialsQuery {
|
||
readonly universeMarket: UniverseMarket;
|
||
readonly horizonBucket: HorizonBucket;
|
||
readonly asOf?: string | Date;
|
||
}
|
||
|
||
export interface TrialLedgerRow {
|
||
readonly trialId: number;
|
||
readonly createdAt: string;
|
||
readonly principalId: string;
|
||
readonly campaignId: string | null;
|
||
readonly stage: TrialStage;
|
||
readonly universeMarket: UniverseMarket;
|
||
readonly horizonBucket: HorizonBucket;
|
||
readonly hypothesisId: string | null;
|
||
readonly expressionHash: string;
|
||
readonly sampleStart: string;
|
||
readonly sampleEnd: string;
|
||
readonly nObs: number;
|
||
readonly sharpeUnann: number;
|
||
readonly skewness: number;
|
||
readonly kurtosis: number;
|
||
readonly dailySeries: readonly number[];
|
||
}
|
||
|
||
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 `sessionDates`
|
||
* covers the trial's full `[sampleStart, sampleEnd]` range (`sessionDates[0] <= sampleStart`
|
||
* and `sessionDates[last] >= sampleEnd`) and 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 {
|
||
readonly trialId: number;
|
||
readonly universeMarket: UniverseMarket;
|
||
readonly horizonBucket: HorizonBucket;
|
||
readonly clusterSize: number;
|
||
readonly effectiveTrials: number;
|
||
readonly meanCorrelation: number | null;
|
||
readonly pairsUsed: number;
|
||
readonly pairsSkipped: number;
|
||
readonly sr0: number | null;
|
||
readonly standardError: number | null;
|
||
readonly dsr: number | null;
|
||
readonly passesGate: boolean;
|
||
}
|
||
|
||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||
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);
|
||
const HORIZON_BUCKET_SET: ReadonlySet<string> = new Set(HORIZON_BUCKETS);
|
||
|
||
const COLUMNS_PER_ROW = 14;
|
||
const UTC_CREATED_AT_SQL = `to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS created_at`;
|
||
|
||
const SELECT_TRIAL_COLUMNS = `
|
||
trial_id,
|
||
${UTC_CREATED_AT_SQL},
|
||
principal_id,
|
||
campaign_id,
|
||
stage,
|
||
universe_market,
|
||
horizon_bucket,
|
||
hypothesis_id,
|
||
expression_hash,
|
||
sample_start::text AS sample_start,
|
||
sample_end::text AS sample_end,
|
||
n_obs,
|
||
sharpe_unann,
|
||
skewness,
|
||
kurtosis,
|
||
daily_series`;
|
||
|
||
function compareAscii(a: string, b: string): number {
|
||
return a < b ? -1 : a > b ? 1 : 0;
|
||
}
|
||
|
||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||
if (typeof value !== 'object' || value === null) {
|
||
return false;
|
||
}
|
||
const proto: unknown = Object.getPrototypeOf(value);
|
||
return proto === Object.prototype || proto === null;
|
||
}
|
||
|
||
function canonicalizeJsonValue(value: unknown, path: string, seen: Set<object>): string {
|
||
if (value === null) {
|
||
return 'null';
|
||
}
|
||
|
||
const valueType = typeof value;
|
||
if (valueType === 'boolean') {
|
||
return value ? 'true' : 'false';
|
||
}
|
||
if (valueType === 'string') {
|
||
return JSON.stringify(value);
|
||
}
|
||
if (valueType === 'number') {
|
||
if (!Number.isFinite(value)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
`Non-finite number at "${path}" is not allowed in canonicalExpressionHash.`
|
||
);
|
||
}
|
||
return JSON.stringify(Object.is(value, -0) ? 0 : value);
|
||
}
|
||
if (valueType === 'undefined') {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
`Undefined value at "${path}" is not allowed in canonicalExpressionHash.`
|
||
);
|
||
}
|
||
if (valueType !== 'object') {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
`Unsupported value type "${valueType}" at "${path}" in canonicalExpressionHash.`
|
||
);
|
||
}
|
||
|
||
const obj = value as object;
|
||
if (seen.has(obj)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
`Circular reference detected at "${path}" in canonicalExpressionHash.`
|
||
);
|
||
}
|
||
|
||
if (Array.isArray(obj)) {
|
||
seen.add(obj);
|
||
try {
|
||
const parts: string[] = new Array(obj.length);
|
||
for (let i = 0; i < obj.length; i += 1) {
|
||
parts[i] = canonicalizeJsonValue(obj[i], `${path}[${i}]`, seen);
|
||
}
|
||
return `[${parts.join(',')}]`;
|
||
} finally {
|
||
seen.delete(obj);
|
||
}
|
||
}
|
||
|
||
if (!isPlainObject(obj)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
`Unsupported non-plain object at "${path}" in canonicalExpressionHash.`
|
||
);
|
||
}
|
||
|
||
seen.add(obj);
|
||
try {
|
||
const keys = Object.keys(obj).sort(compareAscii);
|
||
const entries: string[] = [];
|
||
for (let i = 0; i < keys.length; i += 1) {
|
||
const key = keys[i] as string;
|
||
const entryValue = obj[key];
|
||
if (entryValue === undefined) {
|
||
continue;
|
||
}
|
||
entries.push(`${JSON.stringify(key)}:${canonicalizeJsonValue(entryValue, `${path}.${key}`, seen)}`);
|
||
}
|
||
return `{${entries.join(',')}}`;
|
||
} finally {
|
||
seen.delete(obj);
|
||
}
|
||
}
|
||
|
||
function assertDateOnlyFormat(value: unknown, field: string): string {
|
||
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_DATE',
|
||
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
|
||
);
|
||
}
|
||
return value;
|
||
}
|
||
|
||
function validateSampleWindowUnfenced(sampleStart: unknown, sampleEnd: unknown): {
|
||
sampleStart: string;
|
||
sampleEnd: string;
|
||
} {
|
||
const start = assertDateOnlyFormat(sampleStart, 'sampleStart');
|
||
const end = assertDateOnlyFormat(sampleEnd, 'sampleEnd');
|
||
try {
|
||
applyVaultFence(
|
||
{ from: start, to: end, scope: 'vault_evaluation_only' },
|
||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||
);
|
||
} catch (error) {
|
||
if (error instanceof MarketDataStoreValidationError) {
|
||
if (error.message.includes('must not be after end')) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_SAMPLE_WINDOW',
|
||
`sampleStart "${start}" must not be after sampleEnd "${end}".`
|
||
);
|
||
}
|
||
throw new TrialLedgerError('INVALID_DATE', error.message);
|
||
}
|
||
throw error;
|
||
}
|
||
return { sampleStart: start, sampleEnd: end };
|
||
}
|
||
|
||
function validateSampleWindowFenced(
|
||
sampleStart: unknown,
|
||
sampleEnd: unknown,
|
||
vaultCutoffDate: unknown
|
||
): {
|
||
sampleStart: string;
|
||
sampleEnd: string;
|
||
vaultCutoffDate: string;
|
||
} {
|
||
const start = assertDateOnlyFormat(sampleStart, 'sampleStart');
|
||
const end = assertDateOnlyFormat(sampleEnd, 'sampleEnd');
|
||
const cutoff = assertDateOnlyFormat(vaultCutoffDate, 'vaultCutoffDate');
|
||
|
||
let cutoffMs: number;
|
||
try {
|
||
const cutoffRange = applyVaultFence(
|
||
{ from: cutoff, to: cutoff, scope: 'vault_evaluation_only' },
|
||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||
);
|
||
cutoffMs = cutoffRange.fromMs;
|
||
} catch (error) {
|
||
if (error instanceof MarketDataStoreValidationError) {
|
||
throw new TrialLedgerError('INVALID_DATE', `Invalid vaultCutoffDate "${cutoff}": ${error.message}`);
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
let fenced;
|
||
try {
|
||
fenced = applyVaultFence({ from: start, to: end, scope: 'vault_fenced' }, { vaultCutoffTs: cutoffMs });
|
||
} catch (error) {
|
||
if (error instanceof VaultHoldoutFenceError) {
|
||
throw new TrialLedgerError(
|
||
'VAULT_FENCE_VIOLATION',
|
||
`Sample window [${start}, ${end}] violates exclusive vaultCutoffDate "${cutoff}".`
|
||
);
|
||
}
|
||
if (error instanceof MarketDataStoreValidationError) {
|
||
if (error.message.includes('must not be after end')) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_SAMPLE_WINDOW',
|
||
`sampleStart "${start}" must not be after sampleEnd "${end}".`
|
||
);
|
||
}
|
||
throw new TrialLedgerError('INVALID_DATE', error.message);
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
if (fenced.clampedTo) {
|
||
throw new TrialLedgerError(
|
||
'VAULT_FENCE_VIOLATION',
|
||
`sampleEnd "${end}" must be strictly before vaultCutoffDate "${cutoff}".`
|
||
);
|
||
}
|
||
|
||
return { sampleStart: start, sampleEnd: end, vaultCutoffDate: cutoff };
|
||
}
|
||
|
||
function validatePrincipalId(value: unknown): string {
|
||
if (typeof value !== 'string' || (value !== 'operator' && !AGENT_PRINCIPAL_PATTERN.test(value))) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_PRINCIPAL',
|
||
`Invalid principalId "${String(value)}": expected 'operator' or 'agent:<uuid>'.`
|
||
);
|
||
}
|
||
return value;
|
||
}
|
||
|
||
function validateOptionalUuid(value: unknown, field: string): string | null {
|
||
if (value === undefined || value === null) {
|
||
return null;
|
||
}
|
||
if (typeof value !== 'string' || !UUID_PATTERN.test(value)) {
|
||
throw new TrialLedgerError('INVALID_UUID', `Invalid UUID for "${field}": "${String(value)}".`);
|
||
}
|
||
return value.toLowerCase();
|
||
}
|
||
|
||
function validateStage(value: unknown): TrialStage {
|
||
if (typeof value !== 'string' || !TRIAL_STAGE_SET.has(value)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_STAGE',
|
||
`Invalid stage "${String(value)}". Expected one of: ${TRIAL_STAGES.join(', ')}.`
|
||
);
|
||
}
|
||
return value as TrialStage;
|
||
}
|
||
|
||
function validateUniverseMarket(value: unknown): UniverseMarket {
|
||
if (typeof value !== 'string' || !UNIVERSE_MARKET_SET.has(value)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_UNIVERSE_MARKET',
|
||
`Invalid universeMarket "${String(value)}". Expected one of: ${UNIVERSE_MARKETS.join(', ')}.`
|
||
);
|
||
}
|
||
return value as UniverseMarket;
|
||
}
|
||
|
||
function validateHorizonBucket(value: unknown): HorizonBucket {
|
||
if (typeof value !== 'string' || !HORIZON_BUCKET_SET.has(value)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_HORIZON_BUCKET',
|
||
`Invalid horizonBucket "${String(value)}". Expected one of: ${HORIZON_BUCKETS.join(', ')}.`
|
||
);
|
||
}
|
||
return value as HorizonBucket;
|
||
}
|
||
|
||
function validateExpressionHash(value: unknown): string {
|
||
if (typeof value !== 'string' || !EXPRESSION_HASH_PATTERN.test(value)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_HASH',
|
||
`Invalid expressionHash "${String(value)}": expected 64 lowercase hexadecimal characters.`
|
||
);
|
||
}
|
||
return value;
|
||
}
|
||
|
||
function validateDailySeries(value: unknown, allowZeroVariance = false): number[] {
|
||
const isTyped = value instanceof Float32Array || value instanceof Float64Array;
|
||
if (!Array.isArray(value) && !isTyped) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_SERIES_VALUE',
|
||
'dailySeries must be an array, Float32Array, or Float64Array of finite numbers.'
|
||
);
|
||
}
|
||
const len = value.length;
|
||
if (len < 2) {
|
||
throw new TrialLedgerError(
|
||
'SERIES_TOO_SHORT',
|
||
`dailySeries must contain at least 2 finite observations (got ${len}).`
|
||
);
|
||
}
|
||
|
||
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)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_SERIES_VALUE',
|
||
`dailySeries[${i}] is not a finite number: ${String(v)}.`
|
||
);
|
||
}
|
||
const asReal = Math.fround(v);
|
||
if (!Number.isFinite(asReal) || (v !== 0 && asReal === 0)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_SERIES_VALUE',
|
||
`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;
|
||
}
|
||
|
||
function assertExecutor(executor: unknown): asserts executor is TrialLedgerExecutor {
|
||
if (
|
||
typeof executor !== 'object' ||
|
||
executor === null ||
|
||
typeof (executor as { query?: unknown }).query !== 'function'
|
||
) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
'Expected a TrialLedgerExecutor object with a query(text, params) method.'
|
||
);
|
||
}
|
||
}
|
||
|
||
function parseTrialId(value: unknown): number {
|
||
if (typeof value === 'number') {
|
||
if (!Number.isSafeInteger(value) || value < 1) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_TRIAL_ID',
|
||
`Invalid trialId "${String(value)}": expected a positive safe integer.`
|
||
);
|
||
}
|
||
return value;
|
||
}
|
||
if (typeof value === 'bigint') {
|
||
if (value < 1n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_TRIAL_ID',
|
||
`Invalid trialId "${value.toString()}": expected a positive safe integer.`
|
||
);
|
||
}
|
||
return Number(value);
|
||
}
|
||
if (typeof value === 'string' && POSITIVE_INT_PATTERN.test(value)) {
|
||
const parsed = Number(value);
|
||
if (Number.isSafeInteger(parsed) && parsed >= 1) {
|
||
return parsed;
|
||
}
|
||
}
|
||
throw new TrialLedgerError(
|
||
'INVALID_TRIAL_ID',
|
||
`Invalid trialId "${String(value)}": expected a positive safe integer.`
|
||
);
|
||
}
|
||
|
||
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;
|
||
}
|
||
if (asOf instanceof Date) {
|
||
const ms = asOf.getTime();
|
||
if (!Number.isFinite(ms)) {
|
||
throw new TrialLedgerError('INVALID_DATE', 'Invalid asOf Date instance.');
|
||
}
|
||
return asOf.toISOString();
|
||
}
|
||
if (typeof asOf !== 'string') {
|
||
throw new TrialLedgerError(
|
||
'INVALID_DATE',
|
||
`Invalid asOf "${String(asOf)}": expected ISO-8601 UTC timestamp, YYYY-MM-DD date, or Date.`
|
||
);
|
||
}
|
||
try {
|
||
const fenced = applyVaultFence(
|
||
{ from: '1970-01-01', to: '1970-01-01', asOf, scope: 'vault_evaluation_only' },
|
||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||
);
|
||
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) {
|
||
if (error instanceof MarketDataStoreValidationError) {
|
||
throw new TrialLedgerError('INVALID_DATE', error.message);
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
function formatUtcTimestamp(value: unknown, field: string): string {
|
||
if (value instanceof Date) {
|
||
if (!Number.isFinite(value.getTime())) {
|
||
throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp for "${field}".`);
|
||
}
|
||
return value.toISOString();
|
||
}
|
||
if (typeof value === 'string') {
|
||
const ms = Date.parse(value);
|
||
if (!Number.isFinite(ms)) {
|
||
throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp string for "${field}": "${value}".`);
|
||
}
|
||
const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(value);
|
||
if (instantMatch !== null) {
|
||
return formatUtcInstantFromMs(ms, instantMatch[2]);
|
||
}
|
||
return new Date(ms).toISOString();
|
||
}
|
||
throw new TrialLedgerError('INVALID_ROW', `Unexpected timestamp value for "${field}".`);
|
||
}
|
||
|
||
function formatDateOnlyFromDb(value: unknown, field: string): string {
|
||
if (typeof value === 'string' && DATE_ONLY_PATTERN.test(value)) {
|
||
return value;
|
||
}
|
||
if (value instanceof Date && Number.isFinite(value.getTime())) {
|
||
return value.toISOString().slice(0, 10);
|
||
}
|
||
throw new TrialLedgerError('INVALID_ROW', `Unexpected date value for "${field}": "${String(value)}".`);
|
||
}
|
||
|
||
function parsePgRealArray(value: unknown): number[] {
|
||
if (Array.isArray(value)) {
|
||
return validateDailySeries(
|
||
value.map(v => Number(v)),
|
||
true
|
||
);
|
||
}
|
||
if (value instanceof Float32Array || value instanceof Float64Array) {
|
||
return validateDailySeries(value, true);
|
||
}
|
||
if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
|
||
const inner = value.slice(1, -1).trim();
|
||
if (inner.length === 0) {
|
||
throw new TrialLedgerError('SERIES_TOO_SHORT', 'Empty daily_series returned from database.');
|
||
}
|
||
const elements = inner.split(',').map(token => Number(token));
|
||
return validateDailySeries(elements, true);
|
||
}
|
||
throw new TrialLedgerError('INVALID_ROW', 'Unexpected daily_series value returned from database.');
|
||
}
|
||
|
||
function parseDbTrialRow(raw: Record<string, unknown>): TrialLedgerRow {
|
||
const trialId = parseTrialId(raw.trial_id);
|
||
const createdAt = formatUtcTimestamp(raw.created_at, 'created_at');
|
||
const principalId = validatePrincipalId(raw.principal_id);
|
||
const campaignId = validateOptionalUuid(raw.campaign_id, 'campaign_id');
|
||
const stage = validateStage(raw.stage);
|
||
const universeMarket = validateUniverseMarket(raw.universe_market);
|
||
const horizonBucket = validateHorizonBucket(raw.horizon_bucket);
|
||
const hypothesisId = validateOptionalUuid(raw.hypothesis_id, 'hypothesis_id');
|
||
const expressionHash = validateExpressionHash(
|
||
typeof raw.expression_hash === 'string' ? raw.expression_hash.trim() : raw.expression_hash
|
||
);
|
||
const sampleStart = formatDateOnlyFromDb(raw.sample_start, 'sample_start');
|
||
const sampleEnd = formatDateOnlyFromDb(raw.sample_end, 'sample_end');
|
||
const nObs = Number(raw.n_obs);
|
||
const sharpeUnann = Number(raw.sharpe_unann);
|
||
const skewness = Number(raw.skewness);
|
||
const kurtosis = Number(raw.kurtosis);
|
||
if (
|
||
!Number.isSafeInteger(nObs) ||
|
||
nObs < 2 ||
|
||
!Number.isFinite(sharpeUnann) ||
|
||
!Number.isFinite(skewness) ||
|
||
!Number.isFinite(kurtosis)
|
||
) {
|
||
throw new TrialLedgerError('INVALID_ROW', `Corrupted numeric moments for trial_id=${trialId}.`);
|
||
}
|
||
const dailySeries = parsePgRealArray(raw.daily_series);
|
||
|
||
return Object.freeze({
|
||
trialId,
|
||
createdAt,
|
||
principalId,
|
||
campaignId,
|
||
stage,
|
||
universeMarket,
|
||
horizonBucket,
|
||
hypothesisId,
|
||
expressionHash,
|
||
sampleStart,
|
||
sampleEnd,
|
||
nObs,
|
||
sharpeUnann,
|
||
skewness,
|
||
kurtosis,
|
||
dailySeries: Object.freeze(dailySeries),
|
||
});
|
||
}
|
||
|
||
function isPreBuiltTrialRow(row: TrialRowInput | BuiltTrialRow): row is BuiltTrialRow {
|
||
return (
|
||
'nObs' in row || 'sharpeUnann' in row || 'skewness' in row || 'kurtosis' in row
|
||
);
|
||
}
|
||
|
||
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.`);
|
||
}
|
||
|
||
if (!isPreBuiltTrialRow(row)) {
|
||
return buildTrialRow(row);
|
||
}
|
||
|
||
const principalId = validatePrincipalId(row.principalId);
|
||
const campaignId = validateOptionalUuid(row.campaignId, 'campaignId');
|
||
const hypothesisId = validateOptionalUuid(row.hypothesisId, 'hypothesisId');
|
||
const stage = validateStage(row.stage);
|
||
const universeMarket = validateUniverseMarket(row.universeMarket);
|
||
const horizonBucket = validateHorizonBucket(row.horizonBucket);
|
||
const expressionHash = validateExpressionHash(row.expressionHash);
|
||
const { sampleStart, sampleEnd, vaultCutoffDate } = validateSampleWindowFenced(
|
||
row.sampleStart,
|
||
row.sampleEnd,
|
||
row.vaultCutoffDate
|
||
);
|
||
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',
|
||
`Row at index ${index} has nObs=${String(row.nObs)} which does not match dailySeries.length (${dailySeries.length}).`
|
||
);
|
||
}
|
||
if (
|
||
typeof row.sharpeUnann !== 'number' ||
|
||
!Number.isFinite(row.sharpeUnann) ||
|
||
typeof row.skewness !== 'number' ||
|
||
!Number.isFinite(row.skewness) ||
|
||
typeof row.kurtosis !== 'number' ||
|
||
!Number.isFinite(row.kurtosis)
|
||
) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
`Row at index ${index} has non-finite moments (sharpeUnann, skewness, kurtosis).`
|
||
);
|
||
}
|
||
|
||
// 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,
|
||
campaignId,
|
||
hypothesisId,
|
||
stage,
|
||
universeMarket,
|
||
horizonBucket,
|
||
expressionHash,
|
||
sampleStart,
|
||
sampleEnd,
|
||
vaultCutoffDate,
|
||
dailyRiskFree,
|
||
nObs: computed.nObs,
|
||
sharpeUnann: computed.sharpeUnann,
|
||
skewness: computed.skewness,
|
||
kurtosis: computed.kurtosis,
|
||
dailySeries: Object.freeze(dailySeries),
|
||
});
|
||
}
|
||
|
||
const DAYS_IN_CALENDAR_MONTH: readonly number[] = [
|
||
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
|
||
];
|
||
|
||
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}".`
|
||
);
|
||
}
|
||
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;
|
||
}
|
||
if (!isPlainObject(raw)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
'observationDatesByTrialId must be a Map or plain object mapping trialId to YYYY-MM-DD[].'
|
||
);
|
||
}
|
||
for (const [key, dates] of Object.entries(raw)) {
|
||
const id = parseTrialId(key);
|
||
result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`));
|
||
}
|
||
return result;
|
||
}
|
||
|
||
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 {
|
||
hi = mid;
|
||
}
|
||
}
|
||
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 {
|
||
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;
|
||
const firstA = aVals[offsetA] as number;
|
||
const firstB = bVals[offsetB] as number;
|
||
let allEqualA = true;
|
||
let allEqualB = true;
|
||
|
||
let cov = 0;
|
||
let varA = 0;
|
||
let varB = 0;
|
||
|
||
for (let t = 0; t < len; t += 1) {
|
||
const va = aVals[offsetA + t] as number;
|
||
const vb = bVals[offsetB + t] as number;
|
||
if (allEqualA && va !== firstA) {
|
||
allEqualA = false;
|
||
}
|
||
if (allEqualB && vb !== firstB) {
|
||
allEqualB = false;
|
||
}
|
||
const da = va - meanA;
|
||
const db = vb - meanB;
|
||
cov += da * db;
|
||
varA += da * da;
|
||
varB += db * db;
|
||
}
|
||
|
||
if (
|
||
allEqualA ||
|
||
allEqualB ||
|
||
!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;
|
||
}
|
||
}
|
||
|
||
if (overlap < 2 || allEqualA || allEqualB) {
|
||
return null;
|
||
}
|
||
|
||
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 &&
|
||
sessionDates.length > 0 &&
|
||
(sessionDates[0] as string) <= trial.sampleStart &&
|
||
(sessionDates[sessionDates.length - 1] as string) >= trial.sampleEnd
|
||
) {
|
||
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;
|
||
}
|
||
}
|
||
|
||
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 {
|
||
rhoSum += rho;
|
||
pairsUsed += 1;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 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 };
|
||
}
|
||
|
||
/**
|
||
* Computes a deterministic 64-character lowercase SHA-256 hex digest over the
|
||
* canonical, ASCII-key-sorted JSON representation of
|
||
* `{ expression, params, universe, sampleStart, sampleEnd, horizon }`.
|
||
*/
|
||
export function canonicalExpressionHash(input: CanonicalExpressionInput): string {
|
||
if (typeof input !== 'object' || input === null) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash input must be a non-null object.'
|
||
);
|
||
}
|
||
|
||
if (typeof input.expression !== 'string') {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash requires a non-empty string expression.'
|
||
);
|
||
}
|
||
const normalizedExpression = input.expression.trim().replace(/\s+/g, ' ');
|
||
if (normalizedExpression.length === 0) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash expression must not be empty or whitespace-only.'
|
||
);
|
||
}
|
||
|
||
const { sampleStart, sampleEnd } = validateSampleWindowUnfenced(
|
||
input.sampleStart,
|
||
input.sampleEnd
|
||
);
|
||
|
||
let normalizedHorizon: string | number;
|
||
if (typeof input.horizon === 'string') {
|
||
if (input.horizon.trim().length === 0) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash horizon string must not be empty.'
|
||
);
|
||
}
|
||
normalizedHorizon = input.horizon;
|
||
} else if (typeof input.horizon === 'number' && Number.isFinite(input.horizon)) {
|
||
normalizedHorizon = Object.is(input.horizon, -0) ? 0 : input.horizon;
|
||
} else {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash horizon must be a non-empty string or finite number.'
|
||
);
|
||
}
|
||
|
||
if (input.params === undefined) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash params must be defined (use null or {} when empty).'
|
||
);
|
||
}
|
||
if (input.universe === undefined) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_EXPRESSION_INPUT',
|
||
'canonicalExpressionHash universe must be defined.'
|
||
);
|
||
}
|
||
|
||
const envelope = {
|
||
expression: normalizedExpression,
|
||
horizon: normalizedHorizon,
|
||
params: input.params,
|
||
sampleEnd,
|
||
sampleStart,
|
||
universe: input.universe,
|
||
};
|
||
|
||
const canonicalJson = canonicalizeJsonValue(envelope, '$', new Set<object>());
|
||
return sha256HexUtf8(canonicalJson);
|
||
}
|
||
|
||
/**
|
||
* Pure validator and moment builder for a single `trial_ledger` row.
|
||
*
|
||
* Enforces the exclusive Vault holdout fence (`sampleEnd < vaultCutoffDate`) via
|
||
* {@link applyVaultFence} and computes `{ nObs, sharpeUnann, skewness, kurtosis }`
|
||
* via {@link trialMoments} from `@stock-bot/calculations`.
|
||
*/
|
||
export function buildTrialRow(input: TrialRowInput): BuiltTrialRow {
|
||
if (typeof input !== 'object' || input === null) {
|
||
throw new TrialLedgerError('INVALID_ROW', 'buildTrialRow input must be a non-null object.');
|
||
}
|
||
|
||
const principalId = validatePrincipalId(input.principalId);
|
||
const campaignId = validateOptionalUuid(input.campaignId, 'campaignId');
|
||
const hypothesisId = validateOptionalUuid(input.hypothesisId, 'hypothesisId');
|
||
const stage = validateStage(input.stage);
|
||
const universeMarket = validateUniverseMarket(input.universeMarket);
|
||
const horizonBucket = validateHorizonBucket(input.horizonBucket);
|
||
const expressionHash = validateExpressionHash(input.expressionHash);
|
||
const { sampleStart, sampleEnd, vaultCutoffDate } = validateSampleWindowFenced(
|
||
input.sampleStart,
|
||
input.sampleEnd,
|
||
input.vaultCutoffDate
|
||
);
|
||
const dailySeries = validateDailySeries(input.dailySeries);
|
||
|
||
const dailyRiskFree = input.dailyRiskFree ?? 0;
|
||
if (typeof dailyRiskFree !== 'number' || !Number.isFinite(dailyRiskFree)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
`Invalid dailyRiskFree "${String(input.dailyRiskFree)}": expected a finite number.`
|
||
);
|
||
}
|
||
|
||
const moments = trialMoments(dailySeries, dailyRiskFree);
|
||
if (moments === null) {
|
||
throw new TrialLedgerError(
|
||
'ZERO_VARIANCE_SERIES',
|
||
'dailySeries has zero variance or degenerate moments (trialMoments returned null).'
|
||
);
|
||
}
|
||
|
||
return Object.freeze({
|
||
principalId,
|
||
campaignId,
|
||
hypothesisId,
|
||
stage,
|
||
universeMarket,
|
||
horizonBucket,
|
||
expressionHash,
|
||
sampleStart,
|
||
sampleEnd,
|
||
vaultCutoffDate,
|
||
dailyRiskFree,
|
||
nObs: moments.nObs,
|
||
sharpeUnann: moments.sharpeUnann,
|
||
skewness: moments.skewness,
|
||
kurtosis: moments.kurtosis,
|
||
dailySeries: Object.freeze(dailySeries),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Atomically appends one or more validated rows to `trial_ledger` in a single
|
||
* parameterised multi-row `INSERT ... RETURNING trial_id, created_at`.
|
||
*
|
||
* All rows are validated upfront before any SQL is sent.
|
||
*/
|
||
export async function recordTrials(
|
||
executor: TrialLedgerExecutor,
|
||
rows: readonly (TrialRowInput | BuiltTrialRow)[]
|
||
): Promise<RecordedTrialReceipt[]> {
|
||
assertExecutor(executor);
|
||
|
||
if (!Array.isArray(rows)) {
|
||
throw new TrialLedgerError('INVALID_ROW', 'recordTrials rows must be an array.');
|
||
}
|
||
if (rows.length === 0) {
|
||
return [];
|
||
}
|
||
if (rows.length > MAX_TRIAL_BATCH_SIZE) {
|
||
throw new TrialLedgerError(
|
||
'BATCH_TOO_LARGE',
|
||
`Batch size ${rows.length} exceeds MAX_TRIAL_BATCH_SIZE (${MAX_TRIAL_BATCH_SIZE}).`
|
||
);
|
||
}
|
||
|
||
const validated: BuiltTrialRow[] = new Array(rows.length);
|
||
for (let i = 0; i < rows.length; i += 1) {
|
||
validated[i] = validateRowForInsert(rows[i] as TrialRowInput | BuiltTrialRow, i);
|
||
}
|
||
|
||
const valueTuples: string[] = new Array(validated.length);
|
||
const params: unknown[] = new Array(validated.length * COLUMNS_PER_ROW);
|
||
|
||
for (let i = 0; i < validated.length; i += 1) {
|
||
const row = validated[i] as BuiltTrialRow;
|
||
const base = i * COLUMNS_PER_ROW;
|
||
const p = base + 1;
|
||
valueTuples[i] =
|
||
`($${p}, $${p + 1}, $${p + 2}, $${p + 3}, $${p + 4}, $${p + 5}, $${p + 6}, $${p + 7}, $${p + 8}, $${p + 9}, $${p + 10}::double precision, $${p + 11}::double precision, $${p + 12}::double precision, $${p + 13}::real[])`;
|
||
|
||
params[base] = row.principalId;
|
||
params[base + 1] = row.campaignId;
|
||
params[base + 2] = row.stage;
|
||
params[base + 3] = row.universeMarket;
|
||
params[base + 4] = row.horizonBucket;
|
||
params[base + 5] = row.hypothesisId;
|
||
params[base + 6] = row.expressionHash;
|
||
params[base + 7] = row.sampleStart;
|
||
params[base + 8] = row.sampleEnd;
|
||
params[base + 9] = row.nObs;
|
||
params[base + 10] = row.sharpeUnann;
|
||
params[base + 11] = row.skewness;
|
||
params[base + 12] = row.kurtosis;
|
||
params[base + 13] = row.dailySeries;
|
||
}
|
||
|
||
const sql = `INSERT INTO trial_ledger (
|
||
principal_id, campaign_id, stage, universe_market, horizon_bucket,
|
||
hypothesis_id, expression_hash, sample_start, sample_end, n_obs,
|
||
sharpe_unann, skewness, kurtosis, daily_series
|
||
) VALUES ${valueTuples.join(', ')}
|
||
RETURNING trial_id, ${UTC_CREATED_AT_SQL}`;
|
||
|
||
const result = await executor.query<Record<string, unknown>>(sql, params);
|
||
if (result.rows.length !== validated.length) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
`Expected ${validated.length} returned receipts from trial_ledger INSERT, got ${result.rows.length}.`
|
||
);
|
||
}
|
||
|
||
const receipts: RecordedTrialReceipt[] = new Array(result.rows.length);
|
||
for (let i = 0; i < result.rows.length; i += 1) {
|
||
const returned = result.rows[i] as Record<string, unknown>;
|
||
receipts[i] = {
|
||
trialId: parseTrialId(returned.trial_id),
|
||
createdAt: formatUtcTimestamp(returned.created_at, 'created_at'),
|
||
};
|
||
}
|
||
return receipts;
|
||
}
|
||
|
||
/**
|
||
* Loads all trials in a `(universeMarket, horizonBucket)` relatedness cluster
|
||
* ordered by `trial_id ASC`, optionally capped at `created_at <= asOf`.
|
||
*/
|
||
export async function loadClusterTrials(
|
||
executor: TrialLedgerExecutor,
|
||
query: LoadClusterTrialsQuery
|
||
): Promise<TrialLedgerRow[]> {
|
||
assertExecutor(executor);
|
||
if (typeof query !== 'object' || query === null) {
|
||
throw new TrialLedgerError('INVALID_ROW', 'loadClusterTrials query must be a non-null object.');
|
||
}
|
||
|
||
const universeMarket = validateUniverseMarket(query.universeMarket);
|
||
const horizonBucket = validateHorizonBucket(query.horizonBucket);
|
||
const normalizedAsOf = normalizeAsOf(query.asOf);
|
||
|
||
const sql =
|
||
normalizedAsOf === undefined
|
||
? `SELECT${SELECT_TRIAL_COLUMNS}
|
||
FROM trial_ledger
|
||
WHERE universe_market = $1
|
||
AND horizon_bucket = $2
|
||
ORDER BY trial_id ASC`
|
||
: `SELECT${SELECT_TRIAL_COLUMNS}
|
||
FROM trial_ledger
|
||
WHERE universe_market = $1
|
||
AND horizon_bucket = $2
|
||
AND created_at <= $3::timestamptz
|
||
ORDER BY trial_id ASC`;
|
||
|
||
const params: readonly unknown[] =
|
||
normalizedAsOf === undefined
|
||
? [universeMarket, horizonBucket]
|
||
: [universeMarket, horizonBucket, normalizedAsOf];
|
||
|
||
const result = await executor.query<Record<string, unknown>>(sql, params);
|
||
return result.rows.map(row => parseDbTrialRow(row));
|
||
}
|
||
|
||
/**
|
||
* Loads the target trial's `(universe_market, horizon_bucket)` relatedness cluster
|
||
* and computes its N-hat-deflated Sharpe Ratio via {@link effectiveIndependentTrials}
|
||
* and {@link deflatedSharpeRatio}.
|
||
*/
|
||
export async function clusterDeflatedSharpe(
|
||
executor: TrialLedgerExecutor,
|
||
query: ClusterDeflatedSharpeQuery
|
||
): Promise<ClusterDeflatedSharpeResult> {
|
||
assertExecutor(executor);
|
||
if (typeof query !== 'object' || query === null) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
'clusterDeflatedSharpe query must be a non-null object.'
|
||
);
|
||
}
|
||
|
||
const trialId = parseTrialId(query.trialId);
|
||
const normalizedAsOf = normalizeAsOf(query.asOf);
|
||
const dsrGate = query.dsrGate ?? DSR_VALIDATION_GATE;
|
||
if (typeof dsrGate !== 'number' || !Number.isFinite(dsrGate)) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_ROW',
|
||
`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}
|
||
FROM trial_ledger
|
||
WHERE trial_id = $1::bigint`,
|
||
[trialId]
|
||
);
|
||
|
||
if (targetResult.rows.length === 0) {
|
||
throw new TrialLedgerError('TRIAL_NOT_FOUND', `Trial ${trialId} was not found in trial_ledger.`);
|
||
}
|
||
|
||
const target = parseDbTrialRow(targetResult.rows[0] as Record<string, unknown>);
|
||
const cluster = await loadClusterTrials(executor, {
|
||
universeMarket: target.universeMarket,
|
||
horizonBucket: target.horizonBucket,
|
||
asOf: normalizedAsOf,
|
||
});
|
||
|
||
const targetInCluster = cluster.find(row => row.trialId === target.trialId);
|
||
if (targetInCluster === undefined) {
|
||
throw new TrialLedgerError(
|
||
'TRIAL_NOT_FOUND',
|
||
`Trial ${trialId} is not visible in cluster (${target.universeMarket}, ${target.horizonBucket}) as of ${normalizedAsOf ?? 'latest'}.`
|
||
);
|
||
}
|
||
|
||
const eff = computeClusterEffectiveTrials(cluster, sessionDates, observationDatesMap);
|
||
const clusterSharpes = cluster.map(row => row.sharpeUnann);
|
||
|
||
const dsrResult = deflatedSharpeRatio({
|
||
sharpeUnann: targetInCluster.sharpeUnann,
|
||
nObs: targetInCluster.nObs,
|
||
skewness: targetInCluster.skewness,
|
||
kurtosis: targetInCluster.kurtosis,
|
||
nHat: eff.nHat,
|
||
clusterSharpes,
|
||
});
|
||
|
||
const dsr = dsrResult?.dsr ?? null;
|
||
const passesGate = passesDsrGate(dsr, dsrGate);
|
||
|
||
return {
|
||
trialId: targetInCluster.trialId,
|
||
universeMarket: targetInCluster.universeMarket,
|
||
horizonBucket: targetInCluster.horizonBucket,
|
||
clusterSize: cluster.length,
|
||
effectiveTrials: eff.nHat,
|
||
meanCorrelation: eff.meanCorrelation,
|
||
pairsUsed: eff.pairsUsed,
|
||
pairsSkipped: eff.pairsSkipped,
|
||
sr0: dsrResult?.sr0 ?? null,
|
||
standardError: dsrResult?.standardError ?? null,
|
||
dsr,
|
||
passesGate,
|
||
};
|
||
}
|