11.1 Portfolio Optimization¶
In this section the Markowitz portfolio optimization problem and variants are implemented using Optimizer API for Rust.
Familiarity with Sec. 6.2 (From Linear to Conic Optimization) is recommended to follow the syntax used to create affine conic constraints (ACCs) throughout all the models appearing in this case study.
11.1.1 The Basic 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
and covariance
The return of the investment is also a random variable \(y = r^Tx\) with mean (or expected return)
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 \(\gamma\)) on the tolerable risk. This leads to the optimization problem
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
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 \in \mathbb{R}^{n\times k}\) such that
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
Hence, we may write the risk constraint as
or equivalently
where \(\Q^{k+1}\) is the \((k+1)\)-dimensional quadratic cone. Note that specifically when \(G\) is derived using Cholesky factorization, \(k = n\).
Therefore, problem (11.1) can be written as
which is a conic quadratic optimization problem that can easily be formulated and solved with Optimizer API for Rust. 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 \(G\) based on a factor model, that leads to more efficient computation.
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
more numerically robust than
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.
Example code
Listing 11.1 demonstrates how the basic Markowitz model (11.3) is implemented.
extern crate mosek;
extern crate itertools;
use mosek::{Task,Objsense,Streamtype,Soltype,Solsta};
use itertools::{iproduct};
/// Solve basic Markowitz portfolio problem: Maximize expected return
/// while bounded the estimated risk.
///
/// ```
/// Maximize mu'x
/// Subject to
/// budget : sum(x) = sum(x0)+w
/// risk: gamma^2 >= || G'x ||^2
/// x >= 0
/// ```
///
/// # Arguments
///
/// - `n` number of assets
/// - `gamma` risk bound (bound on the standard deviation)
/// - `mu` vector of expected returns
/// - `GT` Covariance matrix factor
/// - `x0` vector if initial investment
/// - `w` initial uninvested wealth
#[allow(non_snake_case)]
fn portfolio(n : i32, // number of assets
gamma : f64, // risk bound: maximum stddev
mu : &[f64], // vector of expected returns
GT : &[f64], // covariance matrix factor
x0 : &[f64], // initial investment
w : f64) // initial wealth
-> Result<(Vec<f64>,f64),String> {
let k = (GT.len() / n as usize) as i32;
/* Create the optimization task. */
let mut task = match Task::new() {
Some(e) => e,
None => return Err("Failed to create task".to_string()),
}.with_callbacks();
task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;
/* Total budget */
let total_budget = w + x0.iter().sum::<f64>();
/* Constraints. */
task.append_cons(1i32)?;
/* Variables. */
task.append_vars(n)?;
let x : Vec<i32> = (0i32..n).collect();
/* Total budget constraint - set bounds l^c = u^c */
task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
task.put_con_name(0i32,"budget")?;
task.put_obj_sense(Objsense::MAXIMIZE)?;
task.put_c_slice(0,n,mu)?;
/* x variables. */
for (j,xj) in x.iter().enumerate() {
/* Coefficients in the first row of A */
task.put_aij(0, *xj, 1.0)?;
/* No short-selling - x^l = 0, x^u = inf */
task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
}
// risk bound
{
let acci = task.get_num_acc()?;
let afei = task.get_num_afe()?;
task.append_afes(k as i64 + 1)?;
let dom = task.append_quadratic_cone_domain(k as i64+1)?;
task.append_acc_seq(dom,
afei,
vec![0.0; k as usize + 1].as_slice())?;
task.put_acc_name(acci,"risk")?;
task.put_afe_g(afei,gamma)?;
for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
}
}
/* Dump the problem to a human readable OPF file. */
// task.write_data("portfolio_1_basic.ptf")?;
let _trm = task.optimize()?;
// Check if the interior point solution is an optimal point
if task.get_sol_sta(Soltype::ITR)? != Solsta::OPTIMAL {
// See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
eprintln!("Solution not optimal!");
std::process::exit(1);
}
/* Display the solution summary for quick inspection of results. */
task.solution_summary(Streamtype::MSG)?;
task.write_data("portfolio_1_basic.ptf")?;
/* Read the x variables one by one and compute expected return. */
/* Can also be obtained as value of the objective. */
let mut level = vec![0.0;n as usize];
task.get_xx_slice(Soltype::ITR,0,n,level.as_mut_slice())?;
let expret = task.get_primal_obj(Soltype::ITR)?;
Ok((level.to_vec(),expret))
}
#[allow(non_snake_case)]
fn main() -> Result<(),String> {
let n = 8i32;
let w = 59.0;
let mu = &[0.07197349, 0.15518171, 0.17535435, 0.0898094 , 0.42895777, 0.39291844, 0.32170722, 0.18378628];
let x0 = &[8.0, 5.0, 3.0, 5.0, 2.0, 9.0, 3.0, 6.0];
let gamma = 36.0;
let GT = &[ 0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638,
0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506,
0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914,
0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742,
0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 ,
0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187,
0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327,
0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 ];
let (level,expret) = portfolio(n,gamma,mu,GT,x0,w)?;
println!("Solution x = {:?}",level);
println!("Expected return {:.4e} for gamma = {:.4e}", expret, gamma);
Ok(())
}
The code is organized as follows:
We have \(n\) optimization variables, one per each asset in the portfolio. They correspond to the variable \(x\) from (11.1) and their indices as variables in the task are from \(0\) to \(n-1\) (inclusive).
The linear part of the problem: budget constraint, no-short-selling bounds and the objective are added in the linear data of the task (\(A\) matrix, \(c\) vector and bounds) following the techniques introduced in the tutorial of Sec. 6.1 (Linear Optimization).
For the quadratic constraint we follow the path introduced in the tutorial of Sec. 6.2 (From Linear to Conic Optimization). We add the vector \((\gamma, G^Tx)\) to the affine expression storage (AFE), create a quadratic domain of suitable length, and add the affine conic constraint (ACC) with the selected affine expressions. In the segment
let dom = task.append_quadratic_cone_domain(k as i64+1)?; task.append_acc_seq(dom, afei, vec![0.0; k as usize + 1].as_slice())?;
we use
Task.append_acc_seq
to append a single ACC with the quadratic domainqdom
and with a sequence of affine expressions starting at position \(0\) in the AFE storage and of length equal to the dimension ofqdom
. This is the simplest way to achieve what we need, since previously we also stored the required rows in AFE in the same order.
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
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:
The parameter \(\alpha\) specifies the tradeoff between expected return and variance. Ideally the problem (11.4) should be solved for all values \(\alpha \geq 0\) but in practice it is impossible. Using the example data from Sec. 11.1.1 (The Basic Model), the optimal values of return and variance for several values of \(\alpha\) are shown in the figure.
Example code
Listing 11.2 demonstrates how to compute the efficient portfolios for several values of \(\alpha\).
extern crate mosek;
extern crate itertools;
use mosek::{Task,Objsense,Solsta,Soltype};
use itertools::{iproduct};
/// Solve basic Markowitz portfolio problem for different risk bounds
/// to produce a list of points on the efficient frontier.
///
/// ```
/// Maximize mu'x - alpha * s
/// Subject to
/// budget : sum(x) = sum(x0)+w
/// risk: s >= || G'x ||
/// x >= 0
/// ```
///
/// # Arguments
///
/// - `n` number of assets
/// - `alphas` list of risk bound (bound on the standard deviation)
/// - `mu` vector of expected returns
/// - `GT` Covariance matrix factor
/// - `x0` vector if initial investment
/// - `w` initial uninvested wealth
#[allow(non_snake_case)]
fn portfolio(n : i32,
mu : &[f64],
GT : &[f64],
x0 : &[f64],
alphas : &[f64],
w : f64) -> Result<Vec<(f64,f64)>,String> {
let k = (GT.len() / n as usize) as i32;
/* Create the optimization task. */
let mut task = match Task::new() {
Some(t) => t,
None => return Err("Failed to create task".to_string()),
};
//task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;
task.append_vars(n+1)?;
task.append_cons(1)?;
/* Objective */
task.put_obj_sense(Objsense::MAXIMIZE)?;
let x : Vec<i32> = (0i32..n).collect();
let s = n;
/* Total budget */
let total_budget = w + x0.iter().sum::<f64>();
/* Total budget constraint - set bounds l^c = u^c */
task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
task.put_con_name(0i32,"budget")?;
task.put_c_slice(0,n,mu)?;
/* x variables. */
for (j,xj) in x.iter().enumerate() {
/* Coefficients in the first row of A */
task.put_aij(0, *xj, 1.0)?;
/* No short-selling - x^l = 0, x^u = inf */
task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
}
task.put_var_name(s, "s")?;
task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;
// risk bound
// (s,0.5,GT * x) in Q_r
{
let acci = task.get_num_acc()?;
let afei = task.get_num_afe()?;
task.append_afes(k as i64 + 2)?;
let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
task.append_acc_seq(dom,
afei,
vec![0.0; k as usize + 2].as_slice())?;
task.put_acc_name(acci,"risk")?;
task.put_afe_f_entry(afei,s,1.0)?;
task.put_afe_g(afei+1,0.5)?;
for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
}
}
let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
/* Sets the objective function coefficient for s. */
if let Err(_) = task.put_c_j(s, - *alpha) { None }
else if let Err(_) = task.optimize() { None }
else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
// See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
match solsta {
Solsta::OPTIMAL => {
let mut xx = vec![0.0; n as usize+1];
if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
else {
Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
}
}
_ => None
}
}
else {
None
}
}).collect();
Ok(frontier)
}
#[allow(non_snake_case)]
fn main() -> Result<(),String> {
let n : i32 = 8;
let w = 1.0;
let mu = &[0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379];
let x0 = &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
let GT = &[ 0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638,
0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506,
0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914,
0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742,
0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 ,
0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187,
0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327,
0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 ];
let alphas = &[0.0, 0.01, 0.1, 0.25, 0.30, 0.35, 0.4, 0.45, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 10.0];
println!("{:10} {:10}","alpha","exp.ret.");
for (alpha,expret) in portfolio(n,
mu,
GT,
x0,
alphas,
w)? {
println!("{:10.3e} : {:10.e}",alpha,expret);
}
Ok(())
}
Note that we changed the coefficient \(\alpha\) of the variable \(s\) in a loop. This way we were able to reuse the same model for all solves along the efficient frontier, simply changing the value of \(\alpha\) between the solves.
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
where \(D\) is a positive definite diagonal matrix. Moreover, \(V\) is a matrix with \(n\) rows and \(k\) columns. Such a model for the covariance matrix is called a factor model and usually \(k\) is much smaller than \(n\). In practice \(k\) 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
because then
This choice requires storage proportional to \(n+kn\) which is much less than for the Cholesky choice of \(G\). Indeed assuming \(k\) 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].
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 \(R = \sum_j\beta_j F_j + \theta\), where \(R\) is a random variable representing the return of a security at a particular point in time, \(F_j\) is the random variable representing the common factor \(j\), \(\beta_j\) is the exposure of the return to factor \(j\), and \(\theta\) is the specific component.
Such a model will result in the covariance structure
where \(\Sigma_F\) is the covariance of the factors and \(\Sigma_\theta\) is the residual covariance. This structure is of the form discussed earlier with \(D = \Sigma_\theta\) and \(V = \beta P\), assuming the decomposition \(\Sigma_F = PP^T\). If the number of factors \(k\) is low and \(\Sigma_\theta\) is diagonal, we get a very sparse \(G\) that provides the storage and solution time benefits.
Example code
Here we will work with the example data of a two-factor model (\(k=2\)) built using the variables
and the factor covariance matrix is
giving
Then the matrix \(G\) would look like
This matrix is indeed very sparse.
In general, we get an \(n\times (n+k)\) size matrix this way with \(k\) full columns and an \(n\times n\) diagonal part. In order to maintain a sparse representation we do not construct the matrix \(G\) explicitly in the code but instead work with two pieces of data: the dense matrix \(G_\mathrm{factor} = \beta P\) of shape \(n\times k\) and the diagonal vector \(\theta\) of length \(n\).
Example code
In the following we demonstrate how to write code to compute the matrix \(G_\mathrm{factor}\) of the factor model. We start with the inputs
// Factor exposure matrix, n x 2
let B = Matrix::new_by_row(n as usize, 2,
[ 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 ].to_vec()).unwrap();
// Factor covariance matrix, 2x2
let S_F = Matrix::new_by_row(2,2,
[ 0.0620, 0.0577,
0.0577, 0.0908 ].to_vec()).unwrap();
// Specific risk components
let theta : &[f64] = &[0.0720, 0.0508, 0.0377, 0.0394, 0.0663, 0.0224, 0.0417, 0.0459];
Then the matrix \(G_\mathrm{factor}\) is obtained as:
let S_sqrt_theta = Matrix::diag_matrix(theta.iter().map(|&v| v.sqrt()).collect());
let P = S_F.cholesky().unwrap();
let BP = B.mul(&P).unwrap();
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 \(G^Tx\) appearing in the conic constraint by stacking together two separate vectors \(G_\mathrm{factor}^T x\) and \(\Sigma^{1/2}_\theta x\):
// Input (gamma, G_factor_T x, diag(sqrt(theta))*x) in the AFE (affine expression) storage
// We need k+n+1 rows and we fill them in in three parts
task.append_afes((k+n) as i64 + 1)?;
// 1. The first affine expression = gamma, will be specified later
// 2. The next k expressions comprise G_factor_T*x, we add them row by row
// transposing the matrix G_factor on the fly
task.put_afe_f_row_list((1..1+k as i64).collect::<Vec<i64>>().as_slice(), // f row idxs
vec![n; k as usize].as_slice(), // row lengths
(0..GT.len() as i64).step_by(n as usize).collect::<Vec<i64>>().as_slice(), // row ptr
iproduct!(0..k,0..n).map(|(_,b)| b).collect::<Vec<i32>>().as_slice(), // varidx, 0..n repeated k times
GT.data_by_row().as_slice())?;
// 3. The remaining n rows contain sqrt(theta) on the diagonal
for (i,thetai) in (0..n).zip(theta.iter()) {
task.put_afe_f_entry(i as i64 + 1 + k as i64, voff_x + i, thetai.sqrt())?;
}
The full code is demonstrated below:
#[allow(non_snake_case)]
fn portfolio(w : f64,
mu : &[f64],
x0 : &[f64],
gammas : &[f64],
theta : &[f64],
GT : &Matrix) -> Result<Vec<(f64,f64)>,String> {
let mut task = match Task::new() {
Some(e) => e,
None => return Err("Failed to create task".to_string()),
}.with_callbacks();
task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;
let (kx,nx) = GT.size();
if mu.len() != nx { panic!("Mismatching data"); }
let k : i32 = kx.try_into().unwrap();
let n : i32 = nx.try_into().unwrap();
let total_budget : f64 = w + x0.iter().sum::<f64>();
//Offset of variables into the API variable.
let numvar = n;
let voff_x : i32 = 0;
// Constraint offset
let coff_bud : i32 = 0;
// Holding variable x of length n
// No other auxiliary variables are needed in this formulation
task.append_vars(numvar)?;
// Setting up variable x
for j in 0..n {
task.put_var_name(voff_x+j,format!("x[{}]",j+1).as_str())?;
}
task.put_var_bound_slice_const(voff_x,voff_x+n, Boundkey::LO,0.0, INF)?;
// One linear constraint: total budget
task.append_cons(1)?;
task.put_con_name(coff_bud, "budget")?;
/* Coefficients in the first row of A */
for j in 0..n {
task.put_aij(coff_bud,voff_x + j, 1.0)?;
}
task.put_con_bound(coff_bud, Boundkey::FX, total_budget, total_budget)?;
// Input (gamma, G_factor_T x, diag(sqrt(theta))*x) in the AFE (affine expression) storage
// We need k+n+1 rows and we fill them in in three parts
task.append_afes((k+n) as i64 + 1)?;
// 1. The first affine expression = gamma, will be specified later
// 2. The next k expressions comprise G_factor_T*x, we add them row by row
// transposing the matrix G_factor on the fly
task.put_afe_f_row_list((1..1+k as i64).collect::<Vec<i64>>().as_slice(), // f row idxs
vec![n; k as usize].as_slice(), // row lengths
(0..GT.len() as i64).step_by(n as usize).collect::<Vec<i64>>().as_slice(), // row ptr
iproduct!(0..k,0..n).map(|(_,b)| b).collect::<Vec<i32>>().as_slice(), // varidx, 0..n repeated k times
GT.data_by_row().as_slice())?;
// 3. The remaining n rows contain sqrt(theta) on the diagonal
for (i,thetai) in (0..n).zip(theta.iter()) {
task.put_afe_f_entry(i as i64 + 1 + k as i64, voff_x + i, thetai.sqrt())?;
}
// Input the affine conic constraint (gamma, GT*x) \in QCone
// Add the quadratic domain of dimension k+1
let qdom = task.append_quadratic_cone_domain(k as i64+ 1)?;
// Add the constraint
task.append_acc_seq(qdom, 0, vec![0.0; k as usize+1].as_slice())?;
task.put_acc_name(0, "risk")?;
// Objective: maximize expected return mu^T x
for (j,&muj) in (0..n).zip(mu.iter()) {
task.put_c_j(voff_x + j, muj)?;
}
task.put_obj_sense(Objsense::MAXIMIZE)?;
Ok(gammas.iter().filter_map(|&gamma| {
// Specify gamma in ACC
task.put_afe_g(0, gamma).ok()?;
task.optimize().ok()?;
/* Display solution summary for quick inspection of results */
let _ = task.solution_summary(Streamtype::LOG);
let _ = task.write_data(format!("portfolio_6_factor-{}.ptf",gamma).as_str());
// Check if the interior point solution is an optimal point
if task.get_sol_sta(Soltype::ITR).ok()? != Solsta::OPTIMAL {
// See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
eprintln!("Solution not optimal!");
std::process::exit(1);
}
/* Read the results */
let mut xx = vec![0.0; n as usize];
task.get_xx_slice(Soltype::ITR, voff_x, voff_x + n, xx.as_mut_slice()).ok()?;
Some((gamma,xx.iter().zip(mu.iter()).map(|(&xj,&muj)| xj*muj).sum::<f64>()))
}).collect::<Vec<(f64,f64)>>())
}
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 \(\Delta x_j\) is the change in the holding of asset \(j\) i.e.
and \(T_j(\Delta x_j)\) 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
where \(m_j\) is a constant that is estimated in some way by the trader. See [GK00] [p. 452] for details. From the Modeling Cookbook we know that \(t \geq |z|^{3/2}\) can be modeled directly using the power cone \(\POW_3^{2/3,1/3}\):
Hence, it follows that \(\sum_{j=1}^n T_j(\Delta x_j)=\sum_{j=1}^n m_j|x_j-x_j^0|^{3/2}\) can be modeled by \(\sum_{j=1}^n m_jt_j\) under the constraints
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 \(p>1\) is a real number can be modeled with the power cone as
See the Modeling Cookbook for details.
Example code
Listing 11.5 demonstrates how to compute an optimal portfolio when market impact cost are included.
extern crate mosek;
extern crate itertools;
use mosek::{Task,Objsense,Streamtype,Solsta,Soltype,Boundkey};
use itertools::{izip,iproduct};
const INF : f64 = 0.0;
/// Solve portfolio with market impact terms.
///
/// ```
/// Maximize mu'x
/// Subject to
/// budget : sum(x)+m'c = sum(x0)+w
/// risk : (gamma,G'x) in Q^{k+1}
/// MI : (c_j,1,|x_j-x0_j|) in P^3(2/3,1/3), j = 1..
/// x >= 0
/// ```
///
/// Where
///
/// - m_i is the transaction cost associated with asset i
/// - gamma is the bound on the standard deviation if the portfolio
/// - mu_i is the expected return on asset i
/// - w is the initial wealth held in cash
/// - x0_i is the initial investment in asset i
/// - G'G is the covariance matrix for assets
///
/// The MI constraint is not convex due tot he |.| term, so we relax it:
/// ```
/// MI : (c_j,1,z_j) in P^3(2/3,1/3), j = 1..
/// z_j >= |x_j-x0_j|
/// implemented as
/// z_j >= x_j-x0_j
/// z_j >= x0_j-x_j
/// ```
///
/// # Arguments
///
/// - `n` number of assets
/// - `mu` vector of expected returns
/// - `m` vector of market impact estimates
/// - `GT` factored covariance matrix
/// - `x0` vector if initial investment
/// - `gamma` bound on risk
/// - `w` initial uninvested wealth
///
/// # Returns
///
/// Returns `(solution,objval)`
///
/// - `solution` is the primal investment solution vector
/// - `objval` is the solution expected return
#[allow(non_snake_case)]
pub fn portfolio(n : i32,
mu : &[f64],
m : &[f64],
GT : &[f64],
x0 : &[f64],
gamma : f64,
w : f64) -> Result<(Vec<f64>,f64),String> {
let k = (GT.len() / n as usize) as i32;
/* Create the optimization task. */
let mut task = match Task::new() {
Some(e) => e,
None => return Err("Failed to create task".to_string()),
}.with_callbacks();
task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;
task.append_vars(3*n)?;
let allvars : Vec<i32> = (0i32..3*n).collect();
let var_x = &allvars[0..n as usize];
let var_c = &allvars[n as usize..2*n as usize];
let var_xc = &allvars[0..2*n as usize];
let var_z = &allvars[2*n as usize..3*n as usize];
for (i,j) in var_x.iter().enumerate() {
task.put_var_bound(*j,mosek::Boundkey::LO, 0.0, 0.0)?;
task.put_var_name(*j,format!("x[{}]",i+1).as_str())?; }
for (i,j) in var_c.iter().enumerate() {
task.put_var_bound(*j,mosek::Boundkey::FR, 0.0, 0.0)?;
task.put_var_name(*j,format!("c[{}]",i+1).as_str())?;
}
for (i,j) in var_z.iter().enumerate() {
task.put_var_bound(*j,mosek::Boundkey::FR, 0.0, 0.0)?;
task.put_var_name(*j,format!("z[{}]",i+1).as_str())?;
}
task.put_obj_sense(Objsense::MAXIMIZE)?;
for i in var_x {
task.put_c_j(*i,mu[*i as usize])?;
}
task.append_cons(1)?;
let con_budget = 0i32;
// budget
task.put_con_name(0,"budget")?;
let wealth = w + x0.iter().sum::<f64>();
task.put_a_row(con_budget,
&var_xc,
(0..n).map(|_| 1.0).chain(m.iter().map(|v| *v)).collect::<Vec<f64>>().as_slice())?;
task.put_con_bound(con_budget,mosek::Boundkey::FX, wealth,wealth)?;
// |x-x0| <= z
{
let coni = task.get_num_con()?;
task.append_cons(2 * n)?;
for i in 0..n {
task.put_con_name(coni+i, format!("zabs1[{}]",1 + i).as_str())?;
task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
}
let ones = vec![1.0; n as usize];
let minusones = vec![-1.0; n as usize];
let con_abs1 : Vec<i32> = (coni..coni+n).collect();
let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
task.put_aij_list(con_abs1.as_slice(), var_x, minusones.as_slice())?;
task.put_aij_list(con_abs1.as_slice(), var_z, ones.as_slice())?;
task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
task.put_aij_list(con_abs2.as_slice(), var_x, ones.as_slice())?;
task.put_aij_list(con_abs2.as_slice(), var_z, ones.as_slice())?;
task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
}
// GT
{
let acci = task.get_num_acc()?;
let afei = task.get_num_afe()?;
task.append_afes(k as i64 + 1)?;
let dom = task.append_quadratic_cone_domain(k as i64+1)?;
task.append_acc_seq(dom,
afei,
vec![0.0; k as usize + 1].as_slice())?;
task.put_acc_name(acci,"risk")?;
task.put_afe_g(afei,gamma)?;
for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
}
}
// MI
{
let mut acci = task.get_num_acc()?;
let mut afei = task.get_num_afe()?;
let afe0 = afei;
task.append_afes(n as i64 * 2+1)?;
let dom = task.append_primal_power_cone_domain(3,&[2.0, 1.0])?;
task.put_afe_g(afe0,1.0)?;
afei += 1;
for (i,&cj,&zj,&x0j) in izip!(0..n,var_c,var_z,x0) {
task.put_afe_f_entry(afei,cj,1.0)?;
task.put_afe_f_entry(afei+1,zj,1.0)?;
task.put_afe_g(afei+1, - x0j)?;
task.append_acc(dom,
&[afei,afe0,afei+1],
&[0.0, 0.0, 0.0])?;
task.put_acc_name(acci,format!("market_impact[{}]",i+1).as_str())?;
afei += 2;
acci += 1;
}
}
let _ = task.optimize()?;
task.write_data("portfolio_3_impact.ptf")?;
/* Display the solution summary for quick inspection of results. */
task.solution_summary(Streamtype::MSG)?;
if ! task.solution_def(Soltype::ITR)? {
return Err("No solultion defined".to_string());
}
// See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
let solsta = task.get_sol_sta(Soltype::ITR)?;
if solsta != Solsta::OPTIMAL {
return Err("Unexpected solution status".to_string());
}
let mut level = vec![0.0;n as usize];
task.get_xx_slice(Soltype::ITR,0,n,level.as_mut_slice())?;
let obj = task.get_primal_obj(Soltype::ITR)?;
Ok((level,obj))
}
#[allow(non_snake_case)]
fn main() -> Result<(),String> {
let n : i32 = 8;
let w = 1.0;
let mu = &[0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379];
let x0 = &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
let GT = &[0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638,
0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506,
0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914,
0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742,
0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 ,
0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187,
0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327,
0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 ];
let gamma = 0.36;
let m = vec![0.01; n as usize];
let (level,obj) = portfolio(n,
mu,
m.as_slice(),
GT,
x0,
gamma,
w)?;
println!("Solution x = {:?}",level);
println!("Objective value x = {:?}",obj);
Ok(())
}
Note that in the following part of the code:
{
let mut acci = task.get_num_acc()?;
let mut afei = task.get_num_afe()?;
let afe0 = afei;
task.append_afes(n as i64 * 2+1)?;
let dom = task.append_primal_power_cone_domain(3,&[2.0, 1.0])?;
task.put_afe_g(afe0,1.0)?;
afei += 1;
for (i,&cj,&zj,&x0j) in izip!(0..n,var_c,var_z,x0) {
task.put_afe_f_entry(afei,cj,1.0)?;
task.put_afe_f_entry(afei+1,zj,1.0)?;
task.put_afe_g(afei+1, - x0j)?;
task.append_acc(dom,
&[afei,afe0,afei+1],
&[0.0, 0.0, 0.0])?;
task.put_acc_name(acci,format!("market_impact[{}]",i+1).as_str())?;
afei += 2;
acci += 1;
}
}
we create a sequence of power cones of the form \((t_k, 1, x_k-x_k^0)\in \POW_3^{2/3,1/3}\). The power cones are determined by the sequence of exponents \((2,1)\); we create a single domain to account for that.
Moreover, note that the second coordinate of all these affine conic constraints is the same affine expression equal to \(1\), and we use the feature that allows us to define this affine expression only once (as AFE number aoff_pow + 2 * n
) and reuse it in all the ACCs.
11.1.6 Transaction Costs¶
Now assume there is a cost associated with trading asset \(j\) given by
Hence, whenever asset \(j\) is traded we pay a fixed setup cost \(f_j\) and a variable cost of \(g_j\) per unit traded. Given the assumptions about transaction costs in this section problem (11.6) may be formulated as
(11.11)¶\[\begin{split}\begin{array}{lrcll} \mbox{maximize} & \mu^T x & & &\\ \mbox{subject to} & e^T x + f^Ty + g^T z & = & w + e^T x^0, &\\ & (\gamma,G^T x) & \in & \Q^{k+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_j y_j, & j=1,\ldots,n,\\ & y_j & \in & \{0,1\}, & j=1,\ldots,n, \\ & x & \geq & 0. & \end{array}\end{split}\]
First observe that
We choose \(U_j\) as some a priori 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
Example code
The following example code demonstrates how to compute an optimal portfolio when transaction costs are included.
extern crate mosek;
use mosek::{Task,Objsense,Streamtype,Soltype,Variabletype,Boundkey,Solsta};
extern crate itertools;
use itertools::{iproduct};
const INF : f64 = 0.0;
/// Optimize expected return on an investment with transaction cost.
///
/// ```
/// Maximize mu'x
/// Such That
/// budget: sum(x) + f'y + g'z = w0+sum(x0)
/// risk: gamma > || G'x ||
/// ACC: z_j > |x0_j-x_j|
/// DJC: [ y_j == 0 AND x0_j == x_j ] OR y_j == 1
/// // z_j < U_j y_j, y in {0,1}
/// y free
/// x > 0
/// Where f_i is the fixed cost of a transaction in asset i,
/// g_i is the cost per unit of a transaction in asset i
/// ```
/// # Arguments
///
/// - `n` number of assets
/// - `mu` vector of expected returns
/// - `f` vector of fixed transaction costs
/// - 'g' vector of continuous proportional transaction costs
/// - `GT` Covariance matrix factor
/// - `x0` vector if initial investment
/// - `gamma` risk bound (bound on the standard deviation)
/// - `w` initial uninvested wealth
#[allow(non_snake_case)]
fn portfolio(n : i32,
mu : &[f64],
f : &[f64],
g : &[f64],
GT : &[f64],
x0 : &[f64],
gamma : f64,
w : f64) -> Result<(Vec<f64>,f64),String> {
/* Create the optimization task. */
let mut task = match Task::new() {
Some(e) => e,
None => return Err("Failed to create task".to_string()),
}.with_callbacks();
let k = (GT.len() / n as usize) as i32;
task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;
/* Compute total wealth */
let w0 = w + x0.iter().sum::<f64>();
task.append_cons(1i32)?;
task.append_vars(3*n)?;
for i in 0i32..n {
task.put_var_name(i, format!("x[{}]",i+1).as_str())?;
task.put_var_name(i+n, format!("y[{}]",i+1).as_str())?;
task.put_var_name(i+2*n,format!("z[{}]",i+1).as_str())?;
task.put_var_type(i+n, Variabletype::TYPE_INT)?;
}
let all_vars : Vec<i32> = (0i32..3*n).collect();
let x = &all_vars[0..n as usize];
let y = &all_vars[n as usize..2*n as usize];
let z = &all_vars[2*n as usize..3*n as usize];
task.put_var_bound_slice_const(0i32,n, mosek::Boundkey::LO, 0.0,0.0)?;
task.put_var_bound_slice_const(n,2*n, mosek::Boundkey::RA, 0.0,1.0)?;
task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, 0.0,0.0)?;
/* Constraints. */
task.put_con_name(0,"budget")?;
{
let zeros = vec![0i32; n as usize];
let fones = vec![1.0; n as usize];
task.put_aij_list(zeros.as_slice(), x, fones.as_slice())?;
task.put_aij_list(zeros.as_slice(), y, f)?;
task.put_aij_list(zeros.as_slice(), z, g)?;
task.put_con_bound(0i32,mosek::Boundkey::FX,w0,w0)?;
}
// objective
task.put_obj_sense(Objsense::MAXIMIZE)?;
for (xi,mui) in x.iter().zip(mu.iter()) {
task.put_c_j(*xi, *mui)?;
}
// risk bound
{
let acci = task.get_num_acc()?;
let afei = task.get_num_afe()?;
task.append_afes(k as i64 + 1)?;
let dom = task.append_quadratic_cone_domain(k as i64+1)?;
task.append_acc_seq(dom,
afei,
vec![0.0; k as usize + 1].as_slice())?;
task.put_acc_name(acci,"risk")?;
task.put_afe_g(afei,gamma)?;
for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
}
}
// |x-x0| <= z
{
let coni = task.get_num_con()?;
task.append_cons(2 * n)?;
for i in 0..n {
task.put_con_name(coni+i, format!("zabs1[{}]",1 + i).as_str())?;
task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
}
let ones = vec![1.0; n as usize];
let minusones = vec![-1.0; n as usize];
let con_abs1 : Vec<i32> = (coni..coni+n).collect();
let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
}
// Switch
{
let coni = task.get_num_con()?;
task.append_cons(n)?;
for i in 0..n {
task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
}
let conlist : Vec<i32> = (coni..coni+n).collect();
task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;
task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
}
let _ = task.optimize()?;
task.write_data("portfolio_4_transcost.ptf")?;
/* Display the solution summary for quick inspection of results. */
task.solution_summary(Streamtype::MSG)?;
// Check if the integer solution is an optimal point
if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
// See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
eprintln!("Solution not optimal!");
std::process::exit(1);
}
let mut xx = vec![0.0;n as usize];
task.get_xx_slice(Soltype::ITG, 0,n, xx.as_mut_slice())?;
let expret = xx[0..n as usize].iter().zip(mu.iter()).map(|(a,b)| a*b).sum::<f64>();
Ok((xx,expret))
}
#[allow(non_snake_case)]
fn main() -> Result<(),String> {
let n = 8i32;
let w = 1.0;
let mu = &[0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379];
let x0 = &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
let GT = &[ 0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638,
0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506,
0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914,
0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742,
0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 ,
0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187,
0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327,
0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 ];
let f = vec![0.01; n as usize];
let g = vec![0.001; n as usize];
let gamma = 0.36;
let (level,expret) = portfolio(n,
mu,
f.as_slice(),
g.as_slice(),
GT,
x0,
gamma,
w)?;
println!("Expected return {:.4e} for gamma {:.4e}\n", expret, gamma);
println!("Solution vector = {:?}\n", level);
Ok(())
}
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.12)¶\[\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^{k+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_j y_j, & 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\).
Example code
The following example code demonstrates how to compute an optimal portfolio with cardinality bounds.
#[allow(non_snake_case)]
fn portfolio(n : i32,
mu : &[f64],
GT : &[f64],
x0 : &[f64],
gamma : f64,
p : i32,
w : f64) -> Result<(Vec<f64>,f64),String> {
/* Create the optimization task. */
let mut task = match Task::new() {
Some(e) => e,
None => return Err("Failed to create task".to_string()),
};
let k = (GT.len() / n as usize) as i32;
// task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;
/* Compute total wealth */
let w0 = w + x0.iter().sum::<f64>();
task.append_vars(3*n)?;
let all_vars : Vec<i32> = (0..3*n).collect();
let x = &all_vars[0..n as usize];
let y = &all_vars[n as usize..2*n as usize];
let z = &all_vars[2*n as usize..3*n as usize];
task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;
for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
task.put_var_type(*yj, Variabletype::TYPE_INT)?;
}
// objective
task.put_obj_sense(Objsense::MAXIMIZE)?;
for (j,mui) in x.iter().zip(mu.iter()) {
task.put_c_j(*j, *mui)?;
}
let n_ones = vec![1.0; n as usize];
// budget constraint
{
let coni = task.get_num_con()?;
task.append_cons(1)?;
task.put_con_name(coni,"budget")?;
task.put_a_row(coni,
x,
n_ones.as_slice())?;
task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
}
// |x-x0| <= z
{
let coni = task.get_num_con()?;
task.append_cons(2 * n)?;
for i in 0..n {
task.put_con_name(coni+i, format!("zabs1[{}]",1 + i).as_str())?;
task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
}
let ones = vec![1.0; n as usize];
let minusones = vec![-1.0; n as usize];
let con_abs1 : Vec<i32> = (coni..coni+n).collect();
let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
}
// cardinality constraint
{
let coni = task.get_num_con()?;
task.append_cons(1)?;
task.put_con_name(coni,"cardinality")?;
task.put_a_row(coni, y, n_ones.as_slice())?;
task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
}
// (gamma,G'x) in Q
{
let afei = task.get_num_afe()?;
let acci = task.get_num_acc()?;
task.append_afes(k as i64+1)?;
let dom = task.append_quadratic_cone_domain(k as i64+1)?;
task.append_acc_seq(dom,
afei,
vec![0.0; k as usize + 1].as_slice())?;
task.put_acc_name(acci,"risk")?;
task.put_afe_g(afei,gamma)?;
for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
}
}
// Switch
{
let coni = task.get_num_con()?;
task.append_cons(n)?;
for i in 0..n {
task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
}
let conlist : Vec<i32> = (coni..coni+n).collect();
task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;
task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
}
let _ = task.optimize()?;
task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;
// Check if the integer solution is an optimal point
if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
// See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
eprintln!("Solution not optimal!");
std::process::exit(1);
}
let mut xx = vec![0.0;n as usize];
task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
If we solve our running example with \(K=1,\dots,n\) then we get the following solutions, with increasing expected returns:
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