3
我想用R的優化函數構建我自己的優化。使用優化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? – user1234440 2013-05-07 02:41:46