From 744255c09690c84289d305263d4dda3d388730ee Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 03:09:41 -0500 Subject: [PATCH] =?UTF-8?q?T-84:=20M1.3d=20=E2=80=94=20`trial=5Fledger`=20?= =?UTF-8?q?writer=20+=20cluster=20N=CC=82-deflated=20Sharpe=20reader=20in?= =?UTF-8?q?=20`@stock-bot/research`=20(append=20one=20row=20per=20horizon,?= =?UTF-8?q?=20vault-fenced=20`sample=5Fend`,=20PostgreSQL=20integration=20?= =?UTF-8?q?test=20+=20local=20benchmark)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 6 +- libs/research/src/trial-ledger.ts | 38 ++++++++-- libs/research/test/trial-ledger.test.ts | 99 +++++++++++++++++++++++++ 3 files changed, 134 insertions(+), 9 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index a0d1a32a..541cc0cc 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -12,7 +12,7 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/trial-ledger` - **`buildTrialRow(input)`** — Pure validator and moment builder for a single `trial_ledger` row. Validates principal (`operator` or `agent:`), 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 and non-zero variance at `REAL` storage precision for `dailySeries`. Computes `{ nObs, sharpeUnann, skewness, kurtosis }` via `trialMoments` from `@stock-bot/calculations`. - **`recordTrials(executor, rows)`** — Validates every row upfront (re-verifying that pre-built rows' moments match their `dailySeries`, 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` while preserving PostgreSQL's 6-digit microsecond UTC precision across `Z` and explicit `±HH:MM` offsets. -- **`clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate?, sessionDates?, observationDatesByTrialId? })`** — Loads the target trial and its relatedness cluster and computes `{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }`. Index alignment requires a proven shared session grid (`sessionDates` where the trial's series length matches the session count in `[sampleStart, sampleEnd]`) or explicit per-trial `observationDatesByTrialId` (for sparse `signal_ic` / `event_study` series); trials without proven alignment are counted in `pairsSkipped` without inventing correlations. Cross-window correlations are computed directly within and across alignment groups without materializing dense `NaN` padding. +- **`clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate?, sessionDates?, observationDatesByTrialId? })`** — Loads the target trial and its relatedness cluster and computes `{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }`. Index alignment requires a proven shared session grid (`sessionDates` covering the trial's full `[sampleStart, sampleEnd]` range where the series length matches the session count in `[sampleStart, sampleEnd]`) or explicit per-trial `observationDatesByTrialId` (for sparse `signal_ic` / `event_study` series); trials without proven alignment or pairs with constant overlap slices are counted in `pairsSkipped` without inventing correlations. Cross-window correlations are computed directly within and across alignment groups without materializing dense `NaN` padding. ### Vault Holdout Fence Rule @@ -25,5 +25,5 @@ Fixed-seed (`20260403`) in-memory benchmark covering `200` trials × `5,000` dai - **Command:** `bun test libs/research/test/trial-ledger.test.ts` - **Workload:** 200 trials × 5,000 daily observations (seed `20260403`), shared 5,000-session grid and 200-window staggered rolling grid (shifted by 1 session per trial across 5,199 sessions) - **Measured (Bun 1.2.16):** - - **Shared window (`buildTrialRow` + `clusterDeflatedSharpe`):** `elapsedMs = 732.33 ms`, `trialsPerSec = 273.1 trials/s` (`effectiveTrials = 171.85`, `dsr = 0.011891`) - - **Staggered rolling windows (`clusterDeflatedSharpe`, 200 distinct windows, `19,900` overlapping pairs, zero `NaN` padding):** `staggeredElapsedMs = 509.45 ms`, `staggeredTrialsPerSec = 392.6 trials/s` + - **Shared window (`buildTrialRow` + `clusterDeflatedSharpe`):** `elapsedMs = 710.17 ms`, `trialsPerSec = 281.6 trials/s` (`effectiveTrials = 171.85`, `dsr = 0.011891`) + - **Staggered rolling windows (`clusterDeflatedSharpe`, 200 distinct windows, `19,900` overlapping pairs, zero `NaN` padding):** `staggeredElapsedMs = 508.77 ms`, `staggeredTrialsPerSec = 393.1 trials/s` diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts index 727b2569..bc89a636 100644 --- a/libs/research/src/trial-ledger.ts +++ b/libs/research/src/trial-ledger.ts @@ -157,8 +157,10 @@ export interface ClusterDeflatedSharpeQuery { readonly dsrGate?: number; /** * Optional strictly-ascending `YYYY-MM-DD` trading calendar for the cluster's market. - * A trial without explicit observation dates is index-aligned only when its `dailySeries` - * length exactly matches the number of sessions in `[sampleStart, sampleEnd]`. + * 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[]; /** @@ -1047,20 +1049,39 @@ function pearsonSliceCorrelation( ((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 da = (aVals[offsetA + t] as number) - meanA; - const db = (bVals[offsetB + t] as number) - meanB; + 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 (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) { + if ( + allEqualA || + allEqualB || + !Number.isFinite(varA) || + !Number.isFinite(varB) || + varA <= 0 || + varB <= 0 + ) { return null; } const denom = Math.sqrt(varA * varB); @@ -1238,7 +1259,12 @@ function computeClusterEffectiveTrials( continue; } - if (sessionDates !== undefined) { + 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) { diff --git a/libs/research/test/trial-ledger.test.ts b/libs/research/test/trial-ledger.test.ts index a85099d5..7c44b86d 100644 --- a/libs/research/test/trial-ledger.test.ts +++ b/libs/research/test/trial-ledger.test.ts @@ -808,6 +808,105 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => { expect(sparseAlignedRes.meanCorrelation).not.toBeNull(); expect(sparseAlignedRes.meanCorrelation!).toBeCloseTo(-1.0, 6); expect(sparseAlignedRes.effectiveTrials).toBe(2); + + // 5. Regression: clipped sessionDates calendar whose count matches a sparse older trial. + // Calendar covers only Wed–Fri; older trial spans Tue–Fri and skipped Wed (3 entries). + const wedToFri = ['2024-01-03', '2024-01-04', '2024-01-05']; + const targetWedFri = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: '2024-01-03', + sampleEnd: '2024-01-05', + dailySeries: [0.01, -0.02, 0.03], + }) + ); + const olderSparseTueFri = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: '2024-01-02', + sampleEnd: '2024-01-05', + dailySeries: [0.01, -0.02, 0.03], + }) + ); + const dbClippedStart = [ + builtRowToDbRow(targetWedFri, 40), + builtRowToDbRow(olderSparseTueFri, 41), + ]; + const clippedStartExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') + ? { rows: [dbClippedStart[0]!] } + : { rows: dbClippedStart } + ); + const clippedStartRes = await clusterDeflatedSharpe(clippedStartExec.executor, { + trialId: 40, + sessionDates: wedToFri, + }); + expect(clippedStartRes.pairsUsed).toBe(0); + expect(clippedStartRes.pairsSkipped).toBe(1); + expect(clippedStartRes.meanCorrelation).toBeNull(); + expect(clippedStartRes.effectiveTrials).toBe(2); + + // Symmetric regression: calendar clipped at the end (Tue–Thu) vs a Tue–Fri sparse trial. + const tueToThu = ['2024-01-02', '2024-01-03', '2024-01-04']; + const targetTueThu = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: '2024-01-02', + sampleEnd: '2024-01-04', + dailySeries: [0.01, -0.02, 0.03], + }) + ); + const dbClippedEnd = [ + builtRowToDbRow(targetTueThu, 42), + builtRowToDbRow(olderSparseTueFri, 43), + ]; + const clippedEndExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbClippedEnd[0]!] } : { rows: dbClippedEnd } + ); + const clippedEndRes = await clusterDeflatedSharpe(clippedEndExec.executor, { + trialId: 42, + sessionDates: tueToThu, + }); + expect(clippedEndRes.pairsUsed).toBe(0); + expect(clippedEndRes.pairsSkipped).toBe(1); + expect(clippedEndRes.meanCorrelation).toBeNull(); + expect(clippedEndRes.effectiveTrials).toBe(2); + + // 6. Regression: cross-window Pearson skips pairs whose overlap slice is constant even when + // floating-point rounding in the prefix-sum mean leaves identical nonzero residuals. + const constOverlapA = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: weekDates[0]!, + sampleEnd: weekDates[3]!, + dailySeries: [0, 0.1, 0.1, 0.1], + }) + ); + const constOverlapB = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: weekDates[1]!, + sampleEnd: weekDates[4]!, + dailySeries: [0.1, 0.1, 0.1, -0.1], + }) + ); + const dbConstOverlap = [ + builtRowToDbRow(constOverlapA, 50), + builtRowToDbRow(constOverlapB, 51), + ]; + const constOverlapExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') + ? { rows: [dbConstOverlap[0]!] } + : { rows: dbConstOverlap } + ); + const constOverlapRes = await clusterDeflatedSharpe(constOverlapExec.executor, { + trialId: 50, + sessionDates: weekDates, + }); + expect(constOverlapRes.pairsUsed).toBe(0); + expect(constOverlapRes.pairsSkipped).toBe(1); + expect(constOverlapRes.meanCorrelation).toBeNull(); + expect(constOverlapRes.effectiveTrials).toBe(2); }); it('rejects invalid trialId with zero SQL and throws TRIAL_NOT_FOUND when absent or excluded by asOf', async () => {