<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Reproducible Financ with R on R Views</title>
    <link>https://rviews.rstudio.com/categories/reproducible-financ-with-r/</link>
    <description>Recent content in Reproducible Financ with R on R Views</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Wed, 18 Jul 2018 00:00:00 +0000</lastBuildDate>
    <atom:link href="https://rviews.rstudio.com/categories/reproducible-financ-with-r/" rel="self" type="application/rss+xml" />
    
    
    
    
    <item>
      <title>Monte Carlo Shiny: Part Three</title>
      <link>https://rviews.rstudio.com/2018/07/18/monte-carlo-shiny-part-3/</link>
      <pubDate>Wed, 18 Jul 2018 00:00:00 +0000</pubDate>
      
      <guid>https://rviews.rstudio.com/2018/07/18/monte-carlo-shiny-part-3/</guid>
      <description>
        


&lt;p&gt;In previous posts, we covered how to &lt;a href=&#34;https://rviews.rstudio.com/2018/06/05/monte-carlo/&#34;&gt;run a Monte Carlo simulation&lt;/a&gt; and &lt;a href=&#34;https://rviews.rstudio.com/2018/06/13/monte-carlo-part-two/&#34;&gt;how to visualize the results&lt;/a&gt;. 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.&lt;/p&gt;
&lt;p&gt;A link to that final Shiny app is &lt;a href=&#34;http://www.reproduciblefinance.com/shiny/monte-carlo-simulation/&#34;&gt;here&lt;/a&gt; and here is a snapshot:&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://www.reproduciblefinance.com/shiny/monte-carlo-simulation/&#34;&gt;&lt;img src=&#34;/post/2018-07-17-monte-carlo-shiny-part-3_files/app-snapshot.png&#34; alt=&#34;monte carlo app&#34; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We will use RMarkdown to build our Shiny application by inserting &lt;code&gt;runtime: shiny&lt;/code&gt; 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 &lt;code&gt;flexdashboard&lt;/code&gt;. This is what the yaml header looks like for the app.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;---
title: &amp;quot;Monte Carlo&amp;quot;
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    source_code: embed
---&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that when using RMarkdown and &lt;code&gt;runtime: shiny&lt;/code&gt; we do no need to worry about UI and server logic, just inputs and outputs.&lt;/p&gt;
&lt;p&gt;Our first code chunk is the &lt;code&gt;setup&lt;/code&gt;, wherein we can load packages or data, just as we do with an R Notebook or static RMarkdown file.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This is the setup chunk 
library(tidyverse)
library(highcharter)
library(tidyquant)
library(timetk)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our first substantive task is to build an &lt;code&gt;input sidebar&lt;/code&gt; 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.&lt;/p&gt;
&lt;p&gt;The sidebar looks like this&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;
&lt;img src=&#34;/post/2018-07-17-monte-carlo-shiny-part-3_files/input-sidebar.png&#34; /&gt;

&lt;/div&gt;
&lt;p&gt;The code for building that sidebar starts with &lt;code&gt;textInput(&amp;quot;stock1&amp;quot;,...))&lt;/code&gt; to create a space where the user can type a stock symbol and then &lt;code&gt;numericInput(&amp;quot;w1&amp;quot;,...)&lt;/code&gt; 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 &lt;code&gt;fluidRow()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Since we have five stocks and weights, we repeat this five times. Notice that the stock symbol field uses &lt;code&gt;textInput()&lt;/code&gt; because the user needs to enter text, and the weight field uses &lt;code&gt;numericInput()&lt;/code&gt; because the user needs to enter a number.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fluidRow(
  column(6,
  textInput(&amp;quot;stock1&amp;quot;, &amp;quot;Stock 1&amp;quot;, &amp;quot;SPY&amp;quot;)),
  column(5,
  numericInput(&amp;quot;w1&amp;quot;, &amp;quot;Portf. %&amp;quot;, 25, 
               min = 1, max = 100))
)  

