Geometric Brownian Motion - Monte Carlo Simulation in Shiny

Marco Letico
05 February 2018

Summary

In these slides we are going to explain how to use the Shiny application prepared for the Coursera final assignment of “Developing data products” course. The Geometric Brownian Motion is used here for simulating 1 year (365 days) stocks data and it is given by the following formula:

\[ \Large S_0 \exp\left(\left(\mu - \frac{\sigma^2}{2}\right)t + \sigma W_t\right) \]

where:

  • \( \Large S_0 \) is the current price of the stock;
  • \( \Large \mu \) is the expected rate of return;
  • \( \Large \sigma \) is the volatility of the stock price;
  • \( \Large W_t \) is a Wiener process or Brownian motion;
  • \( \Large t \) is the time.

Code explanation

Below are assigned the necessary variables and is created an empty matrix that will contain the simulation, in this case we are performing 100 stocks simulations:

set.seed(254)
nsim <- 50
S0 <- 100
mu <- 0.15
sigma <- 0.30
t = 365
gbm <- matrix(ncol = nsim, nrow = t)

Here is the Monte Carlo Simulation of the GBM process. The code run for every simulation and for every day is calculated the price of the stock:

for (simu in 1:nsim) {
        for (day in 2:t) {
                epsilon <- rnorm(t)
                dt = 1 / t
                gbm[1, simu] <- S0
                gbm[day, simu] <- exp((mu - sigma * sigma / 2) * dt + sigma * epsilon[day] * sqrt(dt))
        }
}
gbm <- apply(gbm, 2, cumprod)

Plot Example

In this slide we are going to show the output of our Shiny application. The plot shows the 50 simulations for the stock price:

ts.plot(gbm, gpars = list(col=rainbow(10)))

plot of chunk unnamed-chunk-3

Ho to use the Shiny application

The application is composed by a side bar containing the input data that the user wants to input. Please refer to the 'Summary' slide for the meaning of the variables. In the side bar is also possible, through a check box, to set the seed to a fix value. Please mark the check box and select the value from the numeric box. If it is unmarked the seed will be assigned randomly. As the calculation time increases with the number of simulation, there is a 'Submit' button to click as soon as the parameters are decided.

It is possible to access the application through the following link: https://marcoletico.shinyapps.io/shinyapp/

The ui.R and server.R files are stored in the following Github repo: https://github.com/MarcoLeti/GBM_MonteCarlo_ShinyApp