How can I repeat a simulation a function 250 times?

168 views Asked by At

I am trying to simulate a hypothetical stock return. This has been done using:

set.seed(1)

simulate_returns <- function(T) {
  sim_return <- MASS::mvrnorm(n = T, mu = mu, Sigma = sigma)
  sim_return <- as_tibble(sim_return)
  
  return(sim_return)
}

I am now interested in repeating this simulation 250 times and find mean and variance for each of the 250 data frames, and this has to be written out with ggplot.

I have made this loop, but it doesn't seem to work:

simulate_loop[i] <- for (i in 1:250) {
  
  sigma[i] <- simulate_returns(100) %>%
    cov(use = "pairwise.complete.obs") # Compute return sample covariance matrix %>% 
  
  mu[i] <- simulate_returns(100) %>% 
    colMeans() %>% 
    as.matrix() 

  simu_loop[i] <- compute_efficient_frontier(mu[i], sigma[i])

}  
1

There are 1 answers

1
ThomasIsCoding On

I think what you are after is something like this, where simu_loop <- c() initialize simu_loop outsides for loop.

simu_loop <- c()

for (i in 1:250) {
  x <- simulate_returns(100)

  sigma[i] <- x %>%
    cov(use = "pairwise.complete.obs") # Compute return sample covariance matrix %>%

  mu[i] <- x %>%
    colMeans() %>%
    as.matrix()

  simu_loop[i] <- compute_efficient_frontier(mu[i], sigma[i])

}