use*_*440 7 optimization r genetic-algorithm
几个星期前我问了一个关于如何在R中进行优化的问题(使用Optimize R优化矢量).现在我已经掌握了R中的基本优化,我想开始使用GA来解决解决方案.
鉴于目标函数:
div.ratio <- function(weight, vol, cov.mat){
weight <- weight / sum(weight)
dr <- (t(weight) %*% vol) / (sqrt(t(weight) %*% cov.mat %*% (weight)))
return(-dr)
}
Run Code Online (Sandbox Code Playgroud)
我正在使用genalg包进行优化,特别是"rbga.bin"函数.但事情是似乎无法传递多个参数,即无法传递vol和cov.mat.我错过了什么或理解错误.
编辑:在genalg包中,有一个名为rbga.bin的函数,我正在使用它.
以下是上一个问题的简单代码,可以帮助您入门:
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]
ret<-na.omit(prices/mlag(prices) - 1)
vol<-apply(ret,2,sd)
cov.mat<-cov(ret)
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) #optimal weights
Run Code Online (Sandbox Code Playgroud)
虽然上面的优化函数工作得很好,但我在想是否可以使用GA算法重现它.所以将来,如果我正在寻找多个目标,那么与GA相比,我将能够更快地做到这一点.(我不确定它是否更快,但这是要找出来的步骤)
GAmodel <- rbga.bin(size = 7, #genes
popSize = 200, #initial number of chromosomes
iters = 100, #number of iterations
mutationChance = 0.01, #chance of mutation
evalFunc = div.ratio) #objective function
Run Code Online (Sandbox Code Playgroud)
执行上述操作似乎会产生错误,因为div.ratio需要额外的参数,所以我正在寻找一些帮助来构造我的问题,以便它能够产生最佳答案.我希望以上编辑澄清事情.
谢谢
这就是你需要的:
GAmodel <- rbga(stringMin=rep(0, length(vol)), stringMax=rep(1, length(vol)),
popSize = 200,
iters = 100,
mutationChance = 0.01,
evalFunc = function(weight) div.ratio(weight, vol=vol, cov.mat=cov.mat))
Run Code Online (Sandbox Code Playgroud)
(见上面的第一行和最后一行).
问题是:
向量weight,vol必须匹配长度.
evalFunc使用单个参数调用函数,导致其他函数丢失.据我所知,你只想优化weight矢量,保持vol和cov.mat修复.
如果您希望weight被视为连续变量,请rbga改用.