# Load packages

# Core
library(tidyverse)
library(tidyquant)

# Source function
source("../00_scripts/simulate_accumulation.R")

1 Import stock prices

Revise the code below.

symbols <- c("TSLA", "NKE")

prices <- tq_get(x    = symbols,
                 get  = "stock.prices",
                 from = "2012-12-31",
                 to   = "2022-12-31")

2 Convert prices to returns

asset_returns_tbl <- prices %>%
    
    group_by(symbol) %>%
    
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly",
                 type       = "log") %>%
    
    slice(-1) %>%
    
    ungroup() %>%
    
    set_names(c("asset", "date", "returns"))

3 Assign a weight to each asset

Revise the code for weights.

# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "NKE"  "TSLA"
# weights
weights <- c(.5, .5)
weights
## [1] 0.5 0.5
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 2 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 NKE         0.5
## 2 TSLA        0.5

4 Build a portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
    
    tq_portfolio(assets_col = asset, 
                 returns_col = returns, 
                 weights = w_tbl, 
                 rebalance_on = "months", 
                 col_rename = "returns")

portfolio_returns_tbl
## # A tibble: 120 × 2
##    date       returns
##    <date>       <dbl>
##  1 2013-01-31  0.0742
##  2 2013-02-28 -0.0313
##  3 2013-03-28  0.0822
##  4 2013-04-30  0.215 
##  5 2013-05-31  0.283 
##  6 2013-06-28  0.0630
##  7 2013-07-31  0.106 
##  8 2013-08-30  0.116 
##  9 2013-09-30  0.140 
## 10 2013-10-31 -0.0739
## # ℹ 110 more rows

5 Simulating growth of a dollar

# Get mean portfolio return
mean_port_return <- mean(portfolio_returns_tbl$returns)
mean_port_return
## [1] 0.02342483
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.09823808
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1] -0.0478716319  0.1645737269 -0.0468702539  0.0849564235  0.0298717158
##   [6] -0.0202427345  0.0473669925  0.0267924239  0.1844565881  0.0097536843
##  [11] -0.0297193890 -0.0710387171  0.0238073872  0.0195820909  0.0468727091
##  [16]  0.0446494868 -0.1287804375 -0.0119246924 -0.0842181108  0.0408535891
##  [21]  0.1158873841 -0.0454085369  0.1387732905 -0.0593668216 -0.1811904164
##  [26]  0.1376477337  0.0576334054 -0.0554984137  0.0515001141  0.1121211768
##  [31] -0.0524578817  0.1485693621 -0.0380117078  0.0282447742  0.0848814160
##  [36] -0.1972372797 -0.0025454549  0.1136542307  0.1638415529  0.0406701205
##  [41] -0.1100521852 -0.0682494224  0.0563619114 -0.0339140700  0.0492387313
##  [46] -0.2159289372  0.0560219239  0.0915368603  0.0184134248  0.0114730208
##  [51] -0.1019295814 -0.0525376881 -0.0461952253  0.0728681304  0.1391883960
##  [56] -0.1330293725 -0.0899369962  0.0844602559  0.0990009486  0.0625492338
##  [61]  0.0696577052  0.0585978276  0.0104721059  0.1526905070  0.0370818597
##  [66] -0.0171760748 -0.1419066247  0.0855481001  0.0586781356  0.1196622001
##  [71] -0.0536397287  0.0310435691  0.1430574704  0.1162338254 -0.1457486292
##  [76]  0.0903715817  0.0873620650  0.0493245030 -0.0254389692  0.0193691278
##  [81] -0.0815065717  0.0405940844 -0.0138544603  0.1224336160 -0.0275346112
##  [86]  0.0929731382 -0.1248328189 -0.0621201356  0.0577431899 -0.0002052073
##  [91] -0.1147946983  0.0091485215 -0.0044500455 -0.0190309952 -0.0006199591
##  [96] -0.0769641006  0.1281906273  0.0349834716 -0.0127627178 -0.0481940206
## [101] -0.1237473798  0.0315321667 -0.0499059435  0.0005179770 -0.0844072517
## [106]  0.0935227557  0.1562286047  0.0517126546  0.0148767087  0.0148983261
## [111] -0.1434899624  0.1087195902  0.0335433161 -0.0253076899  0.0083464389
## [116] -0.0670093039  0.0684906348  0.1579778450 -0.0158397077 -0.0551648746
# Add a dollar
simulated_returns_add_1 <- tibble(returns = c(1, 1 + simulated_monthly_returns))
simulated_returns_add_1
## # A tibble: 121 × 1
##    returns
##      <dbl>
##  1   1    
##  2   0.952
##  3   1.16 
##  4   0.953
##  5   1.08 
##  6   1.03 
##  7   0.980
##  8   1.05 
##  9   1.03 
## 10   1.18 
## # ℹ 111 more rows
# Calculate the cumulative growth of a dollar
simulated_growth <- simulated_returns_add_1 %>%
    mutate(growth = accumulate(returns, function(x, y) x*y)) %>%
    select(growth)

