使用Optimize R优化向量

时间:2013-05-07 02:40:16

标签: r optimization

我想使用R的优化函数构建自己的优化。

目标函数是多样化比率,以最大化它(希望它是正确的):

div.ratio<-function(weight,vol,cov.mat){
  dr<-(t(weight) %*% vol) / (sqrt(t(weight) %*% cov.mat %*% (weight)))  
  return(-dr)
}

一个例子:

rm(list=ls())
require(RCurl)
sit = getURLContent('https://github.com/systematicinvestor/SIT/raw/master/sit.gz',     binary=TRUE, followlocation = TRUE, ssl.verifypeer = FALSE)
con = gzcon(rawConnection(sit, 'rb'))
source(con)
close(con)
load.packages('quantmod')


data <- new.env()

tickers<-spl("VTI,VGK,VWO,GLD,VNQ,TIP,TLT,AGG,LQD")
getSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T)
for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)

bt.prep(data, align='remove.na', dates='1990::2013')

prices<-data$prices[,-10]  #don't include cash
ret<-na.omit(prices/mlag(prices) - 1)
vol<-apply(ret,2,sd)
cov.mat<-cov(ret)

optimize(div.ratio,
     weight,
     vol=vol,
     cov.mat=cov.mat,
     lower=0, #min constraints
     upper=1, #max 
     tol = 0.00001)$minimum 

我收到以下错误消息,似乎是优化包不进行矢量优化。我做错了什么?

Error in t(weight) %*% cov.mat : non-conformable arguments

1 个答案:

答案 0 :(得分:9)

首先,weight没有理由参与优化调用,如果这是您要优化的内容。 然后,当您尝试求解权重向量时,optimize用于一维优化。您可以改用optim函数。

关于评论中的第二个问题,如何为函数设置一个总和为1的约束?您可以使用此处提出的技巧:How to set parameters' sum to 1 in constrained optimization,即重写您的目标函数,如下所示:

div.ratio <- function(weight, vol, cov.mat){
  weight <- weight / sum(weight)
  dr <- (t(weight) %*% vol) / (sqrt(t(weight) %*% cov.mat %*% (weight)))  
  return(-dr)
}

这给出了:

out <- optim(par     = rep(1 / length(vol), length(vol)),  # initial guess
             fn      = div.ratio,
             vol     = vol,
             cov.mat = cov.mat,
             method  = "L-BFGS-B",
             lower   = 0,
             upper   = 1)

您的最佳体重:

opt.weights <- out$par / sum(out$par)
# [1] 0.154271776 0.131322307 0.073752360 0.030885856 0.370706931 0.049627627
# [7] 0.055785740 0.126062746 0.007584657

pie(opt.weights, names(vol))

enter image description here