-1

I am trying to perform a portfolio optimization (mean-variance) in R. However, I get the following error:

"Error in solve.QP(Dmat, dvec, Amat, bvec, meq = 2) : matrix D in quadratic function is not positive definite!"

I have four contraints:

  1. Expected return of 4.8%
  2. Weights add up to 1
  3. No shorting
  4. Individual weights <0.7

Below is my code:

library(quadprog)
library(readxl)

#Input data 
rnd_m <- read_excel("AssetData.xlsx", sheet = "Tabelle3")
ast_nr <- ncol(rnd_m) #number of assets

#Covariance Matrix
Dmat <- cov(rnd_m)

#Expected Returns Vector used for optimization
dvec <- matrix(colMeans(rnd_m), nrow=ast_nr, ncol=1)

#Constraints of optimization
A.Equality <- matrix(rep(1,ast_nr), ncol=1) 
Amat <- cbind(A.Equality, dvec, diag(ast_nr), -diag(ast_nr))
bvec <- c(1, 4.8, rep(0, ast_nr), rep(-0.7, ast_nr)) 

qp <- solve.QP(Dmat, dvec, Amat, bvec, meq=2)

The input data is a data.frame with 10,000 rows (returns data) and 10 columns (assets).

Thank you very much in advance for your help!!!

EDIT: Since I cannot use solve.QP, I tried it with ipop (kernlab) but I am having difficulties Setting up the arguments correctly. I still need l, u and r.

#Input data
rnd_m <- read_excel("AssetData.xlsx", sheet = "Tabelle3")
ast_nr <- ncol(rnd_m)

#Covariance Matrix
H <- cov(rnd_m)

#Expected Returns Vector
c <- colMeans(rnd_m)

#Constraints 
A.Equality <- matrix(rep(1,ast_nr), ncol=1) 
A <- cbind(A.Equality, c, diag(ast_nr), -diag(ast_nr))
b <- c(1, 1, rep(0, ast_nr), rep(-0.7, ast_nr)) 

qp <- ipop(c, H, A, b)
Algebro1000
  • 161
  • 9

2 Answers2

1

The first thing is to check your data and the eigenvalues of the covariance matrix.

It is rare but possible that the covariance matrix is not positive semi-definite. I only have seen this in cases where the number of assets exceeds the number of observations (link). In your case I would probably perturb the covariance matrix a little bit: add small numbers to the diagonal. Some solvers do this automatically.

Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39
1

Still you cannot find the positive semi definite matrix, I recommend nearest_spd() function, which finds the nearest positive semi definite matrix.

Martin Gal
  • 16,640
  • 5
  • 21
  • 39
momo
  • 11
  • 1