# Load packages

# Core
library(tidyverse)
library(tidyquant)

# time series
library(timetk)

Goal

Simulate future portfolio returns

five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”

market: “SPY”

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

1 Import stock prices

symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")

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] "AGG" "EEM" "EFA" "IJS" "SPY"
# 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 AGG        0.25
## 2 EEM        0.25
## 3 EFA        0.2 
## 4 IJS        0.2 
## 5 SPY        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.0204 
##  2 2013-02-28 -0.00239
##  3 2013-03-28  0.0121 
##  4 2013-04-30  0.0174 
##  5 2013-05-31 -0.0128 
##  6 2013-06-28 -0.0247 
##  7 2013-07-31  0.0321 
##  8 2013-08-30 -0.0224 
##  9 2013-09-30  0.0511 
## 10 2013-10-31  0.0301 
## # ℹ 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.005899134
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.02347491
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1] -1.144303e-02  7.650060e-03 -2.109100e-02 -2.053967e-02 -3.651208e-02
##   [6]  9.921951e-03  8.409682e-03 -3.770865e-02 -2.518013e-02 -2.662528e-02
##  [11] -6.001648e-03  3.104562e-02 -1.819539e-02 -2.364636e-02  6.508269e-03
##  [16] -2.896419e-02  3.205136e-02  3.313768e-02  3.638949e-02 -3.653857e-02
##  [21]  1.200428e-02 -1.269798e-02  2.753850e-02 -2.531928e-02 -1.805814e-02
##  [26]  1.453071e-02  2.966405e-02  4.049136e-02  8.175377e-02  7.575937e-03
##  [31]  1.422071e-02  8.223287e-03 -5.172042e-03 -2.074405e-02 -2.697012e-02
##  [36]  6.460250e-02  8.636664e-03  2.558411e-02  1.750014e-02 -1.180498e-02
##  [41] -5.588643e-03  9.530505e-03  3.112291e-02 -3.356832e-03 -1.405798e-02
##  [46]  3.929561e-02  3.109087e-02  3.214819e-02 -1.864847e-02 -7.857451e-03
##  [51]  1.316152e-02  6.795827e-03  2.773112e-02  2.453815e-02 -2.146361e-02
##  [56] -2.610479e-02 -6.229298e-03 -3.950168e-02 -1.653230e-02  1.081666e-02
##  [61]  9.479370e-03 -1.573308e-03  1.398969e-02  3.188148e-02 -1.989202e-02
##  [66]  2.830456e-03 -4.021286e-02  1.023785e-02 -3.864346e-03  4.112650e-02
##  [71]  2.895146e-02 -3.006563e-02 -1.674495e-02  3.050429e-02  6.653012e-03
##  [76]  1.679747e-02  2.687234e-03  2.124511e-02 -1.477975e-02  2.919787e-02
##  [81]  1.354338e-02 -5.398503e-03 -2.855894e-02 -5.860356e-03 -2.709471e-03
##  [86]  2.087269e-03  3.529388e-02 -2.172672e-02  3.570846e-02 -3.027079e-02
##  [91]  7.955539e-03  3.033426e-03 -1.474080e-02 -2.019771e-03  3.003566e-02
##  [96]  4.016969e-02  2.279682e-03  7.798472e-04 -5.597741e-04  2.854733e-02
## [101] -2.588782e-02  2.222948e-02  2.297654e-02  4.906158e-02  6.988022e-02
## [106] -4.951643e-03 -6.336711e-03 -1.334497e-02  1.682441e-02 -2.087822e-02
## [111]  5.632357e-03 -1.036606e-02  3.249373e-02 -6.056354e-05  1.338578e-02
## [116]  2.389356e-02  2.952019e-02 -2.068758e-04  3.933320e-02 -2.548286e-04
# 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.989
##  3   1.01 
##  4   0.979
##  5   0.979
##  6   0.963
##  7   1.01 
##  8   1.01 
##  9   0.962
## 10   0.975
## # ℹ 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.989
##  3  0.996
##  4  0.975
##  5  0.955
##  6  0.920
##  7  0.929
##  8  0.937
##  9  0.902
## 10  0.879
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 6.009926

6 Simulation function

simulate_accumlation <- 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_accumlation(initial_value = 100, N = 240, mean_return = 0.005, sd_return = 0.01) %>%
    tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   281.
## 2   280.
## 3   283.
## 4   283.
## 5   284.
## 6   284.
dump(list = c("simulate_accumulation"), 
     file = "../00_scripts/simulate_accumlation.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
# fro re
set.seed(1234)
monte_carlo_sim_51 <- starts%>%
    
    #simulate
    map_dfc(.x = .,
            .f = ~simulate_accumlation(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 quantities
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.17 1.59 1.98 2.40 3.88

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  3.88   1.98  1.17
# step 2 plot
monte_carlo_sim_51 %>%
    
    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 of $1 over 120 months",
         subtitle = "Maximum, median, and minimum simulation")