Initializing help system before first use

# QP

To adapt the model developed in Chapter Building models to the new way of looking at the problem, we need to make the following changes:

- New objective function: mean variance instead of total return
- Removal of the risk-related constraint
- Addition of a new constraint: target yield

The new objective function is the mean variance of the portfolio:

∑s,t ∈ SHARES VARst·fracs ·fract

where VARst is the variance/covariance matrix of all shares. This is a quadratic objective function (an objective function becomes quadratic either when a variable is squared, e.g., frac12, or when two variables are multiplied together, e.g., frac1 · frac2).

The target yield constraint can be written as follows:

∑s ∈ SHARES RETs·fracs ≥ TARGET

The limit on the North American shares, as well as the requirement to spend all of the money and the upper bounds on the fraction invested into each share, are retained. We therefore obtain the following complete mathematical model formulation:

minimize ∑s,t ∈ SHARES VARst·fracs ·fract
∑s ∈ NA fracs ≥ 0.5
∑s ∈ SHARES fracs = 1
∑s ∈ SHARES RETs·fracs ≥ TARGET
∀ s ∈ SHARES: 0 ≤ fracs ≤ 0.3

## Implementation with Java

The estimated returns and the variance/covariance matrix are given in the data file foliocppqp.dat:

    ! trs  haw  thr  tel  brw  hgw  car  bnk  sof  elc
    0.1    0    0    0    0    0    0    0    0    0 ! treasury
      0   19   -2    4    1    1    1  0.5   10    5 ! hardware
      0   -2   28    1    2    1    1    0   -2   -1 ! theater
      0    4    1   22    0    1    2    0    3    4 ! telecom
      0    1    2    0    4 -1.5   -2   -1    1    1 ! brewery
      0    1    1    1 -1.5  3.5    2  0.5    1  1.5 ! highways
      0    1    1    2   -2    2    5  0.5    1  2.5 ! cars
      0  0.5    0    0   -1  0.5  0.5    1  0.5  0.5 ! bank
      0   10   -2    3    1    1    1  0.5   25    8 ! software
      0    5   -1    4    1  1.5  2.5  0.5    8   16 ! electronics

We can read this datafile with the function readData: all comments preceded by ! and also empty lines are skipped.

