# 11.1 Portfolio Optimization¶

In this section the Markowitz portfolio optimization problem and variants are implemented using the MOSEK optimizer API.

## 11.1.1 A Basic Portfolio Optimization Model¶

The classical Markowitz portfolio optimization problem considers investing in $$n$$ stocks or assets held over a period of time. Let $$x_j$$ denote the amount invested in asset $$j$$, and assume a stochastic model where the return of the assets is a random variable $$r$$ with known mean

$\mu = \mathbf{E} r$

and covariance

$\Sigma = \mathbf{E}(r-\mu)(r-\mu)^T.$

The return of the investment is also a random variable $$y = r^Tx$$ with mean (or expected return)

$\mathbf{E} y = \mu^T x$

and variance

$\mathbf{E}(y - \mathbf{E} y)^2 = x^T \Sigma x.$

The standard deviation

$\sqrt{ x^T \Sigma x }$

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 $$\gamma$$) on the tolerable risk. This leads to the optimization problem

(11.1)$\begin{split}\begin{array} {lrcl} \mbox{maximize} & \mu^T x & & \\ \st & e^T x & = & w + e^T x^0, \\ & x^T \Sigma x & \leq & \gamma^2, \\ & x & \geq & 0. \end{array}\end{split}$

The variables $$x$$ denote the investment i.e. $$x_j$$ is the amount invested in asset $$j$$ and $$x_j^0$$ is the initial holding of asset $$j$$. Finally, $$w$$ is the initial amount of cash available.

A popular choice is $$x^0=0$$ and $$w=1$$ because then $$x_j$$ may be interpreted as the relative amount of the total portfolio that is invested in asset $$j$$.

Since $$e$$ is the vector of all ones then

$e^T x = \sum_{j=1}^{n} x_j$

is the total investment. Clearly, the total amount invested must be equal to the initial wealth, which is

$w + e^T x^0.$

This leads to the first constraint

$e^T x = w + e^T x^0.$

The second constraint

$x^T \Sigma x \leq \gamma^2$

ensures that the variance, is bounded by the parameter $$\gamma^2$$. Therefore, $$\gamma$$ specifies an upper bound of the standard deviation (risk) the investor is willing to undertake. Finally, the constraint

$x_j \geq 0$

excludes the possibility of short-selling. This constraint can of course be excluded if short-selling is allowed.

The covariance matrix $$\Sigma$$ is positive semidefinite by definition and therefore there exist a matrix $$G$$ such that

(11.2)$\Sigma = G G^T.$

In general the choice of $$G$$ is not unique and one possible choice of $$G$$ is the Cholesky factorization of $$\Sigma$$. However, in many cases another choice is better for efficiency reasons as discussed in Sec. 11.1.3 (Factor model and efficiency). For a given $$G$$ we have that

$\begin{split}\begin{array}{lll} x^T \Sigma x & = & x^T G G^T x \\ & = & \left\|G^T x\right\|^2. \end{array}\end{split}$

Hence, we may write the risk constraint as

$\gamma \geq \left\|G^T x\right\|$

or equivalently

$(\gamma,G^T x) \in \Q^{n+1},$

where $$\Q^{n+1}$$ is the $$(n+1)$$-dimensional quadratic cone. Therefore, problem (11.1) can be written as

(11.3)$\begin{split}\begin{array}{lrcl} \mbox{maximize} & \mu^T x & & \\ \mbox{subject to} & e^T x & = & w+e^T x^0,\\ & (\gamma,G^T x) & \in & \Q^{n+1},\\ & x & \geq & 0, \end{array}\end{split}$

which is a conic quadratic optimization problem that can easily be formulated and solved with Optimizer API for C. Subsequently we will use the example data

$\begin{split}\mu = \left[ \begin{array}{c} 0.1073\\ 0.0737\\ 0.0627\\ \end{array} \right]\end{split}$

and

$\begin{split}\Sigma = 0.1\cdot \left[ \begin{array}{ccc} 0.2778 & 0.0387 & 0.0021\\ 0.0387 & 0.1112 & -0.0020\\ 0.0021 & -0.0020 & 0.0115 \end{array} \right].\end{split}$

This implies

$\begin{split}G^T = \sqrt{0.1} \left[ \begin{array}{ccc} 0.5271 & 0.0734 & 0.0040\\ 0 & 0.3253 & -0.0070\\ 0 & 0 & 0.1069\\ \end{array} \right]\end{split}$

### 11.1.1.1 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 $$\Sigma$$ in (11.1) is positive semidefinite due to the presence of rounding errors. It is also very easy to make a mistake so $$\Sigma$$ becomes indefinite. These problems are completely eliminated in the conic formulation.

Moreover, observe the constraint

$\left\|G^T x\right\| \leq \gamma$

more numerically robust than

$x^T \Sigma x \leq \gamma^2$

for very small and very large values of $$\gamma$$. Indeed, if say $$\gamma \approx 10^4$$ then $$\gamma^2\approx 10^8$$, which introduces a scaling issue in the model. Hence, using conic formulation we work with the standard deviation instead of variance, which usually gives rise to a better scaled model.

### 11.1.1.2 Implementing the Portfolio Model¶

Creating a matrix formulation

The Optimizer API for C requires that an optimization problem is entered in the following standard form:

(11.4)$\begin{split}\begin{array} {lrrcll} \mbox{maximize} & & & c^T \hat{x} & &\\ \mbox{subject to} & l^c & \leq & A \hat{x} & \leq & u^c,\\ & l^x & \leq & \hat{x} & \leq & u^x, \\ & & & \hat{x} \in \K. & & \end{array}\end{split}$

We refer to $$\hat{x}$$ as the API variable. It means we need to reformulate (11.3). The first step is to introduce auxiliary variables so that the conic constraint involves only unique variables:

(11.5)$\begin{split}\begin{array} {lrcl} \mbox{maximize} & \mu^T x & & \\ \mbox{subject to} & e^T x & = & w+e^T x^0, \\ & G^T x - t & = & 0, \\ & [s;t] & \in & \Q^{n+1},\\ & x & \geq & 0,\\ & s & = & \gamma. \end{array}\end{split}$

Here $$s$$ is an additional scalar variable and $$t$$ is a vector variable of dimension $$n$$. The next step is to concatenate all the variables into one long variable vector:

(11.6)$\begin{split}\hat{x} = \left[ x; s; t \right] = \left[ \begin{array} {c} x\\ s\\ t \end{array} \right]\end{split}$

The details of the concatenation are specified below.

Table 11.1 Storage layout of the $$\hat{x}$$ variable.
Variable Length Offset
$$x$$ $$n$$ $$0$$
$$s$$ $$1$$ $$n$$
$$t$$ $$n$$ $$n+1$$

The offset determines where the variable starts. (Note that all variables are indexed from 0). For instance

$\hat{x}_{n+1+i} = t_i.$

because the offset of the $$t$$ variable is $$n+1$$.

Given the ordering of the variables specified by (11.6) it is useful to visualize the linear constraints (11.4) in an explicit block matrix form:

