Skip to content
Prev 14879 / 15274 Next

Using optimize.portfolio

Thank you Brian and Alexios.  In case anyone is interested, here is the
code that produces the exact same results for all five methods:

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)
LB <- rep(0, ncol(returns))
UB <- rep(1, ncol(returns))
popt <- portfolio.optim(x = returns, covmat = sigma, reslow = LB, reshigh =
UB)

library(parma)
# optimal reward to risk (covariance matrix)
parmspec <- parmaspec(S = cov(returns), risk = "EV", forecast =
colMeans(returns), riskType = "minrisk", LB = LB, UB = UB, target =
mean(returns))
parm <- parmasolve(parmspec)

library(PortfolioAnalytics)
simple.moments <- function(R, ...) {
  num_assets = ncol(R)
  out <- list()
  out$mu <- matrix(colMeans(R), ncol = 1)
  out$sigma <- cov(R, use = "pairwise.complete.obs")
  # out$m3 <- PerformanceAnalytics:::M3.MM(R)
  # out$m4 <- PerformanceAnalytics:::M4.MM(R)
  out$m3 <- matrix(0, nrow = num_assets, ncol = num_assets^2)
  out$m4 <- matrix(0, nrow = num_assets, ncol = num_assets^3)
  out
}

num_assets = ncol(returns)
momentargs <- list()
momentargs$mu <- matrix(colMeans(returns), ncol = 1)
momentargs$sigma <- cov(returns, use = "pairwise.complete.obs")
momentargs$m3 <- matrix(0, nrow = num_assets, ncol = num_assets^2)
momentargs$m4 <- matrix(0, nrow = num_assets, ncol = num_assets^3)

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")
pspec <- add.constraint(portfolio=pspec, type = "return", return_target =
mean(returns))

opt      <- optimize.portfolio(R = returns, portfolio = pspec,
optimize_method = "ROI")
opt.fun  <- optimize.portfolio(R = returns, portfolio = pspec,
optimize_method = "ROI", momentFUN = "simple.moments")
opt.args <- optimize.portfolio(R = returns, portfolio = pspec,
optimize_method = "ROI", momentargs = momentargs)
data.frame(opt.portf = round(opt$weights, 3),
           opt.portf.fun = round(opt.fun$weights, 3),
           opt.portf.args = round(opt.args$weights, 3),
           portfolio.optim = round(popt$pw, 3),
           parma = round(weights(parm), 3))


On Sun, Jun 7, 2020 at 8:59 PM Brian G. Peterson <brian at braverock.com>
wrote: