# 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.005899132
# 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] -0.0372485072  0.0084313707 -0.0035024084 -0.0012059103  0.0172982005
##   [6] -0.0235756401  0.0212842337 -0.0164073328 -0.0099610253 -0.0012820396
##  [11] -0.0308599544  0.0140926289  0.0207499480 -0.0335933492  0.0200368219
##  [16]  0.0052025281 -0.0151865895  0.0236629394 -0.0136135738  0.0331710396
##  [21]  0.0062522568  0.0098817588  0.0108856630  0.0203083895  0.0373138488
##  [26] -0.0053366964  0.0042320178  0.0547158030  0.0011544625 -0.0177628093
##  [31]  0.0343649802 -0.0047099723 -0.0158861514  0.0195499161  0.0077984698
##  [36] -0.0201430215  0.0016718791  0.0046977422  0.0008006202  0.0487808175
##  [41]  0.0051093450 -0.0382154592  0.0615375785  0.0271691804  0.0025095535
##  [46] -0.0214472866  0.0292875150  0.0003772257  0.0248041348  0.0216295368
##  [51]  0.0326274646  0.0170331967 -0.0160169182 -0.0124287888  0.0015582751
##  [56]  0.0213757479 -0.0211232961  0.0320765407  0.0083012749  0.0159888424
##  [61]  0.0052788697  0.0056672495  0.0134804531 -0.0086857591  0.0134056560
##  [66] -0.0181009052 -0.0085845950  0.0126414969 -0.0135471541 -0.0027262541
##  [71]  0.0468901762  0.0182526925  0.0080871960 -0.0211728488  0.0008637090
##  [76]  0.0197285490 -0.0207526949  0.0017702112  0.0403479632  0.0046182204
##  [81] -0.0057555440  0.0264548805 -0.0018998218  0.0207492827  0.0077647769
##  [86] -0.0267498045 -0.0154537579  0.0199853477  0.0196604208  0.0109870816
##  [91]  0.0262974311 -0.0369446999  0.0195743953  0.0315536409  0.0204661882
##  [96]  0.0409485262  0.0202354408 -0.0456702587  0.0206717456  0.0005424448
## [101] -0.0479981379  0.0187526405  0.0132968124  0.0368498204 -0.0184294243
## [106]  0.0090299781 -0.0211662527 -0.0070592131 -0.0081609968  0.0389410582
## [111]  0.0238633950 -0.0050453508  0.0358106050  0.0242584592  0.0143841059
## [116] -0.0283416532  0.0093829176  0.0108898714 -0.0273601154  0.0059098121
# 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.963
##  3   1.01 
##  4   0.996
##  5   0.999
##  6   1.02 
##  7   0.976
##  8   1.02 
##  9   0.984
## 10   0.990
## # ℹ 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.963
##  3  0.971
##  4  0.967
##  5  0.966
##  6  0.983
##  7  0.960
##  8  0.980
##  9  0.964
## 10  0.955
## # ℹ 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 6.897092

6 Simulation function

simulate_accmulation <- 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_accmulation(initial_value = 100, N = 240, mean_return = 0.005, sd_return = 0.01) %>%
    tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   457.
## 2   464.
## 3   464.
## 4   470.
## 5   475.
## 6   482.
dump(list = c("simulate_accumulation"),
     file = "../00_scripts/simulate_accumilation.R")

Add a dollar

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 
monte_carlo_sim_51 <- starts %>%
    
    # Simulate
    map_dfc(.x = .,
            .f = ~simulate_accmulation(initial_value = .x, 
                                       N             = 240, 
                                       mean_return   = mean_port_return, 
                                       sd_return     = stddev_port_return)) %>%
    
    # Add column worth
    mutate(month = 1:nrow(.)) %>%
    select(month, everything()) %>%
    
    # Rerange 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: 12,291 × 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
## # ℹ 12,281 more rows
monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarize(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.71  3.22  4.25  5.19 14.09

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 1s over 20 months")

Line plot with max, median, min

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  14.1   4.25  1.71
# Step 2
monte_carlo_sim_51 %>%
    
    # Filter by max, median, min
    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 1s over 20 months",
         subtitle = "Maximum, Median, and Minimum Simulation")
## $title
## [1] "Simulating growth of 1s over 20 months"
## 
## $subtitle
## [1] "Maximum, Median, and Minimum Simulation"
## 
## attr(,"class")
## [1] "labels"