2013-05-07 210 views
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 
+0

另外你如何設置一個約束,它的功能總和爲1? – user1234440 2013-05-07 02:41:46

回答

8

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