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
45a98d309e
commit
9d8dfc9bc8
4 changed files with 299 additions and 13 deletions
|
|
@ -13,10 +13,12 @@ import {
|
|||
SignalAnalysisError,
|
||||
analyzeSignalPanel,
|
||||
eventStudy,
|
||||
type EntityId,
|
||||
type EventStudyEvent,
|
||||
type EventStudyInput,
|
||||
type EventStudyOptions,
|
||||
type EventStudyResult,
|
||||
type NumericSeries,
|
||||
type SignalAnalysisOptions,
|
||||
type SignalCrossSection,
|
||||
type SignalPanelAnalysis,
|
||||
|
|
@ -156,6 +158,51 @@ 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;
|
||||
|
||||
function isNumericTypedArray(value: unknown): value is NumericTypedArray {
|
||||
return (
|
||||
value instanceof Float64Array ||
|
||||
value instanceof Float32Array ||
|
||||
value instanceof Int32Array ||
|
||||
value instanceof Uint32Array ||
|
||||
value instanceof Int16Array ||
|
||||
value instanceof Uint16Array ||
|
||||
value instanceof Int8Array ||
|
||||
value instanceof Uint8Array ||
|
||||
value instanceof Uint8ClampedArray
|
||||
);
|
||||
}
|
||||
|
||||
function isSupportedVector(value: unknown): value is readonly unknown[] | NumericTypedArray {
|
||||
return Array.isArray(value) || isNumericTypedArray(value);
|
||||
}
|
||||
|
||||
function sliceNumericSeries(series: NumericSeries, length: number): NumericSeries {
|
||||
if (series.length === length) {
|
||||
return series;
|
||||
}
|
||||
if (series instanceof Float64Array) {
|
||||
return series.subarray(0, length);
|
||||
}
|
||||
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;
|
||||
|
|
@ -318,6 +365,9 @@ async function persistTrialAndEvaluateDsr(
|
|||
}
|
||||
|
||||
// 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, {
|
||||
|
|
@ -358,7 +408,8 @@ export async function analyzeSignal(
|
|||
): Promise<AnalyzeSignalResult> {
|
||||
validateBaseRequest(executor, request, 'signal_ic');
|
||||
|
||||
const ledgerSeries: SignalLedgerSeries = request.ledgerSeries ?? 'rank_ic';
|
||||
const ledgerSeries: SignalLedgerSeries =
|
||||
request.ledgerSeries === undefined ? 'rank_ic' : request.ledgerSeries;
|
||||
if (ledgerSeries !== 'rank_ic' && ledgerSeries !== 'quantile_spread') {
|
||||
throw new SignalStudyError(
|
||||
'invalid_option',
|
||||
|
|
@ -380,6 +431,32 @@ export async function analyzeSignal(
|
|||
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, {
|
||||
|
|
@ -497,7 +574,8 @@ export async function runEventStudy(
|
|||
throw new SignalStudyError('invalid_option', 'request.options must be a non-null object.');
|
||||
}
|
||||
|
||||
const postDays = request.options?.postDays ?? DEFAULT_EVENT_POST_DAYS;
|
||||
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',
|
||||
|
|
@ -505,7 +583,7 @@ export async function runEventStudy(
|
|||
);
|
||||
}
|
||||
|
||||
const { sessionDates, events } = request.input;
|
||||
const { sessionDates, entityReturns, benchmarkReturns, events } = request.input;
|
||||
if (!Array.isArray(sessionDates)) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_panel',
|
||||
|
|
@ -522,8 +600,10 @@ export async function runEventStudy(
|
|||
throw new SignalStudyError('invalid_panel', 'request.input.events must be an array.');
|
||||
}
|
||||
|
||||
// Validate sessionDates ordering and calendar validity before vault fencing.
|
||||
// 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) {
|
||||
|
|
@ -540,9 +620,86 @@ export async function runEventStudy(
|
|||
);
|
||||
}
|
||||
}
|
||||
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.
|
||||
if (
|
||||
typeof entityReturns !== 'object' ||
|
||||
entityReturns === null ||
|
||||
typeof (entityReturns as { [Symbol.iterator]?: unknown })[Symbol.iterator] !== 'function'
|
||||
) {
|
||||
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) {
|
||||
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;
|
||||
|
|
@ -582,15 +739,17 @@ export async function runEventStudy(
|
|||
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(
|
||||
{
|
||||
...request.input,
|
||||
events: fencedEvents,
|
||||
},
|
||||
request.options
|
||||
);
|
||||
study = eventStudy(fencedInput, request.options);
|
||||
} catch (error) {
|
||||
if (error instanceof EventStudyError) {
|
||||
throw mapEventStudyError(error);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue