876 lines
28 KiB
TypeScript
876 lines
28 KiB
TypeScript
/**
|
|
* 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 EntityId,
|
|
type EventStudyEvent,
|
|
type EventStudyInput,
|
|
type EventStudyOptions,
|
|
type EventStudyResult,
|
|
type NumericSeries,
|
|
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];
|
|
|
|
type NumericTypedArray =
|
|
| Float64Array
|
|
| Float32Array
|
|
| Int32Array
|
|
| Uint32Array
|
|
| Int16Array
|
|
| Uint16Array
|
|
| Int8Array
|
|
| Uint8Array
|
|
| Uint8ClampedArray;
|
|
|
|
const NUMERIC_TYPED_ARRAY_TAGS = new Set<string>([
|
|
'[object Float64Array]',
|
|
'[object Float32Array]',
|
|
'[object Int32Array]',
|
|
'[object Uint32Array]',
|
|
'[object Int16Array]',
|
|
'[object Uint16Array]',
|
|
'[object Int8Array]',
|
|
'[object Uint8Array]',
|
|
'[object Uint8ClampedArray]',
|
|
]);
|
|
|
|
function isNumericTypedArray(value: unknown): value is NumericTypedArray {
|
|
if (!ArrayBuffer.isView(value)) {
|
|
return false;
|
|
}
|
|
const tag = Object.prototype.toString.call(value);
|
|
if (!NUMERIC_TYPED_ARRAY_TAGS.has(tag)) {
|
|
return false;
|
|
}
|
|
return typeof (value as { subarray?: unknown }).subarray === 'function';
|
|
}
|
|
|
|
function isSupportedVector(value: unknown): value is readonly unknown[] | NumericTypedArray {
|
|
return Array.isArray(value) || isNumericTypedArray(value);
|
|
}
|
|
|
|
function isReadonlyMapLike(value: unknown): value is ReadonlyMap<unknown, unknown> {
|
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
return false;
|
|
}
|
|
const candidate = value as {
|
|
get?: unknown;
|
|
has?: unknown;
|
|
[Symbol.iterator]?: unknown;
|
|
};
|
|
return (
|
|
typeof candidate.get === 'function' &&
|
|
typeof candidate.has === 'function' &&
|
|
typeof candidate[Symbol.iterator] === 'function'
|
|
);
|
|
}
|
|
|
|
function sliceNumericSeries(series: NumericSeries, length: number): NumericSeries {
|
|
if (series.length === length) {
|
|
return series;
|
|
}
|
|
if (Array.isArray(series)) {
|
|
return series.slice(0, length);
|
|
}
|
|
if (isNumericTypedArray(series)) {
|
|
return series.subarray(0, length) as unknown as NumericSeries;
|
|
}
|
|
return series;
|
|
}
|
|
|
|
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.
|
|
// Only the newly written trial's observation dates are known here (no shared session grid
|
|
// for earlier cluster trials), so clusterDeflatedSharpe skips unaligned historical pairs
|
|
// (pairsUsed = 0) and falls back conservatively to count-based effectiveTrials = clusterSize.
|
|
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 === undefined ? 'rank_ic' : request.ledgerSeries;
|
|
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.');
|
|
}
|
|
|
|
for (let i = 0; i < request.panel.length; i += 1) {
|
|
const slice: unknown = request.panel[i];
|
|
if (typeof slice !== 'object' || slice === null) {
|
|
throw new SignalStudyError('invalid_panel', `panel[${i}] must be a non-null object.`);
|
|
}
|
|
const candidate = slice as Partial<SignalCrossSection>;
|
|
if (!isSupportedVector(candidate.ids)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`panel[${i}].ids must be an array or typed array of entity IDs.`
|
|
);
|
|
}
|
|
if (!isSupportedVector(candidate.signal)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`panel[${i}].signal must be an array or numeric typed array.`
|
|
);
|
|
}
|
|
if (!isSupportedVector(candidate.forwardReturn)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`panel[${i}].forwardReturn must be an array or numeric typed array.`
|
|
);
|
|
}
|
|
}
|
|
|
|
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 === undefined ? DEFAULT_EVENT_POST_DAYS : request.options.postDays;
|
|
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, entityReturns, benchmarkReturns, 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, and locate
|
|
// the exclusive pre-cutoff prefix boundary.
|
|
let prevDate = '';
|
|
let preCutoffLength = 0;
|
|
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}.`
|
|
);
|
|
}
|
|
}
|
|
if (currentDate < request.vaultCutoffDate) {
|
|
preCutoffLength += 1;
|
|
}
|
|
prevDate = currentDate;
|
|
}
|
|
|
|
const totalSessions = sessionDates.length;
|
|
|
|
// Validate return series shapes against the full calendar before slicing to the pre-cutoff
|
|
// prefix so excluded Vault-tail values (e.g. non-finite returns) never leak into or break
|
|
// the pre-Vault study. Require the ReadonlyMap lookup interface (get/has/iterator) so
|
|
// serialized pair arrays with duplicate keys are rejected rather than coerced into a Map.
|
|
if (!isReadonlyMapLike(entityReturns)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
'request.input.entityReturns must be a ReadonlyMap of entityId to return series.'
|
|
);
|
|
}
|
|
|
|
const needsVaultTrim = preCutoffLength < totalSessions;
|
|
let fencedBenchmarkReturns: NumericSeries | undefined;
|
|
if (benchmarkReturns !== undefined) {
|
|
if (!isSupportedVector(benchmarkReturns)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
'request.input.benchmarkReturns must be an array or numeric typed array.'
|
|
);
|
|
}
|
|
if (benchmarkReturns.length !== totalSessions) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`benchmarkReturns length (${benchmarkReturns.length}) does not match sessionDates length (${totalSessions}).`
|
|
);
|
|
}
|
|
fencedBenchmarkReturns = needsVaultTrim
|
|
? sliceNumericSeries(benchmarkReturns, preCutoffLength)
|
|
: benchmarkReturns;
|
|
}
|
|
|
|
const fencedEntityReturns = needsVaultTrim ? new Map<EntityId, NumericSeries>() : null;
|
|
for (const entry of entityReturns) {
|
|
if (!Array.isArray(entry) || entry.length < 2) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
'request.input.entityReturns entries must be [entityId, series] pairs.'
|
|
);
|
|
}
|
|
const entityId: unknown = entry[0];
|
|
const series: unknown = entry[1];
|
|
const validEntityId =
|
|
typeof entityId === 'string' || (typeof entityId === 'number' && !Number.isNaN(entityId));
|
|
if (!validEntityId) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
'entityReturns key must be a string or non-NaN number.'
|
|
);
|
|
}
|
|
if (!isSupportedVector(series)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`entityReturns[${String(entityId)}] must be an array or numeric typed array.`
|
|
);
|
|
}
|
|
if (series.length !== totalSessions) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`entityReturns[${String(entityId)}] length (${series.length}) does not match sessionDates length (${totalSessions}).`
|
|
);
|
|
}
|
|
if (fencedEntityReturns !== null) {
|
|
if (fencedEntityReturns.has(entityId)) {
|
|
throw new SignalStudyError(
|
|
'invalid_panel',
|
|
`Duplicate entityId "${String(entityId)}" in request.input.entityReturns.`
|
|
);
|
|
}
|
|
fencedEntityReturns.set(
|
|
entityId,
|
|
sliceNumericSeries(series as NumericSeries, preCutoffLength)
|
|
);
|
|
}
|
|
}
|
|
|
|
// 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 });
|
|
}
|
|
|
|
const fencedSessionDates = needsVaultTrim ? sessionDates.slice(0, preCutoffLength) : sessionDates;
|
|
const fencedInput: EventStudyInput = {
|
|
sessionDates: fencedSessionDates,
|
|
entityReturns: fencedEntityReturns ?? entityReturns,
|
|
...(fencedBenchmarkReturns !== undefined ? { benchmarkReturns: fencedBenchmarkReturns } : {}),
|
|
events: fencedEvents,
|
|
};
|
|
|
|
let study: EventStudyResult;
|
|
try {
|
|
study = eventStudy(fencedInput, 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,
|
|
};
|
|
}
|