# 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.02347491
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  2.041733e-02  1.015888e-02 -2.336634e-02 -1.471578e-02 -1.351180e-02
##   [6]  1.010533e-02 -4.756080e-02  4.416466e-02  3.427588e-02  3.471348e-02
##  [11]  8.515783e-03  8.083455e-03  1.317834e-02  2.909665e-02 -1.886589e-02
##  [16]  4.991103e-02  1.354253e-02 -3.156233e-03  2.355579e-02 -8.218881e-04
##  [21] -7.996795e-03  2.118552e-02  5.255245e-02  3.549528e-03  2.073503e-02
##  [26] -2.414747e-02 -1.935889e-03 -8.747973e-04 -1.325908e-02  1.164116e-02
##  [31] -9.814345e-03  6.226363e-02  1.744488e-02  2.489199e-02 -5.716319e-03
##  [36]  4.558888e-02  3.016181e-02  2.160827e-02  2.744917e-02  3.538369e-02
##  [41] -2.234071e-02 -8.604302e-03 -3.383897e-03 -9.684692e-04  3.197252e-02
##  [46]  1.861759e-02  4.982971e-02 -1.691538e-02  3.179543e-02 -1.977228e-02
##  [51]  6.136934e-03  4.988448e-03 -9.181008e-04  3.201019e-02  4.251780e-03
##  [56] -1.479484e-02 -4.177462e-03  3.183675e-02  7.078307e-04  4.170986e-03
##  [61] -4.119657e-03 -9.848269e-03 -2.312064e-03  2.821311e-02  1.971863e-02
##  [66]  1.890609e-02  2.291630e-02  2.505892e-02 -5.974224e-04  1.800173e-02
##  [71]  1.659016e-02  3.105200e-02 -1.124934e-02 -3.431179e-02 -9.372067e-03
##  [76]  2.246292e-02 -2.238927e-02  1.057084e-02  1.706422e-02 -1.245153e-02
##  [81] -1.770593e-02 -8.388476e-03  3.103151e-02  1.555918e-02  6.605948e-03
##  [86] -1.592640e-02 -2.228123e-03 -1.479251e-02  3.155207e-02  3.436638e-02
##  [91]  1.554073e-02  3.056112e-02 -3.348582e-02  2.312346e-03  7.584747e-05
##  [96] -4.246650e-02  9.677393e-03  3.963584e-02 -8.521081e-03 -2.030325e-02
## [101]  2.827347e-02 -3.736899e-03  3.120848e-02  1.968878e-02 -1.640779e-03
## [106]  1.728500e-02  1.637242e-02 -3.979846e-02 -4.006375e-03 -5.645349e-03
## [111] -6.122304e-02  2.645772e-02 -1.519119e-02 -7.304426e-03  1.094772e-02
## [116]  3.943661e-02 -1.458934e-03  7.734013e-03  3.637767e-02  7.424480e-03
# 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.02 
##  3   1.01 
##  4   0.977
##  5   0.985
##  6   0.986
##  7   1.01 
##  8   0.952
##  9   1.04 
## 10   1.03 
## # … 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.02 
##  3  1.03 
##  4  1.01 
##  5  0.992
##  6  0.978
##  7  0.988
##  8  0.941
##  9  0.983
## 10  1.02 
## # … with 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 8.960549

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   248.
## 2   252.
## 3   253.
## 4   258.
## 5   260.
## 6   260.
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())%>%
    
    # Rename 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
## # … 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, medium, and min

# Step 1: Summarize data into max, median and min if 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")