# Load packages

# Core
library(tidyverse)
library(tidyquant)
library(dplyr)

# 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.005899133
# 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] -3.076397e-02  3.152933e-02  2.393321e-02 -1.962732e-02 -2.761079e-02
##   [6]  4.678188e-02  1.813594e-02  1.216246e-02 -3.885792e-03 -2.067830e-02
##  [11] -9.547837e-04  1.809444e-02  2.876219e-02 -1.427328e-02  8.244803e-03
##  [16] -1.178537e-02  7.791348e-03  8.369019e-03 -5.111791e-02 -3.949557e-03
##  [21] -1.084272e-02 -8.456842e-03  3.272768e-02  1.253060e-02  9.563475e-03
##  [26]  4.631880e-02  1.361707e-02  2.654646e-02  3.185823e-02  3.517543e-03
##  [31] -1.337798e-02 -2.201266e-02  1.302965e-02 -1.759546e-02 -7.823509e-03
##  [36] -1.656713e-02  3.045647e-02 -1.612960e-02  7.635043e-03 -2.651379e-03
##  [41] -1.542201e-02  1.377799e-02  3.906753e-03  9.397531e-03  2.228463e-02
##  [46]  2.954436e-03  2.916470e-02  2.405120e-02 -1.449479e-02 -4.820031e-04
##  [51]  1.798133e-02  3.427138e-02 -4.232827e-03  7.327720e-02  4.471158e-02
##  [56] -1.482138e-02 -6.471338e-03 -2.643909e-02  2.105410e-02 -1.156157e-02
##  [61]  3.716436e-02  2.684170e-02  1.046275e-02  1.061535e-02  2.584926e-02
##  [66]  1.754042e-02 -3.186320e-02  1.211679e-03  8.258635e-03 -1.536528e-03
##  [71] -4.577619e-02 -9.891230e-03 -4.914170e-02  2.812236e-02  1.537167e-03
##  [76]  3.695595e-02  2.161532e-02  2.291684e-02  3.345479e-02  3.617308e-02
##  [81]  4.201477e-02 -8.683489e-03  4.644312e-02 -3.195431e-03 -1.377605e-02
##  [86]  3.694438e-02  4.839229e-02  2.363368e-02  6.481770e-03  3.373192e-02
##  [91]  1.761282e-02  3.502568e-02 -8.417773e-05 -2.237515e-02  2.668482e-02
##  [96]  1.778810e-02 -1.499068e-02  9.134965e-03 -2.108577e-02 -3.837461e-03
## [101] -5.170336e-03  2.010616e-02  4.304179e-02 -1.675955e-02  3.606088e-02
## [106]  3.982913e-02 -8.437554e-03  3.507195e-02 -1.174583e-02 -3.575717e-02
## [111]  3.297079e-03  5.165722e-03  2.306231e-02 -3.951143e-02  3.907040e-02
## [116]  3.133349e-02  3.460749e-02  2.176807e-02  4.120226e-02  2.150006e-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   0.969
##  3   1.03 
##  4   1.02 
##  5   0.980
##  6   0.972
##  7   1.05 
##  8   1.02 
##  9   1.01 
## 10   0.996
## # ℹ 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.969
##  3  1.00 
##  4  1.02 
##  5  1.00 
##  6  0.976
##  7  1.02 
##  8  1.04 
##  9  1.05 
## 10  1.05 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 10.63223

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 = .01) %>%
    tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   283.
## 2   284.
## 3   286.
## 4   288.
## 5   290.
## 6   292.

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
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.03 1.59 1.97 2.36 3.85

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