Skip to main content
Glama

max_drawdown

Calculate maximum drawdown to assess portfolio risk by measuring the largest peak-to-trough decline in value, helping identify potential losses during market downturns.

Instructions

Calculates Maximum Drawdown.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function implementing the max_drawdown tool. Computes the maximum drawdown of the portfolio using historical price data fetched via yfinance and position weights.
    def max_drawdown() -> str:
        """Calculates Maximum Drawdown."""
        data, weights = _get_portfolio_data()
        if data is None:
            return "Portfolio is empty."
        
        returns = data.pct_change().dropna()
        port_returns = returns.dot(weights)
        cumulative_returns = (1 + port_returns).cumprod()
        peak = cumulative_returns.expanding(min_periods=1).max()
        drawdown = (cumulative_returns / peak) - 1
        max_dd = drawdown.min()
        
        return f"Maximum Drawdown: {max_dd:.2%}"
  • Helper function that retrieves portfolio positions, downloads historical price data using yfinance, and computes value-based weights. Used by max_drawdown and other risk tools.
    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
  • server.py:380-383 (registration)
    Registration of the max_drawdown tool (along with related risk tools) to the FastMCP server using the register_tools helper.
    register_tools(
        [portfolio_risk, var, max_drawdown, monte_carlo_simulation],
        "Risk Engine"
    )
  • server.py:14-14 (registration)
    Import statement bringing the max_drawdown function into the MCP server module for registration.
    from tools.risk_engine import portfolio_risk, var, max_drawdown, monte_carlo_simulation
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the calculation purpose but lacks details on inputs (e.g., data format, time series requirements), outputs (though an output schema exists), error handling, or computational characteristics (e.g., performance, assumptions). This is inadequate for a tool with zero annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with no wasted words. It's front-loaded with the core action ('Calculates') and resource ('Maximum Drawdown'), making it immediately clear. Every word earns its place, achieving optimal brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (a financial calculation), no annotations, and an output schema (which covers return values), the description is minimally complete. It states what the tool does but lacks context on usage, behavioral traits, or integration with sibling tools, leaving gaps that could hinder an agent's effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters with 100% schema description coverage, so the schema fully documents the absence of inputs. The description doesn't need to add parameter details, but it could mention implicit inputs (e.g., data context). Since no parameters exist, a baseline of 4 is appropriate, as the description doesn't contradict the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Calculates Maximum Drawdown' clearly states the tool's function with a specific verb ('Calculates') and resource ('Maximum Drawdown'), which is a financial metric. However, it doesn't differentiate from sibling tools like 'portfolio_risk', 'var', or 'rolling_stats' that also compute financial risk metrics, leaving ambiguity about when to use this specific calculation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'portfolio_risk', 'var', and 'rolling_stats' that handle related financial analyses, there's no indication of context, prerequisites, or exclusions to help an agent choose appropriately.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/N-lia/MonteWalk'

If you have feedback or need assistance with the MCP directory API, please join our Discord server