Portfolio optimization selects asset allocations subject to various constraints on return, risk, trading, diversification. The classical mean-variance model is a quadratic optimization problem (QP), but practical portfolio construction can quickly become more complex, involving quadratic and conic constraints and integer variables.
ALGLIB can solve these models with several powerful solvers: continuous quadratic and conic portfolio models are handled by the MINQP solver; general continuous nonlinear models can be handled by MINNLC; and models containing integer or binary decisions are handled by the BBSYNC mixed-integer solver. Depending on your workflow, optimization can be performed from C++, C#, Java, Python or a modeling environment.
This page explains how common portfolio requirements translate into mathematical optimization models, which ALGLIB solver is appropriate for each structure, and where to find more detailed guides for individual portfolio problems.
1 ALGLIB and portfolio optimization
Supported problem types
ALGLIB Solver and ALGLIB Library
Benchmark
Code example: Markowitz model
2 Advanced topics
Sparsity and performance
3 More on constraint types
Common portfolio constraints
Quadratic constraints
Cone-based constraints
Risk parity and risk budgeting
4 Discrete-choice portfolio models
ALGLIB support
Cardinality/minimum-position constraints
Other discrete constraints
Code example: cardinality portfolio
5 Downloads section
ALGLIB supports mathematical optimization problems with linear, quadratic or nonlinear objective and a combination of box, linear, quadratic, conic and general nonlinear constraints. Additionally, BBSYNC solver supports mixed-integer optimization problems. This includes virtually all portfolio optimization problems arising in practice:
There are two main ways to use ALGLIB optimization functionality.
The ALGLIB Software Library provides optimization APIs for applications written in languages including C++, C#, Java and Python. This approach is useful when portfolio optimization is embedded directly into an application, service, analytics platform or trading infrastructure.
This approach gives developers direct control over model construction, memory and data representation, repeated solution of related models, integration with existing numerical code.
The ALGLIB Solver provides a modeling-oriented alternative. It can be used from modeling environments compatible with the AMPL .nl format.
In both cases the same highly optimized algorithms are used.
One of the most demanding setups in the nonlinear optimization is mixed-integer optimization, which requirest exhaustive search over branch-and-bound tree. In portfolio optimization it arises due to constraints on maximum number of assets held, minimum position sizes, fixed transaction costs, etc.
We benchmarked commercial version of our BBSYNC solver, which is heavily SIMD-optimized and multithreaded, and compared it against open source MINLP stack. For testing we used a sufficiently nonlinear subset of MINLPLib benchmark set, and our private robust portfolio optimization suite with highly nonlinear QCQP problems.
The charts above clearly show that ALGLIB is much faster than its closest open-source competitor on nonlinear problems!
The classical Markowitz model balances expected return against portfolio risk. Suppose that \(x_i\) is the fraction of the portfolio invested in asset \(i\), \(\mu_i\) is the expected return of asset \(i\). \(\Sigma\) is the covariance matrix of asset returns. Portfolio expected return is \( \mu^T x \) and portfolio variance is \( x^T\Sigma x. \) A minimum-variance portfolio for a required return \(r\) can be written as
\[ \begin{aligned} \min_x \quad & x^T\Sigma x \\ \text{subject to}\quad & \mu^T x \geq r, \\ & \mathbf{1}^T x = 1, \\ & l_i \leq x_i \leq u_i. \end{aligned} \]When \(\Sigma\) is positive semidefinite, this is a convex quadratic optimization problem. For a long-only portfolio, \(0\leq x_i\leq u_i.\) Allowing negative lower bounds permits short positions. Setting the lower and upper bound of an asset to the same value fixes its weight. Sector, factor, regional, currency and other exposure restrictions can usually be expressed as additional linear constraints without changing the basic quadratic structure of the problem.
An example in C# is given below (C++, Java and Python APIs follow the same format):
public static class Markowitz
{
///
/// Minimum-variance portfolio: min x'Sigma*x
/// s.t. mu'x >= r, 1'x = 1, l <= x <= u.
/// Returns weights and ALGLIB completion code (>0 = success, <0 = failure).
///
public static (double[] Weights, int CompletionCode) MinVariance(
double[,] cov, double[] mu, double minReturn, double[] lower, double[] upper)
{
int n = mu.Length;
// ALGLIB minimizes 0.5*x'Ax + b'x; A = S gives the same minimizer as x'Sx.
alglib.minqpcreate(n, out alglib.minqpstate state);
alglib.minqpsetquadraticterm(state, cov, true);
alglib.minqpsetlinearterm(state, new double[n]);
alglib.minqpsetbc(state, lower, upper);
// Row 0: budget 1'x = 1; row 1: return μ'x >= r
// (two-sided form al <= Ax <= au)
var a = new double[2, n];
for (int i = 0; i < n; i++) { a[0, i] = 1.0; a[1, i] = mu[i]; }
alglib.minqpsetlc2dense(state, a,
new[] { 1.0, minReturn },
new[] { 1.0, double.PositiveInfinity });
// Weights are O(1): explicit unit scale avoids code -9 when an asset
// (e.g. cash) has zero variance
double[] s = new double[n];
for (int i = 0; i < n; i++) s[i] = 1.0;
alglib.minqpsetscale(state, s);
// eps=0 -> ALGLIB default tolerance
alglib.minqpsetalgosparsegenipm(state, 0.0);
alglib.minqpoptimize(state);
alglib.minqpresults(state, out double[] x, out alglib.minqpreport rep);
return (x, rep.terminationtype);
}
}
Finding a solution to a portfolio optimization problem is important. It is also important to find it quickly.
ALGLIB offers several ways to accelerate portfolio optimization:
SIMD support. With x64, ARM64 and RISC-V SIMD supported, Commercial Edition of ALGLIB can greatly accelerate dense and sparse linear algebra powering its solvers.
Structure-aware solvers. Some problems better to be solved with dense linear algebra, the other ones call for efficient utilization of sparsity. Finally, large-scale problems often require low-rank approximation to inverses of huge dense covariance matrices to avoid prohibitive O(N3) scaling. ALGLIB offers all three kinds of solvers - dense, sparse, low-rank ones.
Multithreading. Commercial edition of ALGLIB can accelerate solution of quadratic programming problems and mixed-integer optimization. Multithreading can be used for both linear algebra and parallel navigation of a branch-and-bound tree. Parallel processing is particularly valuable for computationally demanding portfolio models involving cardinality constraints, minimum position sizes and other discrete investment decisions.
Portfolio risk models often involve dense covariance matrices, and scenario-based formulations can contain several large dense quadratic constraints. ALGLIB provides more than one way of handling such structure.
Depending on the problem, dense quadratic models can be processed using full-Newton interior-point techniques that compute huge NxN factorizations (minimal iterations count, but very expensive iterations) or with limited memory IPMs (performing somewhat more low-cost iterations) suited to large dense quadratic constraints. The latter can be performed with the hybrid GENIPM algorithm provided by MINQP solver. This can be particularly relevant when the number of assets is large enough that storing and repeatedly processing several unrestricted dense matrices becomes expensive.
The choice of representation is an implementation and performance issue rather than a change in the financial model itself, so detailed discussion belongs in the solver documentation and problem-specific guides rather than on this introductory page.
Constraint types discussed below do not change linear structure of the problem, so it remains within the QP domain and can be solved with the MINQP solver.
Budget constraint. A fully invested portfolio commonly satisfies \(\sum_i x_i=1.\) The model can be modified when cash, borrowing or leverage are permitted.
Position bounds. Individual position limits have the form \(l_i\leq x_i\leq u_i.\). They can represent long-only restrictions, short-selling limits, concentration limits or fixed holdings.
Sector, factor and other exposure constraints. Suppose \(a_i\) is the exposure of asset \(i\) to some factor. A restriction \(L\leq\sum_i a_ix_i\leq U\) can represent limits on industries or sectors, geographic exposure, currencies, other linear portfolio characteristics.
Limited turnover. Let \(x^0\) denote the current portfolio. A common measure of turnover contains \(\sum_i |x_i-x_i^0|.\) Absolute values can be represented with auxiliary variables. Introduce \(t_i\) and require
\[ t_i\geq x_i-x_i^0, \] \[ t_i\geq -(x_i-x_i^0). \]Then \(\sum_i t_i\leq T\) limits total turnover.
Proportional transaction costs. Suppose trading asset \(i\) costs approximately \(c_i\) per unit traded. Total transaction cost is \(\sum_i c_i|t_i|\) (with ti defined above). Again, absolute values can be replaced by auxiliary buy/sell or trade-size variables. Thus proportional transaction costs often do not require a general nonlinear optimizer.
Asymmetric buy and sell costs. Buying and selling need not have identical costs. Introduce nonnegative variables \(d_i^+\geq0,\qquad d_i^-\geq0\) such that \(x_i-x_i^0=d_i^+-d_i^-.\)
Then buying and selling costs can be represented separately: \(c_i^+d_i^+ + c_i^-d_i^-.\) This remains linear in the trade variables.
Robust portfolio optimization often results in a linear programming problem subject to more than one covariance constraint, which is a QCQP (quadratically constrained quadratic programming) problem.
ALGLIB QP solver includes large-scale GENIPM algorithm capable of solving problems with multiple quadratic constraints. The algorithm is available in dense, sparse and hybrid (dense quadratic terms are modeled using a low-rank LBFGS/SR1 approximation) versions.
Modeling market impact often involves adding a fractional power penalty, which can be efficiently modeled with power cones. The GENIPM algorithm provided by the MINQP solver support both quadratic and conic constraints.
Risk-parity and risk-budgeting models reason about the contribution of individual assets to total portfolio risk. These contributions are nonlinear in portfolio weights.
Depending on the exact formulation, the resulting problem may be expressed through quadratic or conic structure, a transformed convex formulation, or as a general nonlinear optimization problem solvable with MINNLC solver from ALGLIB suite.
Discrete choices arise when we have constraints on maximum number of assets held, minimum position sizes, fixed transaction costs, and in many other cases. ALGLIB supports discrete optimization with its BBSYNC branch-and-bound solver capable of efficiently solving large-scale MIQP and MINLP problems. Commercial version of the solver utilizes deterministic parallelism, which results in a good multithreaded speed-up while retaining deterministic behavior.
Consider a portfolio of \(n\) assets. Suppose we want to minimize variance while requiring a target return and limiting every position to at most 20% of the portfolio:
\[ \begin{aligned} \min_x \quad & x^T\Sigma x\\ \text{subject to}\quad & \mu^Tx\geq r,\\ & \sum_i x_i=1,\\ & 0\leq x_i\leq0.2. \end{aligned} \]This is an ordinary continuous quadratic optimization problem and can be handled by MINQP.
Now require that no more than ten assets are held. Introduce binary variables
\[ z_i\in\{0,1\} \]and link them to the portfolio weights:
\[ 0\leq x_i\leq0.2z_i. \]Then impose
\[ \sum_i z_i\leq10. \]In mathematical terminology, the problem has changed from QP to MIQP. From the ALGLIB point of view, the more important transition is that the model now contains integer variables. It therefore moves from the continuous MINQP solver to the BBSYNC mixed-integer solver.
Suppose every selected asset must also represent at least 2% of the portfolio:
\[ 0.02z_i\leq x_i\leq0.2z_i. \]The model remains an MIQP and is still handled by BBSYNC.
Finally, suppose the portfolio must satisfy several quadratic risk restrictions:
\[ x^T\Sigma_kx\leq r_k, \qquad k=1,\ldots,m. \]The mathematical classification is now MIQCQP. This does not require switching to a special ALGLIB "MIQCQP solver." It remains a BBSYNC problem, now containing quadratic constraints.
Fixed transaction costs. Some costs occur whenever a trade is made, regardless of trade size. This introduces a yes/no decision. A binary variable \(z_i\) can indicate whether asset \(i\) is traded, and the objective may contain \( f_i z_i \) for fixed cost \(f_i\).
Minimum trade sizes. A similar construction can prevent economically insignificant trades. If every executed trade must have magnitude of at least \(m_i\), a binary trade variable can activate the corresponding lower bound. This again introduces mixed-integer structure and moves the model to BBSYNC.
Integer lots or share quantities. Some portfolios must be constructed using integer quantities rather than arbitrary continuous weights. Share or lot counts can then be represented using integer variables.
Sparse index tracking. Suppose the objective is to reproduce a benchmark while holding only a small subset of its constituents. Tracking error provides a quadratic objective, while the limit on the number of selected securities introduces binary variables. The resulting model is naturally described as an MIQP. Additional quadratic risk restrictions produce MIQCQP structure, but both remain within the BBSYNC mixed-integer solver.
The classical Markowitz model extends naturally to several risk measures at once, and to restrictions that are common in practice: a limit on the number of assets held, and a minimum size for every position that is opened.
Risk now is described by positive semidefinite matrices \(R_1,\dots,R_m\), each with a variance limit \(\rho_k\). To model whether asset \(i\) is held, introduce a binary variable \(z_i\in\{0,1\}\): \(z_i=1\) means that the asset is part of the portfolio, \(z_i=0\) means that its weight is zero. A maximum-return portfolio holding at most \(K\) assets can be written as
\[ \begin{aligned} \max_{x,z} \quad & \mu^T x \\ \text{subject to}\quad & \mathbf{1}^T x = 1, \\ & l z_i \leq x_i \leq u z_i, \\ & \mathbf{1}^T z \leq K, \\ & x^T R_k x \leq \rho_k, \quad k=1,\dots,m, \\ & z_i \in \{0,1\}. \end{aligned} \]The linking constraints \(l z_i \leq x_i \leq u z_i\) do two things. If \(z_i=0\), they force \(x_i=0\). If \(z_i=1\), they keep the weight between the minimum position size \(l\) and the maximum position s\leq 20\%\). Setting \(l=0\) removes the minimum position requirement. The constraint \(\mathbf{1}^T z \leq K\) limits the number of assets held.
Because of the integer variables \(z_i\) and the quadratic constraints, this is a mixed-integer quadratically constrained quadratic programming problem (MIQCQP). It is solved by the MINLP solver with the BBSYNC branch-and-bound algorithm. The maximization is passed to the solver as minimization of \(-\mu^T x\). The objective and the quadratic constraints are evaluated in a callback that also returns their gradients, \(-\mu\) and \(2R_k x\). When all \(R_k\) are positive semidefinite, every relaxation is convex, and the branch-and-bound search returns a globally optimal portfolio. A negative completion code \(-3\) signals that no portfolio satisfies all the restrictions, e.g. whenimits \(\rho_k\) are too tight for any portfolio of at most \(K\) assets.
An example in C# is given below (C++, Java and Python APIs follow the same format):
public static class CardinalityPortfolio
{
// Return-maximizing portfolio with cardinality, minimum position
// and quadratic risk restrictions (MIQCQP):
//
// maximize mu'*x
// subject to sum(x[i]) = 1
// minWeight*z[i] <= x[i] <= maxWeight*z[i]
// sum(z[i]) <= maxAssets
// x'*R[k]*x <= riskLimits[k], k = 0..m-1
// z[i] binary
//
// Solved with the ALGLIB MINLP solver: BBSYNC algorithm.
//
// Inputs:
// mu - expected returns, n
// minWeight - minimum weight of a held asset (0 = no minimum)
// maxWeight - maximum weight of any asset
// maxAssets - maximum number of held assets
// riskCovs - risk matrices R[k], n x n each, at least one
// riskLimits - limits for x'*R[k]*x (variances),
// same length as riskCovs
//
// Outputs:
// weights - portfolio weights x, n
// result - ALGLIB completion code: >0 success,
// -3 infeasible, other <0 failure
public static int Solve(double[] mu, double minWeight, double maxWeight,
int maxAssets, double[][,] riskCovs, double[] riskLimits,
out double[] weights)
{
int n = mu.Length;
int nv = 2 * n;
int m = riskCovs.Length;
// Variables are [x[0..n-1], z[0..n-1]];
// start from equal weights with all assets selected
double[] x0 = new double[nv];
for (int i = 0; i < n; i++)
{
x0[i] = 1.0 / n;
x0[n + i] = 1.0;
}
alglib.minlpsolverstate state;
alglib.minlpsolvercreate(nv, x0, out state);
// Box constraints: 0 <= x[i] <= maxWeight,
// 0 <= z[i] <= 1
double[] bndl = new double[nv];
double[] bndu = new double[nv];
for (int i = 0; i < n; i++)
{
bndu[i] = maxWeight;
bndu[n + i] = 1.0;
}
alglib.minlpsolversetbc(state, bndl, bndu);
// z[i] are integer (binary because of the box) and
// appear only in linear constraints
for (int i = 0; i < n; i++)
alglib.minlpsolversetintkth(state, n + i);
// Linear constraint: sum(x[i]) = 1
double[] row = new double[nv];
for (int i = 0; i < n; i++)
row[i] = 1.0;
alglib.minlpsolveraddlc2sparsefromdense(state, row, 1.0, 1.0);
// Linear constraint: sum(z[i]) <= maxAssets
row = new double[nv];
for (int i = 0; i < n; i++)
row[n + i] = 1.0;
alglib.minlpsolveraddlc2sparsefromdense(state, row,
double.NegativeInfinity, maxAssets);
// Linking constraints: x[i] - maxWeight*z[i] <= 0
// and x[i] - minWeight*z[i] >= 0
for (int i = 0; i < n; i++)
{
row = new double[nv];
row[i] = 1.0;
row[n + i] = -maxWeight;
alglib.minlpsolveraddlc2sparsefromdense(state, row,
double.NegativeInfinity, 0.0);
row = new double[nv];
row[i] = 1.0;
row[n + i] = -minWeight;
alglib.minlpsolveraddlc2sparsefromdense(state, row, 0.0,
double.PositiveInfinity);
}
// Nonlinear constraints: x'*R[k]*x <= riskLimits[k]
double[] nl = new double[m];
double[] nu = new double[m];
for (int k = 0; k < m; k++)
{
nl[k] = double.NegativeInfinity;
nu[k] = riskLimits[k];
}
alglib.minlpsolversetnlc2(state, nl, nu, m);
// All variables are of order 1
double[] scale = new double[nv];
for (int i = 0; i < nv; i++)
scale[i] = 1.0;
alglib.minlpsolversetscale(state, scale);
// BBSYNC with group size 1,
// choose larger group for better parallelism
alglib.minlpsolversetalgobbsync(state, 1);
alglib.minlpsolversetbbsyncsubsolveripm(state, 0);
// Callback: fi[0] = -mu'*x
// (maximization turned into minimization),
// fi[1+k] = x'*R[k]*x;
// gradients are -mu and 2*R[k]*x for x, zero for z
alglib.minlpsolveroptimize(state,
(double[] v, double[] fi, double[,] jac, object obj) =>
{
fi[0] = 0.0;
for (int i = 0; i < n; i++)
{
fi[0] -= mu[i] * v[i];
jac[0, i] = -mu[i];
jac[0, n + i] = 0.0;
}
for (int k = 0; k < m; k++)
{
double[,] q = riskCovs[k];
double f = 0.0;
for (int i = 0; i < n; i++)
{
double qx = 0.0;
for (int j = 0; j < n; j++)
qx += q[i, j] * v[j];
f += v[i] * qx;
jac[1 + k, i] = 2.0 * qx;
jac[1 + k, n + i] = 0.0;
}
fi[1 + k] = f;
}
},
null, null);
// Extract weights x from the solution vector [x, z]
double[] sol;
alglib.minlpsolverreport rep;
alglib.minlpsolverresults(state, out sol, out rep);
weights = new double[n];
for (int i = 0; i < n; i++)
weights[i] = sol[i];
return rep.terminationtype;
}
}
ALGLIB Project offers you two editions of ALGLIB:
ALGLIB Free Edition:
+delivered for free
+offers full set of numerical functionality
+extensive algorithmic optimizations
-no multithreading
-non-commercial license
ALGLIB Commercial Edition:
+flexible pricing
+offers full set of numerical functionality
+extensive algorithmic optimizations
+high performance (SMP, SIMD)
+commercial license with support plan
Links to download sections for Free and Commercial editions can be found below:




