5

我想使用 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
4

1 回答 1

10

首先,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))

在此处输入图像描述

于 2013-05-07T03:08:00.147 回答