# 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.02347493
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1] -0.0243152453 -0.0070252214  0.0266028745 -0.0011576057  0.0217587742
##   [6]  0.0436784555  0.0626842721  0.0028641757  0.0062895189  0.0495102918
##  [11]  0.0019864414  0.0010577693  0.0345143528  0.0082882028  0.0229028481
##  [16]  0.0070497026  0.0510556522 -0.0274386197  0.0189163513  0.0069742384
##  [21]  0.0192638292 -0.0043540995  0.0228736046  0.0199169574 -0.0135477423
##  [26] -0.0364407027  0.0063523162 -0.0359774476  0.0229112167 -0.0236352726
##  [31] -0.0207102677 -0.0254366019  0.0222463497  0.0103782871  0.0307951567
##  [36]  0.0027512000  0.0272062561  0.0094974620  0.0107727193 -0.0222399011
##  [41]  0.0261320108  0.0103014927  0.0042544333  0.0391441068  0.0124144504
##  [46]  0.0265162372  0.0296197449  0.0463573414  0.0020074320  0.0059355660
##  [51] -0.0108601912 -0.0224875307  0.0201466577 -0.0003746558  0.0059208759
##  [56]  0.0408656887  0.0366074316 -0.0341868268 -0.0158400689  0.0288916601
##  [61]  0.0292677936 -0.0415546437  0.0396964423  0.0231547165 -0.0161574701
##  [66]  0.0084360921 -0.0003568504  0.0421786056  0.0387263512  0.0285183213
##  [71] -0.0084144236 -0.0550349382  0.0120962626 -0.0005397840 -0.0014025411
##  [76]  0.0181528888 -0.0159833763 -0.0536641223  0.0041223567 -0.0013404436
##  [81]  0.0039590226 -0.0305795296  0.0068682259  0.0079409789  0.0024757030
##  [86]  0.0196906825  0.0634935243  0.0129745974 -0.0129133543 -0.0135639272
##  [91]  0.0271532170 -0.0277149568  0.0370530778 -0.0007941085 -0.0022190405
##  [96] -0.0203486042 -0.0274880312 -0.0163418460 -0.0218701301 -0.0030284821
## [101]  0.0048419691  0.0266098657 -0.0204486783  0.0363108810 -0.0065131647
## [106]  0.0121026918 -0.0163333630  0.0033287498  0.0288422295  0.0168924602
## [111] -0.0204444741 -0.0011530325  0.0160499433 -0.0232762705  0.0273476969
## [116] -0.0271567284 -0.0031856362  0.0313842782 -0.0118634757  0.0201310825
# 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.976
##  3   0.993
##  4   1.03 
##  5   0.999
##  6   1.02 
##  7   1.04 
##  8   1.06 
##  9   1.00 
## 10   1.01 
## # ℹ 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.976
##  3  0.969
##  4  0.995
##  5  0.993
##  6  1.02 
##  7  1.06 
##  8  1.13 
##  9  1.13 
## 10  1.14 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 7.168587

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   380.
## 2   387.
## 3   388.
## 4   391.
## 5   394.
## 6   403.
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) %>%
    summarize(growth = last(growth)) %>%
    ungroup() %>%
    pull(growth) %>%
    
    quantile(probs = c(0, 0.25, .50, 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 the last value
sim_summary <- monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarize(growth = last(growth)) %>%
    ungroup() %>%
    
    summarize(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 %>%
    
    # 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 growth of $1 over 120 months",
         subtitle = "Maximum, Median, and Minimum Simulation")