(11.7)$\begin{split}\left[ \begin{array}{ccc|c|ccc} & 1 & & 0 & & 0 & \\ \hline & & & & -1 & & \\ & G^T & & 0 & & -1 & \\ & & & & & & -1 \end{array}\right] \cdot \left[ \begin{array}{c} \\ x \\ \\ \hline s \\ \hline \\ t \\ \\ \end{array}\right] = \left[ \begin{array}{c} w+e^Tx_0\\ \hline \\0\\ \\ \end{array}\right].\end{split}$

In other words, we should define the specific components of the problem description as follows:

(11.8)$\begin{split}\begin{array} {rcl} c & = & \left[ \begin{array} {ccc} \mu^T & 0 & 0_{n} \end{array}\right]^T, \\ A & = & \left[ \begin{array} {ccc} e^T & 0 & 0_{n} \\ G^T & 0_n & -I_n \end{array}\right], \\ l^c & = & {\left[\begin{array} {cc} w+e^T x^0 & 0_{n} \end{array}\right]}^T,\\ u^c & = & {\left[\begin{array} {cc} w+e^T x^0 & 0_{n} \end{array}\right]}^T,\\ l^x & = & {\left[\begin{array} {ccc} 0_{n} & \gamma & -\infty_{n} \end{array}\right]}^T,\\ u^x & = & {\left[\begin{array} {ccc} \infty_{n} & \gamma & \infty_{n} \end{array}\right]}^T. \end{array}\end{split}$

Source code example

From the block matrix form (11.7) and the explicit specification (11.8), using the offset information in Table 11.1 it is easy to calculate the index and value of each entry of the linear constraint matrix. The code below sets up the general optimization problem (11.5) and solves it for the example data. Of course it is only necessary to set non-zero entries of the linear constraint matrix.

Listing 11.1 Code implementing model (11.5). Click here to download.
#include <math.h>
#include <stdio.h>
#include "mosek.h"

#define MOSEKCALL(_r,_call)  if ( (_r)==MSK_RES_OK ) (_r) = (_call)

static void MSKAPI printstr(void *handle,
const char str[])
{
printf("%s", str);
} /* printstr */

int main(int argc, const char **argv)
{
char            buf;

double          expret  = 0.0,
stddev  = 0.0,
xj;

const MSKint32t n       = 3;
const MSKrealt  gamma   = 0.05;
const MSKrealt  mu[]    = {0.1073,  0.0737,  0.0627};
const MSKrealt  GT[] = {{0.1667,  0.0232,  0.0013},
{0.0000,  0.1033, -0.0022},
{0.0000,  0.0000,  0.0338}};
const MSKrealt  x0   = {0.0, 0.0, 0.0};
const MSKrealt  w       = 1.0;
MSKrealt        rtemp;
MSKenv_t        env;
MSKint32t       k, i, j, offsetx, offsets, offsett, *sub;
MSKrescodee     res = MSK_RES_OK, trmcode;

/* Initial setup. */
env  = NULL;
MOSEKCALL(res, MSK_makeenv(&env, NULL));

/* Total budget */
rtemp = w;
for (j = 0; j < n; ++j)
rtemp += x0[j];

/* Constraints. */

/* Total budget constraint - set bounds l^c = u^c */
MOSEKCALL(res, MSK_putconbound(task, 0, MSK_BK_FX, rtemp, rtemp));
sprintf(buf, "%s", "budget");

/* The remaining constraints GT * x - t = 0 - set bounds l^c = u^c*/
for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + i, MSK_BK_FX, 0.0, 0.0));
sprintf(buf, "GT[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + i, buf));
}

/* Variables. */
MOSEKCALL(res, MSK_appendvars(task, 1 + 2 * n));

offsetx = 0;   /* Offset of variable x into the API variable. */
offsets = n;   /* Offset of variable x into the API variable. */
offsett = n + 1; /* Offset of variable t into the API variable. */

/* x variables. */
for (j = 0; j < n; ++j)
{
/* Return of asset j in the objective */
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));
/* Coefficients in the first row of A */
MOSEKCALL(res, MSK_putaij(task, 0, offsetx + j, 1.0));
/* No short-selling - x^l = 0, x^u = inf */
MOSEKCALL(res, MSK_putvarbound(task, offsetx + j, MSK_BK_LO, 0.0, MSK_INFINITY));
sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));
}

/* s variable is a constant equal to gamma. */
MOSEKCALL(res, MSK_putvarbound(task, offsets + 0, MSK_BK_FX, gamma, gamma));
sprintf(buf, "s");
MOSEKCALL(res, MSK_putvarname(task, offsets + 0, buf));

/* t variables (t = GT*x). */
for (j = 0; j < n; ++j)
{
/* Copying the GT matrix in the appropriate block of A */
for (k = 0; k < n; ++k)
if ( GT[k][j] != 0.0 )
MOSEKCALL(res, MSK_putaij(task, 1 + k, offsetx + j, GT[k][j]));
/* Diagonal -1 entries in a block of A */
MOSEKCALL(res, MSK_putaij(task, 1 + j, offsett + j, -1.0));
/* Free - no bounds */
MOSEKCALL(res, MSK_putvarbound(task, offsett + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "t[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsett + j, buf));
}

if ( res == MSK_RES_OK )
{
/* Define the cone spanned by variables (s, t), i.e. dimension = n + 1 */

if ( sub )
{
/* Copy indices of variables involved in the conic constraint */
sub = offsets + 0;
for (j = 0; j < n; ++j)
sub[j + 1] = offsett + j;

}
else
res = MSK_RES_ERR_SPACE;
}

#if 0
/* No log output */
#endif

#if 0
/* Dump the problem to a human readable OPF file. */
#endif

#if 1
/* Display the solution summary for quick inspection of results. */
#endif

if ( res == MSK_RES_OK )
{
expret = 0.0;
stddev = 0.0;

/* Read the x variables one by one and compute expected return. */
/* Can also be obtained as value of the objective. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITR, offsetx + j, offsetx + j + 1, &xj));
expret += mu[j] * xj;
}

/* Read the value of s. This should be gamma. */
MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITR, offsets + 0, offsets + 1, &stddev));

printf("\nExpected return %e for gamma %e\n", expret, stddev);
}

if ( task != NULL )

if ( env != NULL )
MSK_deleteenv(&env);

return ( 0 );
}


The above code produces the result:

Listing 11.2 Output from the solver.
Interior-point solution summary
Problem status  : PRIMAL_AND_DUAL_FEASIBLE
Solution status : OPTIMAL
Primal.  obj: 7.4766507287e-02    nrm: 1e+00    Viol.  con: 2e-08    var: 0e+00    cones: 2e-08
Dual.    obj: 7.4766554102e-02    nrm: 3e-01    Viol.  con: 0e+00    var: 3e-08    cones: 0e+00

Expected return 7.476651e-02 for gamma 5.000000e-02


The source code is a direct translation of the model (11.5) using the explicit block matrix specification (11.8) but a few comments are nevertheless in place.