For the definition of the objective function we now use a quadratic expression (equally represented by the class QuadExpression). Since we now wish to minimize the problem, we use the default optimization sense setting, and optimization as a continuous problem is again started with the method optimize (with an empty string argument indicating the default algorithm).

    import static com.dashoptimization.objects.Utils.scalarProduct;
    import static com.dashoptimization.objects.Utils.sum;
    import static java.util.stream.IntStream.range;

    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StreamTokenizer;

    import com.dashoptimization.ColumnType;
    import com.dashoptimization.DefaultMessageListener;
    import com.dashoptimization.XPRSenumerations.ObjSense;
    import com.dashoptimization.objects.QuadExpression;
    import com.dashoptimization.objects.Variable;
    import com.dashoptimization.objects.XpressProblem;

    /**
     * Modeling a small QP problem to perform portfolio optimization. -- 1. QP:
     * minimize variance 2. MIQP: limited number of assets ---
     */
    public class FolioQP {
        /* Path to Data file */
        private static final String DATAFILE = "foliocppqp.dat";
        /* Target yield */
        private static final int TARGET = 9;
        /* Max. number of different assets */
        private static final int MAXNUM = 4;
        /* Number of shares */
        private static final int NSHARES = 10;
        /* Number of North-American shares */
        private static final int NNA = 4;
        /* Estimated return in investment */
        private static final double[] RET = new double[] { 5, 17, 26, 12, 8, 9, 7, 6, 31, 21 };
        /* Shares issued in N.-America */
        private static final int[] NA = new int[] { 0, 1, 2, 3 };
        /* Variance/covariance matrix of estimated returns */
        private static double[][] VAR;

        private static void readData() throws IOException {
            int s, t;
            FileReader datafile = null;
            StreamTokenizer st = null;

            VAR = new double[NSHARES][NSHARES];

            /* Read `VAR' data from file */
            datafile = new FileReader(DATAFILE); /* Open the data file */
            st = new StreamTokenizer(datafile); /* Initialize the stream tokenizer */
            st.commentChar('!'); /* Use the character '!' for comments */
            st.eolIsSignificant(true); /* Return end-of-line character */
            st.parseNumbers(); /* Read numbers as numbers (not strings) */

            for (s = 0; s < NSHARES; s++) {
                do {
                    st.nextToken();
                } while (st.ttype == StreamTokenizer.TT_EOL); /* Skip empty and comment lines */
                for (t = 0; t < NSHARES; t++) {
                    if (st.ttype != StreamTokenizer.TT_NUMBER)
                        break;
                    VAR[s][t] = st.nval;
                    st.nextToken();
                }
            }
            datafile.close();
        }

        private static void printProblemStatus(XpressProblem prob) {
            System.out.println(String.format("Problem status:%n\tSolve status: %s%n\tSol status:
                    %s", prob.attributes().getSolveStatus(), prob.attributes().getSolStatus()));
        }

        public static void main(String[] args) throws IOException {
            readData();
            try (XpressProblem prob = new XpressProblem()) {
                // Output all messages.
                prob.callbacks.addMessageCallback(DefaultMessageListener::console);

                /***** First problem: unlimited number of assets *****/

                /**** VARIABLES ****/
                Variable[] frac = prob.addVariables(NSHARES)
                        /* Fraction of capital used per share */
                        .withName(i -> String.format("frac_%d", i))
                        /* Upper bounds on the investment per share */
                        .withUB(0.3).toArray();

                /**** CONSTRAINTS ****/
                /* Minimum amount of North-American values */
                prob.addConstraint(sum(NNA, i -> frac[NA[i]]).geq(0.5).setName("NA"));

                /* Spend all the capital */
                prob.addConstraint(sum(frac).eq(1.0).setName("Cap"));

                /* Target yield */
                prob.addConstraint(scalarProduct(frac, RET).geq(TARGET).setName("TargetYield"));

                /* Objective: minimize mean variance */
                QuadExpression variance = QuadExpression.create();
                range(0, NSHARES).forEach(s -> range(0, NSHARES).forEach(
                        /* v * fs * ft */
                        t -> variance.addTerm(frac[s], frac[t], VAR[s][t])));
                prob.setObjective(variance, ObjSense.MINIMIZE);

                /* Solve */
                prob.optimize();

                /* Solution printing */
                printProblemStatus(prob);
                System.out.println("With a target of " + TARGET + " minimum variance is "
                        + prob.attributes().getObjVal());
                double[] sollp = prob.getSolution();
                range(0, NSHARES).forEach(i -> System.out
                        .println(String.format("%s : %.2f%s", frac[i].getName(),
                                 100.0 * frac[i].getValue(sollp), "%")));
            }
        }
    }

This program produces the following solution output with a eight-core processor (notice that the default algorithm for solving QP problems is Newton-Barrier, not the Simplex as in all previous examples):

    FICO Xpress v9.5.0, Hyper, solve started 15:41:25, Jan 22, 2025
    Heap usage: 390KB (peak 390KB, 100KB system)
    Minimizing QP  using up to 20 threads and up to 31GB memory, with default controls
    Original problem has:
             3 rows           10 cols           24 elements
            76 qobjelem
    Presolved problem has:
             3 rows           10 cols           24 elements
            76 qobjelem
    Presolve finished in 0 seconds
    Heap usage: 393KB (peak 403KB, 100KB system)

    Coefficient range                    original                 solved
      Coefficients   [min,max] : [ 1.00e+00,  3.10e+01] / [ 6.25e-02,  7.50e-01]
      RHS and bounds [min,max] : [ 3.00e-01,  9.00e+00] / [ 5.00e-01,  4.80e+00]
      Objective      [min,max] : [      0.0,       0.0] / [      0.0,       0.0]
      Quadratic      [min,max] : [ 2.00e-01,  5.60e+01] / [ 7.81e-03,  6.88e-01]
    Autoscaling applied standard scaling

    Using AVX2 support
    Cores per CPU (CORESPERCPU): 20
    Barrier starts after 0 seconds, using up to 20 threads, 14 cores
    Matrix ordering - Dense cols.:      9   NZ(L):        92   Flops:          584

      Its   P.inf      D.inf      U.inf      Primal obj.     Dual obj.      Compl.
       0   9.07e+00   3.18e+00   5.90e+00   2.8650781e+01  -5.6250781e+01   8.7e+01
       1   7.52e-02   2.60e-02   4.89e-02   2.3780436e+00  -6.3182640e+00   8.8e+00
       2   1.08e-02   3.74e-03   7.05e-03   9.7212114e-01  -1.0512412e+00   2.0e+00
       3   5.18e-08   9.99e-15   8.88e-16   6.5980420e-01   1.9437253e-01   4.7e-01
       4   6.01e-09   1.11e-15   2.22e-16   5.7053744e-01   5.0396352e-01   6.7e-02
       5   1.29e-10   4.44e-16   8.88e-16   5.5898011e-01   5.5539393e-01   3.6e-03
       6   2.55e-14   2.22e-16   8.88e-16   5.5755958e-01   5.5726942e-01   2.9e-04
       7   1.92e-16   4.44e-16   2.22e-16   5.5740317e-01   5.5738209e-01   2.1e-05
       8   1.91e-16   5.55e-17   2.22e-16   5.5739342e-01   5.5739323e-01   1.9e-07
    Barrier method finished in 0 seconds
    Uncrunching matrix
    Optimal solution found
    Barrier solved problem
      8 barrier iterations in 0.01 seconds at time 0

    Final objective                       : 5.573934236206229e-01
      Max primal violation      (abs/rel) : 3.415e-17 / 3.415e-17
      Max dual violation        (abs/rel) :       0.0 /       0.0
      Max complementarity viol. (abs/rel) : 1.741e-07 / 2.487e-08
    Problem status:
    	Solve status: Completed
    	Sol status: Optimal
    With a target of 9 minimum variance is 0.5573934236206229
    frac_0 : 30.00%
    frac_1 : 7.15%
    frac_2 : 7.38%
    frac_3 : 5.46%
    frac_4 : 12.66%
    frac_5 : 5.91%
    frac_6 : 0.33%
    frac_7 : 30.00%
    frac_8 : 1.10%
    frac_9 : 0.00%

Parent Topic Quadratic Programming

© 2001-2026 Fair Isaac Corporation. All rights reserved. This documentation is the property of Fair Isaac Corporation (“FICO”). Receipt or possession of this documentation does not convey rights to disclose, reproduce, make derivative works, use, or allow others to use it except solely for internal evaluation purposes to determine whether to purchase a license to the software described in this documentation, or as otherwise set forth in a written software license agreement between you and FICO (or a FICO affiliate). Use of this documentation and the software described in it must conform strictly to the foregoing permitted uses, and no other use is permitted.