Covariance Matrix
Calculate the full pairwise Covariance Matrix across all assets (and the benchmark) in the Toolkit instance, based on the returns at the frequency given by period.
Unlike get_covariance, which relates a single asset to the benchmark, this computes the covariance between every pair of assets at once. This is a prerequisite for portfolio variance calculations and any mean-variance optimization work.
The formula is as follows:
\[\text{Covariance} (A,\; B) = \operatorname{SUM}((\text{Return}\; A - \text{Mean Return}\; A) \cdot (\text{Return}\; B - \text{Mean Return}\; B)) / (N - 1),\;\; \text{the sample covariance (ddof=1) of the period returns (e.g. monthly) within the Toolkit's date range},\;\; \text{per period and not annualized},\;\; \text{using the overlapping (pairwise complete) observations of each pair}\]Covariance Matrix in Python or via the MCP
Install the Finance Toolkit with:
pip install financetoolkit -U
Then call get_covariance_matrix as shown below.
from financetoolkit import Toolkit
toolkit = Toolkit(
["^GSPC", "EURUSD", "GCUSD", "CLUSD"],
api_key="FINANCIAL_MODELING_PREP_KEY",
start_date="2021-01-01",
end_date="2025-12-31",
)
toolkit.performance.get_covariance_matrix(period="monthly")
Or, after setting up the Finance Toolkit MCP, ask:
What is the covariance matrix of the monthly returns of the S&P 500, the euro against the dollar, gold and crude oil from 2021 to 2025?
Which returns:
| ^GSPC | EURUSD | GCUSD | CLUSD | Benchmark | |
|---|---|---|---|---|---|
| ^GSPC | 0.0019 | 0.0003 | 0.0003 | 0.0003 | 0.0019 |
| EURUSD | 0.0003 | 0.0005 | 0.0005 | -0.0001 | 0.0003 |
| GCUSD | 0.0003 | 0.0005 | 0.0018 | -0.0007 | 0.0003 |
| CLUSD | 0.0003 | -0.0001 | -0.0007 | 0.0067 | 0.0003 |
| Benchmark | 0.0019 | 0.0003 | 0.0003 | 0.0003 | 0.0019 |
Parameters
get_covariance_matrix accepts the following parameters.
| Parameter | Type | Description | Example |
|---|---|---|---|
period | str | The data frequency for returns (weekly, monthly, quarterly, or yearly). Defaults to “quarterly” if the Toolkit is initialised with quarterly=True, otherwise “yearly”. | "quarterly" |
rounding | int | None | The number of decimals to round the results to. Defaults to None, which uses the rounding of the Toolkit (4 unless set otherwise). | 2 |