solve.QP出错

问题描述 投票:1回答:1

所以基本上我有两个矩阵,包含股票的超额收益(R)和预期的超额收益(ER)。

R<-matrix(runif(47*78),ncol = 78) 
ER<-matrix(runif(47*78),ncol = 78) 

然后我组合这些去除R的第一行并添加ER的第一行以形成新的矩阵R1。

然后,我为R2执行此操作,即删除前两行和R,并将其与前两行ER重新绑定。

我这样做,直到从R1到R47有n-1个新矩阵。

然后,我使用cov(),即Var-Cov1到Var-Cov47,找到每个返回矩阵的Var-Cov矩阵。

n<-47
switch_matrices <- function(mat1, mat2, nrows){
  rbind(mat1[(1+nrows):nrow(mat1),],mat2[1:nrows,]) 
}

l<-lapply(1:n-1, function(nrows) switch_matrices(R,ER, nrows))
list2env(setNames(l,paste0("R",seq_along(l))), envir = parent.frame())

b<-lapply(l, cov)
list2env(setNames(b,paste0("VarCov",seq_along(b))), envir = parent.frame())

我现在正试图使用​​quadprog找到资产分配。例如:

D_mat <- 2*VarCov1
d_vec <- rep(0,78)
A_mat <- cbind(rep(1,78),diag(78))
b_vec <- c(1,d_vec)

library(quadprog)
output <- solve.QP(Dmat = D_mat, dvec = d_vec,Amat = A_mat, bvec = b_vec,meq =1)
# The asset allocation
(round(output$solution, 4))

由于某些原因,当运行任何Var-Cov矩阵的solve.QP时,我收到此错误:

Error in solve.QP(Dmat = D_mat, dvec = d_vec, Amat = A_mat, bvec = b_vec,  : 
  matrix D in quadratic function is not positive definite!

我想知道我做错了什么,甚至为什么这不起作用。

r optimization matrix var quadprog
1个回答
1
投票

输入矩阵不是positive definite,这是优化算法的必要条件。

为什么你的矩阵不是肯定的将与你的特定数据(真实数据,而不是随机生成的例子)有关,并且将是统计和主题特定问题。

但是,从编程的角度来看,有一种解决方法。我们可以使用nearPD包中的Matrix找到最接近的正定矩阵作为一个可行的替代方案:

# Data generated by code in the question using set.seed(123)
library(quadprog)
library(Matrix)
pd_D_mat <- nearPD(D_mat)

output <- solve.QP(Dmat = as.matrix(pd_D_mat$mat), 
                   dvec = d_vec,
                   Amat = A_mat, 
                   bvec = b_vec,
                   meq  = 1)

# The asset allocation
(round(output$solution, 4))

 [1] 0.0052 0.0000 0.0173 0.0739 0.0000 0.0248 0.0082 0.0180 0.0000 0.0217 0.0177 0.0000 0.0000 0.0053 0.0000 0.0173 0.0216 0.0000
[19] 0.0000 0.0049 0.0042 0.0546 0.0049 0.0088 0.0250 0.0272 0.0325 0.0298 0.0000 0.0160 0.0000 0.0064 0.0276 0.0145 0.0178 0.0000
[37] 0.0258 0.0000 0.0413 0.0000 0.0071 0.0000 0.0268 0.0095 0.0326 0.0112 0.0381 0.0172 0.0000 0.0179 0.0000 0.0292 0.0125 0.0000
[55] 0.0000 0.0000 0.0232 0.0058 0.0000 0.0000 0.0000 0.0143 0.0274 0.0160 0.0000 0.0287 0.0000 0.0000 0.0203 0.0226 0.0311 0.0345
[73] 0.0012 0.0004 0.0000 0.0000 0.0000 0.0000
© www.soinside.com 2019 - 2024. All rights reserved.