[R-SIG-Finance] Using optimize.portfolio

Roger Bos roger@bo@ @end|ng |rom gm@||@com
Fri Jun 5 20:16:08 CEST 2020


All,

I am comparing optimize.portfolio from the PortfolioAnalytics package to
portfolio.optim from the tseries package.  portfolio.optim seems a bit
easier to use, but I like the set up of optimize.portfolio.  I have created
a minimal reprex below that compares the output of both in case that helps
answer my questions.
Here are my two primary questions:

1) What if I wanted to pass a custom covariance matrix to
optimize.portfolio, like from a risk model.  Is that possible?  I can pass
it to portfolio.optim because covmat is one of the parameters.
2) What if I wanted to pass forecasted returns to optimize.portfolio?  How
would that be done.

If there is anything that can be improved in this example, that would be
helpful as well.  Thank you in advance for any assistance, Roger.

###

library(PortfolioAnalytics)
library(tidyquant)

symbols <-
c("MSFT","AAPL","AMZN","NVDA","CSCO","ADBE","AMGN","ORCL","QCOM","GILD")

getYahooReturns <- function(symbols, return_column = "Ad") {
  returns <- list()
  for (symbol in symbols) {
    getSymbols(symbol, from = '2000-01-01', adjustOHLC = TRUE, env =
.GlobalEnv, auto.assign = TRUE)
    return <- Return.calculate(Ad(get(symbol)))
    colnames(return) <- gsub("\\.Adjusted", "", colnames(return))
    returns[[symbol]] <- return
  }
  returns <- do.call(cbind, returns)
  return(returns)
}

returns <- getYahooReturns(symbols)
returns <- returns[-1, ]
returns[is.na(returns)] <- 0

# portfolio.optim from tseries package
library(tseries)
sigma <- cov(returns)
reslow <- rep(0, ncol(returns))
reshigh <- rep(1, ncol(returns))
popt <- portfolio.optim(x = returns, covmat = sigma, reslow = reslow,
reshigh = reshigh)
popt$pw

pspec <- portfolio.spec(assets = symbols)
pspec <- add.constraint(portfolio=pspec, type="box",
                    min = 0, max = 1, min_sum = 0.99, max_sum = 1.01)
pspec <- add.objective(portfolio=pspec,
                       type="return",
                       name="mean")
pspec <- add.objective(portfolio=pspec,
                       type="risk",
                       name="var")

opt <- optimize.portfolio(R = returns,
                   portfolio = pspec,
                   optimize_method = "DEoptim", )
data.frame(optimize.portfolio = opt$weights, portfolio.optim =
round(popt$pw, 3))

	[[alternative HTML version deleted]]



More information about the R-SIG-Finance mailing list