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:
Studio 2026-11-28 03:27:47 -05:00
parent 17808bbda4
commit 45a98d309e
7 changed files with 2033 additions and 0 deletions

View file

@ -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';

View 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,
};
}