# 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.02347489
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  7.007167e-03 -1.120069e-02 -7.202954e-03 -2.603098e-02  2.296531e-02
##   [6]  6.850456e-02  5.419975e-03  2.696210e-02 -7.458763e-03  7.972068e-03
##  [11] -1.704925e-03 -1.112759e-02  1.406072e-03 -4.983600e-03  2.073622e-02
##  [16] -1.162772e-02  2.340538e-02  1.158981e-02  2.062503e-03  2.448833e-02
##  [21]  2.878508e-02  2.153319e-02  4.479353e-02  1.704621e-02 -6.451777e-03
##  [26]  2.443331e-02  2.136770e-02 -5.425893e-03  2.830732e-03 -6.587222e-03
##  [31] -1.370521e-02  4.456520e-02  5.286544e-03 -5.770919e-03  2.445509e-02
##  [36]  2.245882e-02  4.231758e-02 -1.507591e-02 -2.203672e-02  3.029635e-02
##  [41]  2.872408e-02 -3.404255e-02  5.941100e-03 -3.918016e-03 -1.620816e-02
##  [46] -6.155788e-03 -1.160537e-02  7.034976e-03  3.269813e-02  3.046601e-02
##  [51]  5.408162e-03  3.518736e-02 -6.419689e-03  2.446678e-02  2.675501e-02
##  [56] -1.575817e-02  1.101946e-02 -1.708156e-02 -4.642671e-03  7.291315e-03
##  [61]  1.378982e-02 -2.484471e-02  4.261425e-02  1.935466e-02 -3.555354e-02
##  [66]  2.287178e-02  3.263694e-02  5.316300e-02 -1.766969e-02 -1.215023e-02
##  [71] -8.584360e-03  2.073973e-02 -5.331672e-03 -9.219263e-03 -6.318276e-03
##  [76] -1.262873e-02 -1.648913e-02  1.608701e-03  5.833732e-02  3.398761e-02
##  [81]  3.522679e-03 -5.671290e-03  1.774308e-03 -4.005827e-02  2.273644e-02
##  [86] -1.306014e-02 -2.226120e-02 -1.606420e-02  2.729944e-02  1.063171e-02
##  [91] -7.147639e-02  4.944525e-02  1.825535e-02  9.641408e-03  2.946852e-02
##  [96]  4.734130e-02 -1.873800e-02  1.808891e-02 -8.069022e-03  1.440447e-02
## [101]  9.882744e-03  4.691813e-02 -1.760688e-02  5.404864e-02  5.863402e-03
## [106]  4.545020e-02 -2.118388e-02 -1.177199e-02  3.538998e-02 -3.312908e-02
## [111] -1.530040e-02  1.235587e-02 -2.299402e-03  1.170941e-02  2.510317e-02
## [116]  7.571815e-05 -2.829545e-04 -9.985101e-03 -1.057095e-02  1.907445e-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.01 
##  3   0.989
##  4   0.993
##  5   0.974
##  6   1.02 
##  7   1.07 
##  8   1.01 
##  9   1.03 
## 10   0.993
## # ℹ 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.996
##  4  0.989
##  5  0.963
##  6  0.985
##  7  1.05 
##  8  1.06 
##  9  1.09 
## 10  1.08 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 8.452816

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(100, N = 240, mean_return = 0.005, sd_return = 0.01) %>%
    tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   279.
## 2   275.
## 3   280.
## 4   279.
## 5   282.
## 6   280.

7 Running multiple simulations

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
monte_carlo_sim_51 <- starts %>%
    
    map_dfc(.x = .,
            .f = ~simulate_accumulation(initial_value = .x, 
                                        N = 120, 
                                        mean_return = mean_port_return, 
                                        sd_return = stddev_port_return)) %>%
    
    mutate(month = 1:nrow(.)) %>%
    select(month, everything()) %>%
    
    set_names(c("month", names(starts))) %>%
    
    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
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.18 1.71 1.97 2.29 3.50

8 Visualizing simulations with ggplot

monte_carlo_sim_51 %>%

    ggplot(aes(x = month, y = growth, col = sim)) +
    geom_line() +
    theme(legend.position = "none")

# Simplify the plot

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.50   1.97  1.18
monte_carlo_sim_51 %>%

    group_by(sim) %>%
    filter(last(growth) == sim_summary$max |
           last(growth) == sim_summary$median |
           last(growth) == sim_summary$min) %>%

    # Plot
    ggplot(aes(month, growth, col = sim)) +
    geom_line() +
    theme()