/**
* MCP Tool: compute_historical_vol
*
* Compute historical volatility for a symbol using daily closes.
*/
import { z } from "zod";
import { computeHistoricalVol as coreComputeHistVol } from "@quant-companion/core";
import { getDefaultProvider } from "../marketData";
export const computeHistoricalVolSchema = z.object({
symbol: z.string().describe("Stock/ETF ticker symbol"),
window: z
.number()
.int()
.positive()
.optional()
.default(30)
.describe("Number of trading days to use for calculation (default 30)"),
});
export type ComputeHistoricalVolInput = z.infer<
typeof computeHistoricalVolSchema
>;
export interface ComputeHistoricalVolOutput {
symbol: string;
window: number;
historicalVol: number;
historicalVolPercent: number;
}
export async function computeHistoricalVol(
input: ComputeHistoricalVolInput
): Promise<ComputeHistoricalVolOutput> {
const provider = getDefaultProvider();
// Fetch enough historical data (add buffer for weekends/holidays)
const end = new Date();
const start = new Date();
start.setDate(start.getDate() - Math.ceil(input.window * 1.5) - 30);
const candles = await provider.getHistoricalOHLCV({
symbol: input.symbol,
start,
end,
interval: "1d",
});
if (candles.length < input.window + 1) {
throw new Error(
`Not enough data for ${input.symbol}. Got ${candles.length} candles, need at least ${input.window + 1}.`
);
}
// Extract closing prices
const prices = candles.map((c) => c.close);
const result = coreComputeHistVol(prices, input.window);
return {
symbol: input.symbol,
window: result.window,
historicalVol: result.volatility,
historicalVolPercent: result.volatility * 100,
};
}
export const computeHistoricalVolDefinition = {
name: "compute_historical_vol",
description:
"Compute historical (realized) volatility for a symbol using daily closing prices. Returns annualized volatility. Use this to estimate volatility for option pricing or to compare with implied volatility.",
inputSchema: {
type: "object",
properties: {
symbol: {
type: "string",
description: "Stock/ETF ticker symbol (e.g., AAPL, SPY)",
},
window: {
type: "number",
description:
"Number of trading days to use for calculation (default 30). Common values: 20-30 for short-term, 60-90 for medium-term.",
},
},
required: ["symbol"],
},
};