var
Calculate Value at Risk (VaR) to quantify potential portfolio losses at a specified confidence level for risk management.
Instructions
Calculates Value at Risk (VaR).
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| confidence | No |
Implementation Reference
- tools/risk_engine.py:45-60 (handler)The main handler function for the 'var' tool, which computes the Value at Risk (VaR) for the current portfolio using historical returns and percentile method.def var(confidence: float = 0.95) -> str: """Calculates Value at Risk (VaR).""" data, weights = _get_portfolio_data() if data is None: return "Portfolio is empty." returns = data.pct_change().dropna() # Portfolio historical returns port_returns = returns.dot(weights) # Parametric VaR mean = np.mean(port_returns) std = np.std(port_returns) var_val = np.percentile(port_returns, (1 - confidence) * 100) return f"Daily VaR ({confidence:.0%}): {var_val:.2%}"
- server.py:380-383 (registration)Registration of the 'var' tool (imported from tools.risk_engine) as an MCP tool using the register_tools helper function, which applies @mcp.tool() decorator.register_tools( [portfolio_risk, var, max_drawdown, monte_carlo_simulation], "Risk Engine" )
- tools/risk_engine.py:10-30 (helper)Helper function _get_portfolio_data used by var (and other risk tools) to fetch portfolio positions, historical price data, and compute value weights.def _get_portfolio_data(lookback: str = "1y"): portfolio = get_positions() positions = portfolio.get("positions", {}) if not positions: return None, None tickers = list(positions.keys()) weights = np.array(list(positions.values())) # This is qty, need value weights # Fetch data data = yf.download(tickers, period=lookback, progress=False)['Close'] if isinstance(data, pd.Series): data = data.to_frame(name=tickers[0]) # Calculate current value weights current_prices = data.iloc[-1] values = current_prices * pd.Series(positions) total_value = values.sum() weights = values / total_value return data, weights