# 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.005899136
# 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]  1.325865e-02  1.424862e-02  7.470928e-03  3.690035e-03  3.058941e-02
##   [6]  3.397114e-02 -1.762997e-02 -2.216122e-02  4.857209e-02 -2.033147e-02
##  [11] -1.113413e-02 -2.708836e-02  8.770986e-03  4.482595e-02  4.838984e-03
##  [16]  4.166168e-02  1.534562e-02  1.102349e-02  1.780844e-02  1.015336e-03
##  [21]  3.314248e-02  1.709804e-02  2.240913e-02 -7.849796e-03  4.084634e-03
##  [26]  1.233024e-02  4.406866e-02  3.459559e-02  8.422172e-03  2.685599e-02
##  [31]  1.489639e-02 -7.199866e-03 -4.378060e-03 -3.204202e-03  9.214047e-03
##  [36] -4.923617e-02  5.744560e-02 -2.092909e-02  4.082445e-02  2.515612e-02
##  [41]  2.888590e-02 -2.168239e-02 -3.876620e-03  2.325367e-02  1.199379e-02
##  [46]  2.257274e-03 -1.383982e-02 -8.781516e-03 -4.085591e-03  3.819135e-02
##  [51] -3.235508e-02  1.431811e-02  1.747262e-02  1.833183e-02 -1.000901e-02
##  [56]  3.224292e-02 -8.157968e-03  3.222447e-03 -1.157854e-02 -5.089829e-02
##  [61] -1.713747e-02  7.260416e-02 -1.102216e-02  6.252727e-02 -1.339567e-03
##  [66] -5.622235e-02 -7.209396e-03 -1.315803e-03  6.173669e-02 -1.874933e-02
##  [71] -3.446263e-03  3.580277e-02 -2.099631e-02  5.251997e-02  1.488338e-02
##  [76]  1.251279e-02  2.112237e-02 -3.321124e-02 -2.564261e-02  1.543575e-02
##  [81]  1.533278e-05  8.026437e-03  1.236333e-02  4.311670e-02 -9.191289e-03
##  [86] -1.945302e-03  2.794414e-02  8.934254e-03  7.634465e-03  2.047365e-02
##  [91] -3.545953e-02  2.783733e-02 -1.848034e-02  4.260797e-02  4.720416e-02
##  [96]  2.412467e-03 -5.614803e-03 -1.713190e-03 -2.791021e-02 -1.026426e-02
## [101] -3.107204e-02  7.706796e-03  1.011281e-02 -2.675055e-02  1.968697e-02
## [106] -9.974694e-03  1.060285e-02  1.531650e-02  2.070715e-02 -2.227356e-02
## [111] -4.972545e-03  1.808254e-02  7.481565e-03  8.234668e-03 -3.837347e-03
## [116] -3.663747e-02  4.282376e-03  1.981018e-02  2.645996e-02 -5.416325e-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.01 
##  3   1.01 
##  4   1.01 
##  5   1.00 
##  6   1.03 
##  7   1.03 
##  8   0.982
##  9   0.978
## 10   1.05 
## # ℹ 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.04
##  5   1.04
##  6   1.07
##  7   1.11
##  8   1.09
##  9   1.06
## 10   1.12
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 7.91191

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.05, sd_return = 0.01) %>%
  tail()
## # A tibble: 6 × 1
##      growth
##       <dbl>
## 1 10679709.
## 2 11282997.
## 3 11809197.
## 4 12378377.
## 5 12953503.
## 6 13392187.

7 Running multiple simulations

# Create a vector of 1s as a starting point
sims <- 51
starts <- rep(1, sims) %>%
  set_names (paste("sim", 1:sims))

starts
##  sim 1  sim 2  sim 3  sim 4  sim 5  sim 6  sim 7  sim 8  sim 9 sim 10 sim 11 
##      1      1      1      1      1      1      1      1      1      1      1 
## sim 12 sim 13 sim 14 sim 15 sim 16 sim 17 sim 18 sim 19 sim 20 sim 21 sim 22 
##      1      1      1      1      1      1      1      1      1      1      1 
## sim 23 sim 24 sim 25 sim 26 sim 27 sim 28 sim 29 sim 30 sim 31 sim 32 sim 33 
##      1      1      1      1      1      1      1      1      1      1      1 
## sim 34 sim 35 sim 36 sim 37 sim 38 sim 39 sim 40 sim 41 sim 42 sim 43 sim 44 
##      1      1      1      1      1      1      1      1      1      1      1 
## sim 45 sim 46 sim 47 sim 48 sim 49 sim 50 sim 51 
##      1      1      1      1      1      1      1
# Simulate
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 sim 1       1
##  2     1 sim 2       1
##  3     1 sim 3       1
##  4     1 sim 4       1
##  5     1 sim 5       1
##  6     1 sim 6       1
##  7     1 sim 7       1
##  8     1 sim 8       1
##  9     1 sim 9       1
## 10     1 sim 10      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.09 1.63 1.95 2.22 3.12

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 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.12   1.95  1.09
# 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")