simulated_growth
## # A tibble: 121 × 1
##    growth
##     <dbl>
##  1  1    
##  2  0.952
##  3  1.11 
##  4  1.06 
##  5  1.15 
##  6  1.18 
##  7  1.16 
##  8  1.21 
##  9  1.24 
## 10  1.47 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 11.7027

6 Simulation function

No need

7 Running multiple simulations

# Create a vector of 1s as a starting point
sims <- 51
starts <- rep(100, sims) %>%
    set_names(paste0("sim", 1:sims))

starts
##  sim1  sim2  sim3  sim4  sim5  sim6  sim7  sim8  sim9 sim10 sim11 sim12 sim13 
##   100   100   100   100   100   100   100   100   100   100   100   100   100 
## sim14 sim15 sim16 sim17 sim18 sim19 sim20 sim21 sim22 sim23 sim24 sim25 sim26 
##   100   100   100   100   100   100   100   100   100   100   100   100   100 
## sim27 sim28 sim29 sim30 sim31 sim32 sim33 sim34 sim35 sim36 sim37 sim38 sim39 
##   100   100   100   100   100   100   100   100   100   100   100   100   100 
## sim40 sim41 sim42 sim43 sim44 sim45 sim46 sim47 sim48 sim49 sim50 sim51 
##   100   100   100   100   100   100   100   100   100   100   100   100
# Simulate
# For reproducable research
set.seed(1234)
monte_carlo_sim_51 <- starts %>%
    
    # Simulate
    map_dfc(.x = .,
            .f = ~simulate_accumulation(initial_value = .x, 
                                        N             = 240, 
                                        mean_return   = mean_port_return, 
                                        sd_return     = stddev_port_return)) %>%
    
    # Add column month
    mutate(month = 1:nrow(.)) %>%
    select(month, everything()) %>%
    
    # Rearrange column names
    set_names(c("month", names(starts))) %>%
    
    # Transform to long form
    pivot_longer(cols = -month, names_to = "sim", values_to = "growth")

monte_carlo_sim_51
## # A tibble: 12,291 × 3
##    month sim   growth
##    <int> <chr>  <dbl>
##  1     1 sim1     100
##  2     1 sim2     100
##  3     1 sim3     100
##  4     1 sim4     100
##  5     1 sim5     100
##  6     1 sim6     100
##  7     1 sim7     100
##  8     1 sim8     100
##  9     1 sim9     100
## 10     1 sim10    100
## # ℹ 12,281 more rows
# Find quantiles
monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    ungroup() %>%
    pull(growth) %>%
    
    quantile(probs = c(.5, .5)) %>%
    round(2)
##      50%      50% 
## 13611.43 13611.43

8 Visualizing simulations with ggplot

Line plot with max, median and min

# Step 1 summarize data into max, median and min of last value
sim_summary <- monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
                  ungroup() %>%
                  
                  summarise(max     = max(growth),
                            median  = median(growth),
                            min     = min(growth))

sim_summary
## # A tibble: 1 × 3
##       max median   min
##     <dbl>  <dbl> <dbl>
## 1 121835. 13611.  366.
# Step 2 Plot
monte_carlo_sim_51 %>%
    
    # Filter for max, median and min sim
    group_by(sim) %>%
    filter(last(growth) == sim_summary$max |
           last(growth) == sim_summary$median |
            last(growth) == sim_summary$min) %>%
    ungroup() %>%
    
    # Plot
    
    ggplot(aes(x = month, y = growth, color = sim)) +
    geom_line() +
    theme(legend.position = "none") +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(plot.subtitle = element_text(hjust = 0.5)) +
    
    labs(title = "Simulating growth over $1 over 120 months",
         subtitle = "Maximum, Median, and Minimum Simulation")

Line Plot of Simulations with Max, Median, and Min