Skip to main content
Glama
l4b4r4b4b4
by l4b4r4b4b4

get_covariance_matrix

Compute pairwise covariances between portfolio assets from daily returns. Optionally annualize the results for risk analysis.

Instructions

Get the covariance matrix for portfolio assets.

    Calculates pairwise covariances between all assets in the
    portfolio based on daily returns.

    Args:
        name: The portfolio name.
        annualized: If True, annualize the covariance (multiply by 252).

    Returns:
        Dictionary containing:
        - symbols: List of symbols
        - covariance_matrix: 2D covariance matrix
        - variances: Individual asset variances (diagonal)

    Example:
        ```
        result = get_covariance_matrix(name="tech_stocks")
        print(f"GOOG variance: {result['variances']['GOOG']}")
        ```
    

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
annualizedNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The actual handler function for get_covariance_matrix tool. Calculates covariance matrix from portfolio price data, with optional annualization (multiply by 252). Returns symbols, covariance_matrix, and variances.
    @mcp.tool
    @cache.cached(
        namespace="public",
        ttl=None,  # Deterministic - infinite TTL
    )
    def get_covariance_matrix(name: str, annualized: bool = True) -> dict[str, Any]:
        """Get the covariance matrix for portfolio assets.
    
        Calculates pairwise covariances between all assets in the
        portfolio based on daily returns.
    
        Args:
            name: The portfolio name.
            annualized: If True, annualize the covariance (multiply by 252).
    
        Returns:
            Dictionary containing:
            - symbols: List of symbols
            - covariance_matrix: 2D covariance matrix
            - variances: Individual asset variances (diagonal)
    
        Example:
            ```
            result = get_covariance_matrix(name="tech_stocks")
            print(f"GOOG variance: {result['variances']['GOOG']}")
            ```
        """
        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()
    
        # Calculate covariance matrix
        cov_matrix = returns_df.cov()
    
        # Annualize if requested
        if annualized:
            cov_matrix = cov_matrix * 252
    
        # Extract variances
        symbols = cov_matrix.columns.tolist()
        variances = {
            symbol: float(cov_matrix.loc[symbol, symbol]) for symbol in symbols
        }
    
        return {
            "portfolio_name": name,
            "symbols": symbols,
            "annualized": annualized,
            "covariance_matrix": cov_matrix.values.tolist(),
            "variances": variances,
        }
  • The registration function register_analysis_tools which registers get_covariance_matrix (and other tools) via the @mcp.tool decorator on the inner function.
    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 daily_returns function imported from finquant.returns, used inside get_covariance_matrix to compute daily returns from price data.
    from finquant.returns import cumulative_returns, daily_log_returns, daily_returns
Behavior4/5

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

The description discloses return structure (symbols, covariance_matrix, variances), caching behavior (ref_id, preview, pagination), and the effect of annualization. Since no annotations are provided, this is a thorough account of the tool's behavior.

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

Conciseness3/5

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

The description includes a lengthy example and caching notes, which are useful but make it less concise. Could be streamlined without losing essential information.

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

Completeness4/5

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

Given the tool's complexity and the presence of many sibling tools, the description covers return values, parameters, and caching adequately. It provides enough detail for an agent to use it effectively.

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 description explains both parameters: name is the portfolio name, and annualized annualizes the covariance by multiplying by 252. This adds meaning beyond the schema, which only has defaults and types.

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

Purpose4/5

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

The description clearly states it computes the covariance matrix for portfolio assets based on daily returns, using a specific verb and resource. However, it does not differentiate from sibling tools like get_correlation_matrix.

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?

No guidance on when to use this tool versus alternatives, or when not to use it. The description only describes parameters without context for selection.

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