# 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.02347494
# Construct a normal distribution
simulated_monthly_returns <- rnorm(120, mean_port_return, stddev_port_return)
simulated_monthly_returns
##   [1]  0.019108037  0.007423440  0.009775975  0.009323253  0.023016764
##   [6]  0.027944517 -0.021411589 -0.013848056  0.009664662  0.018798717
##  [11] -0.024264755  0.003162282 -0.012159254 -0.015019843 -0.017254009
##  [16] -0.033001893  0.070737612  0.029007727 -0.029390103 -0.004867164
##  [21] -0.002045550 -0.022718264  0.005183583  0.023926223  0.042053403
##  [26] -0.023118202 -0.018294120  0.016663981 -0.002744558  0.018942200
##  [31] -0.005063453  0.025098735 -0.015566362 -0.032104471 -0.050802982
##  [36]  0.009649763  0.042125999  0.025999348  0.003634232 -0.008833498
##  [41]  0.016489280 -0.018124346 -0.010444461  0.002014509  0.011658999
##  [46]  0.026276775  0.019359216  0.016620352  0.032024406 -0.049469445
##  [51] -0.018006612  0.026084405 -0.034121363 -0.062140111 -0.027874403
##  [56] -0.001603079 -0.020374121 -0.001125365  0.014890987  0.002972947
##  [61]  0.027162987  0.020626758  0.041586454 -0.019272559  0.006046916
##  [66]  0.008499250  0.029939680 -0.019565223 -0.031894033 -0.039127682
##  [71] -0.007734399  0.001649552 -0.012093632  0.003875013  0.002173515
##  [76] -0.039761078  0.013510432 -0.023931265  0.053688774  0.041493144
##  [81]  0.016194581 -0.002191179 -0.040451858  0.023884436  0.010812286
##  [86] -0.028705940  0.007609486 -0.005462884 -0.013162204  0.052818488
##  [91]  0.014609561  0.008210942  0.037284119 -0.033421896  0.013076243
##  [96]  0.011502859 -0.030722318  0.019566556  0.010416363 -0.019802734
## [101] -0.029519058 -0.013993371  0.002410873  0.009742294  0.049381101
## [106]  0.030844337  0.021343618  0.038385122  0.047813361  0.005784428
## [111]  0.039075125  0.035836623  0.018959347 -0.017838847  0.026554395
## [116]  0.023689540  0.027201912  0.002485848  0.022552413 -0.002562977
# 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   1.01 
##  5   1.01 
##  6   1.02 
##  7   1.03 
##  8   0.979
##  9   0.986
## 10   1.01 
## # ℹ 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.04
##  5   1.05
##  6   1.07
##  7   1.10
##  8   1.08
##  9   1.06
## 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] 4.315016

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   353.
## 2   350.
## 3   353.
## 4   364.
## 5   361.
## 6   362.

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

# 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, colour = 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.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, colour = 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")
## $title
## [1] "Simulating Growth of $1 Over 120 Months"
## 
## $subtitle
## [1] "Maximum, Median, and Minimum Simulation"
## 
## attr(,"class")
## [1] "labels"