Skip to main content
Glama
l4b4r4b4b4
by l4b4r4b4b4

get_correlation_matrix

Calculate pairwise correlations between portfolio assets using daily returns to identify relationships and diversification opportunities.

Instructions

Get the correlation matrix for portfolio assets.

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

    Args:
        name: The portfolio name.

    Returns:
        Dictionary containing:
        - symbols: List of symbols
        - correlation_matrix: 2D correlation matrix
        - correlations: Readable format with symbol pairs

    Example:
        ```
        result = get_correlation_matrix(name="tech_stocks")
        # Check correlation between GOOG and AMZN
        corr = result['correlations']['GOOG']['AMZN']
        ```
    

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 get_correlation_matrix function (lines 233-287) is the tool handler. It retrieves a portfolio from the store, rebuilds a price DataFrame, calculates daily returns, computes the pairwise correlation matrix using pandas .corr(), builds a readable correlations dict keyed by symbol pairs, and returns the result with portfolio name, symbols list, raw matrix, and nested correlations dictionary.
    def get_correlation_matrix(name: str) -> dict[str, Any]:
        """Get the correlation matrix for portfolio assets.
    
        Calculates pairwise correlations between all assets in the
        portfolio based on daily returns.
    
        Args:
            name: The portfolio name.
    
        Returns:
            Dictionary containing:
            - symbols: List of symbols
            - correlation_matrix: 2D correlation matrix
            - correlations: Readable format with symbol pairs
    
        Example:
            ```
            result = get_correlation_matrix(name="tech_stocks")
            # Check correlation between GOOG and AMZN
            corr = result['correlations']['GOOG']['AMZN']
            ```
        """
        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 correlation matrix
        corr_matrix = returns_df.corr()
    
        # Build readable correlations dict
        correlations = {}
        symbols = corr_matrix.columns.tolist()
        for symbol in symbols:
            correlations[symbol] = {}
            for other in symbols:
                correlations[symbol][other] = float(corr_matrix.loc[symbol, other])
    
        return {
            "portfolio_name": name,
            "symbols": symbols,
            "correlation_matrix": corr_matrix.values.tolist(),
            "correlations": correlations,
        }
  • The @mcp.tool decorator (line 228) along with @cache.cached (lines 229-232) register get_correlation_matrix as a FastMCP tool. The function belongs to register_analysis_tools() which takes mcp, store, and cache arguments and decorates the inner function to expose it as an MCP tool endpoint.
    @mcp.tool
    @cache.cached(
        namespace="public",
        ttl=None,  # Deterministic - infinite TTL
    )
  • The function uses daily_returns from finquant.returns (line 269) to compute returns, and pandas DataFrame.corr() (line 272) to compute the correlation matrix. These are helper library calls.
    def get_correlation_matrix(name: str) -> dict[str, Any]:
        """Get the correlation matrix for portfolio assets.
    
        Calculates pairwise correlations between all assets in the
        portfolio based on daily returns.
    
        Args:
            name: The portfolio name.
    
        Returns:
            Dictionary containing:
            - symbols: List of symbols
            - correlation_matrix: 2D correlation matrix
            - correlations: Readable format with symbol pairs
    
        Example:
            ```
            result = get_correlation_matrix(name="tech_stocks")
            # Check correlation between GOOG and AMZN
            corr = result['correlations']['GOOG']['AMZN']
            ```
        """
        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 correlation matrix
        corr_matrix = returns_df.corr()
    
        # Build readable correlations dict
        correlations = {}
        symbols = corr_matrix.columns.tolist()
        for symbol in symbols:
            correlations[symbol] = {}
            for other in symbols:
                correlations[symbol][other] = float(corr_matrix.loc[symbol, other])
    
        return {
            "portfolio_name": name,
            "symbols": symbols,
            "correlation_matrix": corr_matrix.values.tolist(),
            "correlations": correlations,
        }
  • Input schema: takes a single string parameter 'name' (the portfolio name). Output schema (docstring lines 242-246): returns a dict with 'symbols' (list of strings), 'correlation_matrix' (2D list), and 'correlations' (nested dict of symbol pairs). On error (lines 257-259), returns {'error': str}.
    """Get the correlation matrix for portfolio assets.
    
    Calculates pairwise correlations between all assets in the
    portfolio based on daily returns.
    
    Args:
        name: The portfolio name.
    
    Returns:
        Dictionary containing:
        - symbols: List of symbols
        - correlation_matrix: 2D correlation matrix
        - correlations: Readable format with symbol pairs
    
    Example:
        ```
        result = get_correlation_matrix(name="tech_stocks")
        # Check correlation between GOOG and AMZN
        corr = result['correlations']['GOOG']['AMZN']
        ```
    """
Behavior3/5

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

No annotations are provided, so the description must disclose behavioral traits. It mentions caching behavior (ref_id, preview, pagination via get_cached_result) and that any input parameter can accept a ref_id. However, it does not explicitly state whether the tool is read-only or any side effects, leaving a gap in transparency.

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 is front-loaded with the purpose but includes a verbose caching behavior section that appears generic. The example adds value but lengthens the text. Every sentence has purpose, but the caching block could be shortened or linked to a shared reference.

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 simple tool (one parameter, clear output), the description covers the return format with an example and explains caching mechanics. It does not mention error cases (e.g., invalid portfolio name) but is otherwise complete for basic usage.

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 input schema has 0% description coverage, so the description must compensate. It adds basic meaning by stating that 'name' is the portfolio name. While minimal, this is sufficient for a single parameter, and the example reinforces usage. No further constraints or format details are needed.

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 it gets the correlation matrix for portfolio assets and calculates pairwise correlations based on daily returns. The example and distinction from the sibling get_covariance_matrix is implied by the function name, but the description explicitly mentions 'correlation' making it unambiguous.

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 like get_covariance_matrix. The description does not specify prerequisites, such as requiring the portfolio to exist or have historical data. It only provides an example but no explicit 'when to use' or 'when not to use' advice.

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