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
6bbdb4049e
commit
bbc31b9cd7
6 changed files with 2467 additions and 1 deletions
27
libs/research/README.md
Normal file
27
libs/research/README.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# `@stock-bot/research`
|
||||
|
||||
Browser-safe research contracts, rolling 6-month Vault holdout fencing, and append-only `trial_ledger` accounting (`design/DATA-CONTRACTS.md`, `design/VALIDATION-AND-RIGOR.md`).
|
||||
|
||||
## `trial_ledger` Writer & Cluster N-hat-Deflated Sharpe Reader
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/trial-ledger` (`libs/research/src/trial-ledger.ts`). The module is dependency-free and browser-safe; PostgreSQL access is injected via `TrialLedgerExecutor` (`{ query(text, params) }`).
|
||||
|
||||
### API
|
||||
|
||||
- **`canonicalExpressionHash(input)`** — Returns a 64-character lowercase SHA-256 hex digest over the recursively ASCII-key-sorted compact JSON of `{ expression, params, universe, sampleStart, sampleEnd, horizon }`. Leading/trailing/internal whitespace in `expression` is collapsed, `undefined` object keys are omitted, `-0` is normalized to `0`, and non-JSON values (`NaN`, `±Infinity`, functions, symbols, `BigInt`, cycles) are rejected with `TrialLedgerError`.
|
||||
- **`buildTrialRow(input)`** — Pure validator and moment builder for a single `trial_ledger` row. Validates principal (`operator` or `agent:<uuid>`), optional UUIDs, schema enums (`stage`, `universeMarket`, `horizonBucket`), 64-hex `expressionHash`, strict `YYYY-MM-DD` dates, the exclusive Vault fence, and IEEE-754 `REAL` (float32) representability for every `dailySeries` element. Computes `{ nObs, sharpeUnann, skewness, kurtosis }` via `trialMoments` from `@stock-bot/calculations`.
|
||||
- **`recordTrials(executor, rows)`** — Validates every row upfront (sending zero SQL on any invalid row or batch > `MAX_TRIAL_BATCH_SIZE = 4681`) and appends the batch atomically in one parameterised multi-row `INSERT ... RETURNING trial_id, created_at`. Multi-horizon analyses (e.g. `1d`, `5d`, `20d`) record one row per horizon.
|
||||
- **`loadClusterTrials(executor, { universeMarket, horizonBucket, asOf? })`** — Loads a `(universe_market, horizon_bucket)` relatedness cluster ordered by `trial_id ASC` (backed by `idx_trial_ledger_cluster`), optionally capped at `created_at <= asOf`.
|
||||
- **`clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate? })`** — Loads the target trial and its relatedness cluster, aligns series without fabricating correlations across unalignable sample windows (shared `sampleStart` uses zero-copy left alignment; shared `sampleEnd` uses leading-`NaN` right alignment; unalignable windows are placed in disjoint `NaN`-padded blocks so `effectiveIndependentTrials` surfaces `pairsSkipped` and `meanCorrelation: null`), and computes `{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }`.
|
||||
|
||||
### Vault Holdout Fence Rule
|
||||
|
||||
Every row built by `buildTrialRow` or persisted by `recordTrials` requires an explicit `vaultCutoffDate` (`YYYY-MM-DD`) and delegates calendar validation and holdout enforcement to `applyVaultFence` in `libs/research/src/market-data-store.ts`. Any trial with `sampleEnd >= vaultCutoffDate` (or `sampleStart >= vaultCutoffDate`) is rejected with `TrialLedgerError('VAULT_FENCE_VIOLATION')` before any SQL is executed.
|
||||
|
||||
### Local In-Memory Benchmark
|
||||
|
||||
Fixed-seed (`20260403`) in-memory benchmark covering `200` trials × `5,000` daily observations (`1,000,000` observations total, `19,900` pairwise correlations) through `buildTrialRow` + `clusterDeflatedSharpe` with no PostgreSQL dependency:
|
||||
|
||||
- **Command:** `bun test libs/research/test/trial-ledger.test.ts`
|
||||
- **Workload:** 200 trials × 5,000 daily observations (seed `20260403`)
|
||||
- **Measured (Bun 1.2.16):** `elapsedMs = 732.35 ms`, `trialsPerSec = 273.1 trials/s` (`effectiveTrials = 171.85`, `dsr = 0.011891`)
|
||||
|
|
@ -12,7 +12,8 @@
|
|||
"./datasets": "./src/datasets.ts",
|
||||
"./market-data-store": "./src/market-data-store.ts",
|
||||
"./results": "./src/results.ts",
|
||||
"./strategy-api": "./src/strategy-api.ts"
|
||||
"./strategy-api": "./src/strategy-api.ts",
|
||||
"./trial-ledger": "./src/trial-ledger.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
export * from './market-data-store';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
1291
libs/research/src/trial-ledger.ts
Normal file
1291
libs/research/src/trial-ledger.ts
Normal file
File diff suppressed because it is too large
Load diff
766
libs/research/test/trial-ledger.test.ts
Normal file
766
libs/research/test/trial-ledger.test.ts
Normal file
|
|
@ -0,0 +1,766 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
deflatedSharpeRatio,
|
||||
effectiveIndependentTrials,
|
||||
trialMoments,
|
||||
} from '@stock-bot/calculations';
|
||||
import {
|
||||
HORIZON_BUCKETS,
|
||||
MAX_TRIAL_BATCH_SIZE,
|
||||
TRIAL_STAGES,
|
||||
TrialLedgerError,
|
||||
UNIVERSE_MARKETS,
|
||||
buildTrialRow,
|
||||
canonicalExpressionHash,
|
||||
clusterDeflatedSharpe,
|
||||
loadClusterTrials,
|
||||
recordTrials,
|
||||
type BuiltTrialRow,
|
||||
type CanonicalExpressionInput,
|
||||
type TrialLedgerErrorCode,
|
||||
type TrialLedgerExecutor,
|
||||
type TrialRowInput,
|
||||
} from '@stock-bot/research';
|
||||
import {
|
||||
HORIZON_BUCKETS as subpathHorizonBuckets,
|
||||
MAX_TRIAL_BATCH_SIZE as subpathMaxBatchSize,
|
||||
TRIAL_STAGES as subpathTrialStages,
|
||||
TrialLedgerError as SubpathTrialLedgerError,
|
||||
UNIVERSE_MARKETS as subpathUniverseMarkets,
|
||||
buildTrialRow as subpathBuildTrialRow,
|
||||
canonicalExpressionHash as subpathCanonicalExpressionHash,
|
||||
clusterDeflatedSharpe as subpathClusterDeflatedSharpe,
|
||||
loadClusterTrials as subpathLoadClusterTrials,
|
||||
recordTrials as subpathRecordTrials,
|
||||
} from '@stock-bot/research/trial-ledger';
|
||||
|
||||
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
||||
const VALID_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||
const VALID_HASH = 'a'.repeat(64);
|
||||
const VAULT_CUTOFF = '2025-05-01';
|
||||
|
||||
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 createGaussianSampler(seed: number): () => number {
|
||||
const next = createSeededRng(seed);
|
||||
let spare: number | null = null;
|
||||
return () => {
|
||||
if (spare !== null) {
|
||||
const value = spare;
|
||||
spare = null;
|
||||
return value;
|
||||
}
|
||||
let u = 0;
|
||||
let v = 0;
|
||||
while (u <= 1e-12) {
|
||||
u = next();
|
||||
}
|
||||
v = next();
|
||||
const mag = Math.sqrt(-2 * Math.log(u));
|
||||
const theta = 2 * Math.PI * v;
|
||||
spare = mag * Math.sin(theta);
|
||||
return mag * Math.cos(theta);
|
||||
};
|
||||
}
|
||||
|
||||
function makeSampleSeries(seed: number, length: number, mean = 0.0004, std = 0.01): number[] {
|
||||
const gauss = createGaussianSampler(seed);
|
||||
const out = new Array<number>(length);
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
out[i] = mean + std * gauss();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeValidInput(overrides: Partial<TrialRowInput> = {}): TrialRowInput {
|
||||
return {
|
||||
principalId: 'operator',
|
||||
campaignId: null,
|
||||
hypothesisId: null,
|
||||
stage: 'signal_ic',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: VALID_HASH,
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: [0.002, -0.001, 0.004, 0.0015, -0.0005, 0.003],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function expectLedgerErrorCode(fn: () => unknown, expectedCode: TrialLedgerErrorCode): void {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(TrialLedgerError);
|
||||
expect((error as TrialLedgerError).code).toBe(expectedCode);
|
||||
return;
|
||||
}
|
||||
throw new Error(`Expected TrialLedgerError(${expectedCode}), but call succeeded`);
|
||||
}
|
||||
|
||||
async function expectAsyncLedgerErrorCode(
|
||||
fn: () => Promise<unknown>,
|
||||
expectedCode: TrialLedgerErrorCode
|
||||
): Promise<void> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(TrialLedgerError);
|
||||
expect((error as TrialLedgerError).code).toBe(expectedCode);
|
||||
return;
|
||||
}
|
||||
throw new Error(`Expected async TrialLedgerError(${expectedCode}), but call succeeded`);
|
||||
}
|
||||
|
||||
interface FakeCall {
|
||||
readonly text: string;
|
||||
readonly params: readonly unknown[] | undefined;
|
||||
}
|
||||
|
||||
function createFakeExecutor(
|
||||
handler?: (text: string, params?: readonly unknown[]) => { rows: readonly Record<string, unknown>[] }
|
||||
): { executor: TrialLedgerExecutor; calls: FakeCall[] } {
|
||||
const calls: FakeCall[] = [];
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
calls.push({ text, params });
|
||||
if (handler !== undefined) {
|
||||
return handler(text, params) as { rows: readonly Row[] };
|
||||
}
|
||||
return { rows: [] };
|
||||
},
|
||||
};
|
||||
return { executor, calls };
|
||||
}
|
||||
|
||||
function builtRowToDbRow(
|
||||
row: BuiltTrialRow,
|
||||
trialId: number,
|
||||
createdAt = '2025-04-01T12:00:00.000Z'
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
trial_id: String(trialId),
|
||||
created_at: new Date(createdAt),
|
||||
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)),
|
||||
};
|
||||
}
|
||||
|
||||
describe('trial-ledger exports', () => {
|
||||
it('exposes identical runtime exports from package root and subpath', () => {
|
||||
expect(canonicalExpressionHash).toBe(subpathCanonicalExpressionHash);
|
||||
expect(buildTrialRow).toBe(subpathBuildTrialRow);
|
||||
expect(recordTrials).toBe(subpathRecordTrials);
|
||||
expect(loadClusterTrials).toBe(subpathLoadClusterTrials);
|
||||
expect(clusterDeflatedSharpe).toBe(subpathClusterDeflatedSharpe);
|
||||
expect(TrialLedgerError).toBe(SubpathTrialLedgerError);
|
||||
expect(TRIAL_STAGES).toBe(subpathTrialStages);
|
||||
expect(UNIVERSE_MARKETS).toBe(subpathUniverseMarkets);
|
||||
expect(HORIZON_BUCKETS).toBe(subpathHorizonBuckets);
|
||||
expect(MAX_TRIAL_BATCH_SIZE).toBe(subpathMaxBatchSize);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonicalExpressionHash', () => {
|
||||
const baseInput: CanonicalExpressionInput = {
|
||||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||||
params: { lookback: 20, winsor: 0.01, nested: { b: 2, a: 1 } },
|
||||
universe: { market: 'US_EQ', minAdvUsd: 5_000_000 },
|
||||
sampleStart: '2018-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
horizon: '5d',
|
||||
};
|
||||
|
||||
it('is invariant to top-level/nested key ordering, undefined keys, -0, and expression whitespace', () => {
|
||||
const h1 = canonicalExpressionHash(baseInput);
|
||||
expect(h1).toMatch(/^[0-9a-f]{64}$/);
|
||||
|
||||
const reordered: CanonicalExpressionInput = {
|
||||
horizon: '5d',
|
||||
sampleEnd: '2024-12-31',
|
||||
sampleStart: '2018-01-02',
|
||||
universe: { minAdvUsd: 5_000_000, market: 'US_EQ', ignored: undefined },
|
||||
params: { nested: { a: 1, b: 2, omitMe: undefined }, winsor: 0.01, lookback: 20 },
|
||||
expression: ' rank(ret_20d)\n\t - zscore(vol_20d) ',
|
||||
};
|
||||
expect(canonicalExpressionHash(reordered)).toBe(h1);
|
||||
|
||||
const negZero = canonicalExpressionHash({
|
||||
...baseInput,
|
||||
params: { zero: -0 },
|
||||
});
|
||||
const posZero = canonicalExpressionHash({
|
||||
...baseInput,
|
||||
params: { zero: 0 },
|
||||
});
|
||||
expect(negZero).toBe(posZero);
|
||||
});
|
||||
|
||||
it('changes when any field or nested value changes', () => {
|
||||
const base = canonicalExpressionHash(baseInput);
|
||||
expect(canonicalExpressionHash({ ...baseInput, expression: 'rank(ret_10d) - zscore(vol_20d)' })).not.toBe(base);
|
||||
expect(
|
||||
canonicalExpressionHash({
|
||||
...baseInput,
|
||||
params: { lookback: 21, winsor: 0.01, nested: { b: 2, a: 1 } },
|
||||
})
|
||||
).not.toBe(base);
|
||||
expect(
|
||||
canonicalExpressionHash({
|
||||
...baseInput,
|
||||
universe: { market: 'CA_EQ', minAdvUsd: 5_000_000 },
|
||||
})
|
||||
).not.toBe(base);
|
||||
expect(canonicalExpressionHash({ ...baseInput, sampleStart: '2018-01-03' })).not.toBe(base);
|
||||
expect(canonicalExpressionHash({ ...baseInput, sampleEnd: '2024-12-30' })).not.toBe(base);
|
||||
expect(canonicalExpressionHash({ ...baseInput, horizon: '20d' })).not.toBe(base);
|
||||
});
|
||||
|
||||
it('matches node:crypto SHA-256 bit-for-bit across ASCII, UTF-8, and block-boundary lengths', () => {
|
||||
const cases: CanonicalExpressionInput[] = [
|
||||
baseInput,
|
||||
{
|
||||
expression: 'α_momentum + 収益率 🚀',
|
||||
params: { label: 'café', tags: ['日本語', 'Ελληνικά'] },
|
||||
universe: 'US_EQ',
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2020-12-31',
|
||||
horizon: '1d',
|
||||
},
|
||||
// Exercise SHA-256 padding boundaries (55, 56, 63, 64, 65 bytes of payload variation)
|
||||
...[1, 8, 15, 16, 17, 63, 64, 65, 128].map(padLen => ({
|
||||
expression: 'x'.repeat(padLen),
|
||||
params: null,
|
||||
universe: 'FX',
|
||||
sampleStart: '2021-01-04',
|
||||
sampleEnd: '2021-06-30',
|
||||
horizon: 5,
|
||||
})),
|
||||
];
|
||||
|
||||
for (const input of cases) {
|
||||
const canonicalJson = JSON.stringify({
|
||||
expression: input.expression.trim().replace(/\s+/g, ' '),
|
||||
horizon: input.horizon,
|
||||
params:
|
||||
input.params !== null && typeof input.params === 'object' && !Array.isArray(input.params)
|
||||
? Object.fromEntries(
|
||||
Object.entries(input.params as Record<string, unknown>)
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
.map(([k, v]) => [
|
||||
k,
|
||||
v !== null && typeof v === 'object' && !Array.isArray(v)
|
||||
? Object.fromEntries(
|
||||
Object.entries(v as Record<string, unknown>).sort(([a], [b]) =>
|
||||
a < b ? -1 : a > b ? 1 : 0
|
||||
)
|
||||
)
|
||||
: v,
|
||||
])
|
||||
)
|
||||
: input.params,
|
||||
sampleEnd: input.sampleEnd,
|
||||
sampleStart: input.sampleStart,
|
||||
universe:
|
||||
input.universe !== null &&
|
||||
typeof input.universe === 'object' &&
|
||||
!Array.isArray(input.universe)
|
||||
? Object.fromEntries(
|
||||
Object.entries(input.universe as Record<string, unknown>).sort(([a], [b]) =>
|
||||
a < b ? -1 : a > b ? 1 : 0
|
||||
)
|
||||
)
|
||||
: input.universe,
|
||||
});
|
||||
|
||||
const expected = createHash('sha256').update(canonicalJson, 'utf8').digest('hex');
|
||||
expect(canonicalExpressionHash(input)).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects non-JSON values, cycles, malformed dates, and inverted sample windows', () => {
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, expression: ' ' }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: { bad: Number.NaN } }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: { bad: Number.POSITIVE_INFINITY } }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: { bad: 1n } }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: { bad: () => 1 } }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: { bad: Symbol('x') } }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: new Map([['a', 1]]) }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: [undefined] }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
|
||||
const cyclic: Record<string, unknown> = {};
|
||||
cyclic.self = cyclic;
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, params: cyclic }),
|
||||
'INVALID_EXPRESSION_INPUT'
|
||||
);
|
||||
|
||||
expectLedgerErrorCode(
|
||||
() => canonicalExpressionHash({ ...baseInput, sampleStart: '2026-02-29' }),
|
||||
'INVALID_DATE'
|
||||
);
|
||||
expectLedgerErrorCode(
|
||||
() =>
|
||||
canonicalExpressionHash({
|
||||
...baseInput,
|
||||
sampleStart: '2024-06-02',
|
||||
sampleEnd: '2024-06-01',
|
||||
}),
|
||||
'INVALID_SAMPLE_WINDOW'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildTrialRow', () => {
|
||||
it('computes moments identical to trialMoments and accepts operator and agent principals', () => {
|
||||
const series = [0.012, -0.004, 0.007, 0.003, -0.009, 0.015, 0.002, -0.001];
|
||||
const expected = trialMoments(series);
|
||||
expect(expected).not.toBeNull();
|
||||
|
||||
const row = buildTrialRow(
|
||||
makeValidInput({
|
||||
principalId: VALID_AGENT_PRINCIPAL,
|
||||
campaignId: VALID_UUID.toUpperCase(),
|
||||
hypothesisId: VALID_UUID,
|
||||
dailySeries: series,
|
||||
})
|
||||
);
|
||||
|
||||
expect(row.principalId).toBe(VALID_AGENT_PRINCIPAL);
|
||||
expect(row.campaignId).toBe(VALID_UUID);
|
||||
expect(row.hypothesisId).toBe(VALID_UUID);
|
||||
expect(row.nObs).toBe(expected!.nObs);
|
||||
expect(row.sharpeUnann).toBe(expected!.sharpeUnann);
|
||||
expect(row.skewness).toBe(expected!.skewness);
|
||||
expect(row.kurtosis).toBe(expected!.kurtosis);
|
||||
expect(Object.isFrozen(row)).toBe(true);
|
||||
expect(Object.isFrozen(row.dailySeries)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects every invalid field and vault fence violation with the expected typed error code', () => {
|
||||
const invalidCases: readonly [Partial<TrialRowInput>, TrialLedgerErrorCode][] = [
|
||||
[{ dailySeries: [] }, 'SERIES_TOO_SHORT'],
|
||||
[{ dailySeries: [0.01] }, 'SERIES_TOO_SHORT'],
|
||||
[{ dailySeries: [0.01, Number.NaN] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, Number.POSITIVE_INFINITY] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, Number.NEGATIVE_INFINITY] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, 1e40] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, 1e-50] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, 0.01, 0.01] }, 'ZERO_VARIANCE_SERIES'],
|
||||
[{ sampleStart: '2024-05-02', sampleEnd: '2024-05-01' }, 'INVALID_SAMPLE_WINDOW'],
|
||||
[{ sampleStart: '2026-02-29' }, 'INVALID_DATE'],
|
||||
[{ sampleEnd: '2024-12-31T00:00:00Z' }, 'INVALID_DATE'],
|
||||
[{ vaultCutoffDate: '2025-02-29' }, 'INVALID_DATE'],
|
||||
[{ principalId: 'service' }, 'INVALID_PRINCIPAL'],
|
||||
[{ principalId: '' }, 'INVALID_PRINCIPAL'],
|
||||
[{ principalId: 'agent:not-a-uuid' }, 'INVALID_PRINCIPAL'],
|
||||
[{ principalId: 'agent:00000000-0000-0000-0000-000000000000' }, 'INVALID_PRINCIPAL'],
|
||||
[{ principalId: 'agent:11111111-2222-4333-8444-55555555555A' }, 'INVALID_PRINCIPAL'],
|
||||
[{ campaignId: 'not-a-uuid' }, 'INVALID_UUID'],
|
||||
[{ hypothesisId: '1234' }, 'INVALID_UUID'],
|
||||
[{ stage: 'live_trade' as TrialRowInput['stage'] }, 'INVALID_STAGE'],
|
||||
[{ universeMarket: 'US' as TrialRowInput['universeMarket'] }, 'INVALID_UNIVERSE_MARKET'],
|
||||
[{ horizonBucket: 'weekly' as TrialRowInput['horizonBucket'] }, 'INVALID_HORIZON_BUCKET'],
|
||||
[{ expressionHash: 'A'.repeat(64) }, 'INVALID_EXPRESSION_HASH'],
|
||||
[{ expressionHash: 'a'.repeat(63) }, 'INVALID_EXPRESSION_HASH'],
|
||||
[{ expressionHash: 'g'.repeat(64) }, 'INVALID_EXPRESSION_HASH'],
|
||||
[{ sampleEnd: VAULT_CUTOFF }, 'VAULT_FENCE_VIOLATION'],
|
||||
[{ sampleEnd: '2025-05-02' }, 'VAULT_FENCE_VIOLATION'],
|
||||
[{ sampleStart: VAULT_CUTOFF, sampleEnd: '2025-06-01' }, 'VAULT_FENCE_VIOLATION'],
|
||||
];
|
||||
|
||||
for (const [overrides, expectedCode] of invalidCases) {
|
||||
expectLedgerErrorCode(() => buildTrialRow(makeValidInput(overrides)), expectedCode);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordTrials', () => {
|
||||
it('returns [] and issues zero SQL for an empty batch', async () => {
|
||||
const { executor, calls } = createFakeExecutor();
|
||||
const receipts = await recordTrials(executor, []);
|
||||
expect(receipts).toEqual([]);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('validates all rows upfront and sends zero SQL when any row is invalid or batch exceeds cap', async () => {
|
||||
const { executor, calls } = createFakeExecutor();
|
||||
|
||||
const invalidOverrides: readonly [Partial<TrialRowInput>, TrialLedgerErrorCode][] = [
|
||||
[{ dailySeries: [0.01] }, 'SERIES_TOO_SHORT'],
|
||||
[{ dailySeries: [0.01, Number.NaN] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, 1e40] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, 1e-50] }, 'INVALID_SERIES_VALUE'],
|
||||
[{ dailySeries: [0.01, 0.01] }, 'ZERO_VARIANCE_SERIES'],
|
||||
[{ sampleStart: '2024-06-02', sampleEnd: '2024-06-01' }, 'INVALID_SAMPLE_WINDOW'],
|
||||
[{ principalId: 'bad' }, 'INVALID_PRINCIPAL'],
|
||||
[{ expressionHash: 'bad' }, 'INVALID_EXPRESSION_HASH'],
|
||||
[{ sampleEnd: VAULT_CUTOFF }, 'VAULT_FENCE_VIOLATION'],
|
||||
];
|
||||
|
||||
for (const [overrides, expectedCode] of invalidOverrides) {
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() => recordTrials(executor, [makeValidInput(), makeValidInput(overrides)]),
|
||||
expectedCode
|
||||
);
|
||||
}
|
||||
|
||||
// Forged pre-built row violating vault fence must also be rejected with zero SQL.
|
||||
const validBuilt = buildTrialRow(makeValidInput());
|
||||
const forgedBuilt: BuiltTrialRow = { ...validBuilt, sampleEnd: VAULT_CUTOFF };
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() => recordTrials(executor, [validBuilt, forgedBuilt]),
|
||||
'VAULT_FENCE_VIOLATION'
|
||||
);
|
||||
|
||||
// Oversized batch rejected before any SQL.
|
||||
const oversized = new Array<BuiltTrialRow>(MAX_TRIAL_BATCH_SIZE + 1).fill(validBuilt);
|
||||
await expectAsyncLedgerErrorCode(() => recordTrials(executor, oversized), 'BATCH_TOO_LARGE');
|
||||
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('executes one parameterised multi-row INSERT for a 3-horizon batch', async () => {
|
||||
const { executor, calls } = createFakeExecutor(() => ({
|
||||
rows: [
|
||||
{ trial_id: '101', created_at: new Date('2025-04-01T10:00:00.000Z') },
|
||||
{ trial_id: '102', created_at: new Date('2025-04-01T10:00:00.001Z') },
|
||||
{ trial_id: '103', created_at: new Date('2025-04-01T10:00:00.002Z') },
|
||||
],
|
||||
}));
|
||||
|
||||
const horizons = ['1d', '5d', '20d'] as const;
|
||||
const batch = horizons.map((horizon, idx) =>
|
||||
buildTrialRow(
|
||||
makeValidInput({
|
||||
horizonBucket: horizon === '20d' ? 'position_10d_plus' : 'swing_1_10d',
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: 'rank(ret_20d)',
|
||||
params: { lookback: 20 },
|
||||
universe: 'US_EQ',
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
horizon,
|
||||
}),
|
||||
dailySeries: makeSampleSeries(100 + idx, 10),
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const receipts = await recordTrials(executor, batch);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.text).toContain('INSERT INTO trial_ledger');
|
||||
expect(calls[0]!.text).toContain('RETURNING trial_id, created_at');
|
||||
expect(calls[0]!.params).toHaveLength(3 * 14);
|
||||
expect(receipts).toEqual([
|
||||
{ trialId: 101, createdAt: '2025-04-01T10:00:00.000Z' },
|
||||
{ trialId: 102, createdAt: '2025-04-01T10:00:00.001Z' },
|
||||
{ trialId: 103, createdAt: '2025-04-01T10:00:00.002Z' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadClusterTrials and clusterDeflatedSharpe', () => {
|
||||
it('validates cluster query inputs before issuing SQL and supports asOf normalization', async () => {
|
||||
const { executor, calls } = createFakeExecutor(() => ({ rows: [] }));
|
||||
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() =>
|
||||
loadClusterTrials(executor, {
|
||||
universeMarket: 'EU_EQ' as 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
}),
|
||||
'INVALID_UNIVERSE_MARKET'
|
||||
);
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() =>
|
||||
loadClusterTrials(executor, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'daily' as 'swing_1_10d',
|
||||
}),
|
||||
'INVALID_HORIZON_BUCKET'
|
||||
);
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() =>
|
||||
loadClusterTrials(executor, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
asOf: '2025-04-01T12:00:00', // naive datetime rejected
|
||||
}),
|
||||
'INVALID_DATE'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
|
||||
await loadClusterTrials(executor, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
asOf: '2025-04-01',
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.text).toContain('AND created_at <= $3::timestamptz');
|
||||
expect(calls[0]!.params).toEqual(['US_EQ', 'swing_1_10d', '2025-04-01T23:59:59.999Z']);
|
||||
});
|
||||
|
||||
it('computes exact N-hat and DSR for same-window, prefix-overlap, suffix-overlap, and unalignable clusters', async () => {
|
||||
const baseSeries = makeSampleSeries(701, 100, 0.001, 0.01);
|
||||
const twinSeries = baseSeries.map((v, i) => v * 0.98 + (i % 2 === 0 ? 0.0005 : -0.0005));
|
||||
|
||||
// 1. Same-start, different-end (prefix overlap)
|
||||
const rowPrefixA = buildTrialRow(
|
||||
makeValidInput({
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2020-05-26',
|
||||
dailySeries: baseSeries,
|
||||
})
|
||||
);
|
||||
const rowPrefixB = buildTrialRow(
|
||||
makeValidInput({
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2020-04-15',
|
||||
dailySeries: twinSeries.slice(0, 70),
|
||||
})
|
||||
);
|
||||
|
||||
const dbPrefix = [builtRowToDbRow(rowPrefixA, 1), builtRowToDbRow(rowPrefixB, 2)];
|
||||
const prefixExec = createFakeExecutor(text =>
|
||||
text.includes('WHERE trial_id = $1') ? { rows: [dbPrefix[0]!] } : { rows: dbPrefix }
|
||||
);
|
||||
const prefixRes = await clusterDeflatedSharpe(prefixExec.executor, { trialId: 1 });
|
||||
expect(prefixRes.pairsUsed).toBe(1);
|
||||
expect(prefixRes.pairsSkipped).toBe(0);
|
||||
expect(prefixRes.meanCorrelation).not.toBeNull();
|
||||
expect(prefixRes.meanCorrelation!).toBeGreaterThan(0.95);
|
||||
expect(prefixRes.effectiveTrials).toBeLessThan(1.1);
|
||||
|
||||
// 2. Same-end, different-start (suffix overlap)
|
||||
const rowSuffixA = buildTrialRow(
|
||||
makeValidInput({
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2020-05-26',
|
||||
dailySeries: baseSeries,
|
||||
})
|
||||
);
|
||||
const rowSuffixB = buildTrialRow(
|
||||
makeValidInput({
|
||||
sampleStart: '2020-02-15',
|
||||
sampleEnd: '2020-05-26',
|
||||
dailySeries: twinSeries.slice(30),
|
||||
})
|
||||
);
|
||||
const dbSuffix = [builtRowToDbRow(rowSuffixA, 10), builtRowToDbRow(rowSuffixB, 11)];
|
||||
const suffixExec = createFakeExecutor(text =>
|
||||
text.includes('WHERE trial_id = $1') ? { rows: [dbSuffix[0]!] } : { rows: dbSuffix }
|
||||
);
|
||||
const suffixRes = await clusterDeflatedSharpe(suffixExec.executor, { trialId: 10 });
|
||||
expect(suffixRes.pairsUsed).toBe(1);
|
||||
expect(suffixRes.pairsSkipped).toBe(0);
|
||||
expect(suffixRes.meanCorrelation!).toBeGreaterThan(0.95);
|
||||
|
||||
// 3. Disjoint / staggered unalignable windows -> pairsSkipped > 0, meanCorrelation === null, effectiveTrials === clusterSize
|
||||
const rowDisjointA = buildTrialRow(
|
||||
makeValidInput({
|
||||
sampleStart: '2019-01-02',
|
||||
sampleEnd: '2020-12-31',
|
||||
dailySeries: baseSeries,
|
||||
})
|
||||
);
|
||||
const rowDisjointB = buildTrialRow(
|
||||
makeValidInput({
|
||||
sampleStart: '2021-01-04',
|
||||
sampleEnd: '2022-12-30',
|
||||
dailySeries: twinSeries,
|
||||
})
|
||||
);
|
||||
const dbDisjoint = [builtRowToDbRow(rowDisjointA, 20), builtRowToDbRow(rowDisjointB, 21)];
|
||||
const disjointExec = createFakeExecutor(text =>
|
||||
text.includes('WHERE trial_id = $1') ? { rows: [dbDisjoint[0]!] } : { rows: dbDisjoint }
|
||||
);
|
||||
const disjointRes = await clusterDeflatedSharpe(disjointExec.executor, { trialId: 20 });
|
||||
expect(disjointRes.pairsUsed).toBe(0);
|
||||
expect(disjointRes.pairsSkipped).toBe(1);
|
||||
expect(disjointRes.meanCorrelation).toBeNull();
|
||||
expect(disjointRes.effectiveTrials).toBe(2);
|
||||
|
||||
const directDsr = deflatedSharpeRatio({
|
||||
sharpeUnann: rowDisjointA.sharpeUnann,
|
||||
nObs: rowDisjointA.nObs,
|
||||
skewness: rowDisjointA.skewness,
|
||||
kurtosis: rowDisjointA.kurtosis,
|
||||
nHat: 2,
|
||||
clusterSharpes: [rowDisjointA.sharpeUnann, rowDisjointB.sharpeUnann],
|
||||
});
|
||||
expect(disjointRes.dsr).toBeCloseTo(directDsr!.dsr, 12);
|
||||
});
|
||||
|
||||
it('rejects invalid trialId with zero SQL and throws TRIAL_NOT_FOUND when absent or excluded by asOf', async () => {
|
||||
const { executor, calls } = createFakeExecutor(() => ({ rows: [] }));
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() => clusterDeflatedSharpe(executor, { trialId: 0 }),
|
||||
'INVALID_TRIAL_ID'
|
||||
);
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() => clusterDeflatedSharpe(executor, { trialId: -5 }),
|
||||
'INVALID_TRIAL_ID'
|
||||
);
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() => clusterDeflatedSharpe(executor, { trialId: 'abc' }),
|
||||
'INVALID_TRIAL_ID'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() => clusterDeflatedSharpe(executor, { trialId: 999 }),
|
||||
'TRIAL_NOT_FOUND'
|
||||
);
|
||||
|
||||
const row = buildTrialRow(makeValidInput());
|
||||
const dbRow = builtRowToDbRow(row, 42, '2025-04-10T00:00:00.000Z');
|
||||
const asOfExec = createFakeExecutor(text =>
|
||||
text.includes('WHERE trial_id = $1') ? { rows: [dbRow] } : { rows: [] }
|
||||
);
|
||||
await expectAsyncLedgerErrorCode(
|
||||
() =>
|
||||
clusterDeflatedSharpe(asOfExec.executor, {
|
||||
trialId: 42,
|
||||
asOf: '2025-04-01T00:00:00Z',
|
||||
}),
|
||||
'TRIAL_NOT_FOUND'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trial-ledger in-memory benchmark', () => {
|
||||
it('benchmarks 200 trials x 5,000 daily observations through buildTrialRow + clusterDeflatedSharpe', async () => {
|
||||
const trialCount = 200;
|
||||
const obsPerTrial = 5_000;
|
||||
const gauss = createGaussianSampler(20260403);
|
||||
|
||||
// Pre-generate common factor + idiosyncratic series outside the timed region.
|
||||
const common = new Array<number>(obsPerTrial);
|
||||
for (let t = 0; t < obsPerTrial; t += 1) {
|
||||
common[t] = 0.0003 + 0.008 * gauss();
|
||||
}
|
||||
const rawInputs: TrialRowInput[] = new Array(trialCount);
|
||||
for (let k = 0; k < trialCount; k += 1) {
|
||||
const series = new Array<number>(obsPerTrial);
|
||||
const loading = 0.35 + (k % 5) * 0.05;
|
||||
const noiseScale = Math.sqrt(1 - loading * loading) * 0.01;
|
||||
for (let t = 0; t < obsPerTrial; t += 1) {
|
||||
series[t] = loading * (common[t] as number) + noiseScale * gauss();
|
||||
}
|
||||
rawInputs[k] = {
|
||||
principalId: 'operator',
|
||||
stage: 'signal_ic',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: k.toString(16).padStart(64, '0'),
|
||||
sampleStart: '2005-01-03',
|
||||
sampleEnd: '2024-11-15',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: series,
|
||||
};
|
||||
}
|
||||
|
||||
const startNs = Bun.nanoseconds();
|
||||
|
||||
const builtRows: BuiltTrialRow[] = new Array(trialCount);
|
||||
const dbRows: Record<string, unknown>[] = new Array(trialCount);
|
||||
for (let k = 0; k < trialCount; k += 1) {
|
||||
const built = buildTrialRow(rawInputs[k] as TrialRowInput);
|
||||
builtRows[k] = built;
|
||||
dbRows[k] = {
|
||||
trial_id: String(k + 1),
|
||||
created_at: '2025-04-01T12:00:00.000Z',
|
||||
principal_id: built.principalId,
|
||||
campaign_id: built.campaignId,
|
||||
stage: built.stage,
|
||||
universe_market: built.universeMarket,
|
||||
horizon_bucket: built.horizonBucket,
|
||||
hypothesis_id: built.hypothesisId,
|
||||
expression_hash: built.expressionHash,
|
||||
sample_start: built.sampleStart,
|
||||
sample_end: built.sampleEnd,
|
||||
n_obs: built.nObs,
|
||||
sharpe_unann: built.sharpeUnann,
|
||||
skewness: built.skewness,
|
||||
kurtosis: built.kurtosis,
|
||||
daily_series: built.dailySeries,
|
||||
};
|
||||
}
|
||||
|
||||
const memExecutor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string) {
|
||||
if (text.includes('WHERE trial_id = $1')) {
|
||||
return { rows: [dbRows[0] as unknown as Row] };
|
||||
}
|
||||
return { rows: dbRows as unknown as Row[] };
|
||||
},
|
||||
};
|
||||
|
||||
const result = await clusterDeflatedSharpe(memExecutor, { trialId: 1 });
|
||||
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
|
||||
const trialsPerSec = trialCount / (elapsedMs / 1000);
|
||||
|
||||
process.stdout.write(
|
||||
`[trial-ledger benchmark] trials=${trialCount} obsPerTrial=${obsPerTrial} elapsedMs=${elapsedMs.toFixed(2)} trialsPerSec=${trialsPerSec.toFixed(1)} effectiveTrials=${result.effectiveTrials.toFixed(2)} dsr=${(result.dsr ?? Number.NaN).toFixed(6)}\n`
|
||||
);
|
||||
|
||||
expect(result.clusterSize).toBe(trialCount);
|
||||
expect(Number.isFinite(elapsedMs)).toBe(true);
|
||||
expect(Number.isFinite(trialsPerSec)).toBe(true);
|
||||
expect(result.effectiveTrials).toBeGreaterThan(1);
|
||||
expect(result.effectiveTrials).toBeLessThan(trialCount);
|
||||
expect(result.dsr).not.toBeNull();
|
||||
|
||||
// Cross-check against direct calculations on the same cluster.
|
||||
const directEff = effectiveIndependentTrials(builtRows.map(r => r.dailySeries));
|
||||
expect(result.effectiveTrials).toBeCloseTo(directEff.nHat, 12);
|
||||
});
|
||||
});
|
||||
380
test/postgres/trial-ledger-writer.test.ts
Normal file
380
test/postgres/trial-ledger-writer.test.ts
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { deflatedSharpeRatio, effectiveIndependentTrials } from '@stock-bot/calculations';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import {
|
||||
TrialLedgerError,
|
||||
buildTrialRow,
|
||||
canonicalExpressionHash,
|
||||
clusterDeflatedSharpe,
|
||||
loadClusterTrials,
|
||||
recordTrials,
|
||||
type TrialRowInput,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('trial-ledger-writer-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
|
||||
const VAULT_CUTOFF = '2025-05-01';
|
||||
|
||||
const cleanup: (() => Promise<void> | void)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function createIsolatedFixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
|
||||
// Bootstrap pre-additive tables needed by the research migration track.
|
||||
for (const filename of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
]) {
|
||||
await pool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
|
||||
}
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({
|
||||
connect: () => pool.connect(),
|
||||
}),
|
||||
});
|
||||
|
||||
await runPostgresMigrations(postgres, { track: 'research' });
|
||||
|
||||
return { pool, schema, postgres };
|
||||
}
|
||||
|
||||
async function expectPgErrorCode(
|
||||
operation: Promise<unknown>,
|
||||
expectedCode: string,
|
||||
messagePattern?: RegExp
|
||||
): Promise<void> {
|
||||
try {
|
||||
await operation;
|
||||
} catch (error) {
|
||||
const pgError = error as { code?: string; message?: string } | null;
|
||||
expect(pgError?.code).toBe(expectedCode);
|
||||
if (messagePattern) {
|
||||
expect(pgError?.message ?? '').toMatch(messagePattern);
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`);
|
||||
}
|
||||
|
||||
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 createGaussianSampler(seed: number): () => number {
|
||||
const next = createSeededRng(seed);
|
||||
let spare: number | null = null;
|
||||
return () => {
|
||||
if (spare !== null) {
|
||||
const value = spare;
|
||||
spare = null;
|
||||
return value;
|
||||
}
|
||||
let u = 0;
|
||||
while (u <= 1e-12) {
|
||||
u = next();
|
||||
}
|
||||
const v = next();
|
||||
const mag = Math.sqrt(-2 * Math.log(u));
|
||||
const theta = 2 * Math.PI * v;
|
||||
spare = mag * Math.sin(theta);
|
||||
return mag * Math.cos(theta);
|
||||
};
|
||||
}
|
||||
|
||||
function makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] {
|
||||
const gauss = createGaussianSampler(seed);
|
||||
const out = new Array<number>(length);
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
out[i] = mean + std * gauss();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', () => {
|
||||
test('3-horizon recordTrials inserts 3 ascending rows, round-trips REAL series, rejects bad batch atomically, and preserves immutability triggers', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const horizons = [
|
||||
{ label: '1d', bucket: 'swing_1_10d' as const, seed: 1001 },
|
||||
{ label: '5d', bucket: 'swing_1_10d' as const, seed: 1002 },
|
||||
{ label: '20d', bucket: 'position_10d_plus' as const, seed: 1003 },
|
||||
];
|
||||
|
||||
const rows = horizons.map(h =>
|
||||
buildTrialRow({
|
||||
principalId: 'operator',
|
||||
stage: 'signal_ic',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: h.bucket,
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||||
params: { lookback: 20 },
|
||||
universe: 'US_EQ',
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
horizon: h.label,
|
||||
}),
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(h.seed, 25),
|
||||
})
|
||||
);
|
||||
|
||||
const receipts = await recordTrials(f.pool, rows);
|
||||
expect(receipts).toHaveLength(3);
|
||||
expect(receipts[0]!.trialId).toBeLessThan(receipts[1]!.trialId);
|
||||
expect(receipts[1]!.trialId).toBeLessThan(receipts[2]!.trialId);
|
||||
|
||||
const swingRows = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
const positionRows = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'position_10d_plus',
|
||||
});
|
||||
expect(swingRows).toHaveLength(2);
|
||||
expect(positionRows).toHaveLength(1);
|
||||
|
||||
// Verify daily_series round-trips within IEEE-754 REAL precision.
|
||||
for (let i = 0; i < rows[0]!.dailySeries.length; i += 1) {
|
||||
expect(swingRows[0]!.dailySeries[i]).toBe(Math.fround(rows[0]!.dailySeries[i]!));
|
||||
}
|
||||
|
||||
// Batch with one invalid row throws TrialLedgerError and inserts 0 additional rows.
|
||||
const badBatch: TrialRowInput[] = [
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'event_study',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: 'b'.repeat(64),
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(2001, 10),
|
||||
},
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'event_study',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: 'c'.repeat(64),
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: VAULT_CUTOFF, // violates exclusive vault fence
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(2002, 10),
|
||||
},
|
||||
];
|
||||
|
||||
try {
|
||||
await recordTrials(f.pool, badBatch);
|
||||
throw new Error('Expected VAULT_FENCE_VIOLATION');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(TrialLedgerError);
|
||||
expect((error as TrialLedgerError).code).toBe('VAULT_FENCE_VIOLATION');
|
||||
}
|
||||
|
||||
const caRows = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
expect(caRows).toHaveLength(0);
|
||||
|
||||
// Existing append-only triggers still block UPDATE, DELETE, and TRUNCATE.
|
||||
const expectedMsg = /Retained research evidence cannot be rewritten or deleted/;
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('UPDATE trial_ledger SET n_obs = 999'),
|
||||
'23514',
|
||||
expectedMsg
|
||||
);
|
||||
await expectPgErrorCode(f.pool.query('DELETE FROM trial_ledger'), '23514', expectedMsg);
|
||||
await expectPgErrorCode(f.pool.query('TRUNCATE trial_ledger'), '23514', expectedMsg);
|
||||
|
||||
const totalCount = (await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0]
|
||||
.c as number;
|
||||
expect(totalCount).toBe(3);
|
||||
});
|
||||
|
||||
test('computes N-hat and DSR end-to-end through PostgreSQL for near-duplicate vs independent clusters, cluster isolation, and asOf', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const nObs = 500;
|
||||
const clusterK = 12;
|
||||
|
||||
// 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97
|
||||
const factorGauss = createGaussianSampler(9001);
|
||||
const baseFactor = new Array<number>(nObs);
|
||||
for (let t = 0; t < nObs; t += 1) {
|
||||
baseFactor[t] = 0.0008 + 0.01 * factorGauss();
|
||||
}
|
||||
const noiseGauss = createGaussianSampler(9002);
|
||||
const nearDupRows = new Array<TrialRowInput>(clusterK);
|
||||
const loading = Math.sqrt(0.97);
|
||||
const noiseWeight = Math.sqrt(1 - 0.97);
|
||||
for (let k = 0; k < clusterK; k += 1) {
|
||||
const series = new Array<number>(nObs);
|
||||
for (let t = 0; t < nObs; t += 1) {
|
||||
series[t] = loading * (baseFactor[t] as number) + noiseWeight * 0.01 * noiseGauss();
|
||||
}
|
||||
nearDupRows[k] = {
|
||||
principalId: 'operator',
|
||||
stage: 'screen',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: `dup_signal_${k}`,
|
||||
params: { k },
|
||||
universe: 'US_EQ',
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
horizon: '5d',
|
||||
}),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: series,
|
||||
};
|
||||
}
|
||||
|
||||
const nearDupReceipts = await recordTrials(f.pool, nearDupRows);
|
||||
|
||||
// 2. Independent cluster in (CA_EQ, swing_1_10d) — also tests cluster isolation from US_EQ!
|
||||
const indepRows = new Array<TrialRowInput>(clusterK);
|
||||
for (let k = 0; k < clusterK; k += 1) {
|
||||
indepRows[k] = {
|
||||
principalId: 'operator',
|
||||
stage: 'screen',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: `indep_signal_${k}`,
|
||||
params: { k },
|
||||
universe: 'CA_EQ',
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
horizon: '5d',
|
||||
}),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01),
|
||||
};
|
||||
}
|
||||
const indepReceipts = await recordTrials(f.pool, indepRows);
|
||||
|
||||
// 3. Another cluster in (US_EQ, position_10d_plus) to verify horizon_bucket isolation.
|
||||
await recordTrials(f.pool, [
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'engine_backtest',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'position_10d_plus',
|
||||
expressionHash: 'd'.repeat(64),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(7777, nObs),
|
||||
},
|
||||
]);
|
||||
|
||||
const nearDupDsr = await clusterDeflatedSharpe(f.pool, {
|
||||
trialId: nearDupReceipts[0]!.trialId,
|
||||
});
|
||||
expect(nearDupDsr.clusterSize).toBe(clusterK);
|
||||
expect(nearDupDsr.meanCorrelation).not.toBeNull();
|
||||
expect(nearDupDsr.meanCorrelation!).toBeGreaterThan(0.95);
|
||||
expect(nearDupDsr.effectiveTrials).toBeLessThan(clusterK * 0.25);
|
||||
|
||||
const indepDsr = await clusterDeflatedSharpe(f.pool, {
|
||||
trialId: indepReceipts[0]!.trialId,
|
||||
});
|
||||
expect(indepDsr.clusterSize).toBe(clusterK);
|
||||
expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85);
|
||||
expect(indepDsr.effectiveTrials).toBeLessThanOrEqual(clusterK);
|
||||
|
||||
// Direct deflatedSharpeRatio parity within 1e-9 on the persisted cluster rows.
|
||||
const persistedNearDup = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
const directEff = effectiveIndependentTrials(persistedNearDup.map(r => r.dailySeries));
|
||||
const directDsr = deflatedSharpeRatio({
|
||||
sharpeUnann: persistedNearDup[0]!.sharpeUnann,
|
||||
nObs: persistedNearDup[0]!.nObs,
|
||||
skewness: persistedNearDup[0]!.skewness,
|
||||
kurtosis: persistedNearDup[0]!.kurtosis,
|
||||
nHat: directEff.nHat,
|
||||
clusterSharpes: persistedNearDup.map(r => r.sharpeUnann),
|
||||
});
|
||||
expect(directDsr).not.toBeNull();
|
||||
expect(Math.abs((nearDupDsr.dsr ?? Number.NaN) - directDsr!.dsr)).toBeLessThan(1e-9);
|
||||
|
||||
// asOf filtering: record a newer row after a brief delay and verify asOf excludes it.
|
||||
const cutoffTs = nearDupReceipts[clusterK - 1]!.createdAt;
|
||||
await Bun.sleep(15);
|
||||
await recordTrials(f.pool, [
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'screen',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: 'e'.repeat(64),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(9999, nObs),
|
||||
},
|
||||
]);
|
||||
|
||||
const fullCluster = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
const asOfCluster = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
asOf: cutoffTs,
|
||||
});
|
||||
expect(fullCluster).toHaveLength(clusterK + 1);
|
||||
expect(asOfCluster).toHaveLength(clusterK);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue