CVaR Portfolio Optimization in Python: PyPortfolioOpt and skfolio Compared

Introduction: Why Tail Risk Deserves Its Own Objective
This is Week 5 of QBAI’s portfolio-optimization series. The earlier posts covered mean-variance optimization, Black-Litterman, and Hierarchical Risk Parity; here, the focus shifts to measuring and constraining losses in the tail rather than revisiting those methods (Markowitz, Black-Litterman, HRP).
The running example is QBAI’s AI-silicon universe: NVDA, AMD, AVGO, TSM, ASML, MU, INTC, QCOM, TXN, and ARM. These names provide a useful setting for discussing scenario-based tail risk, but no portfolio weights or performance results for them are presented here.
The Math: From VaR to CVaR
What VaR is—and where it falls short
Value-at-Risk (VaR) at a confidence level is a loss threshold: under the modeled distribution, losses beyond that threshold are in the tail. VaR communicates a cutoff, but not how severe losses may be once they pass it.
Rockafellar and Uryasev describe VaR as numerically unstable and difficult to work with when losses are not normally distributed. They also explain that VaR is not coherent and provides no handle on the extent of losses beyond its threshold (Rockafellar and Uryasev, 2002). Those limitations matter when the shape of the loss distribution—not just its variance—is central to the risk objective.
CVaR and the Rockafellar–Uryasev formula
Conditional Value-at-Risk (CVaR), also called Expected Shortfall, summarizes tail losses beyond VaR. A standard scenario-based formulation is:
CVaR_a(L) = min over zeta of { zeta + E[(L - zeta)+] / (1 - a) }
Here, L is portfolio loss and a is the confidence level. The auxiliary variable zeta acts as a VaR threshold; (L-zeta)^+ is the positive part of loss above that threshold; and 1-a scales the average excess loss to the tail probability. Minimizing over zeta gives the Rockafellar–Uryasev representation of CVaR, which makes scenario-based optimization tractable with linear programming (Rockafellar and Uryasev, 2000, Rockafellar and Uryasev, 2002). Convex optimization frameworks such as CVXPY provide a broader context for modeling convex problems.
For a portfolio, each row in the return scenarios represents a possible joint outcome across assets. The optimizer evaluates portfolio losses across those scenarios, so the quality and relevance of the scenarios are fundamental—not incidental—to the result.
Why choose CVaR over VaR?
CVaR adds information about losses beyond a threshold and, under the cited formulation, offers a tractable optimization objective. There is an important qualification for readers familiar with variance-based methods: for normal, or more generally elliptical, distributions, minimizing CVaR, minimizing VaR, or minimizing variance yields equivalent portfolios, although CVaR still exceeds VaR as a loss number (Rockafellar and Uryasev, 2002). The practical difference therefore appears only when returns are not elliptical. Actual return distributions and scenario choices, however, should not be assumed to satisfy that condition without evidence.
Regulatory Context: Why Basel Moved to Expected Shortfall
Basel’s market-risk framework describes the internal models approach as relying on expected-shortfall models (Basel Committee on Banking Supervision). A secondary explanation of the FRTB framework gives the expected-shortfall confidence level as 97.5% (RiskHub, secondary source); the BIS page supports the ES-based approach, while the specific confidence-level figure here is attributed to that secondary source.
This regulatory context helps explain why expected shortfall is an established risk measure. It is not a portfolio-construction prescription: the appropriate objective and assumptions depend on the task, data, and constraints.
The Two Python Routes: PyPortfolioOpt and skfolio
PyPortfolioOpt: EfficientCVaR
PyPortfolioOpt’s EfficientCVaR supports optimization along a mean-CVaR frontier using the Rockafellar–Uryasev formulation (PyPortfolioOpt general efficient-frontier documentation). Its input is a returns DataFrame containing historical or simulated scenarios—not a covariance matrix. The documented constructor takes expected returns, the returns scenarios, a confidence parameter beta (default 0.95), weight bounds, and solver options; consult the class source alongside the documentation when adapting an implementation.
skfolio: MeanRisk
skfolio provides a MeanRisk route using RiskMeasure.CVAR and ObjectiveFunction.MINIMIZE_RISK. Its minimum-CVaR tutorial splits data chronologically with shuffle=False, then compares a fitted portfolio with a benchmark on the test set (skfolio Minimum CVaR tutorial). The tutorial is explicitly a toy example, not a result for the AI-silicon universe.
| Dimension | PyPortfolioOpt EfficientCVaR |
skfolio MeanRisk(CVAR) |
|---|---|---|
| Formulation basis | Rockafellar–Uryasev mean-CVaR frontier | MeanRisk with CVaR as the risk measure |
| Input data type | Scenario returns DataFrame, not a covariance matrix | Return scenarios |
| Objective options | Minimum CVaR and mean-CVaR frontier methods | ObjectiveFunction.MINIMIZE_RISK |
| Frontier support | Mean-CVaR frontier (efficient_return) |
Not covered in the cited tutorial |
| Out-of-sample tooling | None built in; the user supplies a chronological test set | Tutorial demonstrates a chronological train/test split |
| Documentation style | PyPortfolioOpt efficient-frontier docs and class source | Tutorial-led examples and API documentation |
| Best fit | Readers already working with PyPortfolioOpt frontier workflows | Readers who want skfolio’s broader portfolio-modeling workflow |
Code Plan: A Reproducible Workflow
The following example illustrates documented API usage: retrieve prices, form scenario returns, split chronologically, fit each optimizer on training data, and keep test data separate. The yfinance documentation describes the price-retrieval library; no live prices were pulled for this post. The split without shuffling follows the discipline shown in the skfolio tutorial. The code is illustrative and was not executed here.
import pandas as pd
import yfinance as yf
from pypfopt import expected_returns
from pypfopt.efficient_frontier import EfficientCVaR
from skfolio import RiskMeasure
from skfolio.optimization import MeanRisk, ObjectiveFunction
universe = ["NVDA", "AMD", "AVGO", "TSM", "ASML",
"MU", "INTC", "QCOM", "TXN", "ARM"]
# Data retrieval is an example; the post did not pull live prices.
downloaded = yf.download(
tickers=universe,
period="5y",
auto_adjust=True,
)
prices = downloaded["Close"]
# Handle a possible multi-level column index from the data provider.
if isinstance(prices.columns, pd.MultiIndex):
prices.columns = prices.columns.get_level_values(-1)
prices = prices.dropna()
returns = prices.pct_change().dropna()
# Chronological split: do not shuffle returns across time.
split = int(len(returns) * 0.8)
train_returns = returns.iloc[:split]
test_returns = returns.iloc[split:]
train_prices = prices.loc[:train_returns.index[-1]]
# Route A: PyPortfolioOpt takes scenario returns, not a covariance matrix.
mu = expected_returns.mean_historical_return(train_prices)
ef = EfficientCVaR(mu, train_returns)
pypfopt_weights = ef.min_cvar()
# Keep the held-out period separate from fitting.
test_weights = pd.Series(pypfopt_weights).reindex(test_returns.columns)
test_portfolio_returns = test_returns @ test_weights # evaluate on the held-out period
# Route B: skfolio minimum-risk model with CVaR as its risk measure.
model = MeanRisk(
risk_measure=RiskMeasure.CVAR,
objective_function=ObjectiveFunction.MINIMIZE_RISK,
)
model.fit(train_returns.to_numpy())
test_portfolio = model.predict(test_returns.to_numpy())
print(test_portfolio_returns.describe()) # inspect; do not read as a verdict
The code was not run for this post, so it prints nothing here. A research workflow would also compare the skfolio weights with the PyPortfolioOpt weights on the same untouched test period.
Out-of-Sample Discipline: Why You Never Shuffle
Randomly shuffling time-series observations can mix later regimes into training data and earlier observations into a test set. That undermines a chronological evaluation. The skfolio example uses a split without shuffling and evaluates on its test set (skfolio Minimum CVaR tutorial).
Its results must stay in their original context: the tutorial reports that its minimum-CVaR portfolio outperformed an equal-weighted benchmark on deviation and shortfall measures except drawdown measures, and underperformed on mean and ratio measures. Those findings concern the tutorial’s S&P 500 toy example; they are not evidence about this AI-silicon universe (skfolio Minimum CVaR tutorial).
Caveats and Honest Limitations
Scenario-based optimization is only as informative as its scenarios. Historical returns may not represent future tail events, especially in a concentrated, regime-driven sector. Simulated scenarios can broaden the inputs, but they do not remove modeling assumptions or guarantee that the modeled tail resembles future outcomes.
Expected-return estimates remain an important source of uncertainty when constructing a mean-CVaR frontier, just as they are in other methods that use expected returns. The earlier Black-Litterman guide discusses a views-based framework, but no method eliminates estimation risk.
The skfolio example is explicitly a toy example and its reported results should not be generalized to another universe (skfolio Minimum CVaR tutorial). Likewise, the 97.5% expected-shortfall level above is regulatory context from a secondary source, not a recommendation for portfolio construction (RiskHub, secondary source).
This post makes no performance claims for the AI-silicon universe: no in-house backtest was run, and no Sharpe ratio, drawdown, return, or CVaR result is reported. Nothing here is investment advice.
How This Guide Was Built
This guide is based on desk research from library documentation and academic papers, including the Rockafellar–Uryasev paper record. No in-house backtest was run; no live price data was pulled for the universe; and the code is based on documented APIs and was not executed in this post.
FAQ
Is CVaR the same as Expected Shortfall?
The terms are commonly used as synonyms for the tail-average loss measure; see this definitional overview of Expected Shortfall and CVaR. Precise conventions can depend on the loss distribution and definition used.
Is CVaR always better than VaR?
No. CVaR provides information about losses beyond a threshold, but the choice of measure depends on the risk question and assumptions. For normal or elliptical distributions, minimizing CVaR and minimizing VaR give equivalent portfolios, although CVaR remains the larger loss number (Rockafellar and Uryasev, 2002).
Can I pass a covariance matrix to EfficientCVaR?
No. The documented EfficientCVaR input is a DataFrame of historical or simulated return scenarios, not a covariance matrix (PyPortfolioOpt documentation).
What confidence level should I use?
That is a modeling choice, not a universal instruction. The Basel context above describes an expected-shortfall-based internal models approach; the 97.5% figure is attributed to a secondary source and is not presented as a recommended portfolio setting (BIS, RiskHub, secondary source).
Does CVaR optimization guarantee better out-of-sample performance?
No. The skfolio tutorial itself labels its example as a toy example, and its findings apply to that example rather than to other portfolios (skfolio tutorial).
How is this different from HRP?
HRP clusters assets by their correlation structure and does not need scenario returns. CVaR optimization needs a return-scenario matrix and minimizes a tail-loss objective over those scenarios. The earlier HRP guide covers the clustering approach.
The Bottom Line
CVaR is useful when the objective is to account for losses beyond a VaR threshold. The Rockafellar–Uryasev formulation turns that tail-risk measure into a scenario-based optimization problem, and both PyPortfolioOpt and skfolio document ways to work with it. For QBAI’s AI-silicon universe, no performance verdict is possible without a backtest. The appropriate next step for research is a reproducible, chronological evaluation with explicit assumptions—not a conclusion inferred from code that has not been run.
← Back to all posts

