# Load packages

# Core
library(tidyverse)
library(tidyquant)

# time series
library(timetk)

Goal

Simulate future portfolio returns

five stocks: “H”, “HSY”, “BA”, “VOO”, “NOK”

market: “SPY”

from 2012-12-31 to 2017-12-31

1 Import stock prices

symbols <- c("H", "HSY", "BA", "VOO", "NOK")

prices <- tq_get(x    = symbols,
                 get  = "stock.prices",    
                 from = "2012-12-31",
                 to   = "2017-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

# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "BA"  "H"   "HSY" "NOK" "VOO"
# weights
weights <- c(0.25, 0.25, 0.2, 0.2, 0.1)
weights
## [1] 0.25 0.25 0.20 0.20 0.10
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 BA         0.25
## 2 H          0.25
## 3 HSY        0.2 
## 4 NOK        0.2 
## 5 VOO        0.1

4 Build a portfolio

# ?tq_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: 60 × 2
##    date       returns
##    <date>       <dbl>
##  1 2013-01-31  0.0271
##  2 2013-02-28  0.0156
##  3 2013-03-28  0.0322
##  4 2013-04-30  0.0243
##  5 2013-05-31  0.0186
##  6 2013-06-28  0.0194
##  7 2013-07-31  0.0627
##  8 2013-08-30 -0.0225
##  9 2013-09-30  0.135 
## 10 2013-10-31  0.102 
## # ℹ 50 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.01312608
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.04192974
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  7.074638e-02  3.297269e-03  7.811615e-04  2.730747e-02  4.657063e-02
##   [6]  1.890332e-02  5.597453e-02  1.471058e-02  3.642172e-02  1.328472e-02
##  [11]  3.651838e-02  6.388728e-02  9.031919e-03  5.070650e-03  5.383331e-02
##  [16] -2.095412e-02  4.069149e-02 -1.974060e-02  1.168195e-01 -4.038401e-03
##  [21]  1.481093e-02  1.908298e-02  5.452683e-03 -3.241596e-02  9.113829e-02
##  [26] -2.984087e-02  4.637183e-02  5.026511e-03  6.505834e-02  1.709190e-02
##  [31]  3.385905e-02  1.270700e-02  1.081171e-01 -4.016468e-02  2.412336e-03
##  [36] -6.285052e-03 -6.437963e-02  3.092472e-02 -1.528128e-02 -8.963307e-03
##  [41]  1.023129e-02  2.474717e-02  4.484248e-02  1.021223e-02 -3.564569e-02
##  [46]  7.331054e-03  9.127615e-02 -3.032752e-02  3.591440e-02 -4.773872e-02
##  [51] -1.311524e-02 -1.432753e-02 -1.920704e-02 -5.690446e-04  2.121009e-02
##  [56] -4.673492e-03  8.426544e-03 -2.078351e-03  2.007348e-02 -3.785221e-02
##  [61]  3.737638e-02  8.319336e-02 -8.854377e-02  2.864153e-02  9.887279e-03
##  [66]  2.963828e-02 -2.655769e-02  5.515056e-02 -4.737180e-02  7.906510e-02
##  [71]  6.232074e-02  5.647098e-02 -2.248299e-02 -1.439585e-02 -1.362032e-02
##  [76]  8.230458e-02 -3.757097e-02  2.790524e-03  9.010735e-03  3.771651e-02
##  [81]  1.570638e-02 -1.615329e-02  9.871931e-03  5.572946e-02 -2.275591e-02
##  [86]  6.307607e-02  4.416988e-02 -5.653075e-03  1.124694e-02  2.302786e-02
##  [91]  7.227912e-02 -2.992037e-03  4.147932e-02  3.324428e-02 -1.055987e-02
##  [96]  1.954491e-02  1.768240e-02  3.748171e-02  1.975993e-02 -3.067806e-02
## [101]  4.288208e-02  1.342182e-01 -2.645289e-02 -5.166455e-04  2.245118e-02
## [106]  4.941206e-02  6.918669e-02 -8.790901e-03  3.790290e-02  3.439103e-02
## [111]  3.488814e-02  4.089509e-02  1.721101e-02  1.666256e-02  3.752796e-02
## [116]  1.681934e-02  8.644923e-05 -7.623978e-04  2.299787e-02 -9.092053e-02
# 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    1.07
##  3    1.00
##  4    1.00
##  5    1.03
##  6    1.05
##  7    1.02
##  8    1.06
##  9    1.01
## 10    1.04
## # ℹ 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   1.07
##  3   1.07
##  4   1.08
##  5   1.10
##  6   1.16
##  7   1.18
##  8   1.24
##  9   1.26
## 10   1.31
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 21.3982

6 Simulation function

simulate_accumulation <- function(initial_value, N, mean_return, sd_return) {
    

# Add a dollar
simulated_returns_add_1 <- tibble(returns = c(initial_value, 1 + rnorm(N, mean_return, sd_return)))


# Calculate the cumulative growth of a dollar
simulated_growth <- simulated_returns_add_1 %>%
    mutate(growth = accumulate(returns, function(x, y) x*y)) %>%
    select(growth)

return(simulated_growth)    
    
}

simulate_accumulation(initial_value = 100, N = 240, mean_return = 0.005, sd_return = 0.01) %>%
    tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   371.
## 2   371.
## 3   379.
## 4   375.
## 5   374.
## 6   374.
dump(list = c("simulate_accumulation"),
     file = "../00_scripts/simulate_accumulation.R")

7 Running multiple simulations

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

starts
##  sim1  sim2  sim3  sim4  sim5  sim6  sim7  sim8  sim9 sim10 sim11 sim12 sim13 
##     1     1     1     1     1     1     1     1     1     1     1     1     1 
## sim14 sim15 sim16 sim17 sim18 sim19 sim20 sim21 sim22 sim23 sim24 sim25 sim26 
##     1     1     1     1     1     1     1     1     1     1     1     1     1 
## sim27 sim28 sim29 sim30 sim31 sim32 sim33 sim34 sim35 sim36 sim37 sim38 sim39 
##     1     1     1     1     1     1     1     1     1     1     1     1     1 
## sim40 sim41 sim42 sim43 sim44 sim45 sim46 sim47 sim48 sim49 sim50 sim51 
##     1     1     1     1     1     1     1     1     1     1     1     1
#Simulate
#For Reproducible Research
set.seed(1234)

monte_carlo_sim_51 <- starts %>%
    
    # Simulate
    map_dfc(.x = .,
            .f = ~simulate_accumulation(initial_value = .x,
                                        N = 120, 
                                        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: 6,171 × 3
##    month sim   growth
##    <int> <chr>  <dbl>
##  1     1 sim1       1
##  2     1 sim2       1
##  3     1 sim3       1
##  4     1 sim4       1
##  5     1 sim5       1
##  6     1 sim6       1
##  7     1 sim7       1
##  8     1 sim8       1
##  9     1 sim9       1
## 10     1 sim10      1
## # ℹ 6,161 more rows
# Find quantiles
monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    ungroup() %>%
    pull(growth) %>%
    
    quantile(probs = c(0, 0.25, 0.5, 0.75, 1)) %>%
    round(2)
##    0%   25%   50%   75%  100% 
##  1.72  2.98  4.43  6.15 14.56

8 Visualizing simulations with ggplot

monte_carlo_sim_51 %>%
    
    ggplot(aes(x = month, y = growth, color = sim)) +
    geom_line() +
    theme(legend.position = "none") +
    theme(plot.title = element_text(hjust = 0.5)) +
    
    labs(title = "simulating growth of $1 over 120 months")

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  14.6   4.43  1.72
#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 growht of $1 over 120 months",
         subtitle = "Maximum, Median, and Minimum Simulation")