Note
Go to the end to download the full example code. or to run this example in your browser via JupyterLite or Binder
Risk Parity - Covariance shrinkage#
This tutorial shows how to incorporate covariance shrinkage in the
RiskBudgeting
optimization.
Data#
We load the S&P 500 dataset composed of the daily prices of 20 assets from the S&P 500 Index composition starting from 1990-01-02 up to 2022-12-28:
from plotly.io import show
from sklearn.model_selection import train_test_split
from skfolio import Population, RiskMeasure
from skfolio.datasets import load_sp500_dataset
from skfolio.moments import ShrunkCovariance
from skfolio.optimization import RiskBudgeting
from skfolio.preprocessing import prices_to_returns
from skfolio.prior import EmpiricalPrior
prices = load_sp500_dataset()
X = prices_to_returns(prices)
X_train, X_test = train_test_split(X, test_size=0.33, shuffle=False)
Model#
We create a risk parity model by using ShrunkCovariance
as
the covariance estimator then fit it on the training set:
model = RiskBudgeting(
risk_measure=RiskMeasure.VARIANCE,
prior_estimator=EmpiricalPrior(
covariance_estimator=ShrunkCovariance(shrinkage=0.9)
),
portfolio_params=dict(name="Risk Parity - Covariance Shrinkage"),
)
model.fit(X_train)
model.weights_
array([0.04774388, 0.04370282, 0.04503242, 0.04647739, 0.05284608,
0.04907465, 0.0485292 , 0.05373939, 0.04539524, 0.0536071 ,
0.05178498, 0.0513796 , 0.04927133, 0.05375727, 0.05112687,
0.05417611, 0.04755307, 0.0498814 , 0.05199177, 0.05292942])
To compare this model, we use a basic risk parity without covariance shrinkage:
bench = RiskBudgeting(
risk_measure=RiskMeasure.VARIANCE,
portfolio_params=dict(name="Risk Parity - Basic"),
)
bench.fit(X_train)
bench.weights_
array([0.04135234, 0.03210845, 0.03372587, 0.03785082, 0.06105296,
0.04432849, 0.04252282, 0.06593432, 0.03451821, 0.06469294,
0.05418924, 0.05209364, 0.04535247, 0.06568089, 0.05104083,
0.06894458, 0.04046576, 0.04667751, 0.05627127, 0.0611966 ])
Prediction#
We predict the model and the benchmark on the test set:
ptf_model_test = model.predict(X_test)
ptf_bench_test = bench.predict(X_test)
Analysis#
For improved analysis, it’s possible to load both predicted portfolios into a
Population
:
population = Population([ptf_model_test, ptf_bench_test])
Let’s plot each portfolio cumulative returns:
fig = population.plot_cumulative_returns()
show(fig)
Finally, we print a full summary of both strategies evaluated on the test set:
population.summary()
Total running time of the script: (0 minutes 2.333 seconds)