# Repeat this fluidRow() four more times, changing names to 
# stock2, stock3, stock4, stock5 and w2, w3, 4, w5&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s dissect one of those fluid rows line-by-line.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;fluidRow()&lt;/code&gt; creates the row.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;column(6...)&lt;/code&gt; creates a column for our stock ticker input with a length of 6.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;textInput(&amp;quot;stock1&amp;quot;, &amp;quot;Stock 1&amp;quot;, &amp;quot;SPY&amp;quot;))&lt;/code&gt; creates our first text input field.&lt;/p&gt;
&lt;p&gt;We assigned it &lt;code&gt;stock1&lt;/code&gt; which means it will be referenced in downstream code as &lt;code&gt;input$stock1&lt;/code&gt;. We labeled it with “Stock 1”, which is what the end user will see when viewing the app.&lt;/p&gt;
&lt;p&gt;Finally, we set “SPY” as the default initial value. If the user does nothing, the value will be this default.&lt;/p&gt;
&lt;p&gt;We also include a row where the user can choose a start date with &lt;code&gt;dateInput(...)&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fluidRow(
  column(7,
  dateInput(&amp;quot;date&amp;quot;, 
            &amp;quot;Starting Date&amp;quot;, 
            &amp;quot;2013-01-01&amp;quot;, 
            format = &amp;quot;yyyy-mm-dd&amp;quot;))
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we create the &lt;code&gt;numericInput&lt;/code&gt; fields for the number of months to simulate and the number of simulations to run.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;fluidRow(
  column(5,
  numericInput(&amp;quot;sim_months&amp;quot;, &amp;quot;Months&amp;quot;, 120, 
               min = 6, max = 240, step = 6)),
  column(5,
  numericInput(&amp;quot;sims&amp;quot;, &amp;quot;Sims&amp;quot;, 51, 
               min = 31, max = 101, step = 10))
)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;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 &lt;code&gt;submit&lt;/code&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;actionButton(&amp;quot;go&amp;quot;, &amp;quot;Submit&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The ‘submit’ button is very important because it enables the use of &lt;code&gt;eventReactive()&lt;/code&gt; to control our computation. An &lt;code&gt;eventReactive()&lt;/code&gt; 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.&lt;/p&gt;
&lt;p&gt;In the next code chunk (and our subsequent calculation chunks as well), we tell &lt;code&gt;prices&lt;/code&gt; to wait for &lt;code&gt;input$go&lt;/code&gt; by calling &lt;code&gt;eventReactive(input$go...)&lt;/code&gt;. When the user clicks, the reactive &lt;code&gt;inputs&lt;/code&gt; get passed to our function.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;prices &amp;lt;- eventReactive(input$go, {
  
  symbols &amp;lt;- c(input$stock1, input$stock2, input$stock3, input$stock4, input$stock5)
  
  getSymbols(symbols, src = &amp;#39;yahoo&amp;#39;, from = input$date, 
             auto.assign = TRUE, warnings = FALSE) %&amp;gt;% 
  map(~Ad(get(.))) %&amp;gt;% 
  reduce(merge) %&amp;gt;%
  `colnames&amp;lt;-`(symbols)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;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.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;portfolio_returns_tq_rebalanced_monthly &amp;lt;- eventReactive(input$go, {
  
  prices &amp;lt;- prices()
  w &amp;lt;- c(input$w1/100, input$w2/100, input$w3/100, input$w4/100, input$w5/100)
  
  portfolio_returns_tq_rebalanced_monthly &amp;lt;- 
      prices %&amp;gt;% 
      to.monthly(indexAt = &amp;quot;last&amp;quot;, OHLC = FALSE) %&amp;gt;% 
      tk_tbl(preserve_index = TRUE, rename_index = &amp;quot;date&amp;quot;) %&amp;gt;%
      gather(asset, returns, -date) %&amp;gt;% 
      group_by(asset) %&amp;gt;%  
    mutate(returns = (log(returns) - log(lag(returns)))) %&amp;gt;%
    tq_portfolio(assets_col  = asset, 
                 returns_col = returns,
                 weights     = w,
                 col_rename  = &amp;quot;returns&amp;quot;,
                 rebalance_on = &amp;quot;months&amp;quot;)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We now have a reactive object called &lt;code&gt;portfolio_returns_tq_rebalanced_monthly&lt;/code&gt; and need to use it to find the mean and standard deviation of returns. Those are the parameters we need for the simulation.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;mean_port_return &amp;lt;- eventReactive(input$go, {
  
  portfolio_returns_tq_rebalanced_monthly &amp;lt;- 
    portfolio_returns_tq_rebalanced_monthly()
  
  mean(portfolio_returns_tq_rebalanced_monthly$returns)
})

stddev_port_return &amp;lt;- eventReactive(input$go, {
  
  portfolio_returns_tq_rebalanced_monthly &amp;lt;- 
    portfolio_returns_tq_rebalanced_monthly()
  
  sd(portfolio_returns_tq_rebalanced_monthly$returns)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we define one of our simulation functions that we discussed in the &lt;a href=&#34;https://rviews.rstudio.com/2018/06/05/monte-carlo/&#34;&gt;previous post&lt;/a&gt;.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;simulation_accum_1 &amp;lt;- function(init_value, N, mean, stdev) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev))) %&amp;gt;% 
    `colnames&amp;lt;-`(&amp;quot;returns&amp;quot;) %&amp;gt;%
    mutate(growth = 
             accumulate(returns, function(x, y) x * y)) %&amp;gt;% 
    select(growth)
    
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, we call &lt;code&gt;eventReactive()&lt;/code&gt; to run the simulation following the same logic as we did above.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;sims &amp;lt;- eventReactive(input$go, {input$sims})

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

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

  hchart(mc_max_med_min, 
       type = &amp;#39;line&amp;#39;, 
       hcaes(y = growth,
             x = month,
             group = sim)) %&amp;gt;% 
  hc_title(text = &amp;quot;Min Max Median Simulations&amp;quot;) %&amp;gt;%
  hc_xAxis(title = list(text = &amp;quot;months&amp;quot;)) %&amp;gt;%
  hc_yAxis(title = list(text = &amp;quot;dollar growth&amp;quot;),
           labels = list(format = &amp;quot;${value}&amp;quot;)) %&amp;gt;%
  hc_add_theme(hc_theme_flat()) %&amp;gt;%
  hc_exporting(enabled = TRUE) %&amp;gt;% 
  hc_legend(enabled = FALSE)
})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;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!&lt;/p&gt;

        &lt;script&gt;window.location.href=&#39;https://rviews.rstudio.com/2018/07/18/monte-carlo-shiny-part-3/&#39;;&lt;/script&gt;
      </description>
    </item>
    
  </channel>
</rss>
