# 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.005899138
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.02347489
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  0.0069775087 -0.0154897058 -0.0059977151  0.0025217892 -0.0081421732
##   [6]  0.0084578970  0.0211735309  0.0405471289 -0.0109948252 -0.0078324418
##  [11] -0.0256458036  0.0288656664 -0.0017367493 -0.0154146137  0.0000136658
##  [16] -0.0221349441 -0.0002418098 -0.0563077952  0.0039174109 -0.0094379799
##  [21] -0.0128626024 -0.0457771892  0.0173119978  0.0434895551  0.0022352218
##  [26] -0.0359336420 -0.0065279437  0.0044975671 -0.0726662013  0.0004031295
##  [31]  0.0332074894  0.0168780058  0.0123575618  0.0151399076  0.0176034976
##  [36]  0.0077914522 -0.0132105581 -0.0095540624  0.0664896144 -0.0130799296
##  [41] -0.0037353963  0.0199008049  0.0222473695  0.0259483499 -0.0032350157
##  [46]  0.0171537989 -0.0187041772  0.0096839265 -0.0026268889  0.0097938094
##  [51] -0.0143975249  0.0395672467  0.0095279276 -0.0013105944  0.0124309310
##  [56] -0.0375797172  0.0374763184  0.0117154569  0.0427175122  0.0467394463
##  [61] -0.0409826029  0.0390838226  0.0192792364  0.0047267202 -0.0020350436
##  [66]  0.0263789922  0.0079525369 -0.0251212622  0.0056485095  0.0070495775
##  [71]  0.0291356170  0.0190560182  0.0005173322  0.0359818628 -0.0288524664
##  [76] -0.0051734897  0.0150646617 -0.0383248403  0.0340324521  0.0290663489
##  [81] -0.0302357742  0.0068731876  0.0238664885 -0.0153004638  0.0199604116
##  [86]  0.0466228444  0.0097079617  0.0437602913 -0.0135064805  0.0233215408
##  [91]  0.0292252188 -0.0070105745  0.0105092511 -0.0049905583 -0.0230262593
##  [96]  0.0348154816 -0.0103336559  0.0030916911 -0.0012322308 -0.0563668267
## [101] -0.0116207610 -0.0164968557 -0.0117692651 -0.0034118931  0.0123061259
## [106]  0.0234626276  0.0115462353 -0.0330357875  0.0016673201  0.0004261275
## [111] -0.0326671992  0.0206161889  0.0298778343  0.0099034248  0.0064907749
## [116]  0.0077481206 -0.0228619039 -0.0458283106  0.0092079455  0.0307238731
# 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.01 
##  3   0.985
##  4   0.994
##  5   1.00 
##  6   0.992
##  7   1.01 
##  8   1.02 
##  9   1.04 
## 10   0.989
## # ℹ 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.01 
##  3  0.991
##  4  0.985
##  5  0.988
##  6  0.980
##  7  0.988
##  8  1.01 
##  9  1.05 
## 10  1.04 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 3.632855

6 Simulation function

simulate_accumulation <- function(initial_value, N, mean_return, sd_return) {
  
    # Add a dollar
    simulated_returns_add_1 <- tibble(returns = c(1, 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)
## # A tibble: 241 × 1
##    growth
##     <dbl>
##  1  1    
##  2  0.987
##  3  0.983
##  4  0.980
##  5  0.979
##  6  0.981
##  7  0.992
##  8  1.01 
##  9  1.02 
## 10  1.03 
## # ℹ 231 more rows

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_carle_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")

# Find quantiles 
monte_carle_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_carle_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")

# Step 1 Summarize data into max, median, and min of last value
sim_summary <- monte_carle_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_carle_sim_51 %>%
    
    # Filter for max, median, 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 of $1 over 120 months", 
         subtitle = "Maximum, Median, and Mimimum Simulation")