Skip to main content
Glama
l4b4r4b4b4
by l4b4r4b4b4

get_individual_stock_metrics

Calculate return and volatility metrics for each stock in a portfolio to identify best and worst performers.

Instructions

Get metrics for each individual stock in a portfolio.

    Calculates return and volatility metrics for each stock
    separately, useful for identifying best/worst performers.

    Args:
        name: The portfolio name.

    Returns:
        Dictionary containing metrics per stock:
        - mean_return: Average daily return (annualized)
        - volatility: Standard deviation (annualized)
        - sharpe_ratio: Individual Sharpe ratio
        - weight: Current allocation weight

    Example:
        ```
        result = get_individual_stock_metrics(name="tech_stocks")
        for symbol, metrics in result['stocks'].items():
            print(f"{symbol}: Return={metrics['mean_return']:.2%}")
        ```
    

Caching Behavior:

  • Any input parameter can accept a ref_id from a previous tool call

  • Large results return ref_id + preview; use get_cached_result to paginate

  • All responses include ref_id for future reference

Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for get_individual_stock_metrics tool. It retrieves stock metrics (mean_return, volatility, sharpe_ratio, weight) for each stock in a portfolio, sorted by Sharpe ratio.
    def get_individual_stock_metrics(name: str) -> dict[str, Any]:
        """Get metrics for each individual stock in a portfolio.
    
        Calculates return and volatility metrics for each stock
        separately, useful for identifying best/worst performers.
    
        Args:
            name: The portfolio name.
    
        Returns:
            Dictionary containing metrics per stock:
            - mean_return: Average daily return (annualized)
            - volatility: Standard deviation (annualized)
            - sharpe_ratio: Individual Sharpe ratio
            - weight: Current allocation weight
    
        Example:
            ```
            result = get_individual_stock_metrics(name="tech_stocks")
            for symbol, metrics in result['stocks'].items():
                print(f"{symbol}: Return={metrics['mean_return']:.2%}")
            ```
        """
        data = store.get(name)
        if data is None:
            return {
                "error": f"Portfolio '{name}' not found",
            }
    
        # Rebuild price DataFrame
        prices_df = pd.DataFrame(
            data=data["prices"]["values"],
            index=pd.to_datetime(data["prices"]["index"]),
            columns=data["prices"]["columns"],
        )
    
        # Calculate daily returns
        returns_df = daily_returns(prices_df).dropna()
    
        # Get weights
        weights = {}
        for row in data["allocation"]["values"]:
            weights[row[1]] = row[0] / 100.0
    
        risk_free_rate = data["settings"]["risk_free_rate"]
    
        # Calculate metrics per stock
        stocks = {}
        for symbol in returns_df.columns:
            daily_mean = returns_df[symbol].mean()
            daily_std = returns_df[symbol].std()
    
            annual_return = daily_mean * 252
            annual_vol = daily_std * np.sqrt(252)
    
            sharpe = (
                (annual_return - risk_free_rate) / annual_vol if annual_vol > 0 else 0
            )
    
            stocks[symbol] = {
                "mean_return": float(annual_return),
                "volatility": float(annual_vol),
                "sharpe_ratio": float(sharpe),
                "weight": weights.get(symbol, 0),
                "daily_mean": float(daily_mean),
                "daily_std": float(daily_std),
            }
    
        # Sort by Sharpe ratio
        sorted_stocks = sorted(
            stocks.items(), key=lambda x: x[1]["sharpe_ratio"], reverse=True
        )
    
        return {
            "portfolio_name": name,
            "stocks": stocks,
            "ranking_by_sharpe": [s[0] for s in sorted_stocks],
            "best_performer": sorted_stocks[0][0] if sorted_stocks else None,
            "worst_performer": sorted_stocks[-1][0] if sorted_stocks else None,
            "risk_free_rate": risk_free_rate,
        }
  • The tool is registered via @mcp.tool decorator and @cache.cached decorator on the handler function inside register_analysis_tools().
    @mcp.tool
    @cache.cached(
        namespace="public",
        ttl=None,  # Deterministic - infinite TTL
    )
  • The registration function signature - register_analysis_tools registers this and other tools with the FastMCP server.
    def register_analysis_tools(
        mcp: FastMCP, store: PortfolioStore, cache: RefCache
    ) -> None:
Behavior5/5

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

No annotations provided, so description carries full burden. It details return structure, caching behavior (ref_id, preview, pagination), and that any parameter can accept ref_id. This is comprehensive.

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

Conciseness4/5

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

Well-structured with clear sections (args, returns, example, caching behavior). However, the caching block is somewhat verbose and could be streamlined if generic across tools. Not overly long, but not maximally concise.

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

Completeness5/5

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

Covers all aspects: purpose, when to use, parameter explanation, output structure with example, caching behavior. Given the tool's simplicity (1 param, no annotations), the description is fully complete.

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

Parameters3/5

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

Schema has 1 parameter 'name' with 0% schema description coverage. The description explains 'The portfolio name' and provides an example ('tech_stocks'), adding meaning beyond the raw schema. However, no format constraints or source hints are given.

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

Purpose5/5

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

Clearly states it gets metrics for each individual stock in a portfolio, distinguishing it from get_portfolio_metrics which gives overall metrics. Uses specific verb 'Get' and resource 'individual stock metrics'.

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

Usage Guidelines4/5

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

Explicitly says 'useful for identifying best/worst performers', implying diagnostic use case. While it does not mention when not to use or alternatives, the sibling context makes the distinction clear enough.

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/l4b4r4b4b4/portfolio-mcp'

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