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