T-85: M1.4c — analyzeSignal / runEventStudy study runners in @stock-bot/research: analyzer math + automatic trial_ledger write + cluster N̂-deflated Sharpe (no new dependencies)
This commit is contained in:
parent
17808bbda4
commit
45a98d309e
7 changed files with 2033 additions and 0 deletions
|
|
@ -27,3 +27,49 @@ Fixed-seed (`20260403`) in-memory benchmark covering `200` trials × `5,000` dai
|
|||
- **Measured (Bun 1.2.16):**
|
||||
- **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`
|
||||
|
||||
## Signal Study Runners
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/signal-study` (`libs/research/src/signal-study.ts`). Browser-safe and dependency-free; database access is injected via `TrialLedgerExecutor`.
|
||||
|
||||
### API & Write-Before-Return Guarantee
|
||||
|
||||
- **`analyzeSignal(executor, request)`** — Validates inputs upfront, runs `analyzeSignalPanel` under the exclusive `vaultCutoffDate` fence, appends one `stage = 'signal_ic'` row to `trial_ledger`, and computes `clusterDeflatedSharpe` for the newly recorded trial.
|
||||
- **`runEventStudy(executor, request)`** — Validates inputs upfront, fences out events whose event date or post-event window end (`sessionDates[dayIndex + postDays]`) falls on or after `vaultCutoffDate`, runs `eventStudy`, appends one `stage = 'event_study'` row to `trial_ledger`, and computes `clusterDeflatedSharpe`.
|
||||
- **Write-before-return & partial-failure semantics:**
|
||||
- If `recordTrials` (`INSERT`) fails, the error propagates directly and no analysis or study result is returned.
|
||||
- If `recordTrials` succeeds but `clusterDeflatedSharpe` (`SELECT`) fails, the runner throws `SignalStudyError` with `code: 'dsr_read_failed'`, exposing the already-written `trialId` and original `cause`. The `INSERT` is never retried.
|
||||
- Validation errors and `status: 'insufficient_data'` paths (too few observations, `below_min_events`, `too_few_event_dates`, or zero-variance series at `REAL` precision) issue **zero** SQL queries.
|
||||
|
||||
### Logged Series by Stage
|
||||
|
||||
| Runner | `trial_ledger.stage` | Logged `daily_series` | Observation Dates |
|
||||
| --- | --- | --- | --- |
|
||||
| `analyzeSignal` (default `ledgerSeries: 'rank_ic'`) | `'signal_ic'` | `analysis.rankIcSeries` | `analysis.dates` |
|
||||
| `analyzeSignal` (`ledgerSeries: 'quantile_spread'`) | `'signal_ic'` | `analysis.quantiles.spreadSeries` | `analysis.quantiles.dates` |
|
||||
| `runEventStudy` | `'event_study'` | `study.clustered.meanCars` | `study.clustered.dates` |
|
||||
|
||||
### Vault Holdout Behavior
|
||||
|
||||
- **`analyzeSignal`** delegates to `analyzeSignalPanel`'s exclusive `vaultCutoffDate` fence, excluding all cross-sections with `date >= vaultCutoffDate` (reported in `analysis.diagnostics.vaultExcludedDates`) so `sampleEnd < vaultCutoffDate`. Callers assembling pre-computed forward-return panels remain responsible for ensuring forward-return horizons do not consume post-cutoff prices.
|
||||
- **`runEventStudy`** drops every event where `sessionDates[dayIndex] >= vaultCutoffDate` or `sessionDates[dayIndex + postDays] >= vaultCutoffDate` without mutating caller inputs, reporting the count in `vaultExcludedEvents`.
|
||||
|
||||
### `SignalStudyError` Codes
|
||||
|
||||
| Code | Meaning |
|
||||
| --- | --- |
|
||||
| `'invalid_request'` | Invalid executor, request envelope, expression, principal, UUID, market, or horizon bucket (0 SQL queries) |
|
||||
| `'empty_panel'` | Empty `panel` or empty `input.sessionDates` (0 SQL queries) |
|
||||
| `'invalid_date'` | Malformed or non-calendar `YYYY-MM-DD` date in `vaultCutoffDate`, panel, or `sessionDates` (0 SQL queries) |
|
||||
| `'unsorted_dates'` | Panel or `sessionDates` not strictly ascending (0 SQL queries) |
|
||||
| `'duplicate_date'` | Duplicate date in panel or `sessionDates` (0 SQL queries) |
|
||||
| `'invalid_panel'` | Malformed cross-section vectors/IDs, return arrays, or event descriptors (0 SQL queries) |
|
||||
| `'invalid_option'` | Invalid `ledgerSeries`, `dsrGate`, or analyzer/event-study options (0 SQL queries) |
|
||||
| `'dsr_read_failed'` | Trial row was inserted (`error.trialId` is set), but `clusterDeflatedSharpe` failed (`error.cause` holds the original error) |
|
||||
|
||||
### Local In-Memory Benchmark (`analyzeSignal`)
|
||||
|
||||
Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` business dates × `3,000` listings (`15,120,000` observations) with an in-memory `TrialLedgerExecutor`:
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-signal-study.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 1691.13 ms`, `rowsPerSec = 8,940,793 rows/s` (`2,980 dates/s`, `nObs = 5040`, `meanRankIc = 0.057294`, `recencyGatePassed = true`)
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
"./datasets": "./src/datasets.ts",
|
||||
"./market-data-store": "./src/market-data-store.ts",
|
||||
"./results": "./src/results.ts",
|
||||
"./signal-study": "./src/signal-study.ts",
|
||||
"./strategy-api": "./src/strategy-api.ts",
|
||||
"./trial-ledger": "./src/trial-ledger.ts"
|
||||
},
|
||||
|
|
|
|||
228
libs/research/scripts/benchmark-signal-study.ts
Normal file
228
libs/research/scripts/benchmark-signal-study.ts
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
import type { SignalCrossSection } from '@stock-bot/calculations';
|
||||
import { analyzeSignal } from '../src/signal-study';
|
||||
import type { TrialLedgerExecutor } from '../src/trial-ledger';
|
||||
|
||||
const SEED = 20260402;
|
||||
const DATES = 5040;
|
||||
const NAMES_PER_DATE = 3000;
|
||||
const VAULT_CUTOFF_DATE = '2026-06-01';
|
||||
|
||||
function createMulberry32(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) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function createStandardNormal(seed: number): () => number {
|
||||
const nextUniform = createMulberry32(seed);
|
||||
let spare: number | null = null;
|
||||
return () => {
|
||||
if (spare !== null) {
|
||||
const value = spare;
|
||||
spare = null;
|
||||
return value;
|
||||
}
|
||||
let u1 = nextUniform();
|
||||
while (u1 <= 1e-12) {
|
||||
u1 = nextUniform();
|
||||
}
|
||||
const u2 = nextUniform();
|
||||
const radius = Math.sqrt(-2 * Math.log(u1));
|
||||
const theta = 2 * Math.PI * u2;
|
||||
spare = radius * Math.sin(theta);
|
||||
return radius * Math.cos(theta);
|
||||
};
|
||||
}
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function generateBusinessDates(count: number, startYear: number): string[] {
|
||||
const dates: string[] = new Array(count);
|
||||
let year = startYear;
|
||||
let month = 1;
|
||||
let day = 1;
|
||||
// 2006-01-01 was a Sunday (dow = 0)
|
||||
let dow = 0;
|
||||
let produced = 0;
|
||||
|
||||
while (produced < count) {
|
||||
if (dow !== 0 && dow !== 6) {
|
||||
const yyyy = String(year).padStart(4, '0');
|
||||
const mm = String(month).padStart(2, '0');
|
||||
const dd = String(day).padStart(2, '0');
|
||||
dates[produced++] = `${yyyy}-${mm}-${dd}`;
|
||||
}
|
||||
|
||||
dow = (dow + 1) % 7;
|
||||
day++;
|
||||
const baseDays = DAYS_IN_MONTH[month] ?? 31;
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
|
||||
if (day > maxDay) {
|
||||
day = 1;
|
||||
month++;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dates;
|
||||
}
|
||||
|
||||
interface StoredRow {
|
||||
readonly trial_id: string;
|
||||
readonly created_at: Date;
|
||||
readonly principal_id: string;
|
||||
readonly campaign_id: string | null;
|
||||
readonly stage: string;
|
||||
readonly universe_market: string;
|
||||
readonly horizon_bucket: string;
|
||||
readonly hypothesis_id: string | null;
|
||||
readonly expression_hash: string;
|
||||
readonly sample_start: string;
|
||||
readonly sample_end: string;
|
||||
readonly n_obs: number;
|
||||
readonly sharpe_unann: number;
|
||||
readonly skewness: number;
|
||||
readonly kurtosis: number;
|
||||
readonly daily_series: readonly number[];
|
||||
}
|
||||
|
||||
function createInMemoryExecutor(): TrialLedgerExecutor {
|
||||
const rows: StoredRow[] = [];
|
||||
let nextId = 0;
|
||||
|
||||
return {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
const p = params ?? [];
|
||||
const trialId = ++nextId;
|
||||
const createdAt = new Date(Date.UTC(2026, 4, 1, 0, 0, trialId));
|
||||
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
||||
const row: StoredRow = {
|
||||
trial_id: String(trialId),
|
||||
created_at: createdAt,
|
||||
principal_id: p[0] as string,
|
||||
campaign_id: (p[1] as string | null) ?? null,
|
||||
stage: p[2] as string,
|
||||
universe_market: p[3] as string,
|
||||
horizon_bucket: p[4] as string,
|
||||
hypothesis_id: (p[5] as string | null) ?? null,
|
||||
expression_hash: p[6] as string,
|
||||
sample_start: p[7] as string,
|
||||
sample_end: p[8] as string,
|
||||
n_obs: p[9] as number,
|
||||
sharpe_unann: p[10] as number,
|
||||
skewness: p[11] as number,
|
||||
kurtosis: p[12] as number,
|
||||
daily_series: dailySeries,
|
||||
};
|
||||
rows.push(row);
|
||||
return {
|
||||
rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const targetId = String(params?.[0]);
|
||||
const matched = rows.filter(r => r.trial_id === targetId);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const market = params?.[0] as string;
|
||||
const bucket = params?.[1] as string;
|
||||
const matched = rows.filter(
|
||||
r => r.universe_market === market && r.horizon_bucket === bucket
|
||||
);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const randn = createStandardNormal(SEED);
|
||||
const isoDates = generateBusinessDates(DATES, 2006);
|
||||
const sharedIds = new Int32Array(NAMES_PER_DATE);
|
||||
for (let i = 0; i < NAMES_PER_DATE; i++) {
|
||||
sharedIds[i] = i + 1;
|
||||
}
|
||||
|
||||
const panel: SignalCrossSection[] = new Array(DATES);
|
||||
for (let t = 0; t < DATES; t++) {
|
||||
const signal = new Float64Array(NAMES_PER_DATE);
|
||||
const forwardReturn = new Float64Array(NAMES_PER_DATE);
|
||||
for (let i = 0; i < NAMES_PER_DATE; i++) {
|
||||
const s = randn();
|
||||
signal[i] = s;
|
||||
forwardReturn[i] = 0.0004 + 0.0012 * s + 0.02 * randn();
|
||||
}
|
||||
panel[t] = {
|
||||
date: isoDates[t] as string,
|
||||
ids: sharedIds,
|
||||
signal,
|
||||
forwardReturn,
|
||||
};
|
||||
}
|
||||
|
||||
const executor = createInMemoryExecutor();
|
||||
const started = performance.now();
|
||||
const result = await analyzeSignal(executor, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||||
params: { lookback: 20 },
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
panel,
|
||||
vaultCutoffDate: VAULT_CUTOFF_DATE,
|
||||
});
|
||||
const elapsedMs = performance.now() - started;
|
||||
|
||||
if (result.status !== 'ok') {
|
||||
throw new Error(`Unexpected benchmark status: ${result.status} (${result.reason})`);
|
||||
}
|
||||
|
||||
const totalObservations = DATES * NAMES_PER_DATE;
|
||||
const elapsedSec = elapsedMs / 1000;
|
||||
const datesPerSec = DATES / elapsedSec;
|
||||
const rowsPerSec = totalObservations / elapsedSec;
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
seed: SEED,
|
||||
dates: DATES,
|
||||
namesPerDate: NAMES_PER_DATE,
|
||||
totalObservations,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
datesPerSec: Math.round(datesPerSec),
|
||||
rowsPerSec: Math.round(rowsPerSec),
|
||||
trialId: result.trial.trialId,
|
||||
nObs: result.trial.nObs,
|
||||
effectiveTrials: Number(result.deflatedSharpe.effectiveTrials.toFixed(4)),
|
||||
dsr: result.deflatedSharpe.dsr !== null ? Number(result.deflatedSharpe.dsr.toFixed(6)) : null,
|
||||
meanRankIc: Number((result.analysis.rankIc.mean ?? 0).toFixed(6)),
|
||||
recencyGatePassed: result.analysis.recency.gate.pass,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
export * from './market-data-store';
|
||||
export * from './signal-study';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
692
libs/research/src/signal-study.ts
Normal file
692
libs/research/src/signal-study.ts
Normal file
|
|
@ -0,0 +1,692 @@
|
|||
/**
|
||||
* Signal-analysis and event-study runners that join pure `@stock-bot/calculations`
|
||||
* analytics with mandatory append-only `trial_ledger` logging and relatedness-cluster
|
||||
* N-hat-deflated Sharpe evaluation (`design/MILESTONES.md` M1, `design/VALIDATION-AND-RIGOR.md`).
|
||||
*
|
||||
* Browser-safe and dependency-free: zero `node:*` imports, zero `pg` dependency,
|
||||
* zero bare `process` access. SQL execution is injected via {@link TrialLedgerExecutor}.
|
||||
*/
|
||||
|
||||
import {
|
||||
DEFAULT_EVENT_POST_DAYS,
|
||||
EventStudyError,
|
||||
SignalAnalysisError,
|
||||
analyzeSignalPanel,
|
||||
eventStudy,
|
||||
type EventStudyEvent,
|
||||
type EventStudyInput,
|
||||
type EventStudyOptions,
|
||||
type EventStudyResult,
|
||||
type SignalAnalysisOptions,
|
||||
type SignalCrossSection,
|
||||
type SignalPanelAnalysis,
|
||||
} from '@stock-bot/calculations';
|
||||
import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store';
|
||||
import {
|
||||
TrialLedgerError,
|
||||
buildTrialRow,
|
||||
canonicalExpressionHash,
|
||||
clusterDeflatedSharpe,
|
||||
recordTrials,
|
||||
type BuiltTrialRow,
|
||||
type CanonicalExpressionInput,
|
||||
type ClusterDeflatedSharpeResult,
|
||||
type HorizonBucket,
|
||||
type TrialLedgerExecutor,
|
||||
type TrialStage,
|
||||
type UniverseMarket,
|
||||
} from './trial-ledger';
|
||||
|
||||
export type SignalStudyErrorCode =
|
||||
| 'invalid_request'
|
||||
| 'empty_panel'
|
||||
| 'invalid_date'
|
||||
| 'unsorted_dates'
|
||||
| 'duplicate_date'
|
||||
| 'invalid_panel'
|
||||
| 'invalid_option'
|
||||
| 'dsr_read_failed';
|
||||
|
||||
export interface SignalStudyErrorOptions {
|
||||
readonly trialId?: number;
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
/** Typed validation and orchestration error thrown by {@link analyzeSignal} and {@link runEventStudy}. */
|
||||
export class SignalStudyError extends Error {
|
||||
readonly code: SignalStudyErrorCode;
|
||||
readonly trialId?: number;
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(code: SignalStudyErrorCode, message: string, options?: SignalStudyErrorOptions) {
|
||||
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
|
||||
this.name = 'SignalStudyError';
|
||||
this.code = code;
|
||||
if (options?.trialId !== undefined) {
|
||||
this.trialId = options.trialId;
|
||||
}
|
||||
if (options?.cause !== undefined) {
|
||||
this.cause = options.cause;
|
||||
}
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export type SignalLedgerSeries = 'rank_ic' | 'quantile_spread';
|
||||
|
||||
export type SignalStudyExpression = Omit<CanonicalExpressionInput, 'sampleStart' | 'sampleEnd'>;
|
||||
|
||||
export type AnalyzeSignalOptions = Omit<SignalAnalysisOptions, 'vaultCutoffDate'>;
|
||||
|
||||
export interface StudyTrialSummary {
|
||||
readonly trialId: number;
|
||||
readonly createdAt: string;
|
||||
readonly expressionHash: string;
|
||||
readonly sampleStart: string;
|
||||
readonly sampleEnd: string;
|
||||
readonly nObs: number;
|
||||
}
|
||||
|
||||
export interface AnalyzeSignalRequest {
|
||||
readonly principalId: string;
|
||||
readonly campaignId?: string | null;
|
||||
readonly hypothesisId?: string | null;
|
||||
readonly universeMarket: UniverseMarket;
|
||||
readonly horizonBucket: HorizonBucket;
|
||||
readonly expression: SignalStudyExpression;
|
||||
readonly panel: readonly SignalCrossSection[];
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly options?: AnalyzeSignalOptions;
|
||||
readonly ledgerSeries?: SignalLedgerSeries;
|
||||
readonly dsrGate?: number;
|
||||
}
|
||||
|
||||
export type AnalyzeSignalInsufficientDataReason = 'too_few_observations' | 'zero_variance_series';
|
||||
|
||||
export type AnalyzeSignalResult =
|
||||
| {
|
||||
readonly status: 'ok';
|
||||
readonly analysis: SignalPanelAnalysis;
|
||||
readonly trial: StudyTrialSummary;
|
||||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||||
}
|
||||
| {
|
||||
readonly status: 'insufficient_data';
|
||||
readonly analysis: SignalPanelAnalysis;
|
||||
readonly reason: AnalyzeSignalInsufficientDataReason;
|
||||
};
|
||||
|
||||
export interface RunEventStudyRequest {
|
||||
readonly principalId: string;
|
||||
readonly campaignId?: string | null;
|
||||
readonly hypothesisId?: string | null;
|
||||
readonly universeMarket: UniverseMarket;
|
||||
readonly horizonBucket: HorizonBucket;
|
||||
readonly expression: SignalStudyExpression;
|
||||
readonly input: EventStudyInput;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly options?: EventStudyOptions;
|
||||
readonly dsrGate?: number;
|
||||
}
|
||||
|
||||
export type RunEventStudyInsufficientDataReason =
|
||||
| 'below_min_events'
|
||||
| 'too_few_event_dates'
|
||||
| 'too_few_observations'
|
||||
| 'zero_variance_series';
|
||||
|
||||
export type RunEventStudyResult =
|
||||
| {
|
||||
readonly status: 'ok';
|
||||
readonly study: Extract<EventStudyResult, { readonly status: 'ok' }>;
|
||||
readonly vaultExcludedEvents: number;
|
||||
readonly trial: StudyTrialSummary;
|
||||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||||
}
|
||||
| {
|
||||
readonly status: 'insufficient_data';
|
||||
readonly study: EventStudyResult;
|
||||
readonly vaultExcludedEvents: number;
|
||||
readonly reason: RunEventStudyInsufficientDataReason;
|
||||
};
|
||||
|
||||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const PROBE_SAMPLE_START = '2000-01-01';
|
||||
const PROBE_SAMPLE_END = '2000-01-02';
|
||||
const PROBE_VAULT_CUTOFF = '2000-01-03';
|
||||
const PROBE_DAILY_SERIES: readonly number[] = [0, 1];
|
||||
|
||||
interface BaseStudyRequest {
|
||||
readonly principalId: string;
|
||||
readonly campaignId?: string | null;
|
||||
readonly hypothesisId?: string | null;
|
||||
readonly universeMarket: UniverseMarket;
|
||||
readonly horizonBucket: HorizonBucket;
|
||||
readonly expression: SignalStudyExpression;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly dsrGate?: number;
|
||||
}
|
||||
|
||||
function assertStrictCalendarDate(value: unknown, field: string): string {
|
||||
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_date',
|
||||
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
|
||||
);
|
||||
}
|
||||
try {
|
||||
applyVaultFence(
|
||||
{ from: value, to: value, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof MarketDataStoreValidationError) {
|
||||
throw new SignalStudyError('invalid_date', `Invalid "${field}": ${error.message}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function mapTrialLedgerError(error: TrialLedgerError): SignalStudyError {
|
||||
const code: SignalStudyErrorCode =
|
||||
error.code === 'INVALID_DATE' ? 'invalid_date' : 'invalid_request';
|
||||
return new SignalStudyError(code, error.message, { cause: error });
|
||||
}
|
||||
|
||||
function mapSignalAnalysisError(error: SignalAnalysisError): SignalStudyError {
|
||||
switch (error.code) {
|
||||
case 'UNSORTED_DATES':
|
||||
return new SignalStudyError('unsorted_dates', error.message, { cause: error });
|
||||
case 'DUPLICATE_DATE':
|
||||
return new SignalStudyError('duplicate_date', error.message, { cause: error });
|
||||
case 'INVALID_DATE':
|
||||
return new SignalStudyError('invalid_date', error.message, { cause: error });
|
||||
case 'INVALID_OPTION':
|
||||
return new SignalStudyError('invalid_option', error.message, { cause: error });
|
||||
case 'LENGTH_MISMATCH':
|
||||
case 'DUPLICATE_ID':
|
||||
case 'INVALID_ID':
|
||||
return new SignalStudyError('invalid_panel', error.message, { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function mapEventStudyError(error: EventStudyError): SignalStudyError {
|
||||
switch (error.code) {
|
||||
case 'UNSORTED_DATES':
|
||||
return new SignalStudyError('unsorted_dates', error.message, { cause: error });
|
||||
case 'DUPLICATE_DATE':
|
||||
return new SignalStudyError('duplicate_date', error.message, { cause: error });
|
||||
case 'INVALID_DATE':
|
||||
return new SignalStudyError('invalid_date', error.message, { cause: error });
|
||||
case 'INVALID_OPTION':
|
||||
return new SignalStudyError('invalid_option', error.message, { cause: error });
|
||||
case 'INVALID_TIMESTAMP':
|
||||
case 'UNSORTED_TIMESTAMPS':
|
||||
case 'LENGTH_MISMATCH':
|
||||
case 'INVALID_EVENT':
|
||||
case 'NON_FINITE_RETURN':
|
||||
return new SignalStudyError('invalid_panel', error.message, { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function validateBaseRequest(
|
||||
executor: unknown,
|
||||
request: unknown,
|
||||
stage: TrialStage
|
||||
): asserts request is BaseStudyRequest {
|
||||
if (
|
||||
typeof executor !== 'object' ||
|
||||
executor === null ||
|
||||
typeof (executor as { query?: unknown }).query !== 'function'
|
||||
) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_request',
|
||||
'Expected a TrialLedgerExecutor object with a query(text, params) method.'
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof request !== 'object' || request === null) {
|
||||
throw new SignalStudyError('invalid_request', 'Study request must be a non-null object.');
|
||||
}
|
||||
|
||||
const req = request as Partial<BaseStudyRequest>;
|
||||
assertStrictCalendarDate(req.vaultCutoffDate, 'vaultCutoffDate');
|
||||
|
||||
if (req.dsrGate !== undefined && (typeof req.dsrGate !== 'number' || !Number.isFinite(req.dsrGate))) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_option',
|
||||
`Invalid dsrGate "${String(req.dsrGate)}": expected a finite number.`
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof req.expression !== 'object' || req.expression === null) {
|
||||
throw new SignalStudyError('invalid_request', 'request.expression must be a non-null object.');
|
||||
}
|
||||
|
||||
// Probe canonicalExpressionHash and buildTrialRow upfront so metadata/expression errors
|
||||
// fail fast before heavy math and before any SQL query is issued.
|
||||
try {
|
||||
const probeHash = canonicalExpressionHash({
|
||||
expression: req.expression.expression,
|
||||
params: req.expression.params,
|
||||
universe: req.expression.universe,
|
||||
sampleStart: PROBE_SAMPLE_START,
|
||||
sampleEnd: PROBE_SAMPLE_END,
|
||||
horizon: req.expression.horizon,
|
||||
});
|
||||
buildTrialRow({
|
||||
principalId: req.principalId as string,
|
||||
campaignId: req.campaignId,
|
||||
hypothesisId: req.hypothesisId,
|
||||
stage,
|
||||
universeMarket: req.universeMarket as UniverseMarket,
|
||||
horizonBucket: req.horizonBucket as HorizonBucket,
|
||||
expressionHash: probeHash,
|
||||
sampleStart: PROBE_SAMPLE_START,
|
||||
sampleEnd: PROBE_SAMPLE_END,
|
||||
vaultCutoffDate: PROBE_VAULT_CUTOFF,
|
||||
dailySeries: PROBE_DAILY_SERIES,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof TrialLedgerError) {
|
||||
throw mapTrialLedgerError(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function persistTrialAndEvaluateDsr(
|
||||
executor: TrialLedgerExecutor,
|
||||
row: BuiltTrialRow,
|
||||
seriesDates: readonly string[],
|
||||
dsrGate: number | undefined
|
||||
): Promise<{
|
||||
readonly trial: StudyTrialSummary;
|
||||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||||
}> {
|
||||
// Write-before-return guarantee: if INSERT fails, propagate directly with no result returned.
|
||||
const receipts = await recordTrials(executor, [row]);
|
||||
const receipt = receipts[0];
|
||||
if (receipt === undefined) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_request',
|
||||
'recordTrials returned no receipt after inserting a trial row.'
|
||||
);
|
||||
}
|
||||
|
||||
// Never retry the insert if the subsequent DSR read fails; surface trialId and cause.
|
||||
let deflatedSharpe: ClusterDeflatedSharpeResult;
|
||||
try {
|
||||
deflatedSharpe = await clusterDeflatedSharpe(executor, {
|
||||
trialId: receipt.trialId,
|
||||
...(dsrGate !== undefined ? { dsrGate } : {}),
|
||||
observationDatesByTrialId: { [String(receipt.trialId)]: seriesDates },
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
throw new SignalStudyError(
|
||||
'dsr_read_failed',
|
||||
`Trial ${receipt.trialId} was recorded in trial_ledger, but clusterDeflatedSharpe failed: ${detail}`,
|
||||
{ trialId: receipt.trialId, cause: error }
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
trial: {
|
||||
trialId: receipt.trialId,
|
||||
createdAt: receipt.createdAt,
|
||||
expressionHash: row.expressionHash,
|
||||
sampleStart: row.sampleStart,
|
||||
sampleEnd: row.sampleEnd,
|
||||
nObs: row.nObs,
|
||||
},
|
||||
deflatedSharpe,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs cross-sectional signal analysis (`analyzeSignalPanel`) under an exclusive
|
||||
* `vaultCutoffDate` fence, appends a `stage = 'signal_ic'` row to `trial_ledger`,
|
||||
* and returns the analysis together with its trial receipt and cluster N-hat-deflated Sharpe.
|
||||
*/
|
||||
export async function analyzeSignal(
|
||||
executor: TrialLedgerExecutor,
|
||||
request: AnalyzeSignalRequest
|
||||
): Promise<AnalyzeSignalResult> {
|
||||
validateBaseRequest(executor, request, 'signal_ic');
|
||||
|
||||
const ledgerSeries: SignalLedgerSeries = request.ledgerSeries ?? 'rank_ic';
|
||||
if (ledgerSeries !== 'rank_ic' && ledgerSeries !== 'quantile_spread') {
|
||||
throw new SignalStudyError(
|
||||
'invalid_option',
|
||||
`Invalid ledgerSeries "${String(ledgerSeries)}": expected 'rank_ic' or 'quantile_spread'.`
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
request.options !== undefined &&
|
||||
(typeof request.options !== 'object' || request.options === null)
|
||||
) {
|
||||
throw new SignalStudyError('invalid_option', 'request.options must be a non-null object.');
|
||||
}
|
||||
|
||||
if (!Array.isArray(request.panel)) {
|
||||
throw new SignalStudyError('invalid_panel', 'request.panel must be an array of cross-sections.');
|
||||
}
|
||||
if (request.panel.length === 0) {
|
||||
throw new SignalStudyError('empty_panel', 'request.panel must contain at least one cross-section.');
|
||||
}
|
||||
|
||||
let analysis: SignalPanelAnalysis;
|
||||
try {
|
||||
analysis = analyzeSignalPanel(request.panel, {
|
||||
...request.options,
|
||||
vaultCutoffDate: request.vaultCutoffDate,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof SignalAnalysisError) {
|
||||
throw mapSignalAnalysisError(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const series =
|
||||
ledgerSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries;
|
||||
const seriesDates = ledgerSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates;
|
||||
|
||||
if (series.length < 2 || seriesDates.length < 2) {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
analysis,
|
||||
reason: 'too_few_observations',
|
||||
};
|
||||
}
|
||||
|
||||
const sampleStart = seriesDates[0];
|
||||
const sampleEnd = seriesDates[seriesDates.length - 1];
|
||||
if (sampleStart === undefined || sampleEnd === undefined) {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
analysis,
|
||||
reason: 'too_few_observations',
|
||||
};
|
||||
}
|
||||
|
||||
let row: BuiltTrialRow;
|
||||
try {
|
||||
const expressionHash = canonicalExpressionHash({
|
||||
expression: request.expression.expression,
|
||||
params: request.expression.params,
|
||||
universe: request.expression.universe,
|
||||
sampleStart,
|
||||
sampleEnd,
|
||||
horizon: request.expression.horizon,
|
||||
});
|
||||
row = buildTrialRow({
|
||||
principalId: request.principalId,
|
||||
campaignId: request.campaignId,
|
||||
hypothesisId: request.hypothesisId,
|
||||
stage: 'signal_ic',
|
||||
universeMarket: request.universeMarket,
|
||||
horizonBucket: request.horizonBucket,
|
||||
expressionHash,
|
||||
sampleStart,
|
||||
sampleEnd,
|
||||
vaultCutoffDate: request.vaultCutoffDate,
|
||||
dailySeries: series,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof TrialLedgerError) {
|
||||
if (error.code === 'SERIES_TOO_SHORT') {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
analysis,
|
||||
reason: 'too_few_observations',
|
||||
};
|
||||
}
|
||||
if (error.code === 'ZERO_VARIANCE_SERIES') {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
analysis,
|
||||
reason: 'zero_variance_series',
|
||||
};
|
||||
}
|
||||
throw mapTrialLedgerError(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const { trial, deflatedSharpe } = await persistTrialAndEvaluateDsr(
|
||||
executor,
|
||||
row,
|
||||
seriesDates,
|
||||
request.dsrGate
|
||||
);
|
||||
|
||||
return {
|
||||
status: 'ok',
|
||||
analysis,
|
||||
trial,
|
||||
deflatedSharpe,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a Vault-fenced event study (`eventStudy`), excluding every event whose event date
|
||||
* or post-event window end (`sessionDates[dayIndex + postDays]`) falls on or after
|
||||
* `vaultCutoffDate`, appends a `stage = 'event_study'` row to `trial_ledger`, and returns
|
||||
* the study together with its trial receipt and cluster N-hat-deflated Sharpe.
|
||||
*/
|
||||
export async function runEventStudy(
|
||||
executor: TrialLedgerExecutor,
|
||||
request: RunEventStudyRequest
|
||||
): Promise<RunEventStudyResult> {
|
||||
validateBaseRequest(executor, request, 'event_study');
|
||||
|
||||
if (typeof request.input !== 'object' || request.input === null) {
|
||||
throw new SignalStudyError('invalid_request', 'request.input must be a non-null object.');
|
||||
}
|
||||
|
||||
if (
|
||||
request.options !== undefined &&
|
||||
(typeof request.options !== 'object' || request.options === null)
|
||||
) {
|
||||
throw new SignalStudyError('invalid_option', 'request.options must be a non-null object.');
|
||||
}
|
||||
|
||||
const postDays = request.options?.postDays ?? DEFAULT_EVENT_POST_DAYS;
|
||||
if (typeof postDays !== 'number' || !Number.isInteger(postDays) || postDays < 0) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_option',
|
||||
`postDays must be an integer >= 0, received ${String(postDays)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const { sessionDates, events } = request.input;
|
||||
if (!Array.isArray(sessionDates)) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_panel',
|
||||
'request.input.sessionDates must be an array of YYYY-MM-DD dates.'
|
||||
);
|
||||
}
|
||||
if (sessionDates.length === 0) {
|
||||
throw new SignalStudyError(
|
||||
'empty_panel',
|
||||
'request.input.sessionDates must contain at least one session date.'
|
||||
);
|
||||
}
|
||||
if (!Array.isArray(events)) {
|
||||
throw new SignalStudyError('invalid_panel', 'request.input.events must be an array.');
|
||||
}
|
||||
|
||||
// Validate sessionDates ordering and calendar validity before vault fencing.
|
||||
let prevDate = '';
|
||||
for (let i = 0; i < sessionDates.length; i += 1) {
|
||||
const currentDate = assertStrictCalendarDate(sessionDates[i], `sessionDates[${i}]`);
|
||||
if (i > 0) {
|
||||
if (currentDate === prevDate) {
|
||||
throw new SignalStudyError(
|
||||
'duplicate_date',
|
||||
`Duplicate date "${currentDate}" at sessionDates[${i}].`
|
||||
);
|
||||
}
|
||||
if (currentDate < prevDate) {
|
||||
throw new SignalStudyError(
|
||||
'unsorted_dates',
|
||||
`sessionDates must be strictly ascending: "${currentDate}" < "${prevDate}" at index ${i}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
prevDate = currentDate;
|
||||
}
|
||||
|
||||
// Validate each event and fence out any event touching or extending into the Vault window.
|
||||
const fencedEvents: EventStudyEvent[] = [];
|
||||
let vaultExcludedEvents = 0;
|
||||
for (let i = 0; i < events.length; i += 1) {
|
||||
const evt: unknown = events[i];
|
||||
if (typeof evt !== 'object' || evt === null) {
|
||||
throw new SignalStudyError('invalid_panel', `events[${i}] must be a non-null object.`);
|
||||
}
|
||||
const candidate = evt as Partial<EventStudyEvent>;
|
||||
const entityId = candidate.entityId;
|
||||
const validId =
|
||||
typeof entityId === 'string' || (typeof entityId === 'number' && !Number.isNaN(entityId));
|
||||
if (!validId) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_panel',
|
||||
`events[${i}].entityId must be a string or non-NaN number.`
|
||||
);
|
||||
}
|
||||
const dayIndex = candidate.dayIndex;
|
||||
if (typeof dayIndex !== 'number' || !Number.isInteger(dayIndex) || dayIndex < 0) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_panel',
|
||||
`events[${i}].dayIndex must be a non-negative integer, received ${String(dayIndex)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const eventDate = sessionDates[dayIndex];
|
||||
const postWindowEndDate = sessionDates[dayIndex + postDays];
|
||||
if (
|
||||
(eventDate !== undefined && eventDate >= request.vaultCutoffDate) ||
|
||||
(postWindowEndDate !== undefined && postWindowEndDate >= request.vaultCutoffDate)
|
||||
) {
|
||||
vaultExcludedEvents += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
fencedEvents.push({ entityId, dayIndex });
|
||||
}
|
||||
|
||||
let study: EventStudyResult;
|
||||
try {
|
||||
study = eventStudy(
|
||||
{
|
||||
...request.input,
|
||||
events: fencedEvents,
|
||||
},
|
||||
request.options
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof EventStudyError) {
|
||||
throw mapEventStudyError(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (study.status === 'insufficient_data') {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
study,
|
||||
vaultExcludedEvents,
|
||||
reason: study.reason,
|
||||
};
|
||||
}
|
||||
|
||||
const series = study.clustered.meanCars;
|
||||
const seriesDates = study.clustered.dates;
|
||||
if (series.length < 2 || seriesDates.length < 2) {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
study,
|
||||
vaultExcludedEvents,
|
||||
reason: 'too_few_observations',
|
||||
};
|
||||
}
|
||||
|
||||
const sampleStart = seriesDates[0];
|
||||
const sampleEnd = seriesDates[seriesDates.length - 1];
|
||||
if (sampleStart === undefined || sampleEnd === undefined) {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
study,
|
||||
vaultExcludedEvents,
|
||||
reason: 'too_few_observations',
|
||||
};
|
||||
}
|
||||
|
||||
let row: BuiltTrialRow;
|
||||
try {
|
||||
const expressionHash = canonicalExpressionHash({
|
||||
expression: request.expression.expression,
|
||||
params: request.expression.params,
|
||||
universe: request.expression.universe,
|
||||
sampleStart,
|
||||
sampleEnd,
|
||||
horizon: request.expression.horizon,
|
||||
});
|
||||
row = buildTrialRow({
|
||||
principalId: request.principalId,
|
||||
campaignId: request.campaignId,
|
||||
hypothesisId: request.hypothesisId,
|
||||
stage: 'event_study',
|
||||
universeMarket: request.universeMarket,
|
||||
horizonBucket: request.horizonBucket,
|
||||
expressionHash,
|
||||
sampleStart,
|
||||
sampleEnd,
|
||||
vaultCutoffDate: request.vaultCutoffDate,
|
||||
dailySeries: series,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof TrialLedgerError) {
|
||||
if (error.code === 'SERIES_TOO_SHORT') {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
study,
|
||||
vaultExcludedEvents,
|
||||
reason: 'too_few_observations',
|
||||
};
|
||||
}
|
||||
if (error.code === 'ZERO_VARIANCE_SERIES') {
|
||||
return {
|
||||
status: 'insufficient_data',
|
||||
study,
|
||||
vaultExcludedEvents,
|
||||
reason: 'zero_variance_series',
|
||||
};
|
||||
}
|
||||
throw mapTrialLedgerError(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const { trial, deflatedSharpe } = await persistTrialAndEvaluateDsr(
|
||||
executor,
|
||||
row,
|
||||
seriesDates,
|
||||
request.dsrGate
|
||||
);
|
||||
|
||||
return {
|
||||
status: 'ok',
|
||||
study,
|
||||
vaultExcludedEvents,
|
||||
trial,
|
||||
deflatedSharpe,
|
||||
};
|
||||
}
|
||||
809
libs/research/test/signal-study.test.ts
Normal file
809
libs/research/test/signal-study.test.ts
Normal file
|
|
@ -0,0 +1,809 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations';
|
||||
import {
|
||||
SignalStudyError,
|
||||
analyzeSignal,
|
||||
runEventStudy,
|
||||
type AnalyzeSignalRequest,
|
||||
type RunEventStudyRequest,
|
||||
type SignalStudyErrorCode,
|
||||
type TrialLedgerExecutor,
|
||||
} from '@stock-bot/research';
|
||||
import {
|
||||
SignalStudyError as SubpathSignalStudyError,
|
||||
analyzeSignal as subpathAnalyzeSignal,
|
||||
runEventStudy as subpathRunEventStudy,
|
||||
} from '@stock-bot/research/signal-study';
|
||||
|
||||
const VAULT_CUTOFF = '2025-05-01';
|
||||
const VALID_CAMPAIGN_ID = '11111111-2222-4333-8444-555555555555';
|
||||
const VALID_HYPOTHESIS_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||
|
||||
interface RecordedSqlCall {
|
||||
readonly text: string;
|
||||
readonly params: readonly unknown[] | undefined;
|
||||
}
|
||||
|
||||
interface StoredTrialRow {
|
||||
readonly trial_id: string;
|
||||
readonly created_at: Date;
|
||||
readonly principal_id: string;
|
||||
readonly campaign_id: string | null;
|
||||
readonly stage: string;
|
||||
readonly universe_market: string;
|
||||
readonly horizon_bucket: string;
|
||||
readonly hypothesis_id: string | null;
|
||||
readonly expression_hash: string;
|
||||
readonly sample_start: string;
|
||||
readonly sample_end: string;
|
||||
readonly n_obs: number;
|
||||
readonly sharpe_unann: number;
|
||||
readonly skewness: number;
|
||||
readonly kurtosis: number;
|
||||
readonly daily_series: readonly number[];
|
||||
}
|
||||
|
||||
interface InMemoryExecutorOptions {
|
||||
readonly failOnInsert?: Error;
|
||||
readonly failOnDsrRead?: Error;
|
||||
}
|
||||
|
||||
function createInMemoryTrialExecutor(options: InMemoryExecutorOptions = {}): {
|
||||
executor: TrialLedgerExecutor;
|
||||
calls: RecordedSqlCall[];
|
||||
rows: StoredTrialRow[];
|
||||
} {
|
||||
const calls: RecordedSqlCall[] = [];
|
||||
const rows: StoredTrialRow[] = [];
|
||||
let nextTrialId = 100;
|
||||
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
calls.push({ text, params });
|
||||
const trimmed = text.trimStart();
|
||||
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
if (options.failOnInsert !== undefined) {
|
||||
throw options.failOnInsert;
|
||||
}
|
||||
const p = params ?? [];
|
||||
const trialId = ++nextTrialId;
|
||||
const createdAt = new Date(Date.UTC(2025, 3, 1, 12, 0, trialId));
|
||||
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
||||
const stored: StoredTrialRow = {
|
||||
trial_id: String(trialId),
|
||||
created_at: createdAt,
|
||||
principal_id: p[0] as string,
|
||||
campaign_id: (p[1] as string | null) ?? null,
|
||||
stage: p[2] as string,
|
||||
universe_market: p[3] as string,
|
||||
horizon_bucket: p[4] as string,
|
||||
hypothesis_id: (p[5] as string | null) ?? null,
|
||||
expression_hash: p[6] as string,
|
||||
sample_start: p[7] as string,
|
||||
sample_end: p[8] as string,
|
||||
n_obs: p[9] as number,
|
||||
sharpe_unann: p[10] as number,
|
||||
skewness: p[11] as number,
|
||||
kurtosis: p[12] as number,
|
||||
daily_series: dailySeries,
|
||||
};
|
||||
rows.push(stored);
|
||||
return {
|
||||
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (options.failOnDsrRead !== undefined) {
|
||||
throw options.failOnDsrRead;
|
||||
}
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const targetId = String(params?.[0]);
|
||||
const matched = rows.filter(r => r.trial_id === targetId);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const market = params?.[0] as string;
|
||||
const bucket = params?.[1] as string;
|
||||
const matched = rows.filter(
|
||||
r => r.universe_market === market && r.horizon_bucket === bucket
|
||||
);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, calls, rows };
|
||||
}
|
||||
|
||||
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 makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = new Array(count);
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
let written = 0;
|
||||
while (written < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out[written] = current.toISOString().slice(0, 10);
|
||||
written += 1;
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeSignalPanel(dates: readonly string[], nNames = 15, seed = 42): SignalCrossSection[] {
|
||||
const rand = createSeededRng(seed);
|
||||
const ids = Array.from({ length: nNames }, (_, i) => i + 1);
|
||||
return dates.map((date, t) => {
|
||||
const signal = new Float64Array(nNames);
|
||||
const forwardReturn = new Float64Array(nNames);
|
||||
const slope = 0.002 + ((t % 5) - 2) * 0.0005;
|
||||
for (let i = 0; i < nNames; i += 1) {
|
||||
const s = rand() * 2 - 1;
|
||||
signal[i] = s;
|
||||
forwardReturn[i] = 0.0005 + slope * s + 0.015 * (rand() * 2 - 1);
|
||||
}
|
||||
return { date, ids, signal, forwardReturn };
|
||||
});
|
||||
}
|
||||
|
||||
function makeSignalRequest(overrides: Partial<AnalyzeSignalRequest> = {}): AnalyzeSignalRequest {
|
||||
const dates = makeBusinessDates('2025-03-03', 20);
|
||||
return {
|
||||
principalId: 'operator',
|
||||
campaignId: VALID_CAMPAIGN_ID,
|
||||
hypothesisId: VALID_HYPOTHESIS_ID,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||||
params: { lookback: 20 },
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
panel: makeSignalPanel(dates),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeEventStudyInput(
|
||||
dates: readonly string[],
|
||||
eventDayIndices: readonly number[],
|
||||
seed = 99
|
||||
): EventStudyInput {
|
||||
const rand = createSeededRng(seed);
|
||||
const entityReturns = new Map<number, Float64Array>();
|
||||
for (let entityId = 1; entityId <= 4; entityId += 1) {
|
||||
const series = new Float64Array(dates.length);
|
||||
for (let t = 0; t < dates.length; t += 1) {
|
||||
series[t] = (rand() - 0.5) * 0.02;
|
||||
}
|
||||
entityReturns.set(entityId, series);
|
||||
}
|
||||
const benchmarkReturns = new Float64Array(dates.length);
|
||||
for (let t = 0; t < dates.length; t += 1) {
|
||||
benchmarkReturns[t] = (rand() - 0.5) * 0.01;
|
||||
}
|
||||
const events = eventDayIndices.map((dayIndex, idx) => ({
|
||||
entityId: (idx % 4) + 1,
|
||||
dayIndex,
|
||||
}));
|
||||
return {
|
||||
sessionDates: dates,
|
||||
entityReturns,
|
||||
benchmarkReturns,
|
||||
events,
|
||||
};
|
||||
}
|
||||
|
||||
function makeEventStudyRequest(
|
||||
overrides: Partial<RunEventStudyRequest> = {}
|
||||
): RunEventStudyRequest {
|
||||
const dates = makeBusinessDates('2025-01-02', 60);
|
||||
return {
|
||||
principalId: 'operator',
|
||||
campaignId: VALID_CAMPAIGN_ID,
|
||||
hypothesisId: VALID_HYPOTHESIS_ID,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'earnings_surprise_car',
|
||||
params: { minSurprisePct: 5 },
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
input: makeEventStudyInput(dates, [12, 16, 20, 24, 28, 32]),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
options: { preDays: 5, postDays: 5, minEvents: 5 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function expectStudyError(
|
||||
fn: () => Promise<unknown>,
|
||||
expectedCode: SignalStudyErrorCode
|
||||
): Promise<SignalStudyError> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(SignalStudyError);
|
||||
const typed = error as SignalStudyError;
|
||||
expect(typed.code).toBe(expectedCode);
|
||||
return typed;
|
||||
}
|
||||
throw new Error(`Expected SignalStudyError(${expectedCode}), but call succeeded`);
|
||||
}
|
||||
|
||||
describe('signal-study exports', () => {
|
||||
it('exposes identical runtime exports from package root and subpath', () => {
|
||||
expect(analyzeSignal).toBe(subpathAnalyzeSignal);
|
||||
expect(runEventStudy).toBe(subpathRunEventStudy);
|
||||
expect(SignalStudyError).toBe(SubpathSignalStudyError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('analyzeSignal', () => {
|
||||
it('runs happy path with default rank_ic series, issuing 1 INSERT then 2 SELECTs', async () => {
|
||||
const { executor, calls, rows } = createInMemoryTrialExecutor();
|
||||
const request = makeSignalRequest();
|
||||
|
||||
const result = await analyzeSignal(executor, request);
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
if (result.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true);
|
||||
expect(calls[0]?.params?.[2]).toBe('signal_ic');
|
||||
expect(calls[1]?.text).toContain('WHERE trial_id = $1::bigint');
|
||||
expect(calls[2]?.text).toContain('WHERE universe_market = $1');
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(result.trial.trialId).toBe(101);
|
||||
expect(result.trial.nObs).toBe(result.analysis.rankIcSeries.length);
|
||||
expect(result.trial.sampleStart).toBe(result.analysis.dates[0]!);
|
||||
expect(result.trial.sampleEnd).toBe(result.analysis.dates[result.analysis.dates.length - 1]!);
|
||||
expect(result.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(result.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(result.deflatedSharpe.trialId).toBe(101);
|
||||
expect(result.deflatedSharpe.clusterSize).toBe(1);
|
||||
expect(Number.isFinite(result.deflatedSharpe.effectiveTrials)).toBe(true);
|
||||
});
|
||||
|
||||
it('logs quantile spread series when ledgerSeries is quantile_spread', async () => {
|
||||
const { executor, calls, rows } = createInMemoryTrialExecutor();
|
||||
const request = makeSignalRequest({ ledgerSeries: 'quantile_spread' });
|
||||
|
||||
const result = await analyzeSignal(executor, request);
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
if (result.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(result.trial.nObs).toBe(result.analysis.quantiles.spreadSeries.length);
|
||||
expect(result.trial.sampleStart).toBe(result.analysis.quantiles.dates[0]!);
|
||||
expect(result.trial.sampleEnd).toBe(
|
||||
result.analysis.quantiles.dates[result.analysis.quantiles.dates.length - 1]!
|
||||
);
|
||||
const logged = rows[0]!.daily_series;
|
||||
expect(logged).toHaveLength(result.analysis.quantiles.spreadSeries.length);
|
||||
for (let i = 0; i < logged.length; i += 1) {
|
||||
expect(logged[i]).toBe(Math.fround(result.analysis.quantiles.spreadSeries[i]!));
|
||||
}
|
||||
});
|
||||
|
||||
it('returns insufficient_data with zero queries when fewer than 2 valid dates remain', async () => {
|
||||
const { executor, calls } = createInMemoryTrialExecutor();
|
||||
const dates = ['2025-04-30', '2025-05-01', '2025-05-02'];
|
||||
const request = makeSignalRequest({
|
||||
panel: makeSignalPanel(dates),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
});
|
||||
|
||||
const result = await analyzeSignal(executor, request);
|
||||
|
||||
expect(result.status).toBe('insufficient_data');
|
||||
if (result.status === 'insufficient_data') {
|
||||
expect(result.reason).toBe('too_few_observations');
|
||||
}
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns insufficient_data with zero queries when rankIcSeries has zero variance', async () => {
|
||||
const { executor, calls } = createInMemoryTrialExecutor();
|
||||
const dates = makeBusinessDates('2025-03-03', 6);
|
||||
const ids = [1, 2, 3, 4, 5, 6];
|
||||
const panel: SignalCrossSection[] = dates.map(date => ({
|
||||
date,
|
||||
ids,
|
||||
signal: [1, 2, 3, 4, 5, 6],
|
||||
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05, 0.06],
|
||||
}));
|
||||
|
||||
const result = await analyzeSignal(executor, makeSignalRequest({ panel }));
|
||||
|
||||
expect(result.status).toBe('insufficient_data');
|
||||
if (result.status === 'insufficient_data') {
|
||||
expect(result.reason).toBe('zero_variance_series');
|
||||
}
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('excludes dates >= vaultCutoffDate and is bit-invariant to post-cutoff mutations', async () => {
|
||||
const preDates = makeBusinessDates('2025-04-01', 12);
|
||||
const postDates = ['2025-05-01', '2025-05-02', '2025-05-05'];
|
||||
const allDates = [...preDates, ...postDates];
|
||||
const basePanel = makeSignalPanel(allDates, 15, 77);
|
||||
|
||||
const mutatedPanel: SignalCrossSection[] = basePanel.map(slice => {
|
||||
if (slice.date >= VAULT_CUTOFF) {
|
||||
return {
|
||||
...slice,
|
||||
signal: Array.from({ length: slice.ids.length }, (_, i) => (i + 1) * 999),
|
||||
forwardReturn: Array.from({ length: slice.ids.length }, () => -0.75),
|
||||
};
|
||||
}
|
||||
return slice;
|
||||
});
|
||||
|
||||
const run1Store = createInMemoryTrialExecutor();
|
||||
const run2Store = createInMemoryTrialExecutor();
|
||||
const res1 = await analyzeSignal(run1Store.executor, makeSignalRequest({ panel: basePanel }));
|
||||
const res2 = await analyzeSignal(
|
||||
run2Store.executor,
|
||||
makeSignalRequest({ panel: mutatedPanel })
|
||||
);
|
||||
|
||||
expect(res1.status).toBe('ok');
|
||||
expect(res2.status).toBe('ok');
|
||||
if (res1.status !== 'ok' || res2.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(res1.analysis.diagnostics.vaultExcludedDates).toBe(3);
|
||||
expect(res1.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash);
|
||||
expect(res1.trial.sampleStart).toBe(res2.trial.sampleStart);
|
||||
expect(res1.trial.sampleEnd).toBe(res2.trial.sampleEnd);
|
||||
expect(Array.from(res1.analysis.rankIcSeries)).toEqual(Array.from(res2.analysis.rankIcSeries));
|
||||
expect(run1Store.rows[0]?.daily_series).toEqual(run2Store.rows[0]?.daily_series);
|
||||
});
|
||||
|
||||
it('produces identical expressionHash for identical requests and different hashes on param change', async () => {
|
||||
const store1 = createInMemoryTrialExecutor();
|
||||
const store2 = createInMemoryTrialExecutor();
|
||||
const store3 = createInMemoryTrialExecutor();
|
||||
|
||||
const baseReq = makeSignalRequest();
|
||||
const res1 = await analyzeSignal(store1.executor, baseReq);
|
||||
const res2 = await analyzeSignal(store2.executor, baseReq);
|
||||
const res3 = await analyzeSignal(
|
||||
store3.executor,
|
||||
makeSignalRequest({
|
||||
panel: baseReq.panel,
|
||||
expression: {
|
||||
...baseReq.expression,
|
||||
params: { lookback: 40 },
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(res1.status).toBe('ok');
|
||||
expect(res2.status).toBe('ok');
|
||||
expect(res3.status).toBe('ok');
|
||||
if (res1.status === 'ok' && res2.status === 'ok' && res3.status === 'ok') {
|
||||
expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash);
|
||||
expect(res1.trial.expressionHash).not.toBe(res3.trial.expressionHash);
|
||||
}
|
||||
});
|
||||
|
||||
it('propagates INSERT failure with no result and 1 total query', async () => {
|
||||
const insertError = new Error('simulated pg insert failure');
|
||||
const { executor, calls } = createInMemoryTrialExecutor({ failOnInsert: insertError });
|
||||
|
||||
await expect(analyzeSignal(executor, makeSignalRequest())).rejects.toBe(insertError);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true);
|
||||
});
|
||||
|
||||
it('throws SignalStudyError(dsr_read_failed) carrying trialId and cause without retrying INSERT', async () => {
|
||||
const readError = new Error('simulated pg select failure');
|
||||
const { executor, calls, rows } = createInMemoryTrialExecutor({ failOnDsrRead: readError });
|
||||
|
||||
const err = await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest()),
|
||||
'dsr_read_failed'
|
||||
);
|
||||
expect(err.trialId).toBe(101);
|
||||
expect(err.cause).toBe(readError);
|
||||
expect(rows).toHaveLength(1);
|
||||
const insertCount = calls.filter(c => c.text.trimStart().startsWith('INSERT')).length;
|
||||
expect(insertCount).toBe(1);
|
||||
});
|
||||
|
||||
it('rejects invalid inputs with typed SignalStudyError codes and zero SQL queries', async () => {
|
||||
const { executor, calls } = createInMemoryTrialExecutor();
|
||||
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(null as unknown as TrialLedgerExecutor, makeSignalRequest()),
|
||||
'invalid_request'
|
||||
);
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ panel: [] })),
|
||||
'empty_panel'
|
||||
);
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ vaultCutoffDate: '2025-02-30' })),
|
||||
'invalid_date'
|
||||
);
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ principalId: 'bad-principal' })),
|
||||
'invalid_request'
|
||||
);
|
||||
await expectStudyError(
|
||||
() =>
|
||||
analyzeSignal(
|
||||
executor,
|
||||
makeSignalRequest({
|
||||
ledgerSeries: 'bad_series' as unknown as 'rank_ic',
|
||||
})
|
||||
),
|
||||
'invalid_option'
|
||||
);
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ dsrGate: Number.NaN })),
|
||||
'invalid_option'
|
||||
);
|
||||
|
||||
const unsortedPanel = makeSignalPanel(['2025-03-05', '2025-03-04']);
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ panel: unsortedPanel })),
|
||||
'unsorted_dates'
|
||||
);
|
||||
|
||||
const duplicatePanel = makeSignalPanel(['2025-03-05', '2025-03-05']);
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ panel: duplicatePanel })),
|
||||
'duplicate_date'
|
||||
);
|
||||
|
||||
const mismatchedPanel: SignalCrossSection[] = [
|
||||
{ date: '2025-03-05', ids: [1, 2, 3], signal: [1, 2], forwardReturn: [0.1, 0.2, 0.3] },
|
||||
];
|
||||
await expectStudyError(
|
||||
() => analyzeSignal(executor, makeSignalRequest({ panel: mismatchedPanel })),
|
||||
'invalid_panel'
|
||||
);
|
||||
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not mutate frozen caller inputs', async () => {
|
||||
const { executor } = createInMemoryTrialExecutor();
|
||||
const dates = makeBusinessDates('2025-03-03', 10);
|
||||
const panel = Object.freeze(
|
||||
makeSignalPanel(dates).map(slice =>
|
||||
Object.freeze({
|
||||
date: slice.date,
|
||||
ids: Object.freeze([...slice.ids]),
|
||||
signal: Object.freeze([...slice.signal]),
|
||||
forwardReturn: Object.freeze([...slice.forwardReturn]),
|
||||
})
|
||||
)
|
||||
);
|
||||
const expression = Object.freeze({
|
||||
expression: 'rank(ret_5d)',
|
||||
params: Object.freeze({ lookback: 5 }),
|
||||
universe: 'US_EQ',
|
||||
horizon: '5d',
|
||||
});
|
||||
const options = Object.freeze({ minCrossSection: 5, quantiles: 5 });
|
||||
const request = Object.freeze(makeSignalRequest({ panel, expression, options }));
|
||||
|
||||
const result = await analyzeSignal(executor, request);
|
||||
expect(result.status).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runEventStudy', () => {
|
||||
it('runs happy path issuing 1 INSERT (stage=event_study) then 2 SELECTs', async () => {
|
||||
const { executor, calls, rows } = createInMemoryTrialExecutor();
|
||||
const request = makeEventStudyRequest();
|
||||
|
||||
const result = await runEventStudy(executor, request);
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
if (result.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true);
|
||||
expect(calls[0]?.params?.[2]).toBe('event_study');
|
||||
expect(calls[1]?.text).toContain('WHERE trial_id = $1::bigint');
|
||||
expect(calls[2]?.text).toContain('WHERE universe_market = $1');
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(result.vaultExcludedEvents).toBe(0);
|
||||
expect(result.trial.trialId).toBe(101);
|
||||
expect(result.trial.nObs).toBe(result.study.clustered.meanCars.length);
|
||||
expect(result.trial.sampleStart).toBe(result.study.clustered.dates[0]!);
|
||||
expect(result.trial.sampleEnd).toBe(
|
||||
result.study.clustered.dates[result.study.clustered.dates.length - 1]!
|
||||
);
|
||||
expect(result.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(result.deflatedSharpe.clusterSize).toBe(1);
|
||||
});
|
||||
|
||||
it('fences events whose event date OR post-event window end >= vaultCutoffDate and is bit-invariant to post-cutoff return mutations', async () => {
|
||||
const dates = makeBusinessDates('2025-03-03', 55);
|
||||
const cutoffIdx = dates.findIndex(d => d >= VAULT_CUTOFF);
|
||||
expect(cutoffIdx).toBeGreaterThan(25);
|
||||
|
||||
const postDays = 5;
|
||||
// 5 safe events strictly ending before cutoff;
|
||||
// 1 event before cutoff whose dayIndex + postDays lands ON cutoff;
|
||||
// 1 event ON cutoff;
|
||||
// 1 event AFTER cutoff.
|
||||
const eventDayIndices = [
|
||||
6,
|
||||
10,
|
||||
14,
|
||||
18,
|
||||
22,
|
||||
cutoffIdx - postDays,
|
||||
cutoffIdx,
|
||||
cutoffIdx + 2,
|
||||
];
|
||||
const baseInput = makeEventStudyInput(dates, eventDayIndices, 303);
|
||||
|
||||
const mutatedReturns = new Map<number, Float64Array>();
|
||||
for (const [id, series] of baseInput.entityReturns.entries()) {
|
||||
const copy = new Float64Array(series);
|
||||
for (let t = cutoffIdx; t < copy.length; t += 1) {
|
||||
copy[t] = 0.95;
|
||||
}
|
||||
mutatedReturns.set(id, copy);
|
||||
}
|
||||
const mutatedBenchmark = new Float64Array(baseInput.benchmarkReturns!);
|
||||
for (let t = cutoffIdx; t < mutatedBenchmark.length; t += 1) {
|
||||
mutatedBenchmark[t] = -0.5;
|
||||
}
|
||||
const mutatedInput: EventStudyInput = {
|
||||
...baseInput,
|
||||
entityReturns: mutatedReturns,
|
||||
benchmarkReturns: mutatedBenchmark,
|
||||
};
|
||||
|
||||
const store1 = createInMemoryTrialExecutor();
|
||||
const store2 = createInMemoryTrialExecutor();
|
||||
const res1 = await runEventStudy(
|
||||
store1.executor,
|
||||
makeEventStudyRequest({ input: baseInput, options: { preDays: 3, postDays, minEvents: 5 } })
|
||||
);
|
||||
const res2 = await runEventStudy(
|
||||
store2.executor,
|
||||
makeEventStudyRequest({
|
||||
input: mutatedInput,
|
||||
options: { preDays: 3, postDays, minEvents: 5 },
|
||||
})
|
||||
);
|
||||
|
||||
expect(res1.status).toBe('ok');
|
||||
expect(res2.status).toBe('ok');
|
||||
if (res1.status !== 'ok' || res2.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(res1.vaultExcludedEvents).toBe(3);
|
||||
expect(res2.vaultExcludedEvents).toBe(3);
|
||||
expect(res1.study.diagnostics.eventsUsed).toBe(5);
|
||||
expect(res1.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash);
|
||||
expect(Array.from(res1.study.clustered.meanCars)).toEqual(
|
||||
Array.from(res2.study.clustered.meanCars)
|
||||
);
|
||||
expect(store1.rows[0]?.daily_series).toEqual(store2.rows[0]?.daily_series);
|
||||
});
|
||||
|
||||
it('returns insufficient_data with zero queries for below_min_events, too_few_event_dates, and zero-variance clustered CARs', async () => {
|
||||
const { executor, calls } = createInMemoryTrialExecutor();
|
||||
const dates = makeBusinessDates('2025-01-02', 40);
|
||||
|
||||
// below_min_events
|
||||
const resBelowMin = await runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: makeEventStudyInput(dates, [10, 15]),
|
||||
options: { preDays: 3, postDays: 3, minEvents: 5 },
|
||||
})
|
||||
);
|
||||
expect(resBelowMin.status).toBe('insufficient_data');
|
||||
if (resBelowMin.status === 'insufficient_data') {
|
||||
expect(resBelowMin.reason).toBe('below_min_events');
|
||||
}
|
||||
|
||||
// too_few_event_dates (all 5 events on the exact same dayIndex)
|
||||
const sameDayInput = makeEventStudyInput(dates, [15, 15, 15, 15]);
|
||||
const sameDayWithFive = {
|
||||
...sameDayInput,
|
||||
entityReturns: new Map([
|
||||
...sameDayInput.entityReturns.entries(),
|
||||
[5, new Float64Array(dates.length).fill(0.005)],
|
||||
]),
|
||||
events: [1, 2, 3, 4, 5].map(entityId => ({ entityId, dayIndex: 15 })),
|
||||
};
|
||||
const resTooFewDates = await runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: sameDayWithFive,
|
||||
options: { preDays: 3, postDays: 3, minEvents: 5 },
|
||||
})
|
||||
);
|
||||
expect(resTooFewDates.status).toBe('insufficient_data');
|
||||
if (resTooFewDates.status === 'insufficient_data') {
|
||||
expect(resTooFewDates.reason).toBe('too_few_event_dates');
|
||||
}
|
||||
|
||||
// zero_variance_series (identical constant returns on every date -> identical clustered meanCars)
|
||||
const constantReturns = new Map<number, Float64Array>([
|
||||
[1, new Float64Array(dates.length).fill(0.01)],
|
||||
[2, new Float64Array(dates.length).fill(0.01)],
|
||||
]);
|
||||
const constantInput: EventStudyInput = {
|
||||
sessionDates: dates,
|
||||
entityReturns: constantReturns,
|
||||
events: [
|
||||
{ entityId: 1, dayIndex: 6 },
|
||||
{ entityId: 2, dayIndex: 10 },
|
||||
{ entityId: 1, dayIndex: 14 },
|
||||
{ entityId: 2, dayIndex: 18 },
|
||||
{ entityId: 1, dayIndex: 22 },
|
||||
],
|
||||
};
|
||||
const resZeroVar = await runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: constantInput,
|
||||
options: { preDays: 2, postDays: 2, minEvents: 5 },
|
||||
})
|
||||
);
|
||||
expect(resZeroVar.status).toBe('insufficient_data');
|
||||
if (resZeroVar.status === 'insufficient_data') {
|
||||
expect(resZeroVar.reason).toBe('zero_variance_series');
|
||||
}
|
||||
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('propagates INSERT failure and wraps DSR-read failure with trialId and cause without retry', async () => {
|
||||
const insertError = new Error('event insert failed');
|
||||
const failInsertStore = createInMemoryTrialExecutor({ failOnInsert: insertError });
|
||||
await expect(runEventStudy(failInsertStore.executor, makeEventStudyRequest())).rejects.toBe(
|
||||
insertError
|
||||
);
|
||||
expect(failInsertStore.calls).toHaveLength(1);
|
||||
|
||||
const readError = new Error('event dsr read failed');
|
||||
const failReadStore = createInMemoryTrialExecutor({ failOnDsrRead: readError });
|
||||
const err = await expectStudyError(
|
||||
() => runEventStudy(failReadStore.executor, makeEventStudyRequest()),
|
||||
'dsr_read_failed'
|
||||
);
|
||||
expect(err.trialId).toBe(101);
|
||||
expect(err.cause).toBe(readError);
|
||||
expect(failReadStore.calls.filter(c => c.text.trimStart().startsWith('INSERT'))).toHaveLength(
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
it('validates inputs with zero queries and does not mutate frozen caller inputs', async () => {
|
||||
const { executor, calls } = createInMemoryTrialExecutor();
|
||||
|
||||
await expectStudyError(
|
||||
() =>
|
||||
runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: { sessionDates: [], entityReturns: new Map(), events: [] },
|
||||
})
|
||||
),
|
||||
'empty_panel'
|
||||
);
|
||||
await expectStudyError(
|
||||
() =>
|
||||
runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: {
|
||||
sessionDates: ['2025-01-05', '2025-01-04'],
|
||||
entityReturns: new Map(),
|
||||
events: [],
|
||||
},
|
||||
})
|
||||
),
|
||||
'unsorted_dates'
|
||||
);
|
||||
await expectStudyError(
|
||||
() =>
|
||||
runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: {
|
||||
sessionDates: ['2025-01-05', '2025-01-05'],
|
||||
entityReturns: new Map(),
|
||||
events: [],
|
||||
},
|
||||
})
|
||||
),
|
||||
'duplicate_date'
|
||||
);
|
||||
await expectStudyError(
|
||||
() =>
|
||||
runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
options: { postDays: -1 },
|
||||
})
|
||||
),
|
||||
'invalid_option'
|
||||
);
|
||||
await expectStudyError(
|
||||
() =>
|
||||
runEventStudy(
|
||||
executor,
|
||||
makeEventStudyRequest({
|
||||
input: {
|
||||
sessionDates: ['2025-01-05', '2025-01-06'],
|
||||
entityReturns: new Map(),
|
||||
events: [{ entityId: 1, dayIndex: -2 }],
|
||||
},
|
||||
})
|
||||
),
|
||||
'invalid_panel'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
|
||||
// Frozen immutability test
|
||||
const baseReq = makeEventStudyRequest();
|
||||
const frozenInput: EventStudyInput = Object.freeze({
|
||||
sessionDates: Object.freeze([...baseReq.input.sessionDates]),
|
||||
entityReturns: baseReq.input.entityReturns,
|
||||
benchmarkReturns: Object.freeze([...(baseReq.input.benchmarkReturns ?? [])]),
|
||||
events: Object.freeze(baseReq.input.events.map(e => Object.freeze({ ...e }))),
|
||||
});
|
||||
const frozenReq = Object.freeze({
|
||||
...baseReq,
|
||||
input: frozenInput,
|
||||
options: Object.freeze({ ...baseReq.options }),
|
||||
expression: Object.freeze({
|
||||
...baseReq.expression,
|
||||
params: Object.freeze({ minSurprisePct: 5 }),
|
||||
}),
|
||||
});
|
||||
|
||||
const okStore = createInMemoryTrialExecutor();
|
||||
const result = await runEventStudy(okStore.executor, frozenReq);
|
||||
expect(result.status).toBe('ok');
|
||||
});
|
||||
});
|
||||
256
test/postgres/signal-study.test.ts
Normal file
256
test/postgres/signal-study.test.ts
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
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 type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import { analyzeSignal, runEventStudy } from '@stock-bot/research';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('signal-study-postgres-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();
|
||||
});
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
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 makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out = new Array<string>(count);
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
let written = 0;
|
||||
while (written < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out[written] = current.toISOString().slice(0, 10);
|
||||
written += 1;
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeSignalPanel(dates: readonly string[], nNames: number, seed: number): SignalCrossSection[] {
|
||||
const rand = createSeededRng(seed);
|
||||
const ids = Array.from({ length: nNames }, (_, i) => i + 1);
|
||||
return dates.map((date, t) => {
|
||||
const signal = new Float64Array(nNames);
|
||||
const forwardReturn = new Float64Array(nNames);
|
||||
const slope = 0.002 + ((t % 5) - 2) * 0.0004;
|
||||
for (let i = 0; i < nNames; i += 1) {
|
||||
const s = rand() * 2 - 1;
|
||||
signal[i] = s;
|
||||
forwardReturn[i] = 0.0005 + slope * s + 0.015 * (rand() * 2 - 1);
|
||||
}
|
||||
return { date, ids, signal, forwardReturn };
|
||||
});
|
||||
}
|
||||
|
||||
function makeEventStudyInput(dates: readonly string[], eventDayIndices: readonly number[], seed: number): EventStudyInput {
|
||||
const rand = createSeededRng(seed);
|
||||
const entityReturns = new Map<number, Float64Array>();
|
||||
for (let entityId = 1; entityId <= 4; entityId += 1) {
|
||||
const series = new Float64Array(dates.length);
|
||||
for (let t = 0; t < dates.length; t += 1) {
|
||||
series[t] = (rand() - 0.5) * 0.02;
|
||||
}
|
||||
entityReturns.set(entityId, series);
|
||||
}
|
||||
const benchmarkReturns = new Float64Array(dates.length);
|
||||
for (let t = 0; t < dates.length; t += 1) {
|
||||
benchmarkReturns[t] = (rand() - 0.5) * 0.01;
|
||||
}
|
||||
return {
|
||||
sessionDates: dates,
|
||||
entityReturns,
|
||||
benchmarkReturns,
|
||||
events: eventDayIndices.map((dayIndex, idx) => ({
|
||||
entityId: (idx % 4) + 1,
|
||||
dayIndex,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('signal-study runners PostgreSQL integration', () => {
|
||||
test('appends 3 trials (2 signal_ic + 1 event_study), fences Vault dates, computes clusterSize=2 DSR, and writes 0 rows on insufficient_data', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const preDates = makeBusinessDates('2025-03-03', 35);
|
||||
const postDates = ['2025-05-01', '2025-05-02', '2025-05-05'];
|
||||
const allPanelDates = [...preDates, ...postDates];
|
||||
|
||||
const sig1 = await analyzeSignal(f.pool, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||||
params: { lookback: 20 },
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
panel: makeSignalPanel(allPanelDates, 20, 1001),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
});
|
||||
|
||||
expect(sig1.status).toBe('ok');
|
||||
if (sig1.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
expect(sig1.analysis.diagnostics.vaultExcludedDates).toBe(3);
|
||||
expect(sig1.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(sig1.deflatedSharpe.clusterSize).toBe(1);
|
||||
|
||||
const sig2 = await analyzeSignal(f.pool, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'rank(ret_10d) + zscore(turnover_20d)',
|
||||
params: { lookback: 10 },
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
panel: makeSignalPanel(allPanelDates, 20, 2002),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
});
|
||||
|
||||
expect(sig2.status).toBe('ok');
|
||||
if (sig2.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
expect(sig2.analysis.diagnostics.vaultExcludedDates).toBe(3);
|
||||
expect(sig2.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(sig2.trial.expressionHash).not.toBe(sig1.trial.expressionHash);
|
||||
expect(sig2.deflatedSharpe.clusterSize).toBe(2);
|
||||
expect(Number.isFinite(sig2.deflatedSharpe.effectiveTrials)).toBe(true);
|
||||
|
||||
const eventDates = makeBusinessDates('2025-02-03', 70);
|
||||
const cutoffIdx = eventDates.findIndex(d => d >= VAULT_CUTOFF);
|
||||
expect(cutoffIdx).toBeGreaterThan(35);
|
||||
|
||||
const evtRes = await runEventStudy(f.pool, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'earnings_beat_car',
|
||||
params: { minSurprisePct: 5 },
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
input: makeEventStudyInput(
|
||||
eventDates,
|
||||
[8, 12, 16, 20, 24, 28, cutoffIdx - 3, cutoffIdx + 1],
|
||||
3003
|
||||
),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
options: { preDays: 3, postDays: 5, minEvents: 5 },
|
||||
});
|
||||
|
||||
expect(evtRes.status).toBe('ok');
|
||||
if (evtRes.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
expect(evtRes.vaultExcludedEvents).toBe(2);
|
||||
expect(evtRes.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
||||
expect(evtRes.deflatedSharpe.clusterSize).toBe(3);
|
||||
|
||||
// Insufficient-data run must append 0 additional rows.
|
||||
const insufRes = await analyzeSignal(f.pool, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'too_short_signal',
|
||||
params: {},
|
||||
universe: 'US_EQ_TOP3000',
|
||||
horizon: '5d',
|
||||
},
|
||||
panel: makeSignalPanel(['2025-04-30', '2025-05-01'], 10, 4004),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
});
|
||||
expect(insufRes.status).toBe('insufficient_data');
|
||||
|
||||
const dbResult = await f.pool.query<{
|
||||
trial_id: string;
|
||||
stage: string;
|
||||
n_obs: number;
|
||||
expression_hash: string;
|
||||
sample_end: string;
|
||||
}>(
|
||||
`SELECT trial_id, stage, n_obs, expression_hash, sample_end::text AS sample_end
|
||||
FROM trial_ledger
|
||||
ORDER BY trial_id ASC`
|
||||
);
|
||||
|
||||
expect(dbResult.rows).toHaveLength(3);
|
||||
expect(dbResult.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']);
|
||||
expect(dbResult.rows[0]!.n_obs).toBe(sig1.trial.nObs);
|
||||
expect(dbResult.rows[1]!.n_obs).toBe(sig2.trial.nObs);
|
||||
expect(dbResult.rows[2]!.n_obs).toBe(evtRes.trial.nObs);
|
||||
|
||||
const hashes = new Set(dbResult.rows.map(r => r.expression_hash));
|
||||
expect(hashes.size).toBe(3);
|
||||
|
||||
for (const row of dbResult.rows) {
|
||||
expect(row.sample_end < VAULT_CUTOFF).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue