在StackOverflow的贡献者的帮助下,我成功地组合了一个函数来推导出一个2资产组合的权重,该组合使夏普比率最大化。不允许卖空,权重之和为1。我现在想做的是限制资产A不超过或小于10%作为一个例子,我想限制资产A的权重不低于54%或超过66%(即60% +/- 10%)。因此,在下面的示例中,我将以(0.54,0.66)而不是无约束的(0.243,0.7570).我假设这可以通过调整bVect来完成,但我不太确定如何去做。任何帮助都将不胜感激。
asset_A <- c(0.034320510,-0.001209628,0.031900161,0.023163947,-0.001872938,-0.010322489,0.006090395,-0.003270854,0.017778990,0.017204915)
asset_B <- c(0.047103261,0.055175057,0.021019816,0.020602347,0.007281368,-0.006547404,0.019155238,0.005494798,0.025429958,0.014929124)
require(quadprog)
HR_solve <- function(asset_A,asset_B) {
vol_A <- sd(asset_A)
vol_B <- sd(asset_B)
cor_AB <- cor(cbind(asset_A,asset_B),method="pearson")
ret_A_B <- as.matrix(c(mean(asset_A),mean(asset_B)))
vol_AB <- c(vol_A,vol_B)
covmat <- diag(as.vector(vol_AB))%*%cor_AB%*%diag(as.vector(vol_AB))
aMat <- cbind(rep(1,nrow(covmat)),diag(1,nrow(covmat)))
bVec <- c(1,0,0)
zeros <- array(0, dim = c(nrow(covmat),1))
minw <- solve.QP(covmat, zeros, aMat, bVec, meq = 1 ,factorized = FALSE)$solution
rp <- as.numeric(t(minw) %*% ret_A_B)
sp <- sqrt(t(minw) %*% covmat %*% minw)
wp <- t(matrix(minw))
sret <- sort(seq(t(minw) %*% ret_A_B,max(ret_A_B),length.out=100))
aMatt <- cbind(ret_A_B,aMat)
for (ri in sret[-1]){
bVect <- c(ri,bVec)
result <- tryCatch({solve.QP(covmat, zeros, aMatt, bVect, meq = 2,factorized = FALSE)},
warning = function(w){ return(NULL) } , error = function(w){ return(NULL)}, finally = {} )
if (!is.null(result)){
wp <- rbind(wp,as.vector(result$solution))
rp <-c(rp,t(as.vector(result$solution) %*% ret_A_B))
sp <- c(sp,sqrt(t(as.vector(result$solution)) %*% covmat %*% as.vector(result$solution))) }
}
HR_weights <- wp[which.max(rp/sp),]
as.matrix(HR_weights)
}
HR_solve(asset_A,asset_B)
[,1]
[1,] 0.2429662
[2,] 0.7570338
字符串
3条答案
按热度按时间e0bqpujr1#
我想你应该看看下面的链接。
http://economistatlarge.com/portfolio-theory/r-optimized-portfolio/r-code-graph-efficient-frontier
我想你会从中学到很多东西。我会在这里发布代码,以防链接在未来的某个时候关闭。
字符串
qrjkbowd2#
好吧,我已经找到了一种方法来做到这一点.
字符串
11dmarpk3#
只需更改aMat和bVec:
字符串