import pandas as pd
import numpy as np
import sqlite3
from plotnine import *
from mizani.formatters import percent_format
from itertools import product
from scipy.stats import expon
from scipy.optimize import minimize
Constrained Optimization and Backtesting
You are reading Tidy Finance with Python. You can find the equivalent chapter for the sibling Tidy Finance with Rhere.
In this chapter, we conduct portfolio backtesting in a realistic setting by including transaction costs and investment constraints such as no-short-selling rules. We start with standard mean-variance efficient portfolios and introduce constraints in a step-by-step manner. To do so, we rely on numerical optimization procedures in Python. We conclude the chapter by providing an out-of-sample backtesting procedure for the different strategies that we introduce in this chapter.
Throughout this chapter, we use the following Python packages:
Compared to previous chapters, we introduce expon
from scipy.stats
to calculate exponential continuous random variables.
Data Preparation
We start by loading the required data from our SQLite database introduced in Accessing and Managing Financial Data and WRDS, CRSP, and Compustat. For simplicity, we restrict our investment universe to the monthly Fama-French industry portfolio returns in the following application.
= sqlite3.connect(database="data/tidy_finance_python.sqlite")
tidy_finance
= (pd.read_sql_query(
industry_returns ="SELECT * FROM industries_ff_monthly",
sql=tidy_finance,
con={"date"})
parse_dates=["date"])
.drop(columns )
Recap of Portfolio Choice
A common objective for portfolio optimization is to find mean-variance efficient portfolio weights, i.e., the allocation that delivers the lowest possible return variance for a given minimum level of expected returns. In the most extreme case, where the investor is only concerned about portfolio variance, they may choose to implement the minimum variance portfolio (MVP) weights which are given by the solution to
= industry_returns.shape[1]
n_industries
= np.array(industry_returns.mean()).T
mu = np.array(industry_returns.cov())
sigma = np.linalg.inv(sigma) @ np.ones(n_industries)
w_mvp = w_mvp/w_mvp.sum()
w_mvp
= pd.DataFrame({
weights_mvp "Industry": industry_returns.columns.tolist(),
"Minimum variance": w_mvp
})round(3) weights_mvp.
Industry | Minimum variance | |
---|---|---|
0 | nodur | 0.256 |
1 | durbl | 0.001 |
2 | manuf | 0.048 |
3 | enrgy | 0.082 |
4 | hitec | 0.015 |
5 | telcm | 0.236 |
6 | shops | 0.090 |
7 | hlth | 0.161 |
8 | utils | 0.469 |
9 | other | -0.359 |
Next, consider an investor who aims to achieve minimum variance given a required expected portfolio return
Even worse, if the asset universe contains more assets than available time periods
While the uncertainty associated with estimated parameters is challenging, the data-generating process is also unknown to the investor. In other words, model uncertainty reflects that it is ex-ante not even clear which parameters require estimation (for instance, if returns are driven by a factor model, selecting the universe of relevant factors imposes model uncertainty). Wang (2005) and Garlappi, Uppal, and Wang (2007) provide theoretical analysis on optimal portfolio choice under model and estimation uncertainty. In the most extreme case, Pflug, Pichler, and Wozabal (2012) shows that the naive portfolio, which allocates equal wealth to all assets, is the optimal choice for an investor averse to model uncertainty.
On top of the estimation uncertainty, transaction costs are a major concern. Rebalancing portfolios is costly, and, therefore, the optimal choice should depend on the investor’s current holdings. In the presence of transaction costs, the benefits of reallocating wealth may be smaller than the costs associated with turnover. This aspect has been investigated theoretically, among others, for one risky asset by Magill and Constantinides (1976) and Davis and Norman (1990). Subsequent extensions to the case with multiple assets have been proposed by Balduzzi and Lynch (1999) and Balduzzi and Lynch (2000). More recent papers on empirical approaches that explicitly account for transaction costs include Gârleanu and Pedersen (2013), DeMiguel, Nogales, and Uppal (2014), and DeMiguel, Martín-Utrera, and Nogales (2015).
Estimation Uncertainty and Transaction Costs
The empirical evidence regarding the performance of a mean-variance optimization procedure in which you simply plug in some sample estimates
Assume that returns are from a multivariate normal distribution with mean
An alternative formulation of the optimal portfolio can be derived as follows:
Optimal Portfolio Choice
The function below implements the efficient portfolio weights in its general form, allowing for transaction costs (conditional on the holdings before reallocation). For gamma
denotes the coefficient of risk aversion beta
is the transaction cost parameter w_prev
are the weights before rebalancing
def compute_efficient_weight(sigma,
mu, =2,
gamma=0,
beta=np.ones(sigma.shape[1])/sigma.shape[1]):
w_prev"""Compute efficient portfolio weights."""
= sigma.shape[1]
n = np.ones(n)
iota = sigma+(beta/gamma)*np.eye(n)
sigma_processed = mu+beta*w_prev
mu_processed
= np.linalg.inv(sigma_processed)
sigma_inverse
= sigma_inverse @ iota
w_mvp = w_mvp/np.sum(w_mvp)
w_mvp = w_mvp+(1/gamma)*\
w_opt -np.outer(w_mvp, iota) @ sigma_inverse) @ mu_processed
(sigma_inverse
return w_opt
= compute_efficient_weight(sigma, mu)
w_efficient
= pd.DataFrame({
weights_efficient "Industry": industry_returns.columns.tolist(),
"Efficient portfolio": w_efficient
})round(3) weights_efficient.
Industry | Efficient portfolio | |
---|---|---|
0 | nodur | 1.468 |
1 | durbl | 0.203 |
2 | manuf | -1.488 |
3 | enrgy | 0.665 |
4 | hitec | 0.403 |
5 | telcm | -0.421 |
6 | shops | 0.611 |
7 | hlth | 0.389 |
8 | utils | -0.216 |
9 | other | -0.614 |
The portfolio weights above indicate the efficient portfolio for an investor with risk aversion coefficient
= [2, 4, 8, 20]
gammas = 20*expon.ppf(np.arange(1, 100)/100, scale=1)
betas
= (pd.DataFrame(
transaction_costs list(product(gammas, betas)),
=["gamma", "beta"]
columns
)
.assign(=lambda x: x.apply(lambda y:
weights
compute_efficient_weight(=y["gamma"], beta=y["beta"]/10000, w_prev=w_mvp),
sigma, mu, gamma=1
axis
),=lambda x: x["weights"].apply(
concentrationlambda x: np.sum(np.abs(x-w_mvp))
)
) )
The code chunk above computes the optimal weight in the presence of transaction cost for different values of
= (
rebalancing_figure
ggplot(
transaction_costs, ="beta", y="concentration",
aes(x="factor(gamma)", linetype="factor(gamma)")
color
)+ geom_line()
+ guides(linetype=None)
+ labs(
="Transaction cost parameter", y="Distance from MVP",
x="Risk aversion",
color="Portfolio weights for different risk aversion and transaction cost"
title
)
) rebalancing_figure.show()
Figure 1 shows rebalancing from the initial portfolio (which we always set to the minimum variance portfolio weights in this example). The higher the transaction costs parameter
Constrained Optimization
Next, we introduce constraints to the above optimization procedure. Very often, typical constraints such as short-selling restrictions prevent analytical solutions for optimal portfolio weights (short-selling restrictions simply imply that negative weights are not allowed such that we require that
We rely on the powerful scipy.optimize
package, which provides a common interface to a number of different optimization routines. In particular, we employ the Sequential Least-Squares Quadratic Programming (SLSQP) algorithm of Kraft (1994) because it is able to handle multiple equality and inequality constraints at the same time and is typically used for problems where the objective function and the constraints are twice continuously differentiable. We have to provide the algorithm with the objective function and its gradient, as well as the constraints and their Jacobian.
We illustrate the use of minimize()
by replicating the analytical solutions for the minimum variance and efficient portfolio weights from above. Note that the equality constraint for both solutions is given by the requirement that the weights must sum up to one. In addition, we supply a vector of equal weights as an initial value for the algorithm in all applications. We verify that the output is equal to the above solution. Note that np.allclose()
is a safe way to compare two vectors for pairwise equality. The alternative ==
is sensitive to small differences that may occur due to the representation of floating points on a computer, while np.allclose()
has a built-in tolerance. It returns True
if both are equal, which is the case in both applications below.
= np.ones(n_industries)/n_industries
w_initial
def objective_mvp(w):
return 0.5*w.T @ sigma @ w
def gradient_mvp(w):
return sigma @ w
def equality_constraint(w):
return np.sum(w)-1
def jacobian_equality(w):
return np.ones_like(w)
= (
constraints "type": "eq", "fun": equality_constraint, "jac": jacobian_equality}
{
)
= {
options "tol":1e-20,
"maxiter": 10000,
"method":"SLSQP"
}
= minimize(
w_mvp_numerical =w_initial,
x0=objective_mvp,
fun=gradient_mvp,
jac=constraints,
constraints=options["tol"],
tol={"maxiter": options["maxiter"]},
options=options["method"]
method
)
=1e-3)
np.allclose(w_mvp, w_mvp_numerical.x, atol
def objective_efficient(w):
return 2*0.5*w.T @ sigma @ w-(1+mu) @ w
def gradient_efficient(w):
return 2*sigma @ w-(1+mu)
= minimize(
w_efficient_numerical =w_initial,
x0=objective_efficient,
fun=gradient_efficient,
jac=constraints,
constraints=options["tol"],
tol={"maxiter": options["maxiter"]},
options=options["method"]
method
)
= 1e-3) np.allclose(w_efficient, w_efficient_numerical.x, atol
The result above shows that the numerical procedure indeed recovered the optimal weights for a scenario where we already know the analytic solution.
Next, we approach problems where no analytical solutions exist. First, we additionally impose short-sale constraints, which implies lb = rep(0, n_industries)
.
= minimize(
w_no_short_sale =w_initial,
x0=objective_efficient,
fun=gradient_efficient,
jac=constraints,
constraints=((0, None), )*n_industries,
bounds=options["tol"],
tol={"maxiter": options["maxiter"]},
options=options["method"]
method
)
= pd.DataFrame({
weights_no_short_sale "Industry": industry_returns.columns.tolist(),
"No short-sale": w_no_short_sale.x
})round(3) weights_no_short_sale.
Industry | No short-sale | |
---|---|---|
0 | nodur | 0.461 |
1 | durbl | 0.000 |
2 | manuf | 0.000 |
3 | enrgy | 0.206 |
4 | hitec | 0.000 |
5 | telcm | 0.000 |
6 | shops | 0.146 |
7 | hlth | 0.187 |
8 | utils | 0.000 |
9 | other | 0.000 |
As expected, the resulting portfolio weights are all positive (up to numerical precision). Typically, the holdings in the presence of short-sale constraints are concentrated among way fewer assets than in the unrestricted case. You can verify that np.sum(w_no_short_sale.x)
returns 1. In other words, minimize()
provides the numerical solution to a portfolio choice problem for a mean-variance investor with risk aversion gamma = 2
, where negative holdings are forbidden.
minimize()
can also handle more complex problems. As an example, we show how to compute optimal weights, subject to the so-called Regulation-T constraint, which requires that the sum of all absolute portfolio weights is smaller than 1.5, that is
= 1.5
reg_t
def inequality_constraint(w):
return reg_t-np.sum(np.abs(w))
def jacobian_inequality(w):
return -np.sign(w)
def objective_reg_t(w):
return -w @ (1+mu)+2*0.5*w.T @ sigma @ w
def gradient_reg_t(w):
return -(1+mu)+2*np.dot(sigma, w)
= (
constraints "type": "eq", "fun": equality_constraint, "jac": jacobian_equality},
{"type": "ineq", "fun": inequality_constraint, "jac": jacobian_inequality}
{
)
= minimize(
w_reg_t =w_initial,
x0=objective_reg_t,
fun=gradient_reg_t,
jac=constraints,
constraints=options["tol"],
tol={"maxiter": options["maxiter"]},
options=options["method"]
method
)
= pd.DataFrame({
weights_reg_t "Industry": industry_returns.columns.tolist(),
"Regulation-T": w_reg_t.x
})round(3) weights_reg_t.
Industry | Regulation-T | |
---|---|---|
0 | nodur | 0.533 |
1 | durbl | -0.000 |
2 | manuf | -0.186 |
3 | enrgy | 0.254 |
4 | hitec | 0.019 |
5 | telcm | -0.030 |
6 | shops | 0.231 |
7 | hlth | 0.213 |
8 | utils | 0.000 |
9 | other | -0.034 |
Figure 2 shows the optimal allocation weights across all python len(industry_returns.columns)
industries for the four different strategies considered so far: minimum variance, efficient portfolio with
= (weights_mvp
weights
.merge(weights_efficient)
.merge(weights_no_short_sale)
.merge(weights_reg_t)="Industry", var_name="Strategy", value_name="weights")
.melt(id_vars
)
= (
weights_figure
ggplot(
weights, ="Industry", y="weights", fill="Strategy")
aes(x
)+ geom_bar(stat="identity", position="dodge", width=0.7)
+ coord_flip()
+ labs(
="Allocation weight", fill="",
y="Optimal allocations for different strategies"
title
)+ scale_y_continuous(labels=percent_format())
) weights_figure.show()
The results clearly indicate the effect of imposing additional constraints: the extreme holdings the investor implements if they follow the (theoretically optimal) efficient portfolio vanish under, e.g., the Regulation-T constraint. You may wonder why an investor would deviate from what is theoretically the optimal portfolio by imposing potentially arbitrary constraints. The short answer is: the efficient portfolio is only efficient if the true parameters of the data-generating process correspond to the estimated parameters
Before we move on, we want to propose a final allocation strategy, which reflects a somewhat more realistic structure of transaction costs instead of the quadratic specification used above. The function below computes efficient portfolio weights while adjusting for transaction costs of the form
def compute_efficient_weight_L1_TC(mu, sigma, gamma, beta, initial_weights):
"""Compute efficient portfolio weights with L1 constraint."""
def objective(w):
return (gamma*0.5*w.T @ sigma @ w-(1+mu) @ w
+(beta/10000)/2*np.sum(np.abs(w-initial_weights)))
def gradient(w):
return (-mu+gamma*sigma @ w
+(beta/10000)*0.5*np.sign(w-initial_weights))
= (
constraints "type": "eq", "fun": equality_constraint, "jac": jacobian_equality}
{
)
= minimize(
result =initial_weights,
x0=objective,
fun=gradient,
jac=constraints,
constraints=options["tol"],
tol={"maxiter": options["maxiter"]},
options=options["method"]
method
)
return result.x
Out-of-Sample Backtesting
For the sake of simplicity, we committed one fundamental error in computing portfolio weights above: we used the full sample of the data to determine the optimal allocation (Arnott, Harvey, and Markowitz 2019). To implement this strategy at the beginning of the 2000s, you will need to know how the returns will evolve until 2021. While interesting from a methodological point of view, we cannot evaluate the performance of the portfolios in a reasonable out-of-sample fashion. We do so next in a backtesting application for three strategies. For the backtest, we recompute optimal weights just based on past available data.
The few lines below define the general setup. We consider 120 periods from the past to update the parameter estimates before recomputing portfolio weights. Then, we update portfolio weights, which is costly and affects the performance. The portfolio weights determine the portfolio return. A period later, the current portfolio weights have changed and form the foundation for transaction costs incurred in the next period. We consider three different competing strategies: the mean-variance efficient portfolio, the mean-variance efficient portfolio with ex-ante adjustment for transaction costs, and the naive portfolio, which allocates wealth equally across the different assets.
= 120
window_length = industry_returns.shape[0]-window_length
periods
= 50
beta = 2
gamma
= np.empty((periods, 3))
performance_values = np.nan
performance_values[:] = {
performance_values "MV (TC)": performance_values.copy(),
"Naive": performance_values.copy(),
"MV": performance_values.copy()
}
= industry_returns.shape[1]
n_industries = w_prev_2 = w_prev_3 = np.ones(n_industries)/n_industries w_prev_1
We also define two helper functions: One to adjust the weights due to returns and one for performance evaluation, where we compute realized returns net of transaction costs.
def adjust_weights(w, next_return):
= 1+w*next_return
w_prev return np.array(w_prev/np.sum(np.array(w_prev)))
def evaluate_performance(w, w_previous, next_return, beta=50):
"""Calculate portfolio evaluation measures."""
= np.dot(next_return, w)
raw_return = np.sum(np.abs(w-w_previous))
turnover = raw_return-beta/10000*turnover
net_return
return np.array([raw_return, turnover, net_return])
The following code chunk performs a rolling-window estimation, which we implement in a loop. In each period, the estimation window contains the returns available up to the current period. Note that we use the sample variance-covariance matrix and ignore the estimation of
for p in range(periods):
= industry_returns.iloc[p:(p+window_length-1), :]
returns_window = industry_returns.iloc[p+window_length, :]
next_return
= np.array(returns_window.cov())
sigma_window = 0*np.array(returns_window.mean())
mu
# Transaction-cost adjusted portfolio
= compute_efficient_weight_L1_TC(
w_1 =mu, sigma=sigma_window,
mu=beta,
beta=gamma,
gamma=w_prev_1
initial_weights
)
"MV (TC)"][p, :] = evaluate_performance(
performance_values[=beta
w_1, w_prev_1, next_return, beta
)= adjust_weights(w_1, next_return)
w_prev_1
# Naive portfolio
= np.ones(n_industries)/n_industries
w_2 "Naive"][p, :] = evaluate_performance(
performance_values[
w_2, w_prev_2, next_return
)= adjust_weights(w_2, next_return)
w_prev_2
# Mean-variance efficient portfolio (w/o transaction costs)
= compute_efficient_weight(sigma=sigma_window, mu=mu, gamma=gamma)
w_3 "MV"][p, :] = evaluate_performance(
performance_values[
w_3, w_prev_3, next_return
)= adjust_weights(w_3, next_return) w_prev_3
Finally, we get to the evaluation of the portfolio strategies net-of-transaction costs. Note that we compute annualized returns and standard deviations.
= pd.DataFrame()
performance for i in enumerate(performance_values.keys()):
= pd.DataFrame(
tmp_data 1]],
performance_values[i[=["raw_return", "turnover", "net_return"]
columns
)"strategy"] = i[1]
tmp_data[= pd.concat([performance, tmp_data], axis=0)
performance
= 12
length_year
= (performance
performance_table "strategy")
.groupby(
.aggregate(=("net_return", lambda x: length_year*100*x.mean()),
mean=("net_return", lambda x: np.sqrt(length_year)*100*x.std()),
sd=("net_return", lambda x: (
sharpe_ratio*100*x.mean())/(np.sqrt(length_year)*100*x.std())
(length_yearif x.mean() > 0 else np.nan)
),=("turnover", lambda x: 100*x.mean())
turnover
)
.reset_index()
)round(3) performance_table.
strategy | mean | sd | sharpe_ratio | turnover | |
---|---|---|---|---|---|
0 | MV | -1.106 | 12.590 | NaN | 210.637 |
1 | MV (TC) | 11.972 | 15.183 | 0.789 | 0.001 |
2 | Naive | 11.952 | 15.186 | 0.787 | 0.236 |
The results clearly speak against mean-variance optimization. Turnover is huge when the investor only considers their portfolio’s expected return and variance. Effectively, the mean-variance portfolio generates a negative annualized return after adjusting for transaction costs. At the same time, the naive portfolio turns out to perform very well. In fact, the performance gains of the transaction-cost adjusted mean-variance portfolio are small. The out-of-sample Sharpe ratio is slightly higher than for the naive portfolio. Note the extreme effect of turnover penalization on turnover: MV (TC) effectively resembles a buy-and-hold strategy which only updates the portfolio once the estimated parameters
Key Takeaways
- The
scipy
Python package can be used to solve constrained portfolio optimization problems that cannot be addressed analytically, including margin and regulatory constraints. - Transaction costs can be modeled in both quadratic and absolute terms, showing how rebalancing penalties influence portfolio allocations and reduce excessive turnover.
- An out-of-sample backtesting framework demonstrates that naive portfolios often outperform classical mean-variance strategies once transaction costs are considered.
- The findings highlight the practical trade-offs between theoretical optimality and robust, implementable investment strategies under uncertainty.
Exercises
- Consider the portfolio choice problem for transaction-cost adjusted certainty equivalent maximization with risk aversion parameter
where and are (estimators of) the variance-covariance matrix of the returns and the vector of expected returns. Assume for now that transaction costs are quadratic in rebalancing and proportional to stock illiquidity such that where is a diagonal matrix, where . Derive a closed-form solution for the mean-variance efficient portfolio based on the transaction cost specification above. Discuss the effect of illiquidity on the individual portfolio weights relative to an investor that myopically ignores transaction costs in their decision. - Use the solution from the previous exercise to update the function
compute_efficient_weight()
such that you can compute optimal weights conditional on a matrix with illiquidity measures. - Illustrate the evolution of the optimal weights from the naive portfolio to the efficient portfolio in the mean-standard deviation diagram.
- Is it always optimal to choose the same
in the optimization problem than the value used in evaluating the portfolio performance? In other words, can it be optimal to choose theoretically sub-optimal portfolios based on transaction cost considerations that do not reflect the actual incurred costs? Evaluate the out-of-sample Sharpe ratio after transaction costs for a range of different values of imposed values.