The code uses a macro which can be defined as follows:

#define MOSEKCALL(_r,_call)  ( (_r)==MSK_RES_OK ? ( (_r) = (_call) ) : ( (_r) = (_r) ) );


and then used as a method of hiding multiple if statements and hence making the code more compact:

  MOSEKCALL(res, MSK_optimize(task));

//is the same as
if ( res == MSK_RES_OK )


In the lines

  offsetx = 0;   /* Offset of variable x into the API variable. */
offsets = n;   /* Offset of variable x into the API variable. */
offsett = n + 1; /* Offset of variable t into the API variable. */


offsets into the MOSEK API variable are stored as in Table 11.1. The code

  for (j = 0; j < n; ++j)
{
/* Return of asset j in the objective */
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));
/* Coefficients in the first row of A */
MOSEKCALL(res, MSK_putaij(task, 0, offsetx + j, 1.0));
/* No short-selling - x^l = 0, x^u = inf */
MOSEKCALL(res, MSK_putvarbound(task, offsetx + j, MSK_BK_LO, 0.0, MSK_INFINITY));
sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));
}


sets up the data for $$x$$ variables. For instance

    /* Return of asset j in the objective */
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));


inputs the objective coefficients for the $$x$$ variables. Moreover, the code

    sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));


assigns meaningful names to the API variables. This is not needed but it makes debugging easier.

Note that the solution values are only accessed for the interesting variables; for instance the auxiliary variable $$t$$ is omitted from this process.

### 11.1.1.3 Debugging Tips¶

Implementing an optimization model in Optimizer API for C can be error-prone. In order to check the code for accidental errors it is very useful to dump the problem to a file in a human readable form for visual inspection. The line

  /* Dump the problem to a human readable OPF file. */


does that and it produces a file with the content:

Listing 11.3 Problem (11.5) stored in OPF format.
[comment]
Written by MOSEK version 8.1.0.24
Date 11-09-17
Time 14:34:24
[/comment]

[hints]
[hint NUMVAR] 7 [/hint]
[hint NUMCON] 4 [/hint]
[hint NUMANZ] 12 [/hint]
[hint NUMQNZ] 0 [/hint]
[hint NUMCONE] 1 [/hint]
[/hints]

[variables disallow_new_variables]
'x' 'x' 'x' s 't'
't' 't'
[/variables]

[objective maximize]
1.073e-01 'x' + 7.37e-02 'x' + 6.270000000000001e-02 'x'
[/objective]

[constraints]
[con 'budget']  'x' + 'x' + 'x' = 1e+00 [/con]
[con 'GT']  1.667e-01 'x' + 2.32e-02 'x' + 1.3e-03 'x' - 't' = 0e+00 [/con]
[con 'GT']  1.033e-01 'x' - 2.2e-03 'x' - 't' = 0e+00 [/con]
[con 'GT']  3.38e-02 'x' - 't' = 0e+00 [/con]
[/constraints]

[bounds]
[b] 0e+00      <= 'x','x','x' [/b]
[b]               s =  5e-02 [/b]
[b]               't','t','t' free [/b]
[cone quad 'stddev'] s, 't', 't', 't' [/cone]
[/bounds]


Since the API variables have been given meaningful names it is easy to verify by hand that the model is correct.

## 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 $$\alpha$$ the problem

(11.9)$\begin{split}\begin{array}{ll} \mbox{maximize} & \mu^T x - \alpha x^T\Sigma x\\ \mbox{subject to} & e^T x = w + e^T x^0,\\ & x \geq 0. \end{array}\end{split}$

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 ($$\|G^Tx\|_2^2$$) rather than standard deviation ($$\|G^Tx\|_2$$), therefore the conic model includes a rotated quadratic cone:

(11.10)$\begin{split}\begin{array}{lrcll} \mbox{maximize} & \mu^T x - \alpha s& & &\\ \mbox{subject to} & e^T x & = & w + e^T x^0, &\\ & G^Tx - t & = & 0, & \\ & u & = & 0.5, &\\ & (s,u,t) & \in & Q_r^{n+2} &(\mbox{evaluates to}\ s\geq \|G^Tx\|_2^2 = x^T\Sigma x),\\ & x & \geq & 0. & \end{array}\end{split}$

Ideally the problem (11.9) should be solved for all values $$\alpha \geq 0$$ but in practice it is impossible. Using the example data as before, the optimal values of return and variance for several values of $$\alpha$$ are shown below:

Listing 11.4 Results obtained solving problem (11.9) for different values of $$\alpha$$.
alpha         exp ret       variance
0.000e+00     1.073e-01     2.779e-02
2.500e-01     1.073e-01     2.779e-02
5.000e-01     1.073e-01     2.779e-02
7.500e-01     1.057e-01     2.554e-02
1.000e+00     9.965e-02     1.851e-02
1.500e+00     8.802e-02     8.850e-03
2.000e+00     8.213e-02     5.415e-03
2.500e+00     7.860e-02     3.826e-03
3.000e+00     7.625e-02     2.963e-03
3.500e+00     7.457e-02     2.442e-03
4.000e+00     7.331e-02     2.104e-03
4.500e+00     7.232e-02     1.873e-03


Source code example

The example code in Listing 11.5 demonstrates how to compute the efficient portfolios for several values of $$\alpha$$. The code is mostly similar to the one in Sec. 11.1.1 (A Basic Portfolio Optimization Model), except the problem is re-optimized in a loop for varying $$\alpha$$.

Listing 11.5 Code implementing model (11.9). Click here to download.
#include <math.h>
#include <stdio.h>

#include "mosek.h"

#define MOSEKCALL(_r,_call)  if ( (_r)==MSK_RES_OK ) (_r) = (_call)
#define LOGLEVEL             0

static void MSKAPI printstr(void       *handle,
const char str[])
{
printf("%s", str);
} /* printstr */

int main(int argc, const char **argv)
{
char            buf;
const MSKint32t n          = 3,
numalpha   = 12;
const double    mu[]       = {0.1073,  0.0737,  0.0627},
x0      = {0.0, 0.0, 0.0},
w          = 1.0,
alphas = {0.0, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5},
GT[]    = {{0.1667,  0.0232,  0.0013},
{0.0000,  0.1033, -0.0022},
{0.0000,  0.0000,  0.0338}
};
MSKenv_t        env;
MSKint32t       k, i, j, offsetx, offsets, offsett, offsetu;
MSKrescodee     res = MSK_RES_OK, lres;
MSKrealt        xj;
MSKsolstae      solsta;

/* Initial setup. */
env  = NULL;

/* Replace "" with NULL in production. */
MOSEKCALL(res, MSK_makeenv(&env, ""));

/* Constraints. */
MOSEKCALL(res, MSK_putconbound(task, 0, MSK_BK_FX, 1.0, 1.0));
sprintf(buf, "%s", "budget");

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + i, MSK_BK_FX, 0.0, 0.0));
sprintf(buf, "GT[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + i, buf));
}

/* Variables. */
MOSEKCALL(res, MSK_appendvars(task, 2 + 2 * n));

offsetx = 0;   /* Offset of variable x into the API variable. */
offsets = n;   /* Offset of variable s into the API variable. */
offsett = n + 1; /* Offset of variable t into the API variable. */
offsetu = 2*n + 1; /* Offset of variable u into the API variable. */

/* x variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));
MOSEKCALL(res, MSK_putaij(task, 0, offsetx + j, 1.0));
for (k = 0; k < n; ++k)
if (GT[k][j] != 0.0)
MOSEKCALL(res, MSK_putaij(task, 1 + k, offsetx + j, GT[k][j]));

MOSEKCALL(res, MSK_putvarbound(task, offsetx + j, MSK_BK_LO, 0.0, MSK_INFINITY));
sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));
}

/* s variable. */
MOSEKCALL(res, MSK_putvarbound(task, offsets + 0, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "s");
MOSEKCALL(res, MSK_putvarname(task, offsets + 0, buf));

/* t variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + j, offsett + j, -1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsett + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "t[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsett + j, buf));
}

/* u variable. */
MOSEKCALL(res, MSK_putvarbound(task, offsetu + 0, MSK_BK_FX, 0.5, 0.5));
sprintf(buf, "u");
MOSEKCALL(res, MSK_putvarname(task, offsetu + 0, buf));

if (res == MSK_RES_OK)
{
/* sub should be n+2 long i.e. the dimmension of the cone. */

if (sub)
{
sub = offsets + 0;
sub = offsetu + 0;
for (j = 0; j < n; ++j)
sub[j + 2] = offsett + j;

}
else
res = MSK_RES_ERR_SPACE;
}

/* Set the log level */

printf("%-12s  %-12s  %-12s\n", "alpha", "exp ret", "variance");

for (k = 0; k < numalpha && res==MSK_RES_OK; ++k)
{
const double alpha = alphas[k];
MSKrescodee  trmcode;

/* Sets the objective function coefficient for s. */
MOSEKCALL(res, MSK_putcj(task, offsets + 0, -alpha));

if (solsta == MSK_SOL_STA_OPTIMAL)
{
double expret = 0.0,
stddev;

for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITR, offsetx + j, offsetx + j + 1, &xj));
expret += mu[j] * xj;
}

MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITR, offsets + 0, offsets + 1, &stddev));

printf("%-12.3e  %-12.3e  %-12.3e\n", alpha, expret, stddev);
}
else
{
printf("An error occurred when solving for alpha=%e\n", alpha);
}
}
res  = res==MSK_RES_OK ? lres : res;

lres = MSK_deleteenv(&env);
res  = res==MSK_RES_OK ? lres : res;

return ( res );
}


## 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 $$G$$ see (11.2) and try to reduce that number by for instance changing the choice of $$G$$.

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

$\Sigma = D + VV^T$

where $$D$$ is a positive definite diagonal matrix. Moreover, $$V$$ is a matrix with $$n$$ rows and $$p$$ columns. Such a model for the covariance matrix is called a factor model and usually $$p$$ is much smaller than $$n$$. In practice $$p$$ tends to be a small number independent of $$n$$, say less than 100.

One possible choice for $$G$$ is the Cholesky factorization of $$\Sigma$$ which requires storage proportional to $$n(n+1)/2$$. However, another choice is

$\begin{split}G^T = \left[ \begin{array}{c} D^{1/2}\\ V^T \end{array} \right]\end{split}$

because then

$GG^T = D + VV^T.$

This choice requires storage proportional to $$n+pn$$ which is much less than for the Cholesky choice of $$G$$. Indeed assuming $$p$$ is a constant storage requirements are reduced by a factor of $$n$$.

The example above exploits the so-called factor structure and demonstrates that an alternative choice of $$G$$ may lead to a significant reduction in the amount of storage used to represent the problem. This will in most cases also lead to a significant reduction in the solution time.

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 $$G$$ that helps reducing the storage requirements and enhance the computational efficiency. More details about this process can be found in [And13].

## 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

(11.11)$\begin{split}\begin{array}{lrcl} \mbox{maximize} & \mu^T x & & \\ \mbox{subject to} & e^T x + \sum_{j=1}^{n} C_j|x_j - x_j^0| & = & w + e^T x^0,\\ & x^T \Sigma x & \leq & \gamma^2,\\ & x & \geq & 0, \end{array}\end{split}$

where the function

$C_j| x_j - x_j^0|$

specifies the transaction costs when the holding of asset $$j$$ is changed from its initial value. In the next two sections we show two different variants of this problem with two nonlinear cost functions $$T$$.

## 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 $$j$$ can be modeled by

$C_j= m_j \sqrt{|x_j-x_j^0|}$

where $$m_j$$ is a constant that is estimated in some way by the trader. See [GK00] [p. 452] for details. Hence, we have

$C_j(x_j-x_j^0) = m_j |x_j - x_j^0| \sqrt{|x_j-x_j^0|} = m_j |x_j - x_j^0|^{3/2}.$

From the Modeling Cookbook we know that $$c \geq z^{3/2}$$ can be modeled directly using the power cone $$\POW_3^{2/3,1/3}$$:

$\{(c,z): c \geq z^{3/2}, z\geq 0\} = \{ (c,z): (c,1,z) \in \POW_3^{2/3,1/3} \}$

Hence, it follows that we can write the model as

$\begin{split}\begin{array}{rl} z_j & = |x_j - x_j^0|, \\ (c_j,1,z_j) & \in \POW_3^{2/3,1/3},\\ \sum_{j=1}^n C_j|x_j - x_j^0| & = \sum_{j=1}^n c_jm_j. \end{array}\end{split}$

Unfortunately this set of constraints is nonconvex due to the constraint

(11.12)$z_j = |x_j - x_j^0|$

but in many cases the constraint may be replaced by the relaxed constraint

(11.13)$z_j \geq |x_j - x_j^0|,$

which is equivalent to

(11.14)$\begin{split}\begin{array}{l} z_j \geq x_j - x_j^0, \\ z_j \geq -(x_j - x_j^0). \end{array}\end{split}$

For instance if the universe of assets contains a risk free asset then

(11.15)$z_j > |x_j-x_j^0|$

cannot hold for an optimal solution.

If the optimal solution has the property (11.15) 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.12) and (11.13) are equivalent.

(11.16)$\begin{split}\begin{array}{lrcll} \mbox{maximize} & \mu^T x & & &\\ \mbox{subject to} & e^T x + m^T c & = & w + e^T x^0, &\\ & [\gamma;G^T x] & \in & \Q^{n+1}, & \\ & z_j & \geq & x_j - x_j^0, & j=1,\ldots,n,\\ & z_j & \geq & x_j^0 - x_j, & j=1,\ldots,n, \\ & (c_j,1,z_j) & \in & \POW_3^{2/3,1/3}, & j=1,\ldots,n,\\ & x & \geq & 0. & \end{array}\end{split}$

The revised budget constraint

$e^T x + m^Tc = w + e^T x^0$

