<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-shiny-part-three/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2018/07/18/monte-carlo-shiny-part-3/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In previous posts, we covered how to <a rel="nofollow" href="https://rviews.rstudio.com/2018/06/05/monte-carlo/" target="_blank">run a Monte Carlo simulation</a> and <a rel="nofollow" href="https://rviews.rstudio.com/2018/06/13/monte-carlo-part-two/" target="_blank">how to visualize the results</a>. Today, we will wrap that work into a Shiny app wherein a user can build a custom portfolio, and then choose a number of simulations to run and a number of months to simulate into the future.</p>
<p>A link to that final Shiny app is <a rel="nofollow" href="http://www.reproduciblefinance.com/shiny/monte-carlo-simulation/" target="_blank">here</a> and here is a snapshot:</p>
<p><a rel="nofollow" href="http://www.reproduciblefinance.com/shiny/monte-carlo-simulation/" target="_blank"><img alt="monte carlo app" src="https://i0.wp.com/rviews.rstudio.com/post/2018-07-17-monte-carlo-shiny-part-3_files/app-snapshot.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<p>We will use RMarkdown to build our Shiny application by inserting <code>runtime: shiny</code> into the yaml header. This will alert the server (or our laptop) that this is an interactive document. The yaml header also gives us a space for the title and to specify the format as <code>flexdashboard</code>. This is what the yaml header looks like for the app.</p>
<pre><code>---
title: &quot;Monte Carlo&quot;
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    source_code: embed
---</code></pre>
<p>Note that when using RMarkdown and <code>runtime: shiny</code> we do no need to worry about UI and server logic, just inputs and outputs.</p>
<p>Our first code chunk is the <code>setup</code>, wherein we can load packages or data, just as we do with an R Notebook or static RMarkdown file.</p>
<pre><code># This is the setup chunk 
library(tidyverse)
library(highcharter)
library(tidyquant)
library(timetk)</code></pre>
<p>Our first substantive task is to build an <code>input sidebar</code> where users choose five stocks and weights, a starting date, the number of months to be simulated and the number of simulations to be run.</p>
<p>The sidebar looks like this</p>
<div>
<img src="https://i1.wp.com/rviews.rstudio.com/post/2018-07-17-monte-carlo-shiny-part-3_files/input-sidebar.png?w=456&ssl=1" data-recalc-dims="1">
</div>
<p>The code for building that sidebar starts with <code>textInput(&quot;stock1&quot;,...))</code> to create a space where the user can type a stock symbol and then <code>numericInput(&quot;w1&quot;,...)</code> to create a space where the user can enter a numeric weight. We want those entry spaces to be on the same line so we will nest them inside of a call to <code>fluidRow()</code>.</p>
<p>Since we have five stocks and weights, we repeat this five times. Notice that the stock symbol field uses <code>textInput()</code> because the user needs to enter text, and the weight field uses <code>numericInput()</code> because the user needs to enter a number.</p>
<pre><code>fluidRow(
  column(6,
  textInput(&quot;stock1&quot;, &quot;Stock 1&quot;, &quot;SPY&quot;)),
  column(5,
  numericInput(&quot;w1&quot;, &quot;Portf. %&quot;, 25, 
               min = 1, max = 100))
)  

