如果可能,我会尽量避免使用 for 循环。这是整个代码,矩阵的数据只是百分比。
x.r = read.zoo("Matrix.csv", header=F, sep = ",", format = "%m/%d/%Y")
yrs = 5
niter = nrow(x.r)-yrs*52+1
N = ncol(x.r)
x.r.w = matrix(0,nrow=niter,ncol=N)
for (i in 1:niter) {
x.r.sub = x.r[i:(i+yrs*52-1),]
covar = cov.shrink(x.r.sub)
zeros = array(0, dim = c(N,1))
aMat = t(array(1, dim = c(1,N)))
res = solve.QP(covar, zeros, aMat, bvec=1, meq = 1)
x.r.w[i,] = res$solution
}
我已在此链接中上传了 Matrix.csv 中的部分数据