11.1 Portfolio Optimization¶
In this section the Markowitz portfolio optimization problem and variants are implemented using Fusion API for Python.
11.1.1 The Basic Model¶
The classical Markowitz portfolio optimization problem considers investing in
and covariance
The return of the investment is also a random variable
and variance
The standard deviation
is usually associated with risk.
The problem facing the investor is to rebalance the portfolio to achieve a good compromise between risk and expected return, e.g., maximize the expected return subject to a budget constraint and an upper bound (denoted
The variables
A popular choice is
Since
is the total investment. Clearly, the total amount invested must be equal to the initial wealth, which is
This leads to the first constraint
The second constraint
ensures that the variance, is bounded by the parameter
excludes the possibility of short-selling. This constraint can of course be excluded if short-selling is allowed.
The covariance matrix
In general the choice of
Hence, we may write the risk constraint as
or equivalently
where
Therefore, problem (11.1) can be written as
which is a conic quadratic optimization problem that can easily be formulated and solved with Fusion API for Python. Subsequently we will use the example data
and
Using Cholesky factorization, this implies
In Sec. 11.1.3 (Factor model and efficiency), we present a different way of obtaining
Why a Conic Formulation?
Problem (11.1) is a convex quadratically constrained optimization problem that can be solved directly using MOSEK. Why then reformulate it as a conic quadratic optimization problem (11.3)? The main reason for choosing a conic model is that it is more robust and usually solves faster and more reliably. For instance it is not always easy to numerically validate that the matrix
Moreover, observe the constraint
more numerically robust than
for very small and very large values of
Example code
Listing 11.1 demonstrates how the basic Markowitz model (11.3) is implemented.
def BasicMarkowitz(n,mu,GT,x0,w,gamma):
with Model("Basic Markowitz") as M:
# Redirect log output from the solver to stdout for debugging.
# if uncommented.
# M.setLogHandler(sys.stdout)
# Defines the variables (holdings). Shortselling is not allowed.
x = M.variable("x", n, Domain.greaterThan(0.0))
# Maximize expected return
M.objective('obj', ObjectiveSense.Maximize, x.T @ mu)
# The amount invested must be identical to initial wealth
M.constraint('budget', Expr.sum(x) == w+sum(x0))
# Imposes a bound on the risk
M.constraint('risk', Expr.vstack(gamma, GT @ x) == Domain.inQCone())
#M.constraint('risk', Expr.vstack(gamma, 0.5, Expr.mul(GT, x)), Domain.inRotatedQCone())
# Solves the model.
M.solve()
# Check if the solution is an optimal point
solsta = M.getPrimalSolutionStatus()
if (solsta != SolutionStatus.Optimal):
# See https://docs.mosek.com/latest/pythonfusion/accessing-solution.html about handling solution statuses.
raise Exception(f"Unexpected solution status: {solsta}")
return np.dot(mu, x.level()), x.level()
The source code should be self-explanatory except perhaps for
M.constraint('risk', Expr.vstack(gamma, GT @ x) == Domain.inQCone())
#M.constraint('risk', Expr.vstack(gamma, 0.5, Expr.mul(GT, x)), Domain.inRotatedQCone())
where the linear expression
is created using the Expr.vstack
operator. Finally, the linear expression must lie in a quadratic cone implying
11.1.2 The Efficient Frontier¶
The portfolio computed by the Markowitz model is efficient in the sense that there is no other portfolio giving a strictly higher return for the same amount of risk. An efficient portfolio is also sometimes called a Pareto optimal portfolio. Clearly, an investor should only invest in efficient portfolios and therefore it may be relevant to present the investor with all efficient portfolios so the investor can choose the portfolio that has the desired tradeoff between return and risk.
Given a nonnegative
is one standard way to trade the expected return against penalizing variance. Note that, in contrast to the previous example, we explicitly use the variance (
The parameter

Fig. 11.1 The efficient frontier for the sample data.¶
Example code
Listing 11.2 demonstrates how to compute the efficient portfolios for several values of
here
to download.¶def EfficientFrontier(n,mu,GT,x0,w,alphas):
with Model("Efficient frontier") as M:
frontier = []
# Defines the variables (holdings). Shortselling is not allowed.
x = M.variable("x", n, Domain.greaterThan(0.0)) # Portfolio variables
s = M.variable("s", 1, Domain.unbounded()) # Variance variable
# Total budget constraint
M.constraint('budget', Expr.sum(x) == w+sum(x0))
# Computes the risk
M.constraint('variance', Expr.vstack(s, 0.5, GT @ x), Domain.inRotatedQCone())
# Define objective as a weighted combination of return and variance
alpha = M.parameter()
M.objective('obj', ObjectiveSense.Maximize, x.T @ mu - s * alpha)
# Solve multiple instances by varying the parameter alpha
for a in alphas:
alpha.setValue(a)
M.solve()
# Check if the solution is an optimal point
solsta = M.getPrimalSolutionStatus()
if (solsta != SolutionStatus.Optimal):
# See https://docs.mosek.com/latest/pythonfusion/accessing-solution.html about handling solution statuses.
raise Exception(f"Unexpected solution status: {solsta}")
frontier.append((a, np.dot(mu,x.level()), s.level()[0]))
return frontier
Note that we defined
11.1.3 Factor model and efficiency¶
In practice it is often important to solve the portfolio problem very quickly. Therefore, in this section we discuss how to improve computational efficiency at the modeling stage.
The computational cost is of course to some extent dependent on the number of constraints and variables in the optimization problem. However, in practice a more important factor is the sparsity: the number of nonzeros used to represent the problem. Indeed it is often better to focus on the number of nonzeros in
In other words if the computational efficiency should be improved then it is always good idea to start with focusing at the covariance matrix. As an example assume that
where
One possible choice for
because then
This choice requires storage proportional to
The example above exploits the so-called factor structure and demonstrates that an alternative choice of
The lesson to be learned is that it is important to investigate how the covariance matrix is formed. Given this knowledge it might be possible to make a special choice for
Factor model in finance
Factor model structure is typical in financial context. It is common to model security returns as the sum of two components using a factor model. The first component is the linear combination of a small number of factors common among a group of securities. The second component is a residual, specific to each security. It can be written as
Such a model will result in the covariance structure
where
Example code
Here we will work with the example data of a two-factor model (
and the factor covariance matrix is
giving
Then the matrix
This matrix is indeed very sparse.
In general, we get an
Example code
In the following we demonstrate how to write code to compute the matrix
B = np.array([
[0.4256, 0.1869],
[0.2413, 0.3877],
[0.2235, 0.3697],
[0.1503, 0.4612],
[1.5325, -0.2633],
[1.2741, -0.2613],
[0.6939, 0.2372],
[0.5425, 0.2116]
])
S_F = np.array([
[0.0620, 0.0577],
[0.0577, 0.0908]
])
theta = np.array([0.0720, 0.0508, 0.0377, 0.0394, 0.0663, 0.0224, 0.0417, 0.0459])
Then the matrix
P = np.linalg.cholesky(S_F)
G_factor = B @ P
G_factor_T = G_factor.T
The code for computing an optimal portfolio in the factor model is very similar to the one from the basic model in Listing 11.1 with one notable exception: we construct the expression
# Conic constraint for the portfolio std. dev
M.constraint('risk', Expr.vstack([Expr.constTerm(gamma),
G_factor_T @ x,
Expr.mulElm(np.sqrt(theta), x)]), Domain.inQCone())
The full code is demonstrated below:
def FactorModelMarkowitz(n, mu, G_factor_T, S_theta, x0, w, gamma):
with Model("Factor model Markowitz") as M:
# Variables
# The variable x is the fraction of holdings in each security.
# It is restricted to be positive, which imposes the constraint of no short-selling.
x = M.variable("x", n, Domain.greaterThan(0.0))
# Objective (quadratic utility version)
M.objective('obj', ObjectiveSense.Maximize, x.T @ mu)
# Budget constraint
M.constraint('budget', Expr.sum(x) == w + sum(x0))
# Conic constraint for the portfolio std. dev
M.constraint('risk', Expr.vstack([Expr.constTerm(gamma),
G_factor_T @ x,
Expr.mulElm(np.sqrt(theta), x)]), Domain.inQCone())
# Solve optimization
M.solve()
# Check if the solution is an optimal point
solsta = M.getPrimalSolutionStatus()
if (solsta != SolutionStatus.Optimal):
# See https://docs.mosek.com/latest/pythonfusion/accessing-solution.html about handling solution statuses.
raise Exception(f"Unexpected solution status: {solsta}")
return mu @ x.level(), x.level()
11.1.4 Slippage Cost¶
The basic Markowitz model assumes that there are no costs associated with trading the assets and that the returns of the assets are independent of the amount traded. Neither of those assumptions is usually valid in practice. Therefore, a more realistic model is
Here
and
11.1.5 Market Impact Costs¶
If the initial wealth is fairly small and no short selling is allowed, then the holdings will be small and the traded amount of each asset must also be small. Therefore, it is reasonable to assume that the prices of the assets are independent of the amount traded. However, if a large volume of an asset is sold or purchased, the price, and hence return, can be expected to change. This effect is called market impact costs. It is common to assume that the market impact cost for asset
where
Hence, it follows that
Unfortunately this set of constraints is nonconvex due to the constraint
but in many cases the constraint may be replaced by the relaxed constraint
For instance if the universe of assets contains a risk free asset then
cannot hold for an optimal solution.
If the optimal solution has the property (11.9) then the market impact cost within the model is larger than the true market impact cost and hence money are essentially considered garbage and removed by generating transaction costs. This may happen if a portfolio with very small risk is requested because the only way to obtain a small risk is to get rid of some of the assets by generating transaction costs. We generally assume that this is not the case and hence the models (11.7) and (11.8) are equivalent.
The above observations lead to
The revised budget constraint
specifies that the initial wealth covers the investment and the transaction costs. It should be mentioned that transaction costs of the form
where
See the Modeling Cookbook for details.
Example code
Listing 11.5 demonstrates how to compute an optimal portfolio when market impact cost are included.
def MarkowitzWithMarketImpact(n,mu,GT,x0,w,gamma,m):
with Model("Markowitz portfolio with market impact") as M:
#M.setLogHandler(sys.stdout)
# Defines the variables. No shortselling is allowed.
x = M.variable("x", n, Domain.greaterThan(0.0))
# Variables computing market impact
t = M.variable("t", n, Domain.unbounded())
# Maximize expected return
M.objective('obj', ObjectiveSense.Maximize, x.T @ mu)
# Invested amount + slippage cost = initial wealth
M.constraint('budget', Expr.sum(x) + Expr.dot(m,t) == w+sum(x0))
# Imposes a bound on the risk
M.constraint('risk', Expr.vstack(gamma, GT @ x), Domain.inQCone())
# t >= |x-x0|^1.5 using a power cone
M.constraint('tz', Expr.hstack(t, Expr.constTerm(n, 1.0), x-x0), Domain.inPPowerCone(2.0/3.0))
M.solve()
# Check if the solution is an optimal point
solsta = M.getPrimalSolutionStatus()
if (solsta != SolutionStatus.Optimal):
# See https://docs.mosek.com/latest/pythonfusion/accessing-solution.html about handling solution statuses.
raise Exception(f"Unexpected solution status: {solsta}")
return x.level(), t.level()
11.1.6 Transaction Costs¶
Now assume there is a cost associated with trading asset
Hence, whenever asset
(11.11)¶
First observe that
We choose
Example code
The following example code demonstrates how to compute an optimal portfolio when transaction costs are included.
def MarkowitzWithTransactionsCost(n,mu,GT,x0,w,gamma,f,g):
# Upper bound on the traded amount
w0 = w+sum(x0)
u = n*[w0]
with Model("Markowitz portfolio with transaction costs") as M:
#M.setLogHandler(sys.stdout)
# Defines the variables. No shortselling is allowed.
x = M.variable("x", n, Domain.greaterThan(0.0))
# Additional "helper" variables
z = M.variable("z", n, Domain.unbounded())
# Binary variables
y = M.variable("y", n, Domain.binary())
# Maximize expected return
M.objective('obj', ObjectiveSense.Maximize, x.T @ mu)
# Invest amount + transactions costs = initial wealth
M.constraint('budget', Expr.sum(x) + Expr.dot(f,y) + Expr.dot(g,z) == w0)
# Imposes a bound on the risk
M.constraint('risk', Expr.vstack(gamma, GT @ x), Domain.inQCone())
# z >= |x-x0|
M.constraint('buy', z >= x-x0)
M.constraint('sell', z >= x0-x)
# Alternatively, formulate the two constraints as
#M.constraint('trade', Expr.hstack(z, x-x0), Domain.inQcone())
# Constraints for turning y off and on. z-diag(u)*y<=0 i.e. z_j <= u_j*y_j
M.constraint('y_on_off', z <= Expr.mulElm(u, y))
# Integer optimization problems can be very hard to solve so limiting the
# maximum amount of time is a valuable safe guard
M.setSolverParam('mioMaxTime', 180.0)
M.solve()
# Check if the solution is an optimal point
solsta = M.getPrimalSolutionStatus()
if (solsta != SolutionStatus.Optimal):
# See https://docs.mosek.com/latest/pythonfusion/accessing-solution.html about handling solution statuses.
raise Exception(f"Unexpected solution status: {solsta}")
return x.level(), y.level(), z.level()
11.1.7 Cardinality constraints¶
Another method to reduce costs involved with processing transactions is to only change positions in a small number of assets. In other words, at most
This type of constraint can be again modeled by introducing a binary variable
(11.12)¶
were
Example code
The following example code demonstrates how to compute an optimal portfolio with cardinality bounds. Note that we define the maximum cardinality as a parameter in the model and use it to parametrize the cardinality constraint. This way we can use one model to solve many problems with the same structure and data except for the cardinality bound by simply changing this parameter between the solves.
def MarkowitzWithCardinality(n,mu,GT,x0,w,gamma,KValues):
# Upper bound on the traded amount
w0 = w+sum(x0)
u = n*[w0]
with Model("Markowitz portfolio with cardinality bound") as M:
#M.setLogHandler(sys.stdout)
# Defines the variables. No shortselling is allowed.
x = M.variable("x", n, Domain.greaterThan(0.0))
# Additional "helper" variables
z = M.variable("z", n, Domain.unbounded())
# Binary variables - do we change position in assets
y = M.variable("y", n, Domain.binary())
# Maximize expected return
M.objective('obj', ObjectiveSense.Maximize, x.T @ mu)
# The amount invested must be identical to initial wealth
M.constraint('budget', Expr.sum(x) == w+sum(x0))
# Imposes a bound on the risk
M.constraint('risk', Expr.vstack(gamma, GT @ x), Domain.inQCone())
# z >= |x-x0|
M.constraint('buy', z >= x-x0)
M.constraint('sell', z >= x0-x)
# Constraints for turning y off and on. z-diag(u)*y<=0 i.e. z_j <= u_j*y_j
M.constraint('y_on_off', z <= Expr.mulElm(u,y))
# At most K assets change position
cardMax = M.parameter()
M.constraint('cardinality', Expr.sum(y)<= cardMax)
# Integer optimization problems can be very hard to solve so limiting the
# maximum amount of time is a valuable safe guard
M.setSolverParam('mioMaxTime', 180.0)
# Solve multiple instances by varying the parameter K
results = []
for K in KValues:
cardMax.setValue(K)
M.solve()
# Check if the solution is an optimal point
solsta = M.getPrimalSolutionStatus()
if (solsta != SolutionStatus.Optimal):
# See https://docs.mosek.com/latest/pythonfusion/accessing-solution.html about handling solution statuses.
raise Exception(f"Unexpected solution status: {solsta}")
results.append(x.level())
return results
If we solve our running example with
Bound 1 Solution: 0.0000e+00 0.0000e+00 1.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00
Bound 2 Solution: 0.0000e+00 0.0000e+00 3.5691e-01 0.0000e+00 0.0000e+00 6.4309e-01 -0.0000e+00 0.0000e+00
Bound 3 Solution: 0.0000e+00 0.0000e+00 1.9258e-01 0.0000e+00 0.0000e+00 5.4592e-01 2.6150e-01 0.0000e+00
Bound 4 Solution: 0.0000e+00 0.0000e+00 2.0391e-01 0.0000e+00 6.7098e-02 4.9181e-01 2.3718e-01 0.0000e+00
Bound 5 Solution: 0.0000e+00 3.1970e-02 1.7028e-01 0.0000e+00 7.0741e-02 4.9551e-01 2.3150e-01 0.0000e+00
Bound 6 Solution: 0.0000e+00 3.1970e-02 1.7028e-01 0.0000e+00 7.0740e-02 4.9551e-01 2.3150e-01 0.0000e+00
Bound 7 Solution: 0.0000e+00 3.1970e-02 1.7028e-01 0.0000e+00 7.0740e-02 4.9551e-01 2.3150e-01 0.0000e+00
Bound 8 Solution: 1.9557e-10 2.6992e-02 1.6706e-01 2.9676e-10 7.1245e-02 4.9559e-01 2.2943e-01 9.6905e-03