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
| Name | Required | Description | Default |
|---|---|---|---|
| name | Yes |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- app/tools/analysis.py:233-287 (handler)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, } - app/tools/analysis.py:228-232 (registration)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 ) - app/tools/analysis.py:233-287 (helper)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, } - app/tools/analysis.py:234-254 (schema)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'] ``` """