470 lines
17 KiB
TypeScript
470 lines
17 KiB
TypeScript
/**
|
|
* QA edge-case coverage for `@stock-bot/research` trial-ledger (T-84).
|
|
*
|
|
* Focus: the hand-written cross-window / date-merged correlation paths in
|
|
* `clusterDeflatedSharpe` must agree with the canonical `effectiveIndependentTrials`
|
|
* helper applied to an explicitly date-aligned, NaN-padded oracle; pair accounting must
|
|
* be complete; pre-built rows must be re-fenced; SQL must never interpolate values.
|
|
*/
|
|
import { describe, expect, it } from 'bun:test';
|
|
import {
|
|
deflatedSharpeRatio,
|
|
effectiveIndependentTrials,
|
|
passesDsrGate,
|
|
} from '@stock-bot/calculations';
|
|
import {
|
|
TrialLedgerError,
|
|
buildTrialRow,
|
|
clusterDeflatedSharpe,
|
|
loadClusterTrials,
|
|
recordTrials,
|
|
type BuiltTrialRow,
|
|
type TrialLedgerErrorCode,
|
|
type TrialLedgerExecutor,
|
|
type TrialRowInput,
|
|
} from '@stock-bot/research';
|
|
|
|
const VAULT_CUTOFF = '2025-05-01';
|
|
const HASH_A = 'a'.repeat(64);
|
|
|
|
function createSeededRng(seed: number): () => number {
|
|
let state = seed >>> 0;
|
|
return () => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
|
};
|
|
}
|
|
|
|
function gaussianSeries(seed: number, length: number, mean = 0.0003, std = 0.01): number[] {
|
|
const next = createSeededRng(seed);
|
|
const out = new Array<number>(length);
|
|
for (let i = 0; i < length; i += 1) {
|
|
const u = Math.max(next(), 1e-12);
|
|
const v = next();
|
|
out[i] = mean + std * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function businessDates(start: string, count: number): string[] {
|
|
const out: string[] = [];
|
|
const current = new Date(`${start}T00:00:00.000Z`);
|
|
while (out.length < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out.push(current.toISOString().slice(0, 10));
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function input(overrides: Partial<TrialRowInput>): TrialRowInput {
|
|
return {
|
|
principalId: 'operator',
|
|
stage: 'signal_ic',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expressionHash: HASH_A,
|
|
sampleStart: '2020-01-02',
|
|
sampleEnd: '2020-01-10',
|
|
vaultCutoffDate: VAULT_CUTOFF,
|
|
dailySeries: [0.01, -0.02, 0.015, 0.003],
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function toDbRow(row: BuiltTrialRow, trialId: number): Record<string, unknown> {
|
|
return {
|
|
trial_id: String(trialId),
|
|
created_at: '2025-04-01T12:00:00.000000Z',
|
|
principal_id: row.principalId,
|
|
campaign_id: row.campaignId,
|
|
stage: row.stage,
|
|
universe_market: row.universeMarket,
|
|
horizon_bucket: row.horizonBucket,
|
|
hypothesis_id: row.hypothesisId,
|
|
expression_hash: row.expressionHash,
|
|
sample_start: row.sampleStart,
|
|
sample_end: row.sampleEnd,
|
|
n_obs: row.nObs,
|
|
sharpe_unann: row.sharpeUnann,
|
|
skewness: row.skewness,
|
|
kurtosis: row.kurtosis,
|
|
daily_series: row.dailySeries.map(v => Math.fround(v)),
|
|
};
|
|
}
|
|
|
|
function clusterExecutor(dbRows: readonly Record<string, unknown>[]): {
|
|
executor: TrialLedgerExecutor;
|
|
calls: { text: string; params: readonly unknown[] | undefined }[];
|
|
} {
|
|
const calls: { text: string; params: readonly unknown[] | undefined }[] = [];
|
|
const executor: TrialLedgerExecutor = {
|
|
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
|
calls.push({ text, params });
|
|
if (text.includes('WHERE trial_id = $1')) {
|
|
const id = String(params?.[0]);
|
|
return { rows: dbRows.filter(r => r.trial_id === id) as unknown as readonly Row[] };
|
|
}
|
|
return { rows: dbRows as unknown as readonly Row[] };
|
|
},
|
|
};
|
|
return { executor, calls };
|
|
}
|
|
|
|
async function expectCode(fn: () => Promise<unknown> | unknown, code: TrialLedgerErrorCode) {
|
|
let caught: unknown;
|
|
try {
|
|
await fn();
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
expect(caught).toBeInstanceOf(TrialLedgerError);
|
|
expect((caught as TrialLedgerError).code).toBe(code);
|
|
}
|
|
|
|
/** Oracle: place each stored (float32) series on the global session grid, NaN elsewhere. */
|
|
function alignOnGrid(
|
|
grid: readonly string[],
|
|
series: readonly number[],
|
|
dates: readonly string[]
|
|
): number[] {
|
|
const out = new Array<number>(grid.length).fill(Number.NaN);
|
|
const index = new Map(grid.map((d, i) => [d, i] as const));
|
|
for (let i = 0; i < dates.length; i += 1) {
|
|
out[index.get(dates[i] as string) as number] = Math.fround(series[i] as number);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
describe('trial-ledger QA: cross-window correlation agrees with effectiveIndependentTrials oracle', () => {
|
|
it('mixed dense windows (shared, prefix, suffix, staggered, disjoint) match the NaN-padded oracle', async () => {
|
|
// Arrange: 120-session grid; 7 trials on 5 distinct windows with a common factor.
|
|
const grid = businessDates('2020-01-02', 120);
|
|
const factor = gaussianSeries(11, 120, 0, 0.01);
|
|
const windows: [number, number][] = [
|
|
[0, 119],
|
|
[0, 119],
|
|
[0, 79],
|
|
[40, 119],
|
|
[20, 99],
|
|
[100, 119],
|
|
[0, 9],
|
|
];
|
|
const rows: BuiltTrialRow[] = [];
|
|
const oracle: number[][] = [];
|
|
windows.forEach(([s, e], i) => {
|
|
const noise = gaussianSeries(100 + i, 120, 0, 0.01);
|
|
const full = factor.map((f, t) => 0.0002 + 0.7 * f + 0.5 * (noise[t] as number));
|
|
const series = full.slice(s, e + 1);
|
|
const row = buildTrialRow(
|
|
input({ sampleStart: grid[s]!, sampleEnd: grid[e]!, dailySeries: series })
|
|
);
|
|
rows.push(row);
|
|
oracle.push(alignOnGrid(grid, row.dailySeries, grid.slice(s, e + 1)));
|
|
});
|
|
const db = rows.map((r, i) => toDbRow(r, i + 1));
|
|
const { executor } = clusterExecutor(db);
|
|
|
|
// Act
|
|
const result = await clusterDeflatedSharpe(executor, { trialId: 1, sessionDates: grid });
|
|
const expected = effectiveIndependentTrials(oracle);
|
|
|
|
// Assert
|
|
expect(result.clusterSize).toBe(7);
|
|
expect(result.pairsUsed).toBe(expected.pairsUsed);
|
|
expect(result.pairsSkipped).toBe(expected.pairsSkipped);
|
|
expect(result.pairsUsed + result.pairsSkipped).toBe((7 * 6) / 2);
|
|
expect(result.meanCorrelation).not.toBeNull();
|
|
expect(Math.abs(result.meanCorrelation! - expected.meanCorrelation!)).toBeLessThan(1e-9);
|
|
expect(Math.abs(result.effectiveTrials - expected.nHat)).toBeLessThan(1e-9);
|
|
// [100,119] vs [0,9] are disjoint and must be skipped, never fabricated.
|
|
expect(result.pairsSkipped).toBeGreaterThan(0);
|
|
|
|
const directDsr = deflatedSharpeRatio({
|
|
sharpeUnann: rows[0]!.sharpeUnann,
|
|
nObs: rows[0]!.nObs,
|
|
skewness: rows[0]!.skewness,
|
|
kurtosis: rows[0]!.kurtosis,
|
|
nHat: result.effectiveTrials,
|
|
clusterSharpes: rows.map(r => r.sharpeUnann),
|
|
});
|
|
expect(result.dsr).not.toBeNull();
|
|
expect(Math.abs(result.dsr! - directDsr!.dsr)).toBeLessThan(1e-9);
|
|
expect(result.passesGate).toBe(passesDsrGate(directDsr!.dsr));
|
|
});
|
|
|
|
it('sparse explicit-date trials mixed with dense-grid trials match the date-aligned oracle', async () => {
|
|
// Arrange: two sparse signal trials omitting different dates, plus two dense trials.
|
|
const grid = businessDates('2021-03-01', 60);
|
|
const factor = gaussianSeries(21, 60, 0, 0.01);
|
|
const make = (seed: number) => {
|
|
const noise = gaussianSeries(seed, 60, 0, 0.01);
|
|
return factor.map((f, t) => 0.8 * f + 0.4 * (noise[t] as number));
|
|
};
|
|
const fullA = make(31);
|
|
const fullB = make(32);
|
|
const fullC = make(33);
|
|
const fullD = make(34);
|
|
const keepA = grid.map((_, i) => i).filter(i => i % 7 !== 3);
|
|
const keepB = grid.map((_, i) => i).filter(i => i >= 5 && i % 5 !== 1);
|
|
const datesA = keepA.map(i => grid[i]!);
|
|
const datesB = keepB.map(i => grid[i]!);
|
|
|
|
const rowA = buildTrialRow(
|
|
input({ sampleStart: grid[0]!, sampleEnd: grid[59]!, dailySeries: keepA.map(i => fullA[i]!) })
|
|
);
|
|
const rowB = buildTrialRow(
|
|
input({ sampleStart: grid[5]!, sampleEnd: grid[59]!, dailySeries: keepB.map(i => fullB[i]!) })
|
|
);
|
|
const rowC = buildTrialRow(
|
|
input({ sampleStart: grid[0]!, sampleEnd: grid[59]!, dailySeries: fullC })
|
|
);
|
|
const rowD = buildTrialRow(
|
|
input({ sampleStart: grid[10]!, sampleEnd: grid[49]!, dailySeries: fullD.slice(10, 50) })
|
|
);
|
|
const db = [toDbRow(rowA, 1), toDbRow(rowB, 2), toDbRow(rowC, 3), toDbRow(rowD, 4)];
|
|
const { executor } = clusterExecutor(db);
|
|
|
|
// Act
|
|
const result = await clusterDeflatedSharpe(executor, {
|
|
trialId: 3,
|
|
sessionDates: grid,
|
|
observationDatesByTrialId: new Map<number, readonly string[]>([
|
|
[1, datesA],
|
|
[2, datesB],
|
|
]),
|
|
});
|
|
const expected = effectiveIndependentTrials([
|
|
alignOnGrid(grid, rowA.dailySeries, datesA),
|
|
alignOnGrid(grid, rowB.dailySeries, datesB),
|
|
alignOnGrid(grid, rowC.dailySeries, grid),
|
|
alignOnGrid(grid, rowD.dailySeries, grid.slice(10, 50)),
|
|
]);
|
|
|
|
// Assert
|
|
expect(result.pairsUsed).toBe(6);
|
|
expect(expected.pairsUsed).toBe(6);
|
|
expect(Math.abs(result.meanCorrelation! - expected.meanCorrelation!)).toBeLessThan(1e-9);
|
|
expect(Math.abs(result.effectiveTrials - expected.nHat)).toBeLessThan(1e-9);
|
|
});
|
|
|
|
it('accounts for every pair exactly once when unaligned trials are mixed in', async () => {
|
|
// Arrange: 3 dense trials on the grid + 2 trials whose length does not match the grid.
|
|
const grid = businessDates('2022-01-03', 40);
|
|
const dense = [0, 1, 2].map(i =>
|
|
buildTrialRow(
|
|
input({ sampleStart: grid[0]!, sampleEnd: grid[39]!, dailySeries: gaussianSeries(50 + i, 40) })
|
|
)
|
|
);
|
|
const unaligned = [0, 1].map(i =>
|
|
buildTrialRow(
|
|
input({ sampleStart: grid[0]!, sampleEnd: grid[39]!, dailySeries: gaussianSeries(60 + i, 37) })
|
|
)
|
|
);
|
|
const db = [...dense, ...unaligned].map((r, i) => toDbRow(r, i + 1));
|
|
const { executor } = clusterExecutor(db);
|
|
|
|
// Act
|
|
const result = await clusterDeflatedSharpe(executor, { trialId: 4, sessionDates: grid });
|
|
|
|
// Assert: 3 dense pairs used; 3*2 + 1 = 7 pairs skipped; total C(5,2) = 10.
|
|
expect(result.clusterSize).toBe(5);
|
|
expect(result.pairsUsed).toBe(3);
|
|
expect(result.pairsSkipped).toBe(7);
|
|
const denseOnly = effectiveIndependentTrials(dense.map(r => r.dailySeries.map(Math.fround)));
|
|
expect(Math.abs(result.meanCorrelation! - denseOnly.meanCorrelation!)).toBeLessThan(1e-9);
|
|
const expectedNHat = Math.max(1, 1 + 4 * (1 - Math.max(0, denseOnly.meanCorrelation!)));
|
|
expect(Math.abs(result.effectiveTrials - expectedNHat)).toBeLessThan(1e-9);
|
|
});
|
|
|
|
it('is deterministic: repeated calls on the same retained inputs return identical results', async () => {
|
|
const grid = businessDates('2020-06-01', 50);
|
|
const rows = [0, 1, 2, 3].map(i =>
|
|
buildTrialRow(
|
|
input({
|
|
sampleStart: grid[i * 5]!,
|
|
sampleEnd: grid[49]!,
|
|
dailySeries: gaussianSeries(900 + i, 50 - i * 5),
|
|
})
|
|
)
|
|
);
|
|
const { executor } = clusterExecutor(rows.map((r, i) => toDbRow(r, i + 1)));
|
|
const first = await clusterDeflatedSharpe(executor, { trialId: 2, sessionDates: grid });
|
|
const second = await clusterDeflatedSharpe(executor, { trialId: 2, sessionDates: grid });
|
|
expect(second).toEqual(first);
|
|
});
|
|
|
|
it('rejects observation dates that disagree with the stored series or window before any math', async () => {
|
|
const grid = businessDates('2020-01-02', 10);
|
|
const row = buildTrialRow(
|
|
input({ sampleStart: grid[0]!, sampleEnd: grid[9]!, dailySeries: gaussianSeries(5, 10) })
|
|
);
|
|
const { executor } = clusterExecutor([toDbRow(row, 1), toDbRow(row, 2)]);
|
|
|
|
await expectCode(
|
|
() =>
|
|
clusterDeflatedSharpe(executor, {
|
|
trialId: 1,
|
|
observationDatesByTrialId: { '1': grid.slice(0, 9) },
|
|
}),
|
|
'INVALID_ROW'
|
|
);
|
|
await expectCode(
|
|
() =>
|
|
clusterDeflatedSharpe(executor, {
|
|
trialId: 1,
|
|
observationDatesByTrialId: { '1': businessDates('2019-12-30', 10) },
|
|
}),
|
|
'INVALID_SAMPLE_WINDOW'
|
|
);
|
|
await expectCode(
|
|
() =>
|
|
clusterDeflatedSharpe(executor, {
|
|
trialId: 1,
|
|
observationDatesByTrialId: new Map<number | string, readonly string[]>([
|
|
[1, grid],
|
|
['1', grid],
|
|
]),
|
|
}),
|
|
'INVALID_ROW'
|
|
);
|
|
await expectCode(
|
|
() => clusterDeflatedSharpe(executor, { trialId: 1, sessionDates: [grid[1]!, grid[0]!] }),
|
|
'INVALID_DATE'
|
|
);
|
|
});
|
|
});
|
|
|
|
describe('trial-ledger QA: writer re-fences pre-built rows and never interpolates values', () => {
|
|
it('re-applies the vault fence to a pre-built row whose window was edited after building', async () => {
|
|
const built = buildTrialRow(input({}));
|
|
const calls: unknown[] = [];
|
|
const executor: TrialLedgerExecutor = {
|
|
async query() {
|
|
calls.push(1);
|
|
return { rows: [] };
|
|
},
|
|
};
|
|
|
|
await expectCode(
|
|
() => recordTrials(executor, [built, { ...built, sampleEnd: VAULT_CUTOFF }]),
|
|
'VAULT_FENCE_VIOLATION'
|
|
);
|
|
await expectCode(
|
|
() => recordTrials(executor, [{ ...built, vaultCutoffDate: '2020-01-10' }]),
|
|
'VAULT_FENCE_VIOLATION'
|
|
);
|
|
await expectCode(
|
|
() => recordTrials(executor, [{ ...built, nObs: built.nObs + 1 }]),
|
|
'INVALID_ROW'
|
|
);
|
|
await expectCode(
|
|
() => recordTrials(executor, [{ ...built, sharpeUnann: built.sharpeUnann * 1.01 }]),
|
|
'INVALID_ROW'
|
|
);
|
|
expect(calls).toHaveLength(0);
|
|
});
|
|
|
|
it('keeps row order for mixed raw/pre-built batches and passes every value as a bind parameter', async () => {
|
|
// Arrange: hostile-looking but valid strings must never reach the SQL text.
|
|
const hashes = ['1', '2', '3'].map(c => c.repeat(64));
|
|
const prebuilt = buildTrialRow(input({ expressionHash: hashes[1]! }));
|
|
const rows = [
|
|
input({ expressionHash: hashes[0]!, sampleStart: '2020-01-03' }),
|
|
prebuilt,
|
|
input({ expressionHash: hashes[2]!, horizonBucket: 'position_10d_plus' }),
|
|
];
|
|
let seenText = '';
|
|
let seenParams: readonly unknown[] = [];
|
|
const executor: TrialLedgerExecutor = {
|
|
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
|
seenText = text;
|
|
seenParams = params ?? [];
|
|
return {
|
|
rows: [
|
|
{ trial_id: '7', created_at: '2025-04-01T10:00:00.000001Z' },
|
|
{ trial_id: '8', created_at: '2025-04-01T10:00:00.000001Z' },
|
|
{ trial_id: '9', created_at: '2025-04-01T10:00:00.000001Z' },
|
|
] as unknown as readonly Row[],
|
|
};
|
|
},
|
|
};
|
|
|
|
// Act
|
|
const receipts = await recordTrials(executor, rows);
|
|
|
|
// Assert
|
|
expect(receipts.map(r => r.trialId)).toEqual([7, 8, 9]);
|
|
expect(receipts[0]!.createdAt).toBe('2025-04-01T10:00:00.000001Z');
|
|
expect(seenParams).toHaveLength(42);
|
|
expect(seenParams[6]).toBe(hashes[0]);
|
|
expect(seenParams[14 + 6]).toBe(hashes[1]);
|
|
expect(seenParams[28 + 6]).toBe(hashes[2]);
|
|
expect(seenParams[7]).toBe('2020-01-03');
|
|
expect(seenParams[28 + 4]).toBe('position_10d_plus');
|
|
expect(seenParams[14 + 10]).toBe(prebuilt.sharpeUnann);
|
|
for (const h of hashes) {
|
|
expect(seenText.includes(h)).toBe(false);
|
|
}
|
|
expect(seenText.includes('operator')).toBe(false);
|
|
expect(seenText.includes('2020-01-')).toBe(false);
|
|
expect(seenText).toContain('$42::real[]');
|
|
expect(seenText.match(/INSERT INTO/g)).toHaveLength(1);
|
|
});
|
|
|
|
it('fails loudly when the database returns fewer receipts than rows inserted', async () => {
|
|
const executor: TrialLedgerExecutor = {
|
|
async query<Row = Record<string, unknown>>() {
|
|
return {
|
|
rows: [{ trial_id: '1', created_at: '2025-04-01T10:00:00.000000Z' }] as unknown as readonly Row[],
|
|
};
|
|
},
|
|
};
|
|
await expectCode(
|
|
() =>
|
|
recordTrials(executor, [
|
|
input({}),
|
|
input({ horizonBucket: 'position_10d_plus' }),
|
|
]),
|
|
'INVALID_ROW'
|
|
);
|
|
});
|
|
});
|
|
|
|
describe('trial-ledger QA: reader parses PostgreSQL wire shapes', () => {
|
|
it('parses text-form REAL[] arrays and rejects corrupted moments from the database', async () => {
|
|
const built = buildTrialRow(input({}));
|
|
const textRow = {
|
|
...toDbRow(built, 3),
|
|
daily_series: `{${built.dailySeries.map(v => Math.fround(v)).join(',')}}`,
|
|
};
|
|
const ok = await loadClusterTrials(clusterExecutor([textRow]).executor, {
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
expect(ok).toHaveLength(1);
|
|
expect(ok[0]!.dailySeries).toEqual(built.dailySeries.map(v => Math.fround(v)));
|
|
expect(ok[0]!.trialId).toBe(3);
|
|
|
|
await expectCode(
|
|
() =>
|
|
loadClusterTrials(clusterExecutor([{ ...textRow, sharpe_unann: 'NaN' }]).executor, {
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
}),
|
|
'INVALID_ROW'
|
|
);
|
|
await expectCode(
|
|
() =>
|
|
loadClusterTrials(clusterExecutor([{ ...textRow, daily_series: '{}' }]).executor, {
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
}),
|
|
'SERIES_TOO_SHORT'
|
|
);
|
|
});
|
|
});
|