Using optimize.portfolio
On Sat, 2020-06-06 at 14:33 +0200, Enrico Schumann wrote:
On Fri, 05 Jun 2020, Roger Bos writes:
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","G
ILD")
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))
If all else fails, and supposing that 'PortfolioAnalytics' per default computes means and covariances in the standard way, you could create input data (time series) that have exactly the desired covariances and means: https://stackoverflow.com/questions/58293991/how-to-use-fportfolio-package-in-r-for-non-time-series-input/58302451#58302451
per default, PortfolioAnalytics uses sample moments as most users would expect. As I already told the OP, the user may pass mu and sigma and m3 and m4 directly, or may construct custom moment functions to compute the moments using any method they choose. This is outlined in section 2 of the vignette: https://cran.r-project.org/web/packages/PortfolioAnalytics/vignettes/custom_moments_objectives.pdf and, of course, in the manual.