specifies that the initial wealth covers the investment and the transaction costs. It should be mentioned that transaction costs of the form

$t_j \geq z_j^{p}$

where $$p>1$$ is a real number can be modeled with the power cone as

$(t_j,1,z_j)\in\POW_3^{1/p, 1-1/p}.$

See Modeling Cookbook for details.

Creating a matrix formulation

One more reformulation of (11.16) is needed to bring it to the standard form (11.4).

(11.17)$\begin{split}\begin{array} {lcccc} \mbox{maximize} & \mu^T x & & & \\ \mbox{subject to} & e^T x + m^T c & = & w + e^T x^0, &\\ & G^T x - t & = & 0, &\\ & z_j - x_j & \geq & - x_j^0, & j=1,\ldots,n,\\ & z_j + x_j & \geq & x_j^0, & j=1,\ldots,n, \\ & (s,t) & \in & \Q^{n+1}, & \\ & (c_j, f_j, z_j) & \in & \POW_3^{2/3,1/3}, & j=1,\ldots,n,\\ & x & \geq & 0, & \\ & f_j & = & 1, & j=1,\ldots,n,\\ & s & = & \gamma, & \end{array}\end{split}$

where $$f \in \real^{n}$$ is an additional variable representing the unused coordinate in the power cone. The formulation (11.17) is not the most compact possible, but it is easy to implement. MOSEK presolve will automatically simplify it.

The first step in developing the implementation is to chose an ordering of the variables. We will choose the following ordering:

$\hat{x} = [x; s; t; c; z; f]$

Table 11.2 shows the mapping between the $$\hat{x}$$ vector and the model variables.

Table 11.2 Storage layout for $$\hat{x}$$
Variable Length Offset
$$x$$ $$n$$ $$0$$
$$s$$ $$1$$ $$n$$
$$t$$ $$n$$ $$n+1$$
$$c$$ $$n$$ $$2n+1$$
$$z$$ $$n$$ $$3n+1$$
$$f$$ $$n$$ $$4n+1$$

The next step is to consider how the linear constraint matrix $$A$$ and the remaining data vectors are laid out. Reusing the idea in Sec. 11.1.1 (A Basic Portfolio Optimization Model) we can write the data in block matrix form and read off all the required coordinates. This extension of the code setting up the constraint $$G^Tx-t=0$$ from Sec. 11.1.1 (A Basic Portfolio Optimization Model) is shown below.

Source code example

The example code in Listing 11.6 demonstrates how to implement the model (11.17).

Listing 11.6 Code implementing model (11.17). Click here to download.
#include <math.h>
#include <stdio.h>

#include "mosek.h"

#define MOSEKCALL(_r,_call)  if ( (_r)==MSK_RES_OK ) (_r) = (_call)

static void MSKAPI printstr(void *handle,
const char str[])
{
printf("%s", str);
} /* printstr */

int main(int argc, const char **argv)
{
char            buf;
const MSKint32t n       = 3;
const double    w       = 1.0,
x0[]    = {0.0, 0.0, 0.0},
gamma   = 0.05,
mu[]    = {0.1073,  0.0737,  0.0627},
m[]     = {0.01, 0.01, 0.01},
GT[] = {{0.1667,  0.0232,  0.0013},
{0.0000,  0.1033, -0.0022},
{0.0000,  0.0000,  0.0338}
};
double          expret,
stddev,
xj;
MSKenv_t        env;
MSKint32t       k, i, j,
offsetx, offsets, offsett, offsetc,
offsetz, offsetf;
MSKrescodee     res = MSK_RES_OK, trmcode;

/* Initial setup. */
env  = NULL;
MOSEKCALL(res, MSK_makeenv(&env, NULL));

/* Constraints. */
MOSEKCALL(res, MSK_appendcons(task, 1 + 3 * n));
MOSEKCALL(res, MSK_putconbound(task, 0, MSK_BK_FX, w, w));
sprintf(buf, "%s", "budget");

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + i, MSK_BK_FX, 0.0, 0.0));
sprintf(buf, "GT[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + n + i, MSK_BK_LO, -x0[i], MSK_INFINITY));
sprintf(buf, "zabs1[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + n + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + 2 * n + i, MSK_BK_LO, x0[i], MSK_INFINITY));
sprintf(buf, "zabs2[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + 2 * n + i, buf));
}

/* Offsets of variables into the (serialized) API variable. */
offsetx = 0;
offsets = n;
offsett = n + 1;
offsetc = 2 * n + 1;
offsetz = 3 * n + 1;
offsetf = 4 * n + 1;

/* Variables. */
MOSEKCALL(res, MSK_appendvars(task, 5 * n + 1));

/* x variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));
MOSEKCALL(res, MSK_putaij(task, 0, offsetx + j, 1.0));
for (k = 0; k < n; ++k)
if (GT[k][j] != 0.0)
MOSEKCALL(res, MSK_putaij(task, 1 + k, offsetx + j, GT[k][j]));
MOSEKCALL(res, MSK_putaij(task, 1 + n + j, offsetx + j, -1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 2 * n + j, offsetx + j, 1.0));

MOSEKCALL(res, MSK_putvarbound(task, offsetx + j, MSK_BK_LO, 0.0, MSK_INFINITY));
sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));
}

/* s variable. */
MOSEKCALL(res, MSK_putvarbound(task, offsets + 0, MSK_BK_FX, gamma, gamma));
sprintf(buf, "s");
MOSEKCALL(res, MSK_putvarname(task, offsets + 0, buf));

/* t variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + j, offsett + j, -1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsett + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "t[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsett + j, buf));
}

/* c variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 0, offsetc + j, m[j]));
MOSEKCALL(res, MSK_putvarbound(task, offsetc + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "c[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetc + j, buf));
}

/* z variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + 1 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 2 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsetz + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "z[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetz + j, buf));
}

/* f variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putvarbound(task, offsetf + j, MSK_BK_FX, 1.0, 1.0));
sprintf(buf, "f[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetf + j, buf));
}

if (res == MSK_RES_OK)
{
/* sub should be n+1 long i.e. the dimmension of the cone. */
MSKint32t *sub = (MSKint32t *) MSK_calloctask(task, 3 >= n + 1 ? 3 : n + 1, sizeof(MSKint32t));

if (sub)
{
sub = offsets + 0;
for (j = 0; j < n; ++j)
sub[j + 1] = offsett + j;

for (k = 0; k < n; ++k)
{
sub = offsetc + k, sub = offsetf + k, sub = offsetz + k;
MOSEKCALL(res, MSK_appendcone(task, MSK_CT_PPOW, 2.0/3.0, 3, sub));
sprintf(buf, "trans[%d]", 1 + k);
MOSEKCALL(res, MSK_putconename(task, 1 + k, buf));
}

}
else
res = MSK_RES_ERR_SPACE;
}

#if 0
/* no log output. */
#endif

#if 0
/* Dump the problem to a human readable OPF file. */
#endif

/* Display the solution summary for quick inspection of results. */
#if 1
#endif

if (res == MSK_RES_OK)
{
expret = 0.0;
stddev = 0.0;

for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITR, offsetx + j, offsetx + j + 1, &xj));
expret += mu[j] * xj;
}

MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITR, offsets + 0, offsets + 1, &stddev));

printf("\nExpected return %e for gamma %e\n", expret, stddev);
}

MSK_deleteenv(&env);

return (0);
}


The example code above produces the result

Interior-point solution summary
Problem status  : PRIMAL_AND_DUAL_FEASIBLE
Solution status : OPTIMAL
Primal.  obj: 7.4390639578e-02    nrm: 1e+00    Viol.  con: 1e-08    var: 0e+00    cones: 7e-09
Dual.    obj: 7.4390755614e-02    nrm: 3e-01    Viol.  con: 1e-19    var: 3e-08    cones: 0e+00

Expected return 7.439064e-02 for gamma 5.000000e-02


If the problem is dumped to an OPF file, it has the following content.

Listing 11.7 OPF file for problem (11.17).
[comment]
Written by MOSEK version 9.0.0.31
Date 10-01-18
Time 12:10:24
[/comment]

[hints]
[hint NUMVAR] 16 [/hint]
[hint NUMCON] 10 [/hint]
[hint NUMANZ] 27 [/hint]
[hint NUMQNZ] 0 [/hint]
[hint NUMCONE] 4 [/hint]
[/hints]

[variables disallow_new_variables]
'x' 'x' 'x' s 't'
't' 't' 'c' 'c' 'c'
'z' 'z' 'z' 'f' 'f'
'f'
[/variables]

[objective maximize]
1.073e-01 'x' + 7.37e-02 'x' + 6.270000000000001e-02 'x'
[/objective]

[constraints]
[con 'budget']  'x' + 'x' + 'x' + 1e-02 'c' + 1e-02 'c'
+ 1e-02 'c' = 1e+00 [/con]
[con 'GT']  1.667e-01 'x' + 2.32e-02 'x' + 1.3e-03 'x' - 't' = 0e+00 [/con]
[con 'GT']  1.033e-01 'x' - 2.2e-03 'x' - 't' = 0e+00 [/con]
[con 'GT']  3.38e-02 'x' - 't' = 0e+00 [/con]
[con 'zabs1'] 0e+00 <= - 'x' + 'z' [/con]
[con 'zabs1'] 0e+00 <= - 'x' + 'z' [/con]
[con 'zabs1'] 0e+00 <= - 'x' + 'z' [/con]
[con 'zabs2'] 0e+00 <= 'x' + 'z' [/con]
[con 'zabs2'] 0e+00 <= 'x' + 'z' [/con]
[con 'zabs2'] 0e+00 <= 'x' + 'z' [/con]
[/constraints]

[bounds]
[b] 0e+00      <= 'x','x','x' [/b]
[b]               s =  5e-02 [/b]
[b]               't','t','t','c','c','c' free [/b]
[b]               'z','z','z' free [/b]
[b]               'f','f','f' =  1e+00 [/b]
[cone quad 'stddev'] s, 't', 't', 't' [/cone]
[cone ppow '6.666666666666666e-01' 'trans'] 'c', 'f', 'z' [/cone]
[cone ppow '6.666666666666666e-01' 'trans'] 'c', 'f', 'z' [/cone]
[cone ppow '6.666666666666666e-01' 'trans'] 'c', 'f', 'z' [/cone]
[/bounds]


The file verifies that the correct problem has been set up.

## 11.1.6 Transaction Costs¶

Now assume there is a cost associated with trading asset $$j$$ given by

$\begin{split}T_j(\Delta x_j) = \left\lbrace \begin{array}{lll} 0, & \Delta x_j=0, & \\ f_j + g_j |\Delta x_j|,& \mbox{otherwise}. & \end{array}\right.\end{split}$

Here $$\Delta x_j$$ is the change in the holding of asset $$j$$ i.e.

$\Delta x_j = x_j - x_j^0.$

Hence, whenever asset $$j$$ is traded we pay a fixed setup cost $$f_j$$ and a variable cost of $$g_j$$ per unit traded. This sort of cost function can be modeled using mixed-integer optimization, in particular using a binary variable $$y_j$$ to indicate if asset $$j$$ is traded. Given the assumptions about transaction costs in this section problem (11.11) may be formulated as

(11.18)$\begin{split}\begin{array}{lrcll} \mbox{maximize} & \mu^T x & & &\\ \mbox{subject to} & e^T x + f^T y + g^T z & = & w + e^T x^0, &\\ & [\gamma;G^T x] & \in & \Q^{n+1}, & \\ & z_j & \geq & x_j - x_j^0, & j=1,\ldots,n,\\ & z_j & \geq & x_j^0 - x_j, & j=1,\ldots,n, \\ & z_j & \leq & U_jy_j, & j=1,\ldots,n,\\ & y_j & \in & \{0,1\}, & j=1,\ldots,n,\\ & x & \geq & 0. & \end{array}\end{split}$

First observe that

$z_j \geq |x_j - x_j^0|=|\Delta x_j|.$

Here $$U_j$$ is some a priori chosen upper bound on the amount of trading in asset $$j$$ and therefore if $$z_j>0$$ then $$y_j = 1$$ has to be the case. This implies that the transaction cost for asset $$j$$ is given by

$f_j y_j + g_j z_j.$

In our problem a safe bound for each $$U_j$$ is the total initial wealth $$w+e^Tx^0$$, however knowing a tighter bound may lead to shorter solution times.

Creating a matrix formulation

One more reformulation of (11.18) is needed to bring it to the standard form (11.4).

(11.19)$\begin{split}\begin{array} {lcccc} \mbox{maximize} & \mu^T x & & & \\ \mbox{subject to} & e^T x + f^T y + g^T z & = & w + e^T x^0, &\\ & G^T x - t & = & 0, &\\ & z_j - x_j & \geq & - x_j^0, & j=1,\ldots,n,\\ & z_j + x_j & \geq & x_j^0, & j=1,\ldots,n, \\ & (s,t) & \in & \Q^{n+1}, & \\ & z_j - U_j y_j & \leq & 0, & j=1,\ldots,n, \\ & x & \geq & 0, & \\ & y_j & \in & [0,1], & j=1,\ldots,n,\\ & y_j & \in & \integral, & j=1,\ldots,n,\\ & s & = & \gamma. & \end{array}\end{split}$

We will choose the following ordering of variables:

$\hat{x} = [x; s; t; z; y]$

Table 11.3 shows the mapping between the $$\hat{x}$$ vector and the model variables.

Table 11.3 Storage layout for $$\hat{x}$$
Variable Length Offset
$$x$$ $$n$$ $$0$$
$$s$$ $$1$$ $$n$$
$$t$$ $$n$$ $$n+1$$
$$z$$ $$n$$ $$2n+1$$
$$y$$ $$n$$ $$3n+1$$

The next step is to consider how the linear constraint matrix $$A$$ and the remaining data vectors are laid out. Reusing the idea in Sec. 11.1.1 (A Basic Portfolio Optimization Model) we can write the data in block matrix form and read off all the required coordinates. This extension of the code setting up the constraint $$G^Tx-t=0$$ from Sec. 11.1.1 (A Basic Portfolio Optimization Model) is shown below.

Example code

The following example code demonstrates how to compute an optimal portfolio when transaction setup costs are included. Note that we are now solving a problem with integer variables, and therefore the solution must be retrieved from MSK_SOL_ITG rather than MSK_SOL_ITR.

Listing 11.8 Code solving problem (11.18). Click here to download.
#include <math.h>
#include <stdio.h>

#include "mosek.h"

#define MOSEKCALL(_r,_call)  if ( (_r)==MSK_RES_OK ) (_r) = (_call)

static void MSKAPI printstr(void *handle,
const char str[])
{
printf("%s", str);
} /* printstr */

int main(int argc, const char **argv)
{
char            buf;
const MSKint32t n       = 3;
const double    w       = 1.0,
x0[]    = {0.0, 0.0, 0.0},
gamma   = 0.05,
mu[]    = {0.1073,  0.0737,  0.0627},
f[]     = {0.01, 0.01, 0.01},
g[]     = {0.001, 0.001, 0.001},
GT[] = {{0.1667,  0.0232,  0.0013},
{0.0000,  0.1033, -0.0022},
{0.0000,  0.0000,  0.0338}
};
double          U,
expret,
stddev,
xj;
MSKenv_t        env;
MSKint32t       k, i, j,
offsetx, offsets, offsett, offsetz, offsety;
MSKrescodee     res = MSK_RES_OK, trmcode;

/* Initial setup. */
env  = NULL;
MOSEKCALL(res, MSK_makeenv(&env, NULL));

/* Compute total wealth */
U = w;
for (k = 0; k < n; ++k) U += x0[k];

/* Constraints. */
MOSEKCALL(res, MSK_appendcons(task, 1 + 4 * n));
MOSEKCALL(res, MSK_putconbound(task, 0, MSK_BK_FX, w, w));
sprintf(buf, "%s", "budget");

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + i, MSK_BK_FX, 0.0, 0.0));
sprintf(buf, "GT[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + n + i, MSK_BK_LO, -x0[i], MSK_INFINITY));
sprintf(buf, "zabs1[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + n + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + 2 * n + i, MSK_BK_LO, x0[i], MSK_INFINITY));
sprintf(buf, "zabs2[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + 2 * n + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + 3 * n + i, MSK_BK_UP, -MSK_INFINITY, 0.0));
sprintf(buf, "indicator[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + 3 * n + i, buf));
}

/* Offsets of variables into the (serialized) API variable. */
offsetx = 0;
offsets = n;
offsett = n + 1;
offsetz = 2 * n + 1;
offsety = 3 * n + 1;

/* Variables. */
MOSEKCALL(res, MSK_appendvars(task, 4 * n + 1));

/* x variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));
MOSEKCALL(res, MSK_putaij(task, 0, offsetx + j, 1.0));
for (k = 0; k < n; ++k)
if (GT[k][j] != 0.0)
MOSEKCALL(res, MSK_putaij(task, 1 + k, offsetx + j, GT[k][j]));
MOSEKCALL(res, MSK_putaij(task, 1 + n + j, offsetx + j, -1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 2 * n + j, offsetx + j, 1.0));

MOSEKCALL(res, MSK_putvarbound(task, offsetx + j, MSK_BK_LO, 0.0, MSK_INFINITY));
sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));
}

/* s variable. */
MOSEKCALL(res, MSK_putvarbound(task, offsets + 0, MSK_BK_FX, gamma, gamma));
sprintf(buf, "s");
MOSEKCALL(res, MSK_putvarname(task, offsets + 0, buf));

/* t variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + j, offsett + j, -1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsett + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "t[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsett + j, buf));
}

/* z variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 0, offsetz + j, g[j]));
MOSEKCALL(res, MSK_putaij(task, 1 + 1 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 2 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 3 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsetz + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "z[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetz + j, buf));
}

/* y variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 0, offsety + j, f[j]));
MOSEKCALL(res, MSK_putaij(task, 1 + 3 * n + j, offsety + j, -U));
MOSEKCALL(res, MSK_putvarbound(task, offsety + j, MSK_BK_RA, 0.0, 1.0));
MOSEKCALL(res, MSK_putvartype(task, offsety + j, MSK_VAR_TYPE_INT));
sprintf(buf, "y[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsety + j, buf));
}

if (res == MSK_RES_OK)
{
/* sub should be n+1 long i.e. the dimmension of the cone. */
MSKint32t *sub = (MSKint32t *) MSK_calloctask(task, 3 >= n + 1 ? 3 : n + 1, sizeof(MSKint32t));

if (sub)
{
sub = offsets + 0;
for (j = 0; j < n; ++j)
sub[j + 1] = offsett + j;

}
else
res = MSK_RES_ERR_SPACE;
}

#if 0
/* no log output. */
#endif

#if 0
/* Dump the problem to a human readable OPF file. */
#endif

#if 1
/* Display the solution summary for quick inspection of results. */
#endif

if (res == MSK_RES_OK)
{
expret = 0.0;
stddev = 0.0;

for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITG, offsetx + j, offsetx + j + 1, &xj));
expret += mu[j] * xj;
}

MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITG, offsets + 0, offsets + 1, &stddev));

printf("\nExpected return %e for gamma %e\n", expret, stddev);
}

MSK_deleteenv(&env);

return (0);
}


## 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 $$k$$ of the differences $$|\Delta x_j|=|x_j - x_j^0|$$ are allowed to be non-zero, where $$k$$ is (much) smaller than the total number of assets $$n$$.

This type of constraint can be again modeled by introducing a binary variable $$y_j$$ which indicates if $$\Delta x_j\neq 0$$ and bounding the sum of $$y_j$$. The basic Markowitz model then gets updated as follows:

(11.20)$\begin{split}\begin{array}{lrcll} \mbox{maximize} & \mu^T x & & &\\ \mbox{subject to} & e^T x & = & w + e^T x^0, &\\ & [\gamma;G^T x] & \in & \Q^{n+1}, & \\ & U_j y_j & \geq & |x_j - x_j^0|, & j=1,\ldots,n,\\ & y_j & \in & \{0,1\}, & j=1,\ldots,n, \\ & e^T y & \leq & k, & \\ & x & \geq & 0, & \end{array}\end{split}$

were $$U_j$$ is some a priori chosen upper bound on the amount of trading in asset $$j$$. This guarantees that $$|x_j-x_j^0|$$ forces $$y_j=1$$ and therefore $$e^Ty$$ counts the number of assets in which we trade. In our problem a safe bound for each $$U_j$$ is the total initial wealth $$w+e^Tx^0$$, however knowing a tighter bound may lead to shorter solution times.

Creating a matrix formulation

One more reformulation of (11.20) is needed to bring it to the standard form (11.4).

