1201 lines
39 KiB
TypeScript
1201 lines
39 KiB
TypeScript
import {
|
||
type IcSummary,
|
||
type RecencySplitResult,
|
||
type SignalPanelAnalysis,
|
||
type SignalPanelDiagnostics as CalcSignalPanelDiagnostics,
|
||
analyzeSignalPanel,
|
||
} from '@stock-bot/calculations';
|
||
import { z } from 'zod';
|
||
import {
|
||
type BarRecord,
|
||
type MarketDataStore,
|
||
MarketDataStoreValidationError,
|
||
type Table,
|
||
type TableRow,
|
||
type VaultFenceContext,
|
||
} from '../../market-data-store';
|
||
import {
|
||
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
||
type FundamentalsPitValueField,
|
||
UNIVERSE_REFS,
|
||
} from '../../market-data-store-duckdb';
|
||
import {
|
||
SHORTS_SIGNAL_FIELDS,
|
||
type SignalObservation,
|
||
type SignalPanelDiagnostics,
|
||
SignalPanelError,
|
||
type SignalPanelErrorCode,
|
||
buildForwardReturnPanel,
|
||
collectBars,
|
||
shortsTableToSignalRows,
|
||
} from '../../signal-panel';
|
||
import {
|
||
type AnalyzeSignalInsufficientDataReason,
|
||
type SignalLedgerSeries,
|
||
SignalStudyError,
|
||
type SignalStudyErrorCode,
|
||
type SignalStudyExpression,
|
||
type StudyTrialSummary,
|
||
analyzeSignal,
|
||
} from '../../signal-study';
|
||
import {
|
||
type ClusterDeflatedSharpeResult,
|
||
HORIZON_BUCKETS,
|
||
type HorizonBucket,
|
||
TrialLedgerError,
|
||
type TrialLedgerErrorCode,
|
||
type TrialLedgerExecutor,
|
||
UNIVERSE_MARKETS,
|
||
type UniverseMarket,
|
||
} from '../../trial-ledger';
|
||
import type { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol';
|
||
import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server';
|
||
import {
|
||
EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||
MCP_MAX_LISTING_IDS,
|
||
createListingIdsFieldSchema,
|
||
createUniverseFieldSchema,
|
||
fenceVaultQueryBounds,
|
||
formatMappedStoreError,
|
||
formatUtcIsoWithMicros,
|
||
hasExclusiveListingSelector,
|
||
isValidUtcBoundString,
|
||
resolvePreStartUniverseDate,
|
||
utcDateOf,
|
||
validateVaultCutoffTs,
|
||
} from './vault-fenced-input';
|
||
|
||
/** Hard maximum number of explicit `listingIds` accepted by `analyze_signal`. */
|
||
export const ANALYZE_SIGNAL_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS;
|
||
|
||
/** Hard maximum forward-return horizon in trading sessions. */
|
||
export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252;
|
||
|
||
/** Maximum number of latest dated observations exposed in the tool response preview. */
|
||
export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100;
|
||
|
||
/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */
|
||
export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120;
|
||
|
||
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 SUPPORTED_UNIVERSE_REF_SET: ReadonlySet<string> = new Set(UNIVERSE_REFS);
|
||
|
||
function canonicalDailyHorizonBucket(horizonSessions: number): HorizonBucket {
|
||
return horizonSessions <= 10 ? 'swing_1_10d' : 'position_10d_plus';
|
||
}
|
||
|
||
const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE);
|
||
|
||
const shortsSignalSpecSchema = z
|
||
.object({
|
||
source: z.literal('shorts').describe('Signal data source ("shorts").'),
|
||
field: z
|
||
.enum(SHORTS_SIGNAL_FIELDS)
|
||
.describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'),
|
||
})
|
||
.strict()
|
||
.describe('Short-interest signal specification.');
|
||
|
||
const fundamentalsSignalSpecSchema = z
|
||
.object({
|
||
source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'),
|
||
field: z
|
||
.enum(FUNDAMENTALS_PIT_VALUE_FIELDS)
|
||
.describe(
|
||
'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).'
|
||
),
|
||
allowEstimatedLag: z
|
||
.boolean()
|
||
.default(false)
|
||
.describe(
|
||
'Whether to include fundamentals snapshots with estimated publication lag (default false).'
|
||
),
|
||
})
|
||
.strict()
|
||
.describe('Point-in-time fundamentals signal specification.');
|
||
|
||
const signalSpecSchema = z
|
||
.discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema])
|
||
.describe('Discriminated signal source and field specification ("shorts" or "fundamentals").');
|
||
|
||
const analyzeSignalSharedFieldsSchema = 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.'
|
||
),
|
||
horizonSessions: z
|
||
.number()
|
||
.int()
|
||
.min(1)
|
||
.max(ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS)
|
||
.describe(
|
||
`Forward-return horizon in trading sessions (1–${ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS}).`
|
||
),
|
||
maxSignalAgeSessions: z
|
||
.number()
|
||
.int()
|
||
.min(0)
|
||
.max(Number.MAX_SAFE_INTEGER)
|
||
.optional()
|
||
.describe('Optional maximum signal age in trading sessions before a signal is treated as stale.'),
|
||
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.'),
|
||
ledgerSeries: z
|
||
.enum(['rank_ic', 'quantile_spread'])
|
||
.default('rank_ic')
|
||
.describe('Daily series recorded to trial_ledger and evaluated for DSR (default rank_ic).'),
|
||
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.'),
|
||
adjustment: z
|
||
.enum(['raw', 'split', 'total'])
|
||
.default('raw')
|
||
.describe('Bar price adjustment mode (default raw).'),
|
||
})
|
||
.strict();
|
||
|
||
/**
|
||
* Strict Zod input schema for the `analyze_signal` 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 analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema
|
||
.extend({
|
||
signal: signalSpecSchema,
|
||
})
|
||
.strict()
|
||
.superRefine((data, ctx) => {
|
||
if (!hasExclusiveListingSelector(data)) {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||
});
|
||
}
|
||
|
||
const expectedBucket = canonicalDailyHorizonBucket(data.horizonSessions);
|
||
if (data.horizonBucket !== expectedBucket) {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
path: ['horizonBucket'],
|
||
message: `Daily horizonSessions=${data.horizonSessions} requires horizonBucket "${expectedBucket}".`,
|
||
});
|
||
}
|
||
|
||
if (data.universe !== undefined && SUPPORTED_UNIVERSE_REF_SET.has(data.universe)) {
|
||
if (data.universeMarket !== data.universe) {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
path: ['universeMarket'],
|
||
message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`,
|
||
});
|
||
}
|
||
} else if (data.universeMarket === 'FX') {
|
||
ctx.addIssue({
|
||
code: z.ZodIssueCode.custom,
|
||
path: ['universeMarket'],
|
||
message:
|
||
data.signal.source === 'shorts'
|
||
? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).'
|
||
: 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).',
|
||
});
|
||
}
|
||
});
|
||
|
||
export type AnalyzeSignalInput = z.infer<typeof analyzeSignalInputSchema>;
|
||
|
||
function buildAnalyzeSignalJsonSchema(): JsonSchemaObject {
|
||
const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema);
|
||
const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema);
|
||
const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema);
|
||
const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? {
|
||
type: 'boolean' as const,
|
||
default: false,
|
||
};
|
||
const signalProperty: JsonSchemaProperty = {
|
||
type: 'object',
|
||
description: signalSpecSchema.description,
|
||
properties: {
|
||
source: {
|
||
type: 'string',
|
||
enum: ['shorts', 'fundamentals'],
|
||
description: 'Signal data source ("shorts" or "fundamentals").',
|
||
},
|
||
field: {
|
||
type: 'string',
|
||
enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS],
|
||
description: 'Signal field name valid for the chosen source.',
|
||
},
|
||
allowEstimatedLag: allowEstimatedLagProp,
|
||
},
|
||
required: ['source', 'field'],
|
||
additionalProperties: false,
|
||
anyOf: [shortsBranch, fundamentalsBranch],
|
||
};
|
||
|
||
return {
|
||
type: 'object',
|
||
properties: {
|
||
...sharedSchema.properties,
|
||
signal: signalProperty,
|
||
},
|
||
required: [...(sharedSchema.required ?? []), 'signal'],
|
||
additionalProperties: false,
|
||
};
|
||
}
|
||
|
||
const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema();
|
||
|
||
/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */
|
||
export interface AnalyzeSignalToolOptions {
|
||
readonly store: MarketDataStore;
|
||
readonly ledger: TrialLedgerExecutor;
|
||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||
readonly principalId: string;
|
||
}
|
||
|
||
/** Single dated observation in the bounded series preview. */
|
||
export interface AnalyzeSignalSeriesPoint {
|
||
readonly date: string;
|
||
readonly value: number;
|
||
}
|
||
|
||
/** Bounded preview of the selected ledger series (latest 100 observations). */
|
||
export interface AnalyzeSignalSeriesPreview {
|
||
readonly series: SignalLedgerSeries;
|
||
readonly totalCount: number;
|
||
readonly truncated: boolean;
|
||
readonly points: readonly AnalyzeSignalSeriesPoint[];
|
||
}
|
||
|
||
/** Projected quantile-spread summary without raw per-bucket typed arrays. */
|
||
export interface AnalyzeSignalQuantilesSummary {
|
||
readonly quantiles: number;
|
||
readonly validDates: number;
|
||
readonly skippedDates: number;
|
||
readonly bucketMeanReturns: readonly (number | null)[];
|
||
readonly spreadSummary: IcSummary;
|
||
}
|
||
|
||
/** Projected top/bottom quantile membership turnover summary. */
|
||
export interface AnalyzeSignalTurnoverSummary {
|
||
readonly count: number;
|
||
readonly meanTopTurnover: number | null;
|
||
readonly meanBottomTurnover: number | null;
|
||
}
|
||
|
||
/** Bounded summary projection of {@link SignalPanelAnalysis}. */
|
||
export interface AnalyzeSignalAnalysisSummary {
|
||
readonly pearsonIc: IcSummary;
|
||
readonly rankIc: IcSummary;
|
||
readonly quantiles: AnalyzeSignalQuantilesSummary;
|
||
readonly turnover: AnalyzeSignalTurnoverSummary;
|
||
readonly recency: RecencySplitResult;
|
||
readonly diagnostics: CalcSignalPanelDiagnostics;
|
||
readonly ledgerSeries: AnalyzeSignalSeriesPreview;
|
||
}
|
||
|
||
interface AnalyzeSignalResultBase {
|
||
readonly scope: 'vault_fenced';
|
||
readonly vaultCutoffTs: number;
|
||
readonly vaultCutoffDate: string;
|
||
readonly signal: AnalyzeSignalInput['signal'];
|
||
readonly horizonSessions: number;
|
||
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 panelDiagnostics: SignalPanelDiagnostics;
|
||
readonly analysis: AnalyzeSignalAnalysisSummary;
|
||
}
|
||
|
||
/** Structured JSON payload serialized into the `analyze_signal` MCP text result. */
|
||
export type AnalyzeSignalResultPayload =
|
||
| (AnalyzeSignalResultBase & {
|
||
readonly status: 'ok';
|
||
readonly trial: StudyTrialSummary;
|
||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||
})
|
||
| (AnalyzeSignalResultBase & {
|
||
readonly status: 'insufficient_data';
|
||
readonly reason: AnalyzeSignalInsufficientDataReason;
|
||
});
|
||
|
||
const ZERO_PANEL_DIAGNOSTICS: SignalPanelDiagnostics = {
|
||
vaultExcludedDates: 0,
|
||
droppedNoSignal: 0,
|
||
droppedStaleSignal: 0,
|
||
droppedMissingForwardBar: 0,
|
||
droppedNonPositiveClose: 0,
|
||
duplicateBars: 0,
|
||
};
|
||
|
||
const SIGNAL_PANEL_ERROR_MESSAGES: Readonly<Record<SignalPanelErrorCode, string>> = {
|
||
invalid_input: 'Invalid signal panel input.',
|
||
invalid_horizon: 'Invalid forward-return horizon.',
|
||
invalid_option: 'Invalid signal panel option.',
|
||
invalid_date: 'Invalid signal panel date.',
|
||
invalid_bar: 'Market bar data failed panel validation.',
|
||
invalid_signal: 'Signal table data failed panel validation.',
|
||
duplicate_bar: 'Conflicting duplicate daily bars detected.',
|
||
};
|
||
|
||
const SIGNAL_STUDY_ERROR_MESSAGES: Readonly<Record<SignalStudyErrorCode, string>> = {
|
||
invalid_request: 'Invalid signal study request.',
|
||
empty_panel: 'Signal panel is empty.',
|
||
invalid_date: 'Invalid signal study date.',
|
||
unsorted_dates: 'Signal panel dates are not strictly ascending.',
|
||
duplicate_date: 'Duplicate date detected in signal panel.',
|
||
invalid_panel: 'Signal panel failed validation.',
|
||
invalid_option: 'Invalid signal 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 projectAnalysisSummary(
|
||
analysis: SignalPanelAnalysis,
|
||
selectedSeries: SignalLedgerSeries
|
||
): AnalyzeSignalAnalysisSummary {
|
||
const rawDates = selectedSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates;
|
||
const rawValues =
|
||
selectedSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries;
|
||
const totalCount = Math.min(rawDates.length, rawValues.length);
|
||
const truncated = totalCount > ANALYZE_SIGNAL_MAX_SERIES_POINTS;
|
||
const startIdx = truncated ? totalCount - ANALYZE_SIGNAL_MAX_SERIES_POINTS : 0;
|
||
const points: AnalyzeSignalSeriesPoint[] = [];
|
||
|
||
for (let i = startIdx; i < totalCount; i += 1) {
|
||
points.push({
|
||
date: rawDates[i] as string,
|
||
value: rawValues[i] as number,
|
||
});
|
||
}
|
||
|
||
return {
|
||
pearsonIc: analysis.pearsonIc,
|
||
rankIc: analysis.rankIc,
|
||
quantiles: {
|
||
quantiles: analysis.quantiles.quantiles,
|
||
validDates: analysis.quantiles.validDates,
|
||
skippedDates: analysis.quantiles.skippedDates,
|
||
bucketMeanReturns: [...analysis.quantiles.bucketMeanReturns],
|
||
spreadSummary: analysis.quantiles.spreadSummary,
|
||
},
|
||
turnover: {
|
||
count: analysis.turnover.count,
|
||
meanTopTurnover: analysis.turnover.meanTopTurnover,
|
||
meanBottomTurnover: analysis.turnover.meanBottomTurnover,
|
||
},
|
||
recency: analysis.recency,
|
||
diagnostics: analysis.diagnostics,
|
||
ledgerSeries: {
|
||
series: selectedSeries,
|
||
totalCount,
|
||
truncated,
|
||
points,
|
||
},
|
||
};
|
||
}
|
||
|
||
function filterEligibleBars(
|
||
bars: readonly BarRecord[],
|
||
listingIdSet: ReadonlySet<number>,
|
||
fromMs: number,
|
||
toMs: number,
|
||
asOfMs: number,
|
||
vaultCutoffTs: number,
|
||
vaultCutoffDate: string
|
||
): BarRecord[] {
|
||
const eligible: BarRecord[] = [];
|
||
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.ts === 'number' && Number.isFinite(row.ts)) {
|
||
if (
|
||
row.ts < fromMs ||
|
||
row.ts > toMs ||
|
||
row.ts > asOfMs ||
|
||
row.ts >= vaultCutoffTs ||
|
||
utcDateOf(row.ts) >= vaultCutoffDate
|
||
) {
|
||
continue;
|
||
}
|
||
}
|
||
if (typeof row.knownAt === 'number' && Number.isFinite(row.knownAt)) {
|
||
if (row.knownAt > asOfMs || row.knownAt >= vaultCutoffTs) {
|
||
continue;
|
||
}
|
||
}
|
||
if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) {
|
||
continue;
|
||
}
|
||
eligible.push(row);
|
||
}
|
||
return eligible;
|
||
}
|
||
|
||
function filterEligibleShortsTable(
|
||
table: Table,
|
||
listingIdSet: ReadonlySet<number>,
|
||
fromUtcDate: string,
|
||
toUtcDate: string,
|
||
asOfMs: number,
|
||
vaultCutoffTs: number,
|
||
vaultCutoffDate: string
|
||
): Table {
|
||
if (
|
||
typeof table !== 'object' ||
|
||
table === null ||
|
||
!Array.isArray(table.columns) ||
|
||
!Array.isArray(table.rows)
|
||
) {
|
||
return table;
|
||
}
|
||
|
||
const eligibleRows: TableRow[] = [];
|
||
for (let i = 0; i < table.rows.length; i += 1) {
|
||
const row = table.rows[i];
|
||
if (typeof row !== 'object' || row === null) {
|
||
eligibleRows.push(row as TableRow);
|
||
continue;
|
||
}
|
||
const knownAt = row.known_at;
|
||
if (typeof knownAt === 'number' && Number.isFinite(knownAt)) {
|
||
if (knownAt > asOfMs || knownAt >= vaultCutoffTs) {
|
||
continue;
|
||
}
|
||
}
|
||
const reportDate = row.report_date;
|
||
if (typeof reportDate === 'string') {
|
||
if (reportDate < fromUtcDate || reportDate > toUtcDate || reportDate >= vaultCutoffDate) {
|
||
continue;
|
||
}
|
||
}
|
||
const listingId = row.listing_id;
|
||
if (typeof listingId === 'number' && !listingIdSet.has(listingId)) {
|
||
continue;
|
||
}
|
||
eligibleRows.push(row);
|
||
}
|
||
|
||
return {
|
||
columns: table.columns,
|
||
rows: eligibleRows,
|
||
};
|
||
}
|
||
|
||
function deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] {
|
||
const latestByMonth = new Map<string, string>();
|
||
for (let i = 0; i < bars.length; i += 1) {
|
||
const bar = bars[i];
|
||
if (
|
||
typeof bar !== 'object' ||
|
||
bar === null ||
|
||
typeof bar.ts !== 'number' ||
|
||
!Number.isFinite(bar.ts)
|
||
) {
|
||
continue;
|
||
}
|
||
const sessionDate = utcDateOf(bar.ts);
|
||
const monthKey = sessionDate.slice(0, 7);
|
||
const prev = latestByMonth.get(monthKey);
|
||
if (prev === undefined || sessionDate > prev) {
|
||
latestByMonth.set(monthKey, sessionDate);
|
||
}
|
||
}
|
||
return [...latestByMonth.values()].sort();
|
||
}
|
||
|
||
function resolveSnapshotAsOf(
|
||
snapshotDate: string,
|
||
fencedAsOfMs: number,
|
||
canonicalAsOf: string
|
||
): { readonly asOf: string; readonly asOfMs: number } {
|
||
const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`);
|
||
if (fencedAsOfMs <= snapshotDayEndMs) {
|
||
return {
|
||
asOf: canonicalAsOf,
|
||
asOfMs: fencedAsOfMs,
|
||
};
|
||
}
|
||
return {
|
||
asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999),
|
||
asOfMs: snapshotDayEndMs,
|
||
};
|
||
}
|
||
|
||
function buildBarTimestampsByListing(bars: readonly BarRecord[]): Map<number, number[]> {
|
||
const byListing = new Map<number, number[]>();
|
||
for (let i = 0; i < bars.length; i += 1) {
|
||
const bar = bars[i];
|
||
if (
|
||
typeof bar !== 'object' ||
|
||
bar === null ||
|
||
typeof bar.listingId !== 'number' ||
|
||
!Number.isSafeInteger(bar.listingId) ||
|
||
typeof bar.ts !== 'number' ||
|
||
!Number.isFinite(bar.ts)
|
||
) {
|
||
continue;
|
||
}
|
||
let list = byListing.get(bar.listingId);
|
||
if (list === undefined) {
|
||
list = [];
|
||
byListing.set(bar.listingId, list);
|
||
}
|
||
list.push(bar.ts);
|
||
}
|
||
for (const [lid, list] of byListing) {
|
||
list.sort((a, b) => a - b);
|
||
let write = 0;
|
||
for (let i = 0; i < list.length; i += 1) {
|
||
const ts = list[i] as number;
|
||
if (write === 0 || list[write - 1] !== ts) {
|
||
list[write] = ts;
|
||
write += 1;
|
||
}
|
||
}
|
||
list.length = write;
|
||
byListing.set(lid, list);
|
||
}
|
||
return byListing;
|
||
}
|
||
|
||
function findLatestBarBefore(
|
||
sortedTs: readonly number[] | undefined,
|
||
upperExclusiveMs: number,
|
||
lowerExclusiveMs: number
|
||
): number | null {
|
||
if (sortedTs === undefined || sortedTs.length === 0) {
|
||
return null;
|
||
}
|
||
let lo = 0;
|
||
let hi = sortedTs.length;
|
||
while (lo < hi) {
|
||
const mid = (lo + hi) >>> 1;
|
||
if ((sortedTs[mid] as number) < upperExclusiveMs) {
|
||
lo = mid + 1;
|
||
} else {
|
||
hi = mid;
|
||
}
|
||
}
|
||
const idx = lo - 1;
|
||
if (idx < 0) {
|
||
return null;
|
||
}
|
||
const candidate = sortedTs[idx] as number;
|
||
return candidate > lowerExclusiveMs ? candidate : null;
|
||
}
|
||
|
||
function appendEligibleFundamentalsObservations(params: {
|
||
readonly table: Table;
|
||
readonly field: FundamentalsPitValueField;
|
||
readonly listingIdSet: ReadonlySet<number>;
|
||
readonly snapshotAsOfMs: number;
|
||
readonly fencedAsOfMs: number;
|
||
readonly vaultCutoffTs: number;
|
||
readonly seenKeys: Set<string>;
|
||
readonly out: SignalObservation[];
|
||
}): Map<number, number> {
|
||
const {
|
||
table,
|
||
field,
|
||
listingIdSet,
|
||
snapshotAsOfMs,
|
||
fencedAsOfMs,
|
||
vaultCutoffTs,
|
||
seenKeys,
|
||
out,
|
||
} = params;
|
||
|
||
if (
|
||
typeof table !== 'object' ||
|
||
table === null ||
|
||
!Array.isArray(table.columns) ||
|
||
!Array.isArray(table.rows)
|
||
) {
|
||
throw new SignalPanelError(
|
||
'invalid_input',
|
||
'Expected a fundamentals Table object with array columns and rows.'
|
||
);
|
||
}
|
||
|
||
const latestKnownAtByListing = new Map<number, number>();
|
||
|
||
for (let i = 0; i < table.rows.length; i += 1) {
|
||
const row = table.rows[i];
|
||
if (typeof row !== 'object' || row === null) {
|
||
continue;
|
||
}
|
||
|
||
const listingId = row.listing_id;
|
||
if (
|
||
typeof listingId !== 'number' ||
|
||
!Number.isSafeInteger(listingId) ||
|
||
!listingIdSet.has(listingId)
|
||
) {
|
||
continue;
|
||
}
|
||
|
||
const knownAt = row.effective_known_at;
|
||
if (
|
||
typeof knownAt !== 'number' ||
|
||
!Number.isFinite(knownAt) ||
|
||
!Number.isSafeInteger(knownAt)
|
||
) {
|
||
continue;
|
||
}
|
||
if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) {
|
||
continue;
|
||
}
|
||
|
||
const rawValue = row[field];
|
||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||
continue;
|
||
}
|
||
|
||
const normalizedListingId = listingId === 0 ? 0 : listingId;
|
||
const normalizedKnownAt = knownAt === 0 ? 0 : knownAt;
|
||
const prevLatest = latestKnownAtByListing.get(normalizedListingId);
|
||
if (prevLatest === undefined || normalizedKnownAt > prevLatest) {
|
||
latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt);
|
||
}
|
||
|
||
const normalizedValue = rawValue === 0 ? 0 : rawValue;
|
||
const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`;
|
||
if (seenKeys.has(dedupeKey)) {
|
||
continue;
|
||
}
|
||
seenKeys.add(dedupeKey);
|
||
out.push({
|
||
listingId: normalizedListingId,
|
||
knownAt: normalizedKnownAt,
|
||
value: normalizedValue,
|
||
});
|
||
}
|
||
|
||
return latestKnownAtByListing;
|
||
}
|
||
|
||
function buildCanonicalStudyExpression(params: {
|
||
readonly input: AnalyzeSignalInput;
|
||
readonly listingIds: readonly number[];
|
||
readonly universeSnapshotDate: string | null;
|
||
readonly effectiveFrom: string;
|
||
readonly effectiveTo: string;
|
||
readonly effectiveAsOf: string;
|
||
}): SignalStudyExpression {
|
||
const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } =
|
||
params;
|
||
return {
|
||
expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`,
|
||
params: {
|
||
version: 1,
|
||
signalSource: input.signal.source,
|
||
signalField: input.signal.field,
|
||
...(input.signal.source === 'fundamentals'
|
||
? { allowEstimatedLag: input.signal.allowEstimatedLag }
|
||
: {}),
|
||
horizonSessions: input.horizonSessions,
|
||
maxSignalAgeSessions: input.maxSignalAgeSessions ?? null,
|
||
adjustment: input.adjustment,
|
||
ledgerSeries: input.ledgerSeries,
|
||
effectiveFrom,
|
||
effectiveTo,
|
||
effectiveAsOf,
|
||
},
|
||
universe:
|
||
input.universe !== undefined
|
||
? {
|
||
kind: 'universe',
|
||
ref: input.universe,
|
||
snapshotDate: universeSnapshotDate,
|
||
listingIds,
|
||
}
|
||
: {
|
||
kind: 'listingIds',
|
||
listingIds,
|
||
},
|
||
horizon: `${input.horizonSessions}d`,
|
||
};
|
||
}
|
||
|
||
function formatMappedAnalyzeSignalError(err: unknown): McpToolCallResult {
|
||
const storeMapped = formatMappedStoreError(err);
|
||
if (storeMapped !== null) {
|
||
return storeMapped;
|
||
}
|
||
|
||
if (err instanceof SignalPanelError) {
|
||
const detail = Object.prototype.hasOwnProperty.call(SIGNAL_PANEL_ERROR_MESSAGES, err.code)
|
||
? SIGNAL_PANEL_ERROR_MESSAGES[err.code]
|
||
: 'Signal panel construction failed.';
|
||
return {
|
||
content: [{ type: 'text', text: `SignalPanelError: ${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]
|
||
: 'Signal 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: AnalyzeSignalToolOptions): number {
|
||
if (
|
||
typeof options.store !== 'object' ||
|
||
options.store === null ||
|
||
typeof options.store.bars !== 'function' ||
|
||
typeof options.store.shortsAsOf !== 'function' ||
|
||
typeof options.store.fundamentalsAsOf !== 'function' ||
|
||
typeof options.store.universe !== 'function'
|
||
) {
|
||
throw new MarketDataStoreValidationError(
|
||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, 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.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 `analyze_signal` MCP tool backed by an injected
|
||
* {@link MarketDataStore} and {@link TrialLedgerExecutor}.
|
||
*
|
||
* Enforces `scope: 'vault_fenced'`, fences bounds before any store call,
|
||
* resolves named universes strictly prior to the study start date, filters
|
||
* bars and shorts defensively against the effective window and Vault cutoff,
|
||
* builds the forward-return panel, runs `analyzeSignal` with the injected
|
||
* research principal, and returns a bounded summary payload.
|
||
*/
|
||
export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpToolEntry {
|
||
const vaultCutoffTs = validateFactoryOptions(options);
|
||
const { store, ledger, principalId } = options;
|
||
|
||
return defineMcpTool({
|
||
name: 'analyze_signal',
|
||
description:
|
||
'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.',
|
||
inputSchema: analyzeSignalInputSchema,
|
||
jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA,
|
||
async handler(input: AnalyzeSignalInput): Promise<McpToolCallResult> {
|
||
try {
|
||
const fenced = fenceVaultQueryBounds(
|
||
{
|
||
from: input.from,
|
||
to: input.to,
|
||
asOf: input.asOf,
|
||
},
|
||
vaultCutoffTs
|
||
);
|
||
|
||
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 signalEcho: AnalyzeSignalInput['signal'] =
|
||
input.signal.source === 'shorts'
|
||
? {
|
||
source: 'shorts',
|
||
field: input.signal.field,
|
||
}
|
||
: {
|
||
source: 'fundamentals',
|
||
field: input.signal.field,
|
||
allowEstimatedLag: input.signal.allowEstimatedLag,
|
||
};
|
||
|
||
const basePayloadFields = {
|
||
scope: 'vault_fenced' as const,
|
||
vaultCutoffTs,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
signal: signalEcho,
|
||
horizonSessions: input.horizonSessions,
|
||
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 emptyAnalysis = analyzeSignalPanel([], {
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
});
|
||
const payload: AnalyzeSignalResultPayload = {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: 'too_few_observations',
|
||
panelDiagnostics: ZERO_PANEL_DIAGNOSTICS,
|
||
analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries),
|
||
};
|
||
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 listingIdSet = new Set<number>(listingIds);
|
||
const eligibleBars = filterEligibleBars(
|
||
rawBars,
|
||
listingIdSet,
|
||
fenced.fromMs,
|
||
fenced.toMs,
|
||
fenced.asOfMs,
|
||
vaultCutoffTs,
|
||
fenced.vaultCutoffDate
|
||
);
|
||
|
||
let signals: SignalObservation[];
|
||
if (input.signal.source === 'shorts') {
|
||
const rawShortsTable = await store.shortsAsOf({
|
||
listingIds,
|
||
from: fenced.canonicalFrom,
|
||
to: fenced.canonicalTo,
|
||
asOf: fenced.canonicalAsOf,
|
||
});
|
||
const eligibleShortsTable = filterEligibleShortsTable(
|
||
rawShortsTable,
|
||
listingIdSet,
|
||
utcDateOf(fenced.fromMs),
|
||
utcDateOf(fenced.toMs),
|
||
fenced.asOfMs,
|
||
vaultCutoffTs,
|
||
fenced.vaultCutoffDate
|
||
);
|
||
signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field);
|
||
} else {
|
||
const { field: fundamentalsField, allowEstimatedLag } = input.signal;
|
||
const snapshotDates = deriveMonthlySnapshotDates(eligibleBars);
|
||
if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) {
|
||
return {
|
||
content: [
|
||
{
|
||
type: 'text',
|
||
text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`,
|
||
},
|
||
],
|
||
isError: true,
|
||
};
|
||
}
|
||
|
||
signals = [];
|
||
const seenKeys = new Set<string>();
|
||
const barTimestampsByListing = buildBarTimestampsByListing(eligibleBars);
|
||
let windowFloorMs = Number.NEGATIVE_INFINITY;
|
||
|
||
for (const snapshotDate of snapshotDates) {
|
||
const snapshot = resolveSnapshotAsOf(
|
||
snapshotDate,
|
||
fenced.asOfMs,
|
||
fenced.canonicalAsOf
|
||
);
|
||
const rawTable = await store.fundamentalsAsOf({
|
||
listingIds,
|
||
fields: [fundamentalsField],
|
||
asOf: snapshot.asOf,
|
||
allowEstimatedLag,
|
||
});
|
||
const latestKnownByListing = appendEligibleFundamentalsObservations({
|
||
table: rawTable,
|
||
field: fundamentalsField,
|
||
listingIdSet,
|
||
snapshotAsOfMs: snapshot.asOfMs,
|
||
fencedAsOfMs: fenced.asOfMs,
|
||
vaultCutoffTs,
|
||
seenKeys,
|
||
out: signals,
|
||
});
|
||
|
||
// Backfill vintages superseded earlier within this month (or prior
|
||
// to the first eligible bar for the initial month) by stepping to
|
||
// the latest uncovered eligible bar strictly before each returned
|
||
// vintage. Under either lag setting, a requested listing with no
|
||
// valid observation (omitted by DuckDB or carrying a null/non-finite
|
||
// field) is treated as an unresolved interval so earlier eligible
|
||
// closes within the month are probed. Listings sharing a target bar
|
||
// timestamp are batched.
|
||
const pendingByBarTs = new Map<number, number[]>();
|
||
const enqueueBackfill = (
|
||
queriedListingIds: readonly number[],
|
||
knownByListing: ReadonlyMap<number, number>,
|
||
upperBoundExclusiveMs: number
|
||
): void => {
|
||
for (const lid of queriedListingIds) {
|
||
const knownAt = knownByListing.get(lid);
|
||
const upperExclusive =
|
||
knownAt !== undefined
|
||
? Math.min(knownAt, upperBoundExclusiveMs)
|
||
: upperBoundExclusiveMs;
|
||
const prevBarTs = findLatestBarBefore(
|
||
barTimestampsByListing.get(lid),
|
||
upperExclusive,
|
||
windowFloorMs
|
||
);
|
||
if (prevBarTs !== null) {
|
||
let bucket = pendingByBarTs.get(prevBarTs);
|
||
if (bucket === undefined) {
|
||
bucket = [];
|
||
pendingByBarTs.set(prevBarTs, bucket);
|
||
}
|
||
bucket.push(lid);
|
||
}
|
||
}
|
||
};
|
||
|
||
enqueueBackfill(listingIds, latestKnownByListing, snapshot.asOfMs);
|
||
|
||
while (pendingByBarTs.size > 0) {
|
||
// Pop the highest bar timestamp first so earlier buckets merge
|
||
// newly discovered listings landing on the same session.
|
||
let nextBarTs = Number.NEGATIVE_INFINITY;
|
||
for (const ts of pendingByBarTs.keys()) {
|
||
if (ts > nextBarTs) {
|
||
nextBarTs = ts;
|
||
}
|
||
}
|
||
const batchListingIds = sortAndDedupeListingIds(pendingByBarTs.get(nextBarTs) ?? []);
|
||
pendingByBarTs.delete(nextBarTs);
|
||
if (batchListingIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const batchAsOfMs = Math.min(nextBarTs, fenced.asOfMs);
|
||
const batchAsOf =
|
||
batchAsOfMs === fenced.asOfMs
|
||
? fenced.canonicalAsOf
|
||
: formatUtcIsoWithMicros(batchAsOfMs, 0);
|
||
const batchListingIdSet = new Set<number>(batchListingIds);
|
||
|
||
const backfillTable = await store.fundamentalsAsOf({
|
||
listingIds: batchListingIds,
|
||
fields: [fundamentalsField],
|
||
asOf: batchAsOf,
|
||
allowEstimatedLag,
|
||
});
|
||
const backfillKnownByListing = appendEligibleFundamentalsObservations({
|
||
table: backfillTable,
|
||
field: fundamentalsField,
|
||
listingIdSet: batchListingIdSet,
|
||
snapshotAsOfMs: batchAsOfMs,
|
||
fencedAsOfMs: fenced.asOfMs,
|
||
vaultCutoffTs,
|
||
seenKeys,
|
||
out: signals,
|
||
});
|
||
|
||
enqueueBackfill(batchListingIds, backfillKnownByListing, nextBarTs);
|
||
}
|
||
|
||
windowFloorMs = snapshot.asOfMs;
|
||
}
|
||
}
|
||
|
||
const built = buildForwardReturnPanel({
|
||
bars: eligibleBars,
|
||
signals,
|
||
horizonSessions: input.horizonSessions,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
...(input.maxSignalAgeSessions !== undefined
|
||
? { maxSignalAgeSessions: input.maxSignalAgeSessions }
|
||
: {}),
|
||
});
|
||
|
||
if (built.panel.length === 0) {
|
||
const emptyAnalysis = analyzeSignalPanel([], {
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
});
|
||
const payload: AnalyzeSignalResultPayload = {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: 'too_few_observations',
|
||
panelDiagnostics: built.diagnostics,
|
||
analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries),
|
||
};
|
||
return {
|
||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||
};
|
||
}
|
||
|
||
const expression = buildCanonicalStudyExpression({
|
||
input,
|
||
listingIds,
|
||
universeSnapshotDate,
|
||
effectiveFrom: fenced.canonicalFrom,
|
||
effectiveTo: fenced.canonicalTo,
|
||
effectiveAsOf: fenced.canonicalAsOf,
|
||
});
|
||
|
||
const studyResult = await analyzeSignal(ledger, {
|
||
principalId,
|
||
...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}),
|
||
...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}),
|
||
universeMarket: input.universeMarket,
|
||
horizonBucket: input.horizonBucket,
|
||
expression,
|
||
panel: built.panel,
|
||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||
ledgerSeries: input.ledgerSeries,
|
||
});
|
||
|
||
const analysisSummary = projectAnalysisSummary(studyResult.analysis, input.ledgerSeries);
|
||
|
||
const payload: AnalyzeSignalResultPayload =
|
||
studyResult.status === 'ok'
|
||
? {
|
||
...basePayloadFields,
|
||
status: 'ok',
|
||
panelDiagnostics: built.diagnostics,
|
||
analysis: analysisSummary,
|
||
trial: studyResult.trial,
|
||
deflatedSharpe: studyResult.deflatedSharpe,
|
||
}
|
||
: {
|
||
...basePayloadFields,
|
||
status: 'insufficient_data',
|
||
reason: studyResult.reason,
|
||
panelDiagnostics: built.diagnostics,
|
||
analysis: analysisSummary,
|
||
};
|
||
|
||
return {
|
||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||
};
|
||
} catch (err: unknown) {
|
||
return formatMappedAnalyzeSignalError(err);
|
||
}
|
||
},
|
||
});
|
||
}
|