# 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.005899133
# 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]  3.062685e-05  4.233574e-02 -4.398624e-03  2.264499e-02 -1.057662e-02
##   [6] -4.696845e-03 -1.585848e-02  1.684246e-02  2.621087e-02  4.324203e-02
##  [11] -1.676672e-02  5.785743e-02  2.579575e-02  2.476738e-02 -2.562261e-02
##  [16]  4.017410e-02 -2.128887e-02 -3.924119e-02 -2.642693e-02  2.931042e-02
##  [21]  2.298258e-02  3.649870e-02 -4.870266e-03  2.306966e-02  1.662744e-02
##  [26]  1.607967e-03  2.296525e-02 -4.599065e-02  2.754170e-02 -2.042464e-02
##  [31]  3.149570e-02  1.018121e-02  2.424727e-04 -2.108595e-02 -1.598634e-02
##  [36] -2.159256e-02  1.639595e-02  6.750562e-03  3.932387e-02 -8.762017e-05
##  [41] -4.013559e-03 -2.416861e-02  7.721519e-03  1.876680e-02  2.672358e-02
##  [46]  3.012843e-02  1.633513e-02  1.034499e-02  5.844194e-02  5.659841e-03
##  [51] -1.505889e-02  4.875720e-02  1.314665e-02  5.532185e-03  5.938856e-03
##  [56]  7.113641e-03  1.270066e-02  2.507221e-02 -1.835060e-03  2.833785e-02
##  [61]  6.677125e-02 -4.445966e-03  3.664436e-02  4.221553e-02  4.902183e-02
##  [66] -3.187519e-02  5.509144e-02 -2.696073e-02  2.539710e-02  1.136307e-02
##  [71]  5.948907e-03 -2.443244e-03  2.269710e-04 -6.546831e-03  3.839075e-02
##  [76]  2.126654e-02  6.106340e-03  8.379518e-02 -1.133829e-03 -2.947433e-03
##  [81] -1.107693e-02  1.293624e-02 -2.679458e-02  1.479834e-02 -3.791097e-02
##  [86]  1.179340e-02  2.420060e-02  2.824006e-03 -5.139290e-02  3.339425e-02
##  [91] -3.703838e-02 -2.334008e-02  3.950091e-02 -5.770043e-03  3.419852e-02
##  [96]  3.047693e-02 -1.706679e-02  7.332404e-03  3.991807e-02  4.763534e-02
## [101]  1.136618e-02  1.506465e-02  1.258181e-02 -1.290352e-02 -2.912625e-03
## [106]  5.573545e-03  7.474927e-03 -1.849674e-02  1.280156e-02  2.827718e-02
## [111]  8.603772e-03  5.259132e-03  4.682342e-02  4.127334e-03 -1.906741e-02
## [116]  1.161834e-02  8.571648e-03 -3.491842e-02  2.200364e-02 -3.342574e-02
# 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.00 
##  3   1.04 
##  4   0.996
##  5   1.02 
##  6   0.989
##  7   0.995
##  8   0.984
##  9   1.02 
## 10   1.03 
## # ℹ 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.00
##  3   1.04
##  4   1.04
##  5   1.06
##  6   1.05
##  7   1.05
##  8   1.03
##  9   1.05
## 10   1.07
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 11.13393

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 cumative 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   371.
## 2   361.
## 3   361.
## 4   371.
## 5   371.
## 6   373.

7 Running multiple simulations

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

# 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 into 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 sin1       1
##  2     1 sin2       1
##  3     1 sin3       1
##  4     1 sin4       1
##  5     1 sin5       1
##  6     1 sin6       1
##  7     1 sin7       1
##  8     1 sin8       1
##  9     1 sin9       1
## 10     1 sin10      1
## # ℹ 6,161 more rows
# find quantiles
monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    pull(growth) %>%
    
    quantile(probs = c(0, 0.25, 0.5, 0.75, 1)) %>%
    round(2)
##   0%  25%  50%  75% 100% 
## 1.06 1.63 1.89 2.19 3.75

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")

# 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.75   1.89  1.06
# 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 = "Max, Median and Minimum")
## $title
## [1] "Simulating growth of $1 over 120 months"
## 
## $subtitle
## [1] "Max, Median and Minimum"
## 
## attr(,"class")
## [1] "labels"