Skip to main content
Glama
l4b4r4b4b4
by l4b4r4b4b4

compare_portfolios

Compare multiple investment portfolios side by side. Retrieve key metrics, rankings, and identify the top performer for each metric.

Instructions

Compare multiple portfolios side by side.

Retrieves metrics for multiple portfolios and ranks them by key performance indicators.

Args: names: List of portfolio names to compare.

Returns: Dictionary containing: - portfolios: Dict of metrics per portfolio - rankings: Rankings by each metric - best_by_metric: Best portfolio for each metric

Example: result = compare_portfolios( names=["stocks", "crypto", "metals"] ) print(f"Best Sharpe: {result['best_by_metric']['sharpe_ratio']}")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
namesYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function for compare_portfolios tool. It retrieves metrics for multiple portfolios, builds comparison structure with key metrics (expected_return, volatility, sharpe_ratio, sortino_ratio, value_at_risk, downside_risk), ranks portfolios by each metric, and identifies the best portfolio per metric.
    @mcp.tool
    def compare_portfolios(names: list[str]) -> dict[str, Any]:
        """Compare multiple portfolios side by side.
    
        Retrieves metrics for multiple portfolios and ranks them
        by key performance indicators.
    
        Args:
            names: List of portfolio names to compare.
    
        Returns:
            Dictionary containing:
            - portfolios: Dict of metrics per portfolio
            - rankings: Rankings by each metric
            - best_by_metric: Best portfolio for each metric
    
        Example:
            ```
            result = compare_portfolios(
                names=["stocks", "crypto", "metals"]
            )
            print(f"Best Sharpe: {result['best_by_metric']['sharpe_ratio']}")
            ```
        """
        if len(names) < 2:
            return {
                "error": "Need at least 2 portfolios to compare",
            }
    
        # Collect metrics for all portfolios
        portfolios_data = {}
        errors = []
    
        for name in names:
            data = store.get(name)
            if data is None:
                errors.append(f"Portfolio '{name}' not found")
                continue
            portfolios_data[name] = data["metrics"]
    
        if errors:
            return {
                "error": "Some portfolios not found",
                "details": errors,
                "found": list(portfolios_data.keys()),
            }
    
        # Build comparison structure
        portfolios = {}
        for name, metrics in portfolios_data.items():
            portfolios[name] = {
                "expected_return": metrics["expected_return"],
                "volatility": metrics["volatility"],
                "sharpe_ratio": metrics["sharpe"],
                "sortino_ratio": metrics["sortino"],
                "value_at_risk": metrics["var"],
                "downside_risk": metrics["downside_risk"],
            }
    
        # Create rankings
        metrics_to_rank = [
            ("expected_return", True),  # Higher is better
            ("volatility", False),  # Lower is better
            ("sharpe_ratio", True),
            ("sortino_ratio", True),
            ("value_at_risk", False),  # Lower (less negative) is better
            ("downside_risk", False),
        ]
    
        rankings = {}
        best_by_metric = {}
    
        for metric, higher_is_better in metrics_to_rank:
            sorted_names = sorted(
                portfolios_data.keys(),
                key=lambda n: portfolios[n][metric],
                reverse=higher_is_better,
            )
            rankings[metric] = sorted_names
            best_by_metric[metric] = sorted_names[0]
    
        return {
            "portfolios": portfolios,
            "rankings": rankings,
            "best_by_metric": best_by_metric,
            "num_portfolios": len(portfolios),
        }
  • The registration function `register_analysis_tools` that registers the compare_portfolios function as an MCP tool via the @mcp.tool decorator. This is called from app/server.py to wire up all analysis tools.
    def register_analysis_tools(
        mcp: FastMCP, store: PortfolioStore, cache: RefCache
    ) -> None:
        """Register analysis tools with the FastMCP server.
    
        Args:
            mcp: The FastMCP server instance.
            store: The portfolio store for persistence.
            cache: The RefCache instance for caching large results.
        """
  • The schema/type signature for compare_portfolios: takes a list of portfolio names (list[str]) and returns a dict with 'portfolios', 'rankings', 'best_by_metric', and 'num_portfolios'.
    def compare_portfolios(names: list[str]) -> dict[str, Any]:
        """Compare multiple portfolios side by side.
    
        Retrieves metrics for multiple portfolios and ranks them
        by key performance indicators.
    
        Args:
            names: List of portfolio names to compare.
    
        Returns:
            Dictionary containing:
            - portfolios: Dict of metrics per portfolio
            - rankings: Rankings by each metric
            - best_by_metric: Best portfolio for each metric
Behavior4/5

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

No annotations are provided, so the description carries full burden. It details the operation (comparison, retrieval) and return format (dictionary with portfolios, rankings, best_by_metric). However, it does not explicitly state it is read-only or mention any side effects, which is a minor gap.

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 uses a clean structure with Args, Returns, and an Example section. Every sentence is purposeful, concise, and easy to parse.

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?

Given an output schema exists, the description adequately explains the return structure. For a comparison tool with one parameter, it covers all necessary aspects without overcomplicating.

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 param 'names' is described as 'List of portfolio names to compare.' This adds meaning beyond the schema's type (array of strings) and compensates for the 0% schema description coverage. The example further clarifies usage.

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?

The description clearly states 'Compare multiple portfolios side by side' and specifies retrieving metrics and ranking by KPIs. It differentiates from sibling tools like get_portfolio_metrics (single portfolio) and list_portfolios (listing only) by focusing on comparison.

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

Usage Guidelines3/5

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

The description implies usage for comparing multiple portfolios via the example and returns section, but does not explicitly state when to use this tool over alternatives or provide when-not conditions.

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