(11.21)$\begin{split}\begin{array} {lcccc} \mbox{maximize} & \mu^T x & & & \\ \mbox{subject to} & e^T x & = & w + e^T x^0, &\\ & G^T x - t & = & 0, &\\ & z_j - x_j & \geq & - x_j^0, & j=1,\ldots,n,\\ & z_j + x_j & \geq & x_j^0, & j=1,\ldots,n, \\ & (s,t) & \in & \Q^{n+1}, & \\ & z_j - U_j y_j & \leq & 0, & j=1,\ldots,n, \\ & e^T y & \leq & k, & \\ & x & \geq & 0, & \\ & y_j & \in & [0,1], & j=1,\ldots,n,\\ & y_j & \in & \integral, & j=1,\ldots,n,\\ & s & = & \gamma. & \end{array}\end{split}$

We will choose the following ordering of variables:

$\hat{x} = [x; s; t; z; y]$

Table 11.4 shows the mapping between the $$\hat{x}$$ vector and the model variables.

Table 11.4 Storage layout for $$\hat{x}$$
Variable Length Offset
$$x$$ $$n$$ $$0$$
$$s$$ $$1$$ $$n$$
$$t$$ $$n$$ $$n+1$$
$$z$$ $$n$$ $$2n+1$$
$$y$$ $$n$$ $$3n+1$$

The next step is to consider how the linear constraint matrix $$A$$ and the remaining data vectors are laid out. Reusing the idea in Sec. 11.1.1 (A Basic Portfolio Optimization Model) we can write the data in block matrix form and read off all the required coordinates. This extension of the code setting up the constraint $$G^Tx-t=0$$ from Sec. 11.1.1 (A Basic Portfolio Optimization Model) is shown below.

Example code

The following example code demonstrates how to compute an optimal portfolio with cardinality bounds. Note that we are now solving a problem with integer variables, and therefore the solution must be retrieved from MSK_SOL_ITG.

Listing 11.9 Code solving problem (11.20). Click here to download.
MSKrescodee markowitz_with_card(const int        n,
const double     x0[],
const double     w,
const double     gamma,
const double     mu[],
const double     GT[],
const int        k,
double     *xx)
{
char            buf;
double          U;
MSKenv_t        env;
MSKint32t       i, j,
offsetx, offsets, offsett, offsetz, offsety;
MSKrescodee     res = MSK_RES_OK, trmcode;

/* Initial setup. */
env  = NULL;
MOSEKCALL(res, MSK_makeenv(&env, NULL));

/* Compute total wealth */
U = w;
for (i = 0; i < n; ++i) U += x0[i];

/* Constraints. */
MOSEKCALL(res, MSK_appendcons(task, 2 + 4 * n));

MOSEKCALL(res, MSK_putconbound(task, 0, MSK_BK_FX, w, w));
sprintf(buf, "%s", "budget");

MOSEKCALL(res, MSK_putconbound(task, 1 + 4 * n, MSK_BK_UP, -MSK_INFINITY, (double)k));
sprintf(buf, "%s", "cardinality");
MOSEKCALL(res, MSK_putconname(task, 1 + 4 * n, buf));

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + i, MSK_BK_FX, 0.0, 0.0));
sprintf(buf, "GT[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + n + i, MSK_BK_LO, -x0[i], MSK_INFINITY));
sprintf(buf, "zabs1[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + n + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + 2 * n + i, MSK_BK_LO, x0[i], MSK_INFINITY));
sprintf(buf, "zabs2[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + 2 * n + i, buf));
}

for (i = 0; i < n; ++i)
{
MOSEKCALL(res, MSK_putconbound(task, 1 + 3 * n + i, MSK_BK_UP, -MSK_INFINITY, 0.0));
sprintf(buf, "indicator[%d]", 1 + i);
MOSEKCALL(res, MSK_putconname(task, 1 + 3 * n + i, buf));
}

/* Offsets of variables into the (serialized) API variable. */
offsetx = 0;
offsets = n;
offsett = n + 1;
offsetz = 2 * n + 1;
offsety = 3 * n + 1;

/* Variables. */
MOSEKCALL(res, MSK_appendvars(task, 4 * n + 1));

/* x variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putcj(task, offsetx + j, mu[j]));
MOSEKCALL(res, MSK_putaij(task, 0, offsetx + j, 1.0));
for (i = 0; i < n; ++i)
if (GT[i*n+j] != 0.0)
MOSEKCALL(res, MSK_putaij(task, 1 + i, offsetx + j, GT[i*n+j]));
MOSEKCALL(res, MSK_putaij(task, 1 + n + j, offsetx + j, -1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 2 * n + j, offsetx + j, 1.0));

MOSEKCALL(res, MSK_putvarbound(task, offsetx + j, MSK_BK_LO, 0.0, MSK_INFINITY));
sprintf(buf, "x[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetx + j, buf));
}

/* s variable. */
MOSEKCALL(res, MSK_putvarbound(task, offsets + 0, MSK_BK_FX, gamma, gamma));
sprintf(buf, "s");
MOSEKCALL(res, MSK_putvarname(task, offsets + 0, buf));

/* t variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + j, offsett + j, -1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsett + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "t[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsett + j, buf));
}

/* z variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + 1 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 2 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 3 * n + j, offsetz + j, 1.0));
MOSEKCALL(res, MSK_putvarbound(task, offsetz + j, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY));
sprintf(buf, "z[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsetz + j, buf));
}

/* y variables. */
for (j = 0; j < n; ++j)
{
MOSEKCALL(res, MSK_putaij(task, 1 + 4 * n, offsety + j, 1.0));
MOSEKCALL(res, MSK_putaij(task, 1 + 3 * n + j, offsety + j, -U));
MOSEKCALL(res, MSK_putvarbound(task, offsety + j, MSK_BK_RA, 0.0, 1.0));
MOSEKCALL(res, MSK_putvartype(task, offsety + j, MSK_VAR_TYPE_INT));
sprintf(buf, "y[%d]", 1 + j);
MOSEKCALL(res, MSK_putvarname(task, offsety + j, buf));
}

if (res == MSK_RES_OK)
{
/* sub should be n+1 long i.e. the dimmension of the cone. */
MSKint32t *sub = (MSKint32t *) MSK_calloctask(task, 3 >= n + 1 ? 3 : n + 1, sizeof(MSKint32t));

if (sub)
{
sub = offsets + 0;
for (j = 0; j < n; ++j)
sub[j + 1] = offsett + j;

}
else
res = MSK_RES_ERR_SPACE;
}

#if 1
/* no log output. */
#endif

#if 0
/* Dump the problem to a human readable OPF file. */
#endif

#if 1
/* Display the solution summary for quick inspection of results. */
#endif

if (res == MSK_RES_OK)
MOSEKCALL(res, MSK_getxxslice(task, MSK_SOL_ITG, offsetx, offsetx + n, xx));


If we solve our running example with $$k=1,2,3$$ then we get the following solutions, with increasing expected returns:
Bound 1:  x = 0.00000 0.00000 1.00000   Return:  x = 0.06270