In previous posts, we covered how to run a Monte Carlo simulation and how to visualize the results. 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.
A link to that final Shiny app is here and here is a snapshot:
We will use RMarkdown to build our Shiny application by inserting runtime: shiny 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 flexdashboard. This is what the yaml header looks like for the app.
---
title: &quot;Monte Carlo&quot;
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: rows
source_code: embed
---
Note that when using RMarkdown and runtime: shiny we do no need to worry about UI and server logic, just inputs and outputs.
Our first code chunk is the setup, wherein we can load packages or data, just as we do with an R Notebook or static RMarkdown file.
# This is the setup chunk library(tidyverse)
library(highcharter)
library(tidyquant)
library(timetk)
Our first substantive task is to build an input sidebar 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.
The sidebar looks like this
The code for building that sidebar starts with textInput(&quot;stock1&quot;,...)) to create a space where the user can type a stock symbol and then numericInput(&quot;w1&quot;,...) 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 fluidRow().
Since we have five stocks and weights, we repeat this five times. Notice that the stock symbol field uses textInput() because the user needs to enter text, and the weight field uses numericInput() because the user needs to enter a number.
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
Let’s dissect one of those fluid rows line-by-line.
fluidRow() creates the row.
column(6...) creates a column for our stock ticker input with a length of 6.
textInput(&quot;stock1&quot;, &quot;Stock 1&quot;, &quot;SPY&quot;)) creates our first text input field.
We assigned it stock1 which means it will be referenced in downstream code as input$stock1. We labeled it with “Stock 1”, which is what the end user will see when viewing the app.
Finally, we set “SPY” as the default initial value. If the user does nothing, the value will be this default.
We also include a row where the user can choose a start date with dateInput(...).
fluidRow(
column(7,
dateInput(&quot;date&quot;, &quot;Starting Date&quot;, &quot;2013-01-01&quot;, format = &quot;yyyy-mm-dd&quot;))
)
Next, we create the numericInput fields for the number of months to simulate and the number of simulations to run.
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))
)
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 submit.
actionButton(&quot;go&quot;, &quot;Submit&quot;)
The ‘submit’ button is very important because it enables the use of eventReactive() to control our computation. An eventReactive() 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.
In the next code chunk (and our subsequent calculation chunks as well), we tell prices to wait for input$go by calling eventReactive(input$go...). When the user clicks, the reactive inputs get passed to our function.
prices % reduce(merge) %__%
`colnames% 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;)
})
We now have a reactive object called portfolio_returns_tq_rebalanced_monthly and need to use it to find the mean and standard deviation of returns. Those are the parameters we need for the simulation.
mean_port_return % 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)
)
And finally, we isolate the minimum, median and maximum simulations for visualization and pass them to highcharter.
renderHighchart({
sim_summary %
summarise(final = last(growth)) %__% summarise(
max = max(final), min = min(final),
median = median(final))
mc_max_med_min %
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)
})
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!