1032 lines
33 KiB
TypeScript
1032 lines
33 KiB
TypeScript
import type {
|
||
EventStudyDiagnostics,
|
||
EventStudyRecencyResult,
|
||
EventStudyResult,
|
||
NeweyWestResult,
|
||
} from '@stock-bot/calculations';
|
||
import { z } from 'zod';
|
||
import {
|
||
type EventPanelDiagnostics,
|
||
EventPanelError,
|
||
type EventPanelErrorCode,
|
||
type EventStudyBenchmarkMode,
|
||
type EventStudyExchangeCalendars,
|
||
buildEventStudyInput,
|
||
eventsTableToEventRows,
|
||
} from '../../event-panel';
|
||
import {
|
||
type BarRecord,
|
||
type EventKind,
|
||
type MarketDataStore,
|
||
MarketDataStoreValidationError,
|
||
type Table,
|
||
type TableRow,
|
||
type VaultFenceContext,
|
||
} from '../../market-data-store';
|
||
import { EVENT_KINDS } from '../../market-data-store-duckdb';
|
||
import { collectBars } from '../../signal-panel';
|
||
import {
|
||
type RunEventStudyInsufficientDataReason,
|
||
SignalStudyError,
|
||
type SignalStudyErrorCode,
|
||
type SignalStudyExpression,
|
||
type StudyTrialSummary,
|
||
runEventStudy,
|
||
} from '../../signal-study';
|
||
import {
|
||
type ClusterDeflatedSharpeResult,
|
||
HORIZON_BUCKETS,
|
||
type HorizonBucket,
|
||
TrialLedgerError,
|
||
type TrialLedgerErrorCode,
|
||
type TrialLedgerExecutor,
|
||
UNIVERSE_MARKETS,
|
||
type UniverseMarket,
|
||
} from '../../trial-ledger';
|
||
import type { McpToolCallResult } from '../protocol';
|
||
import { type McpToolEntry, defineMcpTool } from '../server';
|
||
import {
|
||
EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||
MAX_ECMASCRIPT_EPOCH_MS,
|
||
MCP_MAX_LISTING_IDS,
|
||
MS_PER_DAY,
|
||
createListingIdsFieldSchema,
|
||
createUniverseFieldSchema,
|
||
fenceVaultQueryBounds,
|
||
formatMappedStoreError,
|
||
hasExclusiveListingSelector,
|
||
isValidUtcBoundString,
|
||
resolvePreStartUniverseDate,
|
||
utcDateOf,
|
||
validateVaultCutoffTs,
|
||
} from './vault-fenced-input';
|
||
|
||
/** Hard maximum number of explicit `listingIds` accepted by `event_study`. */
|
||
export const EVENT_STUDY_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS;
|
||
|
||
/** Hard maximum pre-event window length in trading sessions. */
|
||
export const EVENT_STUDY_MAX_PRE_DAYS = 60;
|
||
|
||
/** Hard maximum post-event window length in trading sessions. */
|
||
export const EVENT_STUDY_MAX_POST_DAYS = 60;
|
||
|
||
/** Hard maximum number of event subtype entries accepted in `event.subtypes`. */
|
||
export const EVENT_STUDY_MAX_SUBTYPES = 100;
|
||
|
||
/** Hard maximum character length of each event subtype string in `event.subtypes`. */
|
||
export const EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128;
|
||
|
||
const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||
const AGENT_PRINCIPAL_RE =
|
||
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||
const UTC_BOUND_ERROR_MESSAGE =
|
||
'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.';
|
||
const EVENT_KIND_SET: ReadonlySet<string> = new Set<string>(EVENT_KINDS);
|
||
|
||
function canonicalDailyHorizonBucket(postDays: number): HorizonBucket {
|
||
return postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus';
|
||
}
|
||
|
||
function isValidEpochMs(value: unknown): value is number {
|
||
return (
|
||
typeof value === 'number' &&
|
||
Number.isFinite(value) &&
|
||
Number.isSafeInteger(value) &&
|
||
Math.abs(value) < MAX_ECMASCRIPT_EPOCH_MS
|
||
);
|
||
}
|
||
|
||
const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE);
|
||
|
||
const eventFilterSpecSchema = z
|
||
.object({
|
||
kinds: z
|
||
.array(z.enum(EVENT_KINDS))
|
||
.min(1)
|
||
.describe(
|
||
'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).'
|
||
),
|
||
subtypes: z
|
||
.array(z.string().min(1).max(EVENT_STUDY_MAX_SUBTYPE_LENGTH))
|
||
.min(1)
|
||
.max(EVENT_STUDY_MAX_SUBTYPES)
|
||
.optional()
|
||
.describe(
|
||
`Optional non-empty exact-match allow-list of event subtypes (max ${EVENT_STUDY_MAX_SUBTYPES} entries, ${EVENT_STUDY_MAX_SUBTYPE_LENGTH} chars each).`
|
||
),
|
||
})
|
||
.strict()
|
||
.describe('Event kind and optional subtype filter specification.');
|
||
|
||
/**
|
||
* Strict Zod input schema for the `event_study` MCP tool.
|
||
*
|
||
* Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and
|
||
* `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them
|
||
* or any other unknown top-level or nested key.
|
||
*/
|
||
export const eventStudyInputSchema = z
|
||
.object({
|
||
listingIds: createListingIdsFieldSchema(
|
||
'Explicit INT32 listing IDs to study (mutually exclusive with universe).'
|
||
),
|
||
universe: createUniverseFieldSchema(
|
||
'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'
|
||
),
|
||
from: utcBoundStringSchema.describe(
|
||
'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.'
|
||
),
|
||
to: utcBoundStringSchema.describe(
|
||
'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.'
|
||
),
|
||
asOf: utcBoundStringSchema
|
||
.optional()
|
||
.describe(
|
||
'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'
|
||
),
|
||
event: eventFilterSpecSchema,
|
||
preDays: z
|
||
.number()
|
||
.int()
|
||
.min(0)
|
||
.max(EVENT_STUDY_MAX_PRE_DAYS)
|
||
.describe(
|
||
`Pre-event window in trading sessions (0–${EVENT_STUDY_MAX_PRE_DAYS}).`
|
||
),
|
||
postDays: z
|
||
.number()
|
||
.int()
|
||
.min(0)
|
||
.max(EVENT_STUDY_MAX_POST_DAYS)
|
||
.describe(
|
||
`Post-event window in trading sessions (0–${EVENT_STUDY_MAX_POST_DAYS}).`
|
||
),
|
||
benchmark: z
|
||
.enum(['equal_weight', 'none'])
|
||
.default('equal_weight')
|
||
.describe(
|
||
'Benchmark return mode: equal_weight (cross-sectional mean of eligible listing returns) or none (default equal_weight).'
|
||
),
|
||
adjustment: z
|
||
.enum(['raw', 'split', 'total'])
|
||
.default('raw')
|
||
.describe('Bar price adjustment mode (default raw).'),
|
||
universeMarket: z
|
||
.enum(UNIVERSE_MARKETS)
|
||
.describe('Relatedness-cluster market bucket recorded in trial_ledger.'),
|
||
horizonBucket: z
|
||
.enum(HORIZON_BUCKETS)
|
||
.describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'),
|
||
campaignId: z
|
||
.string()
|
||
.regex(LEDGER_UUID_RE, 'Expected a UUID string.')
|
||
.optional()
|
||
.describe('Optional research campaign UUID recorded in trial_ledger.'),
|
||
hypothesisId: z
|
||
.string()
|
||
.regex(LEDGER_UUID_RE, 'Expected a UUID string.')
|
||
.optional()
|
||
.describe('Optional research hypothesis UUID recorded in trial_ledger.'),
|
||
})
|
||
.strict()
|
||
.superRefine((data, ctx) => {
|
||
if (!hasExclusiveListingSelector(data)) {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||
});
|
||
}
|
||
|
||
const expectedBucket = canonicalDailyHorizonBucket(data.postDays);
|
||
if (data.horizonBucket !== expectedBucket) {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
path: ['horizonBucket'],
|
||
message: `Daily postDays=${data.postDays} requires horizonBucket "${expectedBucket}".`,
|
||
});
|
||
}
|
||
|
||
if (data.universe !== undefined && data.universeMarket !== data.universe) {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
path: ['universeMarket'],
|
||
message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`,
|
||
});
|
||
}
|
||
});
|
||
|
||
export type EventStudyToolInput = z.infer<typeof eventStudyInputSchema>;
|
||
|
||
/** Query passed to the server-injected exchange-calendar resolver. */
|
||
export interface EventStudyExchangeCalendarQuery {
|
||
readonly listingIds: readonly number[];
|
||
readonly fromDate: string;
|
||
readonly toDate: string;
|
||
}
|
||
|
||
/** Server-injected exchange-calendar resolver returning actual session close calendars. */
|
||
export type EventStudyExchangeCalendarResolver = (
|
||
query: EventStudyExchangeCalendarQuery
|
||
) => Promise<EventStudyExchangeCalendars> | EventStudyExchangeCalendars;
|
||
|
||
/** Server-side injected configuration for {@link createEventStudyTool}. */
|
||
export interface EventStudyToolOptions {
|
||
readonly store: MarketDataStore;
|
||
readonly ledger: TrialLedgerExecutor;
|
||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||
readonly principalId: string;
|
||
readonly resolveExchangeCalendars: EventStudyExchangeCalendarResolver;
|
||
}
|
||
|
||
/** Projected CAR/AAR summary for one relative offset in `[-preDays, +postDays]`. */
|
||
export interface EventStudyOffsetSummary {
|
||
readonly offset: number;
|
||
readonly n: number;
|
||
readonly aar: number;
|
||
readonly caar: number;
|
||
readonly caarFromZero: number | null;
|
||
}
|
||
|
||
/** Bounded date-clustered CAR summary without raw per-date typed arrays. */
|
||
export interface EventStudyClusteredSummary {
|
||
readonly nDates: number;
|
||
readonly carMean: number;
|
||
readonly neweyWest: NeweyWestResult;
|
||
}
|
||
|
||
/** Bounded summary projection of {@link EventStudyResult}. */
|
||
export interface EventStudySummary {
|
||
readonly preDays: number;
|
||
readonly postDays: number;
|
||
readonly hasBenchmark: boolean;
|
||
readonly offsets: readonly EventStudyOffsetSummary[];
|
||
readonly clustered: EventStudyClusteredSummary | null;
|
||
readonly recency: EventStudyRecencyResult | null;
|
||
readonly diagnostics: EventStudyDiagnostics;
|
||
}
|
||
|
||
interface EventStudyResultBase {
|
||
readonly scope: 'vault_fenced';
|
||
readonly vaultCutoffTs: number;
|
||
readonly vaultCutoffDate: string;
|
||
readonly event: {
|
||
readonly kinds: readonly EventKind[];
|
||
readonly subtypes: readonly string[] | null;
|
||
};
|
||
readonly preDays: number;
|
||
readonly postDays: number;
|
||
readonly benchmark: EventStudyBenchmarkMode;
|
||
readonly adjustment: 'raw' | 'split' | 'total';
|
||
readonly universeMarket: UniverseMarket;
|
||
readonly horizonBucket: HorizonBucket;
|
||
readonly fromMs: number;
|
||
readonly toMs: number;
|
||
readonly asOfMs: number;
|
||
readonly effectiveFrom: string;
|
||
readonly effectiveTo: string;
|
||
readonly effectiveAsOf: string;
|
||
readonly clampedTo: boolean;
|
||
readonly clampedAsOf: boolean;
|
||
readonly listingCount: number;
|
||
readonly eventCount: number;
|
||
readonly vaultExcludedEvents: number;
|
||
readonly panelDiagnostics: EventPanelDiagnostics;
|
||
readonly study: EventStudySummary;
|
||
}
|
||
|
||
/** Structured JSON payload serialized into the `event_study` MCP text result. */
|
||
export type EventStudyResultPayload =
|
||
| (EventStudyResultBase & {
|
||
readonly status: 'ok';
|
||
readonly trial: StudyTrialSummary;
|
||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||
})
|
||
| (EventStudyResultBase & {
|
||
readonly status: 'insufficient_data';
|
||
readonly reason: RunEventStudyInsufficientDataReason;
|
||
});
|
||
|
||
class ExchangeCalendarResolverError extends Error {
|
||
override readonly name = 'ExchangeCalendarResolverError';
|
||
override readonly cause?: unknown;
|
||
|
||
constructor(cause: unknown) {
|
||
super('Exchange calendar resolution failed.', { cause });
|
||
this.cause = cause;
|
||
Object.setPrototypeOf(this, new.target.prototype);
|
||
}
|
||
}
|
||
|
||
const ZERO_EVENT_PANEL_DIAGNOSTICS: EventPanelDiagnostics = {
|
||
vaultExcludedDates: 0,
|
||
vaultExcludedEvents: 0,
|
||
droppedUnknownListing: 0,
|
||
droppedAfterLastSession: 0,
|
||
droppedMissingCalendarSession: 0,
|
||
duplicateEvents: 0,
|
||
duplicateBars: 0,
|
||
nonPositiveCloseReturns: 0,
|
||
};
|
||
|
||
const ZERO_EVENT_STUDY_DIAGNOSTICS: EventStudyDiagnostics = {
|
||
eventsIn: 0,
|
||
eventsUsed: 0,
|
||
droppedUnknownEntity: 0,
|
||
droppedWindowOutOfRange: 0,
|
||
droppedMissingReturns: 0,
|
||
duplicateEventsCollapsed: 0,
|
||
};
|
||
|
||
const EVENT_PANEL_ERROR_MESSAGES: Readonly<Record<EventPanelErrorCode, string>> = {
|
||
invalid_input: 'Invalid event panel input.',
|
||
invalid_date: 'Invalid event panel date.',
|
||
invalid_bar: 'Market bar data failed event panel validation.',
|
||
invalid_event: 'Event table data failed event panel validation.',
|
||
invalid_option: 'Invalid event panel option.',
|
||
duplicate_bar: 'Conflicting duplicate daily bars detected.',
|
||
};
|
||
|
||
const SIGNAL_STUDY_ERROR_MESSAGES: Readonly<Record<SignalStudyErrorCode, string>> = {
|
||
invalid_request: 'Invalid event study request.',
|
||
empty_panel: 'Event study session grid is empty.',
|
||
invalid_date: 'Invalid event study date.',
|
||
unsorted_dates: 'Event study session dates are not strictly ascending.',
|
||
duplicate_date: 'Duplicate date detected in event study session grid.',
|
||
invalid_panel: 'Event study panel failed validation.',
|
||
invalid_option: 'Invalid event study option.',
|
||
dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.',
|
||
};
|
||
|
||
const TRIAL_LEDGER_ERROR_MESSAGES: Readonly<Partial<Record<TrialLedgerErrorCode, string>>> = {
|
||
VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.',
|
||
INVALID_PRINCIPAL: 'Invalid trial ledger principal.',
|
||
INVALID_UUID: 'Invalid trial ledger UUID.',
|
||
INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.',
|
||
INVALID_DATE: 'Invalid trial ledger date.',
|
||
SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.',
|
||
ZERO_VARIANCE_SERIES: 'Observation series has zero variance.',
|
||
TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.',
|
||
};
|
||
|
||
function sortAndDedupeListingIds(ids: readonly number[]): number[] {
|
||
return [...new Set(ids)].sort((a, b) => a - b);
|
||
}
|
||
|
||
function sortAndDedupeStrings<T extends string>(items: readonly T[]): T[] {
|
||
return [...new Set(items)].sort() as T[];
|
||
}
|
||
|
||
function makeEmptyStudySummary(
|
||
preDays: number,
|
||
postDays: number,
|
||
hasBenchmark: boolean
|
||
): EventStudySummary {
|
||
return {
|
||
preDays,
|
||
postDays,
|
||
hasBenchmark,
|
||
offsets: [],
|
||
clustered: null,
|
||
recency: null,
|
||
diagnostics: ZERO_EVENT_STUDY_DIAGNOSTICS,
|
||
};
|
||
}
|
||
|
||
function projectStudySummary(study: EventStudyResult): EventStudySummary {
|
||
if (study.status === 'insufficient_data') {
|
||
return {
|
||
preDays: study.preDays,
|
||
postDays: study.postDays,
|
||
hasBenchmark: study.hasBenchmark,
|
||
offsets: [],
|
||
clustered: null,
|
||
recency: null,
|
||
diagnostics: study.diagnostics,
|
||
};
|
||
}
|
||
|
||
return {
|
||
preDays: study.preDays,
|
||
postDays: study.postDays,
|
||
hasBenchmark: study.hasBenchmark,
|
||
offsets: study.offsets.map(o => ({
|
||
offset: o.offset,
|
||
n: o.n,
|
||
aar: o.aar,
|
||
caar: o.caar,
|
||
caarFromZero: o.caarFromZero,
|
||
})),
|
||
clustered: {
|
||
nDates: study.clustered.nDates,
|
||
carMean: study.clustered.carMean,
|
||
neweyWest: study.clustered.neweyWest,
|
||
},
|
||
recency: study.recency,
|
||
diagnostics: study.diagnostics,
|
||
};
|
||
}
|
||
|
||
function filterEligibleBars(
|
||
bars: readonly BarRecord[],
|
||
listingIdSet: ReadonlySet<number>,
|
||
fromMs: number,
|
||
fromSubMs: number,
|
||
toMs: number,
|
||
asOfMs: number,
|
||
vaultCutoffTs: number,
|
||
vaultCutoffDate: string
|
||
): { readonly bars: BarRecord[]; readonly prePanelVaultExcludedDates: number } {
|
||
const eligible: BarRecord[] = [];
|
||
const vaultExcludedDates = new Set<string>();
|
||
const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs;
|
||
|
||
for (let i = 0; i < bars.length; i += 1) {
|
||
const row = bars[i];
|
||
if (typeof row !== 'object' || row === null) {
|
||
eligible.push(row as unknown as BarRecord);
|
||
continue;
|
||
}
|
||
if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) {
|
||
continue;
|
||
}
|
||
|
||
const tsValid = isValidEpochMs(row.ts);
|
||
const tsDate = tsValid ? utcDateOf(row.ts) : null;
|
||
const tsInVault = tsValid && (row.ts >= vaultCutoffTs || (tsDate as string) >= vaultCutoffDate);
|
||
if (tsInVault) {
|
||
vaultExcludedDates.add(tsDate as string);
|
||
continue;
|
||
}
|
||
|
||
if (tsValid) {
|
||
if (row.ts < minTsMs || row.ts > toMs || row.ts > asOfMs) {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
if (isValidEpochMs(row.knownAt)) {
|
||
if (
|
||
row.knownAt > asOfMs ||
|
||
row.knownAt >= vaultCutoffTs ||
|
||
utcDateOf(row.knownAt) >= vaultCutoffDate
|
||
) {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
eligible.push(row);
|
||
}
|
||
|
||
return {
|
||
bars: eligible,
|
||
prePanelVaultExcludedDates: vaultExcludedDates.size,
|
||
};
|
||
}
|
||
|
||
function filterEligibleEventsTable(params: {
|
||
readonly table: Table;
|
||
readonly listingIdSet: ReadonlySet<number>;
|
||
readonly kindSet: ReadonlySet<string>;
|
||
readonly subtypeSet: ReadonlySet<string> | null;
|
||
readonly fromMs: number;
|
||
readonly fromSubMs: number;
|
||
readonly toMs: number;
|
||
readonly asOfMs: number;
|
||
readonly vaultCutoffTs: number;
|
||
readonly vaultCutoffDate: string;
|
||
}): { readonly table: Table; readonly prePanelVaultExcludedEvents: number } {
|
||
const {
|
||
table,
|
||
listingIdSet,
|
||
kindSet,
|
||
subtypeSet,
|
||
fromMs,
|
||
fromSubMs,
|
||
toMs,
|
||
asOfMs,
|
||
vaultCutoffTs,
|
||
vaultCutoffDate,
|
||
} = params;
|
||
|
||
if (
|
||
typeof table !== 'object' ||
|
||
table === null ||
|
||
!Array.isArray(table.columns) ||
|
||
!Array.isArray(table.rows)
|
||
) {
|
||
return { table, prePanelVaultExcludedEvents: 0 };
|
||
}
|
||
|
||
const eligibleRows: TableRow[] = [];
|
||
let prePanelVaultExcludedEvents = 0;
|
||
// TableRow timestamps carry integer epoch-ms precision. When the effective start
|
||
// has non-zero microseconds (fromSubMs > 0), any row stamped at `fromMs` is either
|
||
// strictly earlier (e.g. `.123Z < .123456Z`) or ambiguous at the boundary ms, so
|
||
// require `ts >= fromMs + 1` conservatively.
|
||
const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs;
|
||
|
||
for (let i = 0; i < table.rows.length; i += 1) {
|
||
const row = table.rows[i];
|
||
if (typeof row !== 'object' || row === null || Array.isArray(row)) {
|
||
eligibleRows.push(row as TableRow);
|
||
continue;
|
||
}
|
||
|
||
const listingId = row.listing_id;
|
||
if (typeof listingId === 'number' && !listingIdSet.has(listingId)) {
|
||
continue;
|
||
}
|
||
|
||
// Drop valid but unrequested kinds/subtypes without counting them as Vault exclusions.
|
||
// Malformed kind/subtype values fall through so eventsTableToEventRows rejects them.
|
||
const kind = row.kind;
|
||
if (typeof kind === 'string' && EVENT_KIND_SET.has(kind) && !kindSet.has(kind)) {
|
||
continue;
|
||
}
|
||
if (subtypeSet !== null) {
|
||
const subtype = row.subtype;
|
||
if (subtype === null || (typeof subtype === 'string' && !subtypeSet.has(subtype))) {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
const knownAt = row.known_at;
|
||
const knownAtInVault =
|
||
isValidEpochMs(knownAt) &&
|
||
(knownAt >= vaultCutoffTs || utcDateOf(knownAt) >= vaultCutoffDate);
|
||
|
||
const ts = row.ts;
|
||
const tsInVault =
|
||
isValidEpochMs(ts) &&
|
||
(ts >= vaultCutoffTs || utcDateOf(ts) >= vaultCutoffDate);
|
||
|
||
if (knownAtInVault || tsInVault) {
|
||
prePanelVaultExcludedEvents += 1;
|
||
continue;
|
||
}
|
||
|
||
if (isValidEpochMs(knownAt) && knownAt > asOfMs) {
|
||
continue;
|
||
}
|
||
|
||
if (isValidEpochMs(ts)) {
|
||
if (ts < minTsMs || ts > toMs) {
|
||
continue;
|
||
}
|
||
} else {
|
||
throw new EventPanelError(
|
||
'invalid_event',
|
||
`Invalid ts in events table row[${i}]: ${String(ts)}.`
|
||
);
|
||
}
|
||
|
||
eligibleRows.push(row);
|
||
}
|
||
|
||
return {
|
||
table: {
|
||
columns: table.columns,
|
||
rows: eligibleRows,
|
||
},
|
||
prePanelVaultExcludedEvents,
|
||
};
|
||
}
|
||
|
||
function buildCanonicalEventStudyExpression(params: {
|
||
readonly input: EventStudyToolInput;
|
||
readonly canonicalKinds: readonly EventKind[];
|
||
readonly canonicalSubtypes: readonly string[] | undefined;
|
||
readonly listingIds: readonly number[];
|
||
readonly universeSnapshotDate: string | null;
|
||
readonly effectiveFrom: string;
|
||
readonly effectiveTo: string;
|
||
readonly effectiveAsOf: string;
|
||
}): SignalStudyExpression {
|
||
const {
|
||
input,
|
||
canonicalKinds,
|
||
canonicalSubtypes,
|
||
listingIds,
|
||
universeSnapshotDate,
|
||
effectiveFrom,
|
||
effectiveTo,
|
||
effectiveAsOf,
|
||
} = params;
|
||
|
||
return {
|
||
expression: `mcp:event_study:v1:${canonicalKinds.join(',')}`,
|
||
params: {
|
||
version: 1,
|
||
kinds: canonicalKinds,
|
||
subtypes: canonicalSubtypes ?? null,
|
||
preDays: input.preDays,
|
||
postDays: input.postDays,
|
||
benchmark: input.benchmark,
|
||
adjustment: input.adjustment,
|
||
effectiveFrom,
|
||
effectiveTo,
|
||
effectiveAsOf,
|
||
},
|
||
universe:
|
||
input.universe !== undefined
|
||
? {
|
||
kind: 'universe',
|
||
ref: input.universe,
|
||
snapshotDate: universeSnapshotDate,
|
||
listingIds,
|
||
}
|
||
: {
|
||
kind: 'listingIds',
|
||
listingIds,
|
||
},
|
||
horizon: `${input.postDays}d`,
|
||
};
|
||
}
|
||
|
||
function formatMappedEventStudyError(err: unknown): McpToolCallResult {
|
||
const storeMapped = formatMappedStoreError(err);
|
||
if (storeMapped !== null) {
|
||
return storeMapped;
|
||
}
|
||
|
||
if (err instanceof ExchangeCalendarResolverError) {
|
||
return {
|
||
content: [{ type: 'text', text: 'Error: Exchange calendar resolution failed.' }],
|
||
isError: true,
|
||
};
|
||
}
|
||
|
||
if (err instanceof EventPanelError) {
|
||
const detail = Object.prototype.hasOwnProperty.call(EVENT_PANEL_ERROR_MESSAGES, err.code)
|
||
? EVENT_PANEL_ERROR_MESSAGES[err.code]
|
||
: 'Event panel construction failed.';
|
||
return {
|
||
content: [{ type: 'text', text: `EventPanelError: ${detail}` }],
|
||
isError: true,
|
||
};
|
||
}
|
||
|
||
if (err instanceof SignalStudyError) {
|
||
const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code)
|
||
? SIGNAL_STUDY_ERROR_MESSAGES[err.code]
|
||
: 'Event study execution failed.';
|
||
return {
|
||
content: [{ type: 'text', text: `SignalStudyError: ${detail}` }],
|
||
isError: true,
|
||
};
|
||
}
|
||
|
||
if (err instanceof TrialLedgerError) {
|
||
const detail =
|
||
Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) &&
|
||
TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined
|
||
? TRIAL_LEDGER_ERROR_MESSAGES[err.code]
|
||
: 'Trial ledger operation failed.';
|
||
return {
|
||
content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }],
|
||
isError: true,
|
||
};
|
||
}
|
||
|
||
return {
|
||
content: [{ type: 'text', text: 'Error: Tool execution failed.' }],
|
||
isError: true,
|
||
};
|
||
}
|
||
|
||
function validateFactoryOptions(options: EventStudyToolOptions): number {
|
||
if (typeof options !== 'object' || options === null) {
|
||
throw new MarketDataStoreValidationError(
|
||
'Invalid `options`: expected an EventStudyToolOptions object.',
|
||
'options'
|
||
);
|
||
}
|
||
|
||
if (
|
||
typeof options.store !== 'object' ||
|
||
options.store === null ||
|
||
typeof options.store.bars !== 'function' ||
|
||
typeof options.store.events !== 'function' ||
|
||
typeof options.store.universe !== 'function'
|
||
) {
|
||
throw new MarketDataStoreValidationError(
|
||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `events`, and `universe`.',
|
||
'store'
|
||
);
|
||
}
|
||
|
||
if (
|
||
typeof options.ledger !== 'object' ||
|
||
options.ledger === null ||
|
||
typeof options.ledger.query !== 'function'
|
||
) {
|
||
throw new SignalStudyError(
|
||
'invalid_request',
|
||
'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.'
|
||
);
|
||
}
|
||
|
||
if (typeof options.resolveExchangeCalendars !== 'function') {
|
||
throw new EventPanelError(
|
||
'invalid_option',
|
||
'Invalid `resolveExchangeCalendars`: expected a function.'
|
||
);
|
||
}
|
||
|
||
if (
|
||
typeof options.principalId !== 'string' ||
|
||
(options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId))
|
||
) {
|
||
throw new TrialLedgerError(
|
||
'INVALID_PRINCIPAL',
|
||
`Invalid \`principalId\`: "${String(options.principalId)}".`
|
||
);
|
||
}
|
||
|
||
return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs);
|
||
}
|
||
|
||
/**
|
||
* Creates the Vault-fenced `event_study` MCP tool backed by an injected
|
||
* {@link MarketDataStore}, {@link TrialLedgerExecutor}, and exchange-calendar
|
||
* resolver.
|
||
*
|
||
* Enforces `scope: 'vault_fenced'`, fences bounds before any dependency call,
|
||
* resolves named universes strictly prior to the study start date, filters
|
||
* bars and events defensively against the effective window and Vault cutoff,
|
||
* anchors events using actual exchange close calendars, runs `runEventStudy`
|
||
* under the injected research principal, and returns a bounded summary payload.
|
||
*/
|
||
export function createEventStudyTool(options: EventStudyToolOptions): McpToolEntry {
|
||
const vaultCutoffTs = validateFactoryOptions(options);
|
||
const { store, ledger, principalId, resolveExchangeCalendars } = options;
|
||
|
||
return defineMcpTool({
|
||
name: 'event_study',
|
||
description:
|
||
'Run a Vault-fenced event study over daily bars and point-in-time events and record eligible trials to trial_ledger.',
|
||
inputSchema: eventStudyInputSchema,
|
||
async handler(input: EventStudyToolInput): Promise<McpToolCallResult> {
|
||
try {
|
||
const fenced = fenceVaultQueryBounds(
|
||
{
|
||
from: input.from,
|
||
to: input.to,
|
||
asOf: input.asOf,
|
||
},
|
||
vaultCutoffTs
|
||
);
|
||
|
||
const canonicalKinds = sortAndDedupeStrings(input.event.kinds);
|
||
const canonicalSubtypes =
|
||
input.event.subtypes !== undefined
|
||
? sortAndDedupeStrings(input.event.subtypes)
|
||
: undefined;
|
||
|
||
let listingIds: number[];
|
||
let universeSnapshotDate: string | null = null;
|
||
|
||
if (input.universe !== undefined) {
|
||
universeSnapshotDate = resolvePreStartUniverseDate(
|
||
fenced.fromMs,
|
||
fenced.asOfMs,
|
||
fenced.asOfSubMs
|
||
);
|
||
const resolved = await store.universe({
|
||
ref: input.universe,
|
||
date: universeSnapshotDate,
|
||
});
|
||
listingIds = sortAndDedupeListingIds(resolved);
|
||
} else {
|
||
listingIds = sortAndDedupeListingIds(input.listingIds ?? []);
|
||
}
|
||
|
||
const hasBenchmark = input.benchmark === 'equal_weight';
|
||
const basePayloadFields = {
|
||
scope: 'vault_fenced' as const,
|
||
vaultCutoffTs,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
event: {
|
||
kinds: canonicalKinds,
|
||
subtypes: canonicalSubtypes ?? null,
|
||
},
|
||
preDays: input.preDays,
|
||
postDays: input.postDays,
|
||
benchmark: input.benchmark,
|
||
adjustment: input.adjustment,
|
||
universeMarket: input.universeMarket,
|
||
horizonBucket: input.horizonBucket,
|
||
fromMs: fenced.fromMs,
|
||
toMs: fenced.toMs,
|
||
asOfMs: fenced.asOfMs,
|
||
effectiveFrom: fenced.canonicalFrom,
|
||
effectiveTo: fenced.canonicalTo,
|
||
effectiveAsOf: fenced.canonicalAsOf,
|
||
clampedTo: fenced.clampedTo,
|
||
clampedAsOf: fenced.clampedAsOf,
|
||
listingCount: listingIds.length,
|
||
};
|
||
|
||
if (listingIds.length === 0) {
|
||
const payload: EventStudyResultPayload = {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: 'below_min_events',
|
||
eventCount: 0,
|
||
vaultExcludedEvents: 0,
|
||
panelDiagnostics: ZERO_EVENT_PANEL_DIAGNOSTICS,
|
||
study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark),
|
||
};
|
||
return {
|
||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||
};
|
||
}
|
||
|
||
const rawBars = await collectBars(
|
||
store.bars({
|
||
listingIds,
|
||
timeframe: '1d',
|
||
from: fenced.canonicalFrom,
|
||
to: fenced.canonicalTo,
|
||
adjustment: input.adjustment,
|
||
asOf: fenced.canonicalAsOf,
|
||
scope: 'vault_fenced',
|
||
})
|
||
);
|
||
|
||
const rawEventsTable = await store.events({
|
||
kinds: canonicalKinds,
|
||
listingIds,
|
||
from: fenced.canonicalFrom,
|
||
to: fenced.canonicalTo,
|
||
asOf: fenced.canonicalAsOf,
|
||
});
|
||
|
||
const listingIdSet = new Set<number>(listingIds);
|
||
const kindSet = new Set<string>(canonicalKinds);
|
||
const subtypeSet = canonicalSubtypes !== undefined ? new Set<string>(canonicalSubtypes) : null;
|
||
|
||
const { bars: eligibleBars, prePanelVaultExcludedDates } = filterEligibleBars(
|
||
rawBars,
|
||
listingIdSet,
|
||
fenced.fromMs,
|
||
fenced.fromSubMs,
|
||
fenced.toMs,
|
||
fenced.asOfMs,
|
||
vaultCutoffTs,
|
||
fenced.vaultCutoffDate
|
||
);
|
||
|
||
const { table: eligibleEventsTable, prePanelVaultExcludedEvents } =
|
||
filterEligibleEventsTable({
|
||
table: rawEventsTable,
|
||
listingIdSet,
|
||
kindSet,
|
||
subtypeSet,
|
||
fromMs: fenced.fromMs,
|
||
fromSubMs: fenced.fromSubMs,
|
||
toMs: fenced.toMs,
|
||
asOfMs: fenced.asOfMs,
|
||
vaultCutoffTs,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
});
|
||
|
||
const events = eventsTableToEventRows(eligibleEventsTable, {
|
||
kinds: canonicalKinds,
|
||
...(canonicalSubtypes !== undefined ? { subtypes: canonicalSubtypes } : {}),
|
||
});
|
||
|
||
const fromDate = utcDateOf(fenced.fromMs);
|
||
const toDate = utcDateOf(fenced.toMs);
|
||
const asOfDate = utcDateOf(fenced.asOfMs);
|
||
const vaultCutoffDayStartMs = Math.floor(vaultCutoffTs / MS_PER_DAY) * MS_PER_DAY;
|
||
const lastPreVaultDate = utcDateOf(vaultCutoffDayStartMs - MS_PER_DAY);
|
||
const calendarToDate = [toDate, asOfDate, lastPreVaultDate].reduce((a, b) =>
|
||
a < b ? a : b
|
||
);
|
||
|
||
if (fromDate > calendarToDate) {
|
||
const panelDiagnostics: EventPanelDiagnostics = {
|
||
...ZERO_EVENT_PANEL_DIAGNOSTICS,
|
||
vaultExcludedDates: prePanelVaultExcludedDates,
|
||
vaultExcludedEvents: prePanelVaultExcludedEvents,
|
||
droppedUnknownListing: events.length,
|
||
};
|
||
const payload: EventStudyResultPayload = {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: 'below_min_events',
|
||
eventCount: 0,
|
||
vaultExcludedEvents: prePanelVaultExcludedEvents,
|
||
panelDiagnostics,
|
||
study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark),
|
||
};
|
||
return {
|
||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||
};
|
||
}
|
||
|
||
let exchangeCalendars: EventStudyExchangeCalendars;
|
||
try {
|
||
exchangeCalendars = await resolveExchangeCalendars({
|
||
listingIds,
|
||
fromDate,
|
||
toDate: calendarToDate,
|
||
});
|
||
} catch (err: unknown) {
|
||
if (err instanceof EventPanelError) {
|
||
throw err;
|
||
}
|
||
throw new ExchangeCalendarResolverError(err);
|
||
}
|
||
|
||
const built = buildEventStudyInput({
|
||
bars: eligibleBars,
|
||
events,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
benchmark: input.benchmark,
|
||
exchangeCalendars,
|
||
});
|
||
|
||
const combinedPanelDiagnostics: EventPanelDiagnostics = {
|
||
...built.diagnostics,
|
||
vaultExcludedDates: prePanelVaultExcludedDates + built.diagnostics.vaultExcludedDates,
|
||
vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents,
|
||
};
|
||
|
||
if (built.input.sessionDates.length === 0) {
|
||
const payload: EventStudyResultPayload = {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: 'below_min_events',
|
||
eventCount: 0,
|
||
vaultExcludedEvents: combinedPanelDiagnostics.vaultExcludedEvents,
|
||
panelDiagnostics: combinedPanelDiagnostics,
|
||
study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark),
|
||
};
|
||
return {
|
||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||
};
|
||
}
|
||
|
||
const expression = buildCanonicalEventStudyExpression({
|
||
input,
|
||
canonicalKinds,
|
||
canonicalSubtypes,
|
||
listingIds,
|
||
universeSnapshotDate,
|
||
effectiveFrom: fenced.canonicalFrom,
|
||
effectiveTo: fenced.canonicalTo,
|
||
effectiveAsOf: fenced.canonicalAsOf,
|
||
});
|
||
|
||
const studyResult = await runEventStudy(ledger, {
|
||
principalId,
|
||
...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}),
|
||
...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}),
|
||
universeMarket: input.universeMarket,
|
||
horizonBucket: input.horizonBucket,
|
||
expression,
|
||
input: built.input,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
options: {
|
||
preDays: input.preDays,
|
||
postDays: input.postDays,
|
||
},
|
||
});
|
||
|
||
const totalVaultExcludedEvents =
|
||
combinedPanelDiagnostics.vaultExcludedEvents + studyResult.vaultExcludedEvents;
|
||
const studySummary = projectStudySummary(studyResult.study);
|
||
|
||
const payload: EventStudyResultPayload =
|
||
studyResult.status === 'ok'
|
||
? {
|
||
...basePayloadFields,
|
||
status: 'ok',
|
||
eventCount: built.input.events.length,
|
||
vaultExcludedEvents: totalVaultExcludedEvents,
|
||
panelDiagnostics: combinedPanelDiagnostics,
|
||
study: studySummary,
|
||
trial: studyResult.trial,
|
||
deflatedSharpe: studyResult.deflatedSharpe,
|
||
}
|
||
: {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: studyResult.reason,
|
||
eventCount: built.input.events.length,
|
||
vaultExcludedEvents: totalVaultExcludedEvents,
|
||
panelDiagnostics: combinedPanelDiagnostics,
|
||
study: studySummary,
|
||
};
|
||
|
||
return {
|
||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||
};
|
||
} catch (err: unknown) {
|
||
return formatMappedEventStudyError(err);
|
||
}
|
||
},
|
||
});
|
||
}
|