# Repeat this fluidRow() four more times, changing names to 
# stock2, stock3, stock4, stock5 and w2, w3, 4, w5</code></pre>
<p>Let’s dissect one of those fluid rows line-by-line.</p>
<p><code>fluidRow()</code> creates the row.</p>
<p><code>column(6...)</code> creates a column for our stock ticker input with a length of 6.</p>
<p><code>textInput(&quot;stock1&quot;, &quot;Stock 1&quot;, &quot;SPY&quot;))</code> creates our first text input field.</p>
<p>We assigned it <code>stock1</code> which means it will be referenced in downstream code as <code>input$stock1</code>. We labeled it with “Stock 1”, which is what the end user will see when viewing the app.</p>
<p>Finally, we set “SPY” as the default initial value. If the user does nothing, the value will be this default.</p>
<p>We also include a row where the user can choose a start date with <code>dateInput(...)</code>.</p>
<pre><code>fluidRow(
  column(7,
  dateInput(&quot;date&quot;, 
            &quot;Starting Date&quot;, 
            &quot;2013-01-01&quot;, 
            format = &quot;yyyy-mm-dd&quot;))
)</code></pre>
<p>Next, we create the <code>numericInput</code> fields for the number of months to simulate and the number of simulations to run.</p>
<pre><code>fluidRow(
  column(5,
  numericInput(&quot;sim_months&quot;, &quot;Months&quot;, 120, 
               min = 6, max = 240, step = 6)),
  column(5,
  numericInput(&quot;sims&quot;, &quot;Sims&quot;, 51, 
               min = 31, max = 101, step = 10))
)</code></pre>
<p>We now have all the inputs from the user and are almost ready to start calculating. Before we do so, let’s ask the user to click <code>submit</code>.</p>
<pre><code>actionButton(&quot;go&quot;, &quot;Submit&quot;)</code></pre>
<p>The ‘submit’ button is very important because it enables the use of <code>eventReactive()</code> to control our computation. An <code>eventReactive()</code> is a reactive function that will not start until it observes some event. Without, our reactives would start firing each time a user changed an input.</p>
<p>In the next code chunk (and our subsequent calculation chunks as well), we tell <code>prices</code> to wait for <code>input$go</code> by calling <code>eventReactive(input$go...)</code>. When the user clicks, the reactive <code>inputs</code> get passed to our function.</p>
<pre><code>prices &lt;- eventReactive(input$go, {
  
  symbols &lt;- c(input$stock1, input$stock2, input$stock3, input$stock4, input$stock5)
  
  getSymbols(symbols, src = 'yahoo', from = input$date, 
             auto.assign = TRUE, warnings = FALSE) %>% 
  map(~Ad(get(.))) %>% 
  reduce(merge) %>%
  `colnames&lt;-`(symbols)
})</code></pre>
<p>From here, we pass the prices and weights to a portfolio returns code flow, which should look familiar from the first post. The only difference is that we are passing in the reactively chosen prices instead of the statically defined prices when we constructed the portfolio ourselves.</p>
<pre><code>portfolio_returns_tq_rebalanced_monthly &lt;- eventReactive(input$go, {
  
  prices &lt;- prices()
  w &lt;- c(input$w1/100, input$w2/100, input$w3/100, input$w4/100, input$w5/100)
  
  portfolio_returns_tq_rebalanced_monthly &lt;- 
      prices %>% 
      to.monthly(indexAt = &quot;last&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)))) %>%
    tq_portfolio(assets_col  = asset, 
                 returns_col = returns,
                 weights     = w,
                 col_rename  = &quot;returns&quot;,
                 rebalance_on = &quot;months&quot;)
})</code></pre>
<p>We now have a reactive object called <code>portfolio_returns_tq_rebalanced_monthly</code> and need to use it to find the mean and standard deviation of returns. Those are the parameters we need for the simulation.</p>
<pre><code>mean_port_return &lt;- eventReactive(input$go, {
  
  portfolio_returns_tq_rebalanced_monthly &lt;- 
    portfolio_returns_tq_rebalanced_monthly()
  
  mean(portfolio_returns_tq_rebalanced_monthly$returns)
})

stddev_port_return &lt;- eventReactive(input$go, {
  
  portfolio_returns_tq_rebalanced_monthly &lt;- 
    portfolio_returns_tq_rebalanced_monthly()
  
  sd(portfolio_returns_tq_rebalanced_monthly$returns)
})</code></pre>
<p>Next, we define one of our simulation functions that we discussed in the <a rel="nofollow" href="https://rviews.rstudio.com/2018/06/05/monte-carlo/" target="_blank">previous post</a>.</p>
<pre><code>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>Then, we call <code>eventReactive()</code> to run the simulation following the same logic as we did above.</p>
<pre><code>sims &lt;- eventReactive(input$go, {input$sims})

