<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/monte-carlo-part-two/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2018/06/13/monte-carlo-part-two/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p> <br>
<br>


<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>



</p>
<p>In a <a rel="nofollow" href="https://rviews.rstudio.com/2018/06/05/monte-carlo/" target="_blank">previous post</a>, we reviewed how to set up and run a Monte Carlo (MC) simulation of future portfolio returns and growth of a dollar. Today, we will run that simulation many, many, times and then visualize the results.</p>
<p>Our ultimate goal is to build a Shiny app that allows an end user to build a custom portfolio, simulate returns, and visualize the results. If you just can’t wait, a link to the final Shiny app is available <a rel="nofollow" href="http://www.reproduciblefinance.com/shiny/monte-carlo-simulation/" target="_blank">here</a>.</p>
<p>This post builds off the work we did previously. I won’t go through the logic again, but the code for building a portfolio, calculating returns, mean and standard deviation of returns, and using them for a simulation is here:</p>
<pre><code>library(tidyquant)
library(tidyverse)
library(timetk)
library(broom)
library(highcharter)

symbols &lt;- c(&quot;SPY&quot;,&quot;EFA&quot;, &quot;IJS&quot;, &quot;EEM&quot;,&quot;AGG&quot;)

prices &lt;- 
  getSymbols(symbols, src = 'yahoo', 
             from = &quot;2012-12-31&quot;,
             to = &quot;2017-12-31&quot;,
             auto.assign = TRUE, warnings = FALSE) %>% 
  map(~Ad(get(.))) %>%
  reduce(merge) %>% 
  `colnames&lt;-`(symbols)

w &lt;- c(0.25, 0.25, 0.20, 0.20, 0.10)

asset_returns_long &lt;-  
  prices %>% 
  to.monthly(indexAt = &quot;lastof&quot;, OHLC = FALSE) %>% 
  tk_tbl(preserve_index = TRUE, rename_index = &quot;date&quot;) %>%
  gather(asset, returns, -date) %>% 
  group_by(asset) %>%  
  mutate(returns = (log(returns) - log(lag(returns)))) %>% 
  na.omit()

portfolio_returns_tq_rebalanced_monthly &lt;- 
  asset_returns_long %>%
  tq_portfolio(assets_col  = asset, 
               returns_col = returns,
               weights     = w,
               col_rename  = &quot;returns&quot;,
               rebalance_on = &quot;months&quot;)

mean_port_return &lt;- 
  mean(portfolio_returns_tq_rebalanced_monthly$returns)

stddev_port_return &lt;- 
  sd(portfolio_returns_tq_rebalanced_monthly$returns)


simulation_accum_1 &lt;- function(init_value, N, mean, stdev) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev))) %>% 
    `colnames&lt;-`(&quot;returns&quot;) %>%
    mutate(growth = 
             accumulate(returns, 
                        function(x, y) x * y)) %>% 
    select(growth)
}</code></pre>
<p>That code allows us to run one simulation of the growth of a dollar over the next 10 years, with the <code>simulation_accum_1()</code> that we built for that purpose. Today, we will review how to run 51 simulations, though we could choose any number (and our Shiny application allows an end user to do just that).</p>
<p>First, we need an empty matrix with 51 columns, an initial value of $1, and intuitive column names.</p>
<p>We will use the <code>rep()</code> function to create 51 columns with a 1 as the value, and <code>set_names()</code> to name each column with the appropriate simulation number.</p>
<pre><code>sims &lt;- 51
starts &lt;- 
  rep(1, sims) %>%
  set_names(paste(&quot;sim&quot;, 1:sims, sep = &quot;&quot;))</code></pre>
<p>Take a peek at <code>starts</code> to see what we just created, and how it can house our simulations.</p>
<pre><code>head(starts)</code></pre>
<pre><code>sim1 sim2 sim3 sim4 sim5 sim6 
   1    1    1    1    1    1 </code></pre>
<pre><code>tail(starts)</code></pre>
<pre><code>sim46 sim47 sim48 sim49 sim50 sim51 
    1     1     1     1     1     1 </code></pre>
<p>51 columns, with a value of 1 in one row. This is where we will store the results of the 51 simulations.</p>
<p>Now, we want to apply <code>simulation_accum_1</code> to each of the 51 columns of the <code>starts</code> matrix, and we will do that using the <code>map_dfc()</code> function from the <code>purrr</code> package.</p>
<p><code>map_dfc()</code> takes a vector – in this case, the columns of <code>starts</code> – and applies a function to it. By appending <code>dfc()</code> to the <code>map_</code> function, we are asking the function to store each of its results as the column of a data frame (<code>map_df()</code> does the same thing, but stores results in the rows of a data frame). After running the code below, we will have a data frame with 51 columns, one for each of our simulations.</p>
<p>We also need to choose how many months to simulate (the N argument to our simulation function) and supply the distribution parameters as we did before. We do not supply the <code>init_value</code> argument because the <code>init_value</code> is 1, that same 1 that is already in the 51 columns.</p>
<pre><code>monte_carlo_sim_51 &lt;- 
  map_dfc(starts, 
          simulation_accum_1, 
          N = 120, 
          mean = mean_port_return, 
          stdev = stddev_port_return)

tail(monte_carlo_sim_51 %>%  select(growth1, growth2,
                                    growth49, growth50), 3)</code></pre>
<pre><code># A tibble: 3 x 4
  growth1 growth2 growth49 growth50
    </code></pre>