我正在尝试获取多个时期内均值方差投资组合的权重。我的出发点是这段代码:
library(quadprog)
library(tseries)
mu <- colMeans(log.excess.returns[1:61,])
grid <- seq(from = 0.01, to = max(mu), length.out = 61)
vpm <- vpsd <- rep(NA, times = 61)
mweights <- matrix(NA, 61, 40) # 40 stocks
for(i in 1:length(grid)) {
opt <- portfolio.optim(x = log.excess.returns[1:61,], pm = grid[i])
vpm[i] <- opt$pm
vpsd[i] <- opt$ps
mweights[i, ] <- opt$pw
}
minvar_weight <- mweights[vpsd == min(vpsd),]
但是,我只能从此代码中获得下一个周期的最佳权重,因此我尝试为多个周期创建以下函数:
ret.expanding <- lapply(61:nrow(log.excess.returns), function(i) log.excess.returns[1:i,])
opt.portf <- function(returns) {
mu = colMeans(returns)
grid = seq(from = 0.01, to = max(mu), length.out = length(mu))
vpm = vpsd = rep(NA, times = length(mu))
mweights = matrix(NA, length(mu), 40)
for(i in 1:length(grid)) {
opt <- portfolio.optim(returns, pm = grid[i], shorts = TRUE) # shorts = TRUE for the code to work
vpm[i] <- opt$pm
vpsd[i] <- opt$ps
mweights[i, ] <- opt$pw
}
}
weight = sapply(1:192, function(i) opt.portf(ret.expanding[[i]]))
当我检查体重时,它包含192个显示NULL的列表。我怎样才能解决这个问题?