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.

Covariance Matrix in Python

get_covariance_matrix is part of the Performance module of the open-source Finance Toolkit. Install it with:

pip install financetoolkit -U

Then call get_covariance_matrix as shown below.

from financetoolkit import Toolkit

toolkit = Toolkit(["AMZN", "TSLA"], api_key="FINANCIAL_MODELING_PREP_KEY")

toolkit.performance.get_covariance_matrix()

Which returns:

  AMZN TSLA Benchmark
AMZN 0.1944 0.2418 0.0592
TSLA 0.2418 0.344 0.0913
Benchmark 0.0592 0.0913 0.0301

Parameters

get_covariance_matrix accepts the following parameters:

  • period (str, optional): The data frequency for returns (weekly, monthly, quarterly, or yearly). Defaults to “quarterly” if the Toolkit is initialized with quarterly=True, otherwise “yearly”.
  • rounding (int | None, optional): The number of decimals to round the results to. Defaults to 4.
Share