monte_carlo_sim &lt;- eventReactive(input$go, { 
  
  sims &lt;- sims()
  
  starts &lt;- 
    rep(1, sims) %>%
    set_names(paste(&quot;sim&quot;, 1:sims, sep = &quot;&quot;))
  
  map_dfc(starts, simulation_accum_1,
          N = input$sim_months, mean = mean_port_return(), 
          stdev = stddev_port_return()) %>% 
  mutate(month = seq(1:nrow(.))) %>% 
  select(month, everything()) %>% 
  `colnames&lt;-`(c(&quot;month&quot;, names(starts)))  %>% 
  gather(sim, growth, -month) %>% 
  group_by(sim) %>% 
  mutate_all(funs(round(., 2)))
  
})</code></pre>
<p>We now have a reactive object called <code>monte_carlo_sim()</code> which holds our 51 simulations of the custom portfolio. We can visualize with <code>highcharter()</code>, exactly as we did in the <a rel="nofollow" href="https://rviews.rstudio.com/2018/06/13/monte-carlo-part-two/" target="_blank">visualization post</a>. We pass the reactive object directly to <code>highcharter</code> by calling <code>hchar(monte_carlo_sim()...)</code>. Note that we begin the chunk with <code>renderHighchart()</code>. That alerts the file that the visualization is a reactively defined plot, and not a statically defined plot. If this were a <code>ggplot</code> visualization, we would start the call with <code>renderPlot()</code>.</p>
<pre><code>renderHighchart(
  hchart(monte_carlo_sim(), 
       type = 'line', 
       hcaes(y = growth,
             x = month,
             group = sim)) %>% 
  hc_title(text = paste(sims(), 
                        &quot;Simulations&quot;, 
                        sep = &quot; &quot;)) %>%
  hc_xAxis(title = list(text = &quot;months&quot;)) %>%
  hc_yAxis(title = list(text = &quot;dollar growth&quot;),
           labels = list(format = &quot;${value}&quot;)) %>%
  hc_add_theme(hc_theme_flat()) %>%
  hc_exporting(enabled = TRUE) %>% 
  hc_legend(enabled = FALSE)
)</code></pre>
<p>And finally, we isolate the minimum, median and maximum simulations for visualization and pass them to <code>highcharter</code>.</p>
<pre><code>renderHighchart({
 
sim_summary &lt;- 
  monte_carlo_sim() %>%
  summarise(final = last(growth)) %>% 
  summarise(
            max = max(final), 
            min = min(final),
            median = median(final))

mc_max_med_min &lt;- 
  monte_carlo_sim() %>%
  filter(
      last(growth) == sim_summary$max || 
      last(growth) == sim_summary$median ||
      last(growth) == sim_summary$min)

  hchart(mc_max_med_min, 
       type = 'line', 
       hcaes(y = growth,
             x = month,
             group = sim)) %>% 
  hc_title(text = &quot;Min Max Median Simulations&quot;) %>%
  hc_xAxis(title = list(text = &quot;months&quot;)) %>%
  hc_yAxis(title = list(text = &quot;dollar growth&quot;),
           labels = list(format = &quot;${value}&quot;)) %>%
  hc_add_theme(hc_theme_flat()) %>%
  hc_exporting(enabled = TRUE) %>% 
  hc_legend(enabled = FALSE)
})</code></pre>
<p>That wraps our Monte Carlo application and this showcases a powerful use for Shiny (we could have written any simulation function and then displayed the results). The end user sees the charts and we, as the R coders, can run whatever functions we wish under the hood. Thanks for reading and happy coding!</p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rviews.rstudio.com/2018/07/18/monte-carlo-shiny-part-3/"> R Views</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/PCzBKWnXLXc" height="1"></a></div>