# 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.005899135
# Get standard deviation of portfolio returns
stddev_port_return <- sd(portfolio_returns_tbl$returns)
stddev_port_return
## [1] 0.02347488
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1] -7.404312e-03 -4.126167e-03 -2.499467e-02 -2.376373e-03  3.270812e-02
##   [6] -1.804371e-02  4.972078e-03  3.419272e-02 -8.055983e-03  9.933403e-03
##  [11] -2.564137e-02  2.020817e-02 -8.744405e-03 -1.659414e-02  1.806786e-02
##  [16]  2.594064e-02  1.958632e-02 -3.585763e-02 -1.434735e-02  4.507499e-03
##  [21]  1.953403e-03 -6.848481e-03 -8.398770e-03  1.979438e-02 -7.809989e-03
##  [26] -3.244919e-02 -3.006293e-02  7.503909e-03  2.878774e-02  1.773027e-02
##  [31]  3.027485e-02 -4.146180e-03 -8.450976e-03  5.221664e-03 -1.403036e-02
##  [36] -1.589187e-02  1.318464e-02  3.192075e-03 -7.987499e-04 -9.404603e-03
##  [41]  6.746221e-03 -1.736502e-02 -1.233971e-02 -2.832421e-02  2.651379e-02
##  [46]  2.781808e-02 -3.108868e-02  8.231438e-03  2.458958e-02  4.046298e-02
##  [51]  7.042105e-03  3.213908e-03  3.914599e-02 -1.667563e-02 -1.252818e-02
##  [56] -5.349285e-02 -1.609663e-02 -1.923026e-03 -3.800598e-02  1.095990e-02
##  [61] -3.490615e-02  1.257192e-02 -4.306719e-02  1.927766e-02 -8.008520e-03
##  [66]  2.515030e-02  3.479629e-03  1.221008e-02 -2.686625e-03 -4.123383e-04
##  [71]  8.090473e-03  3.055581e-02  1.189211e-02  2.179588e-02  2.747454e-02
##  [76]  2.329867e-02  1.541788e-02  1.487564e-02 -7.993791e-03  3.187934e-02
##  [81]  2.379701e-02 -9.600298e-03  5.240225e-02 -2.852886e-02 -6.811218e-03
##  [86]  3.560985e-02  3.479368e-02  2.889219e-02  3.737281e-02 -1.581318e-02
##  [91] -8.362821e-03 -2.832078e-02 -2.353193e-03  1.734717e-02  2.801721e-02
##  [96]  2.499535e-02 -3.643451e-02  9.412313e-03 -3.715787e-02 -1.286341e-02
## [101]  2.305565e-04  4.627692e-02 -2.688407e-02  6.347432e-02  2.711783e-02
## [106]  1.686786e-02 -6.176202e-03  1.492534e-02  3.189133e-02 -1.643044e-03
## [111]  1.762592e-02  3.096437e-02 -4.058624e-03  2.821928e-02  2.790025e-02
## [116] -3.227222e-02 -2.187199e-02  4.962936e-02  2.403338e-02 -9.440486e-05
# 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.993
##  3   0.996
##  4   0.975
##  5   0.998
##  6   1.03 
##  7   0.982
##  8   1.00 
##  9   1.03 
## 10   0.992
## # ℹ 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.993
##  3  0.989
##  4  0.964
##  5  0.962
##  6  0.993
##  7  0.975
##  8  0.980
##  9  1.01 
## 10  1.01 
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 4.923999

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   289.
## 2   290.
## 3   301.
## 4   311.
## 5   314.
## 6   312.
dump(list = c("simulate_accumulation"),
     file = "../00_Data/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) %>%
    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 growht of $1 over 120 months")

Line plot with max, median, and min

# Step 1 summarize data into max, median, and min of 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 growht of $1 over 120 months",
         subtitle = "Maximum, Median, and Minimum Simulation")