Search code examples
rfinancequantmod

duplicated entries in indices error in optimize.portfolio in PortfolioAnalytics package


When I try to run the optimize.portfolio function using ROI I get the error.

Error in ROI::V_bound(li = seq.int(1L, N), lb = as.numeric(lb), ui = seq.int(1L,  : duplicated entries in indices.

And when I use DEoptim I get.

Error in sample.int(length(x), size, replace, prob) : 
  invalid first argument

When the stock data is collected using getSymbols there's a warning about the length of the returns objects. The research I did suggests this isn't the problem though.

The code I'm using is below. Any help would be appreciated.

library(quantmod)
library(PortfolioAnalytics)
library(DEoptim)
library(ROI)
require(ROI.plugin.glpk)
require(ROI.plugin.quadprog)

symbols <- c("MSFT", "MMM", "AMZN")

e <- new.env() 
getSymbols(symbols, src="yahoo", env=e)
stocks <- do.call(merge, eapply(e, Cl)[symbols])

ret <- diff(log(df))
ret <- ret[2:(nrow(df)),]

portfolio <- portfolio.spec(ret)
portfolio

portfolio <- add.constraint(portfolio = portfolio, type = "weight_sum", min_sum=0.99,max_sum=1.01)
portfolio <- add.constraint(portfolio = portfolio, type = "long_only")
portfolio <- add.objective(portfolio=portfolio, type="risk", name="StdDev")

optimise <- optimize.portfolio(R = ret, portfolio = portfolio, optimize_method = "ROI")

Solution

  • See the help (?portfolio.spec). That function is expecting names or a number. If you use asset names there is no error.

    portfolio <- portfolio.spec(names(ret))