<a id="sphx-glr-auto-examples-mean-risk-plot-2-minimum-cvar-py"></a>

<a id="minimum-cvar"></a>

# Minimum CVaR

This tutorial uses the [`MeanRisk`](https://skfolio.org/generated/skfolio.optimization.MeanRisk.html.md#skfolio.optimization.MeanRisk) optimization to find the
minimum CVaR (Conditional Value at Risk) portfolio.

<a id="data"></a>

## Data

We load the S&P 500 [dataset](https://skfolio.org/user_guide/datasets.html.md#datasets) 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.
Prices are transformed into linear returns (see [data preparation](https://skfolio.org/user_guide/data_preparation.html.md#data-preparation)) and split into a training set and a test set without shuffling to
avoid [data leakage](https://skfolio.org/user_guide/model_selection.html.md#data-leakage).

```Python
import numpy as np
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.optimization import EqualWeighted, MeanRisk, ObjectiveFunction
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)

print(X_train.head())
```

```none
                AAPL       AMD       BAC  ...       UNH       WMT       XOM
Date                                      ...
1990-01-03  0.007576 -0.030303  0.008045  ... -0.019355  0.000000 -0.010079
1990-01-04  0.003759 -0.015500 -0.021355  ... -0.009868 -0.005201 -0.009933
1990-01-05  0.003745 -0.031996 -0.021821  ... -0.043189 -0.010732 -0.005267
1990-01-08  0.003731  0.000000  0.005633  ... -0.020833  0.013630  0.015381
1990-01-09 -0.007435  0.016527  0.000000  ... -0.024823 -0.026619 -0.020114

[5 rows x 20 columns]
```

<a id="model"></a>

## Model

We create a Minimum CVaR model and then fit it on the training set.
`portfolio_params` are parameters passed to the [`Portfolio`](https://skfolio.org/generated/skfolio.portfolio.Portfolio.html.md#skfolio.portfolio.Portfolio)
returned by the `predict` method. It can be
omitted, here we use it to give a name to our minimum CVaR portfolio:

```Python
model = MeanRisk(
    risk_measure=RiskMeasure.CVAR,
    objective_function=ObjectiveFunction.MINIMIZE_RISK,
    portfolio_params=dict(name="Min CVaR"),
)
model.fit(X_train)
model.weights_
```

```none
array([2.16562597e-02, 1.41765615e-12, 3.64939426e-13, 1.47358244e-02,
       1.35927719e-01, 1.91067310e-12, 3.58410853e-12, 2.10319534e-01,
       4.89865658e-13, 8.14734697e-02, 1.92817428e-02, 4.13677567e-12,
       7.79977277e-12, 1.26155640e-01, 4.04653978e-12, 1.52708774e-01,
       1.20106197e-02, 6.41727678e-03, 1.01024052e-01, 1.18289088e-01])
```

To compare this model, we use an equal-weighted benchmark using
[`EqualWeighted`](https://skfolio.org/generated/skfolio.optimization.EqualWeighted.html.md#skfolio.optimization.EqualWeighted):

```Python
benchmark = EqualWeighted(portfolio_params=dict(name="Equal Weighted"))
# Even if `X` has no impact (as it is equal weighted), we still need to call `fit` for
# API consistency.
benchmark.fit(X_train)
benchmark.weights_
```

```none
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])
```

<a id="prediction"></a>

## Prediction

We predict the model and the benchmark on the test set:

```Python
pred_model = model.predict(X_test)
pred_bench = benchmark.predict(X_test)
```

The `predict` method returns a [`Portfolio`](https://skfolio.org/generated/skfolio.portfolio.Portfolio.html.md#skfolio.portfolio.Portfolio) object.

[`Portfolio`](https://skfolio.org/generated/skfolio.portfolio.Portfolio.html.md#skfolio.portfolio.Portfolio) is an array-container making it compatible
with `scikit-learn` tools: calling `np.asarray(pred_model)` gives the portfolio
returns (same as `pred_model.returns`):

```Python
np.asarray(pred_model)
```

```none
array([ 0.00354605,  0.00342423, -0.00105085, ...,  0.01069377,
        0.00542224, -0.01217676], shape=(2743,))
```

The [`Portfolio`](https://skfolio.org/generated/skfolio.portfolio.Portfolio.html.md#skfolio.portfolio.Portfolio) class contains a vast number of properties
and methods used for analysis.

For example:
<br/>
* pred_model.plot_cumulative_returns()
* pred_model.plot_composition()
* pred_model.summary()

```Python
print(pred_model.cvar)
print(pred_bench.cvar)
```

```none
0.02174155209025761
0.025061083134673378
```

<a id="analysis"></a>

## Analysis

For improved analysis, we load both predicted portfolios into a
[`Population`](https://skfolio.org/generated/skfolio.population.Population.html.md#skfolio.population.Population):

```Python
population = Population([pred_model, pred_bench])
```

The [`Population`](https://skfolio.org/generated/skfolio.population.Population.html.md#skfolio.population.Population) class also contains a
vast number of properties and methods used for analysis.
Let’s plot each portfolio composition:

```Python
population.plot_composition()
```

[plotly figure stripped from llms output]
<br />
<br />

#### NOTE
Every `plot` methods in `skfolio` returns a `plotly` figure.
To display a plotly figure, you may need to call `show()` and change the
default renderer: [https://plotly.com/python/renderers/](https://plotly.com/python/renderers/)

Let’s plot each portfolio cumulative returns:

```Python
fig = population.plot_cumulative_returns()
# show(fig) is only used for the documentation sticker.
show(fig)
```

<!doctype html>
[plotly figure stripped from llms output]

<br/>

Finally, let’s display the full summary of both strategies evaluated on the test
set:

```Python
population.summary()
```

<div class="output_subarea output_html rendered_html output_result">
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Min CVaR</th>
      <th>Equal Weighted</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Mean</th>
      <td>0.052%</td>
      <td>0.069%</td>
    </tr>
    <tr>
      <th>Annualized Mean</th>
      <td>13.07%</td>
      <td>17.30%</td>
    </tr>
    <tr>
      <th>Variance</th>
      <td>0.000090</td>
      <td>0.00012</td>
    </tr>
    <tr>
      <th>Annualized Variance</th>
      <td>2.26%</td>
      <td>2.94%</td>
    </tr>
    <tr>
      <th>Semi-Variance</th>
      <td>0.000046</td>
      <td>0.000060</td>
    </tr>
    <tr>
      <th>Annualized Semi-Variance</th>
      <td>1.16%</td>
      <td>1.52%</td>
    </tr>
    <tr>
      <th>Standard Deviation</th>
      <td>0.95%</td>
      <td>1.08%</td>
    </tr>
    <tr>
      <th>Annualized Standard Deviation</th>
      <td>15.02%</td>
      <td>17.15%</td>
    </tr>
    <tr>
      <th>Semi-Deviation</th>
      <td>0.68%</td>
      <td>0.78%</td>
    </tr>
    <tr>
      <th>Annualized Semi-Deviation</th>
      <td>10.76%</td>
      <td>12.32%</td>
    </tr>
    <tr>
      <th>Mean Absolute Deviation</th>
      <td>0.61%</td>
      <td>0.71%</td>
    </tr>
    <tr>
      <th>CVaR at 95%</th>
      <td>2.17%</td>
      <td>2.51%</td>
    </tr>
    <tr>
      <th>EVaR at 95%</th>
      <td>4.62%</td>
      <td>5.43%</td>
    </tr>
    <tr>
      <th>Worst Realization</th>
      <td>8.53%</td>
      <td>10.77%</td>
    </tr>
    <tr>
      <th>CDaR at 95%</th>
      <td>14.81%</td>
      <td>13.35%</td>
    </tr>
    <tr>
      <th>MAX Drawdown</th>
      <td>34.70%</td>
      <td>34.70%</td>
    </tr>
    <tr>
      <th>Average Drawdown</th>
      <td>3.12%</td>
      <td>2.67%</td>
    </tr>
    <tr>
      <th>EDaR at 95%</th>
      <td>20.48%</td>
      <td>20.49%</td>
    </tr>
    <tr>
      <th>First Lower Partial Moment</th>
      <td>0.31%</td>
      <td>0.35%</td>
    </tr>
    <tr>
      <th>Ulcer Index</th>
      <td>0.050</td>
      <td>0.044</td>
    </tr>
    <tr>
      <th>Gini Mean Difference</th>
      <td>0.92%</td>
      <td>1.06%</td>
    </tr>
    <tr>
      <th>Value at Risk at 95%</th>
      <td>1.33%</td>
      <td>1.54%</td>
    </tr>
    <tr>
      <th>Drawdown at Risk at 95%</th>
      <td>11.23%</td>
      <td>9.48%</td>
    </tr>
    <tr>
      <th>Entropic Risk Measure at 95%</th>
      <td>3.00</td>
      <td>3.00</td>
    </tr>
    <tr>
      <th>Fourth Central Moment</th>
      <td>0.000016%</td>
      <td>0.000027%</td>
    </tr>
    <tr>
      <th>Fourth Lower Partial Moment</th>
      <td>0.000008%</td>
      <td>0.000013%</td>
    </tr>
    <tr>
      <th>Skew</th>
      <td>-0.13%</td>
      <td>-2.79%</td>
    </tr>
    <tr>
      <th>Kurtosis</th>
      <td>1977.71%</td>
      <td>1961.33%</td>
    </tr>
    <tr>
      <th>Sharpe Ratio</th>
      <td>0.055</td>
      <td>0.064</td>
    </tr>
    <tr>
      <th>Annualized Sharpe Ratio</th>
      <td>0.87</td>
      <td>1.01</td>
    </tr>
    <tr>
      <th>Sortino Ratio</th>
      <td>0.076</td>
      <td>0.088</td>
    </tr>
    <tr>
      <th>Annualized Sortino Ratio</th>
      <td>1.21</td>
      <td>1.40</td>
    </tr>
    <tr>
      <th>Mean Absolute Deviation Ratio</th>
      <td>0.085</td>
      <td>0.097</td>
    </tr>
    <tr>
      <th>First Lower Partial Moment Ratio</th>
      <td>0.17</td>
      <td>0.19</td>
    </tr>
    <tr>
      <th>Value at Risk Ratio at 95%</th>
      <td>0.039</td>
      <td>0.045</td>
    </tr>
    <tr>
      <th>CVaR Ratio at 95%</th>
      <td>0.024</td>
      <td>0.027</td>
    </tr>
    <tr>
      <th>Entropic Risk Measure Ratio at 95%</th>
      <td>0.00017</td>
      <td>0.00023</td>
    </tr>
    <tr>
      <th>EVaR Ratio at 95%</th>
      <td>0.011</td>
      <td>0.013</td>
    </tr>
    <tr>
      <th>Worst Realization Ratio</th>
      <td>0.0061</td>
      <td>0.0064</td>
    </tr>
    <tr>
      <th>Drawdown at Risk Ratio at 95%</th>
      <td>0.0046</td>
      <td>0.0072</td>
    </tr>
    <tr>
      <th>CDaR Ratio at 95%</th>
      <td>0.0035</td>
      <td>0.0051</td>
    </tr>
    <tr>
      <th>Calmar Ratio</th>
      <td>0.0015</td>
      <td>0.0020</td>
    </tr>
    <tr>
      <th>Average Drawdown Ratio</th>
      <td>0.017</td>
      <td>0.026</td>
    </tr>
    <tr>
      <th>EDaR Ratio at 95%</th>
      <td>0.0025</td>
      <td>0.0033</td>
    </tr>
    <tr>
      <th>Ulcer Index Ratio</th>
      <td>0.010</td>
      <td>0.015</td>
    </tr>
    <tr>
      <th>Gini Mean Difference Ratio</th>
      <td>0.056</td>
      <td>0.064</td>
    </tr>
    <tr>
      <th>Effective Number of Assets</th>
      <td>7.46127671221519</td>
      <td>19.999999999999993</td>
    </tr>
    <tr>
      <th>Assets Number</th>
      <td>20</td>
      <td>20</td>
    </tr>
  </tbody>
</table>
</div>
</div>
<br />
<br />

<a id="conclusion"></a>

## Conclusion

From the analysis on the test set, we see that the Minimum CVaR portfolio outperforms
the equal-weighted benchmark for all deviation and shortfall risk measures, except for
the drawdown measures, and underperforms for the mean and ratio measures.

#### SEE ALSO
This was a toy example, for more advanced concepts check the
[user guide](https://skfolio.org/user_guide/index.html.md#user-guide) or the [other examples](https://skfolio.org/auto_examples/index.html.md#general-examples).

**Total running time of the script:** (0 minutes 3.183 seconds)

<a id="sphx-glr-download-auto-examples-mean-risk-plot-2-minimum-cvar-py"></a>
