# 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 
## # … with 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.005899135
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.02347492
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  0.0088710537  0.0170672059 -0.0004548328 -0.0140356281  0.0210063301
##   [6] -0.0059013736 -0.0435855400  0.0053841200 -0.0024706302  0.0696154300
##  [11]  0.0175616378  0.0083256783  0.0271655800 -0.0276928130  0.0249499773
##  [16]  0.0108461777  0.0195012780  0.0638649531 -0.0445499038  0.0231739708
##  [21]  0.0361700753 -0.0425469005  0.0166360546  0.0093973975  0.0648637750
##  [26]  0.0141909180 -0.0014697181  0.0175257048 -0.0731629039 -0.0035686183
##  [31]  0.0329499543  0.0019131318 -0.0010975345  0.0465140525 -0.0089545079
##  [36]  0.0298840807  0.0242530786  0.0316577135  0.0070920438 -0.0115832484
##  [41]  0.0516704220  0.0034136741  0.0102909188  0.0136497861 -0.0037870653
##  [46]  0.0518976911 -0.0196637202  0.0060863114 -0.0249436598  0.0248619504
##  [51] -0.0213938275 -0.0085720068 -0.0457776448 -0.0011556409  0.0061809123
##  [56]  0.0123099958 -0.0087335524  0.0436117937  0.0056594502 -0.0218654251
##  [61]  0.0157953292  0.0072071045  0.0104007637 -0.0026197654 -0.0079073016
##  [66] -0.0226060578 -0.0314943267  0.0488004579 -0.0033462225 -0.0307928758
##  [71] -0.0095604447 -0.0063433009  0.0148220991  0.0241331374  0.0102014963
##  [76] -0.0097325306  0.0109617027  0.0307683414  0.0172645745  0.0015128868
##  [81]  0.0090606042  0.0695612330 -0.0166043247 -0.0059767555 -0.0282303928
##  [86]  0.0115112558 -0.0001327350  0.0210776981 -0.0027495826 -0.0349658147
##  [91]  0.0227724373 -0.0207762852  0.0223110316  0.0196293975  0.0049464522
##  [96]  0.0008012361  0.0207015923  0.0386370880  0.0188604117 -0.0009489028
## [101] -0.0087144044 -0.0116988421  0.0258086131  0.0283806137 -0.0214784242
## [106]  0.0090264227  0.0299189366  0.0244584783 -0.0268641985  0.0101658561
## [111]  0.0404513585  0.0172319310  0.0007481837  0.0255751537  0.0124331534
## [116] -0.0250963825  0.0144170416  0.0045894729 -0.0291550012 -0.0228863904
# 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   1.02 
##  4   1.00 
##  5   0.986
##  6   1.02 
##  7   0.994
##  8   0.956
##  9   1.01 
## 10   0.998
## # … with 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  1.03 
##  4  1.03 
##  5  1.01 
##  6  1.03 
##  7  1.03 
##  8  0.982
##  9  0.987
## 10  0.984
## # … with 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 7.446588

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   355.
## 2   360.
## 3   354.
## 4   355.
## 5   357.
## 6   353.
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("sims", 1:sims))

starts
##  sims1  sims2  sims3  sims4  sims5  sims6  sims7  sims8  sims9 sims10 sims11 
##      1      1      1      1      1      1      1      1      1      1      1 
## sims12 sims13 sims14 sims15 sims16 sims17 sims18 sims19 sims20 sims21 sims22 
##      1      1      1      1      1      1      1      1      1      1      1 
## sims23 sims24 sims25 sims26 sims27 sims28 sims29 sims30 sims31 sims32 sims33 
##      1      1      1      1      1      1      1      1      1      1      1 
## sims34 sims35 sims36 sims37 sims38 sims39 sims40 sims41 sims42 sims43 sims44 
##      1      1      1      1      1      1      1      1      1      1      1 
## sims45 sims46 sims47 sims48 sims49 sims50 sims51 
##      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 sims1       1
##  2     1 sims2       1
##  3     1 sims3       1
##  4     1 sims4       1
##  5     1 sims5       1
##  6     1 sims6       1
##  7     1 sims7       1
##  8     1 sims8       1
##  9     1 sims9       1
## 10     1 sims10      1
## # … with 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.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) %>% 
    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 %>% 
    
    # 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")