2

I've been handed a CSV file holding returns for 10 industry portfolios based on which I've estimated sample mean returns (mu) and variance-covariance matrix (sigma). Afterwards, I've conducted a simulation of 100 returns for which I've computed plug-in estimates of the efficient frontier and compared this to the "true" frontier based on the CSV returns. This part runs smooth but now I'm asked to repeat the simulation 250 times and visualize all of the simulated efficient frontiers in one plot. The simulation code is quite simple:

simulate_returns <- function(T, sigma, mu){
  set.seed(2021)
  returns <- mvrnorm(T, Sigma = sigma, mu = mu)
  return(returns)
}

sim_returns <- simulate_returns(100, sigma, mu)

Once I have the simulated returns I calculate sigma and mu:

mu_sim <- sim_returns %>%
  colMeans(na.rm = TRUE) %>%
  as.matrix()


sigma_sim <- sim_returns %>% cov(use = "pairwise.complete.obs")

And then use the formula to compute points for the efficient frontier:

compute_efficient_frontier <- function(sigma, mu){
  sigma_inv <- solve(sigma)
  N <- ncol(sigma)
  w_mvp <- sigma_inv %*% rep(1, N) #Compute mvp weights
  w_mvp <- w_mvp/sum(w_mvp)
  return_mvp <- c(t(w_mvp) %*% mu)
  mu_bar = 2 * return_mvp
  iota <- rep(1, ncol(sigma))
  C <- c(t(iota)%*%solve(sigma)%*%iota)
  D <- c(t(iota)%*%solve(sigma)%*%mu)
  E <- c(t(mu)%*%solve(sigma)%*%mu)
  lambda_tilde <- c(2*(mu_bar - D/C)/(E - D^2/C))
  w_eff <- w_mvp + lambda_tilde/2*(solve(sigma)%*%mu-D/C*solve(sigma)%*%iota)
  c <- seq(from = -0.1, to = 1.2, by = 0.01)
  res <- tibble(c = c, mu = NA, sd = NA)
  for(i in seq_along(c)){ # For loop
    w <- (1-c[i])*w_mvp + (c[i])*w_eff # Portfolio of mvp and efficient portfolio
    res$mu[i] <- t(w) %*% mu # Portfolio expected return
    res$sd[i] <- sqrt(t(w) %*% sigma %*% w) # Portfolio volatility
  }
  return(res)
}

frontier2 <- compute_efficient_frontier(sigma_sim, mu_sim)

I need to figure out a way to repeat this 250 times and plot all of the frontiers in a meaningful way. I'm new to R and the coding community; I hope I've provided you with sufficient information and that the post makes sense.

OPFinance
  • 21
  • 2
  • It is hard to help you without example data or at least specifying the parameters you are using in the functions. Additionally, please include the packages you are using and have a look at this: [how-to-make-a-great-r-reproducible-example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – tester Mar 02 '21 at 22:56

0 Answers0