Skip to content

Commit 93512fa

Browse files
Improve sample_cov docstring with risk parity example and notes
This PR improves the documentation for `sample_cov` by: - Adding a concrete example with real output values. - Clarifying the link to risk parity strategies. Closes #423
1 parent 65cabce commit 93512fa

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

pypfopt/risk_models.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,12 @@ def risk_matrix(prices, method="sample_cov", **kwargs):
148148

149149
def sample_cov(prices, returns_data=False, frequency=252, log_returns=False, **kwargs):
150150
"""
151-
Calculate the annualised sample covariance matrix of (daily) asset returns.
151+
Calculate the covariance matrix of asset returns from historical price data.
152152
153+
The covariance matrix is a fundamental input for portfolio optimization,
154+
including risk parity strategies where the goal is to equalize the risk contribution of each asset.
155+
It quantifies how the returns of different assets move together.
156+
153157
:param prices: adjusted closing prices of the asset, each row is a date
154158
and each column is a ticker/id.
155159
:type prices: pd.DataFrame
@@ -162,7 +166,33 @@ def sample_cov(prices, returns_data=False, frequency=252, log_returns=False, **k
162166
:type log_returns: bool, defaults to False
163167
:return: annualised sample covariance matrix
164168
:rtype: pd.DataFrame
169+
:param **kwargs : dict, Additional arguments passed to pandas.cov().
170+
171+
----------
172+
173+
Example
174+
-------
175+
>>> import pandas as pd
176+
>>> prices = pd.DataFrame({
177+
... 'Asset_A': [100, 101, 102],
178+
... 'Asset_B': [200, 202, 201],
179+
... 'Asset_C': [50, 51, 52]
180+
... })
181+
>>> cov_matrix = sample_cov(prices)
182+
>>> print(cov_matrix)
183+
Asset_A Asset_B Asset_C
184+
Asset_A 0.000001 0.000187 0.000005
185+
Asset_B 0.000187 0.028163 0.000739
186+
Asset_C 0.000005 0.000739 0.000019
187+
188+
Notes
189+
-----
190+
- In risk parity, this matrix is used to compute the risk contribution of each asset.
191+
- The diagonal values represent the variance of each asset's returns.
192+
- Off-diagonal values represent the covariance between assets.
193+
- For example, Asset_B has the highest variance (0.028163), indicating it is the riskiest asset in this sample.
165194
"""
195+
166196
if not isinstance(prices, pd.DataFrame):
167197
warnings.warn("data is not in a dataframe", RuntimeWarning)
168198
prices = pd.DataFrame(prices)

0 commit comments

Comments
 (0)