You are on page 1of 3

library(quantmod) # get stock prices; useful stock analysis functions

library(xts) # working with extensible time series

library(rvest) # web scraping

library(tidyverse) # ggplot2, purrr, dplyr, tidyr, readr, tibble

library(stringr) # working with strings

library(forcats) # working with factors

library(lubridate) # working with dates in tibbles / data frames

library(plotly) # Interactive plots

library(corrplot) # Visuazlize correlation plots

getSymbols("AMZN",from="2001-01-01",to="2019-05-01")

amzn_price=AMZN$AMZN.Adjusted

amzn_ret=diff(log(amzn_price))[-1]

mean=mean(amzn_ret)

sd=sd(amzn_ret)

N <- 1000

mu <- mean

sigma <- sd

day <- 1:N

price_init=AMZN$AMZN.Adjusted[[nrow(AMZN$AMZN.Adjusted)]]

price_init <- MSFT$MSFT.Adjusted[[nrow(MSFT$MSFT.Adjusted)]]

# Simulate prices

set.seed(111)

price = c(price_init, rep(NA, N-1))

for(i in 2:N) {

price[i] <- price[i-1] * exp(rnorm(1, mu, sigma))

}
price_sim <- cbind(day, price) %>% as_tibble()

# Visualize price simulation

price_sim %>%ggplot(aes(day, price)) +

geom_line() + ggtitle(str_c("Amazon Simulated Prices for ",

N," Trading Days"))

#It looks like we are going to lose money with this investment.

#Can we trust this simulation? NO

#We need more such simulations

#Monte Carlo Simulation

#Here we repeatedly perform the random walk simulation process hundreds or thousands of times.

#We'll perform 250 Monte Carlo simulations (M = 250)

#for one year of trading days simulations (N = 252).

N <- 250 # Number of Stock Price Simulations

M <- 252 # Number of Monte Carlo Simulations

day <- 1:N

price_init <- AMZN$AMZN.Adjusted[[nrow(AMZN$AMZN.Adjusted)]]

# Simulate prices

set.seed(1145)

monte_carlo_mat <- matrix(nrow = N, ncol = M)

for (j in 1:M) {

monte_carlo_mat[[1, j]] = price_init

for(i in 2:N) {

monte_carlo_mat[[i, j]] <- monte_carlo_mat[[i - 1, j]] * exp(rnorm(1, mu, sigma))

}
}

# Format and organize data frame

price_sim = cbind(day, monte_carlo_mat) %>%as_tibble()

nm <- str_c("Sim.", seq(1, M))

nm <- c("Day", nm)

names(price_sim) <- nm

price_sim <- price_sim %>%

gather(key = "Simulation", value = "Stock.Price", -(Day))

# Visualize simulation

price_sim %>%

ggplot(aes(x = Day, y = Stock.Price, Group = Simulation)) +

geom_line(alpha = 0.1) +

ggtitle(str_c("Microsoft: ", M,

" Monte Carlo Simulations for Prices Over ", N,

" Trading Days"))

You might also like