0

I cannot figure out what I am doing wrong with this portfolio optimization (find optimal weights) using quadprog in numeric.js

My portfolio constraints are simple: weights should sum up to 1 and all weights (for each of the 3 assets) should be between 0 and 1 (no short selling, no leverage). Constraints are not recognized and weights get very high (and also negative).

    var constraintsmatrix = [[0,0,0,0], [1,0,1,0], [1,0,0,0]]; 
    var covmatrix = [[0.00020817,0.00016281,0.00009747],[0.00016281,0.00026680,0.00009912],[0.00009747,0.00009912,0.00019958]]; 
    var returnsmatrix = [0.1,0.05,0.1];
    var bvec = 1; // [1,0,0,0,0,0,0,1,1,1];
    var result = numeric.solveQP(covmatrix, returnsmatrix, constraintsmatrix, bvec);

Any hint appreciated. Thanks

chriscross
  • 413
  • 5
  • 18

1 Answers1

1

I believe your constraints are not correctly specified and the rhs is not passed on. We want the following constraints (equality first):

x1+x2+x3 = 1
x1 >= 0
x2 >= 0
x3 >= 0

This corresponds to

A=[[1,1,0,0],[1,0,1,0],[1,0,0,1]]
b=[1,0,0,0]

Here is what I get:

enter image description here

Note that the objective of this model is 0.5*x'Dx-d'x. Also note I pass on 5 arguments to solveQP.

Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39
  • Thanks for your solution -great! It works but I do not understand it (cannot apply it for more than three assets). Number of elements in b are the number of constraints right? So if I want to add constraint that no weight can be above 0.5 I would add that to b ( b = [1,0,0,0,0.5,0.5,0,5] ). A contains one array for each asset (currently 3), right? For each asset it sets 0 or 1 (active) for the corresponding constraint in b. A =[[1,1,0,0,1,0,0],[1,0,1,0,0,1,0],[1,0,0,1,0,0,1]]. This does not work. An example with 4 assets and one more constraint per asset would help me understand better. – chriscross Feb 26 '16 at 13:20
  • Figured out the constraints issue: A =[[1,1,0,0,-1,0,0],[1,0,1,0,0,-1,0],[1,0,0,1,0,0,-1]]; and b = [1,0,0,0,-0.4,-0.4,-0.4]; for lower boundary of 0 and upper boundary of 0.4 for each asset. meq hast to be 3 then. – chriscross Feb 26 '16 at 14:35
  • No. Meq is the number of equality constraints. – Erwin Kalvelagen Feb 26 '16 at 14:50
  • Inequalities of the form x <= a need to be transformed to -x >= -a. – Erwin Kalvelagen Feb 26 '16 at 15:05
  • meq = 1. Thanks. Still, I am doing something wrong for the four asset case ("..constraints are inconsistent.."). b = [1,0,0,0,0,-0.8,-0.8,-0.8,-0.8]; A = [ [1,1,0,0,0,-1,0,0,0], [1,0,1,0,0,0,-1,0,0], [1,0,0,1,0,0,0,-1,0], [1,0,0,0,1,0,0,0,-1]]; meq = 1 – chriscross Feb 26 '16 at 15:46
  • 1
    I see some differences in behavior between the javascript version of QuadProg and the R version (both based on the same algorithm). May be the javascript version needs some more testing. – Erwin Kalvelagen Feb 26 '16 at 22:09