本文介绍了使用Optimize R优化向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用R的优化函数构造自己的优化.

I want to construct my own optimization using R's optimization function.

目标函数是分散率,以使其最大化(希望其正确):

The objective function is the diversification ratio, to maximize it (hope its correct):

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 

我收到以下错误消息,似乎是优化程序包没有进行矢量优化.我做错了什么?

I get the following error message which seems to be it that optimization package doesn't do vector optimization. What did I do wrong?

Error in t(weight) %*% cov.mat : non-conformable arguments

推荐答案

首先,如果您要进行优化,则weight没有理由进入Optimize调用.然后,optimize用于一维优化,同时您尝试求解权重向量.您可以改为使用optim函数.

First of all, weight has no reason to be in the optimize call if that's what you are trying to optimize.Then, optimize is for one-dimensional optimization while you are trying to solve for a vector of weights. You could use the optim function instead.

关于注释中的第二个问题,如何为函数设置一个总和为1的约束?您可以使用此处提出的技巧:如何在约束优化中将参数的总和设置为1 ,即按如下所示重写目标函数:

Regarding your second question in the comments, how do you set a constraint that it sums to 1 for the function? You can use the trick proposed here: How to set parameters' sum to 1 in constrained optimization, i.e, rewrite your objective function as follows:

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))

这篇关于使用Optimize R优化向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 09:43