Note
Go to the end to download the full example code. or to run this example in your browser via Binder
Maximum Diversification#
This tutorial uses the MaximumDiversification
optimization to find the portfolio that maximizes the diversification ratio, which is
the ratio of the weighted volatilities over the total volatility.
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
from skfolio.datasets import load_sp500_dataset
from skfolio.optimization import EqualWeighted, MaximumDiversification
from skfolio.preprocessing import prices_to_returns
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 the maximum diversification model and then fit it on the training set:
model = MaximumDiversification()
model.fit(X_train)
model.weights_
array([8.33456624e-02, 6.74138185e-02, 2.93952573e-02, 8.57560762e-02,
4.11892006e-02, 7.98154300e-11, 1.50727312e-10, 4.41147667e-02,
1.90340137e-10, 5.11478008e-02, 6.82592031e-02, 3.02737024e-02,
3.79050966e-03, 9.95048460e-02, 1.48699105e-02, 1.10847215e-01,
1.08086158e-01, 9.45171911e-02, 6.51323607e-02, 2.35632022e-03])
To compare this model, we use an equal weighted benchmark using
the EqualWeighted
estimator:
bench = EqualWeighted()
bench.fit(X_train)
bench.weights_
array([0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05])
Diversification Analysis#
Let’s analyze the diversification ratio of both models on the training set. As expected, the maximum diversification model has the highest diversification ratio:
ptf_model_train = model.predict(X_train)
ptf_bench_train = bench.predict(X_train)
print("Diversification Ratio:")
print(f" Maximum Diversification model: {ptf_model_train.diversification:0.2f}")
print(f" Equal Weighted model: {ptf_bench_train.diversification:0.2f}")
Diversification Ratio:
Maximum Diversification model: 1.92
Equal Weighted model: 1.82
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 composition:
fig = population.plot_composition()
show(fig)
Finally we can show a full summary of both strategies evaluated on the test set:
population.plot_cumulative_returns()
Finally, we print a full summary of both strategies evaluated on the test set:
population.summary()
Total running time of the script: (0 minutes 0.428 seconds)