# 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.005899134
# 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.0047971715  0.0109596698  0.0295569909  0.0119701241 -0.0238972651
##   [6] -0.0177751146  0.0003918942  0.0211387863  0.0151149429  0.0007943032
##  [11] -0.0100295661 -0.0222735109  0.0673171782 -0.0073131989 -0.0239019662
##  [16]  0.0210663301  0.0214666169 -0.0294118132  0.0296454197 -0.0228185084
##  [21]  0.0089243451 -0.0132477955 -0.0082321479 -0.0120306721  0.0150494711
##  [26] -0.0110151050  0.0133332383 -0.0160666111  0.0404155356  0.0057249631
##  [31] -0.0017170627 -0.0250991182 -0.0004696129  0.0170965798  0.0197886252
##  [36] -0.0152822581 -0.0156671148  0.0077228760  0.0126863951 -0.0471283183
##  [41]  0.0296164918  0.0481336536  0.0079012665  0.0154117015  0.0070840419
##  [46] -0.0283119207 -0.0391099293  0.0004032278  0.0344768637  0.0342003243
##  [51]  0.0001150041  0.0302052818  0.0100324959  0.0085446308 -0.0259362168
##  [56]  0.0073060030 -0.0235980435  0.0247166756  0.0354578044 -0.0344367804
##  [61]  0.0155893138  0.0357179619 -0.0154018157  0.0271472338 -0.0204369638
##  [66] -0.0087997723 -0.0273623830 -0.0027157204 -0.0147221618 -0.0062895797
##  [71]  0.0257205844 -0.0169691329  0.0301994416 -0.0217028164  0.0485265774
##  [76] -0.0415171281  0.0077565888 -0.0338247526 -0.0087619147  0.0306796967
##  [81] -0.0153283569 -0.0042885563 -0.0018942633  0.0258371498  0.0243540099
##  [86] -0.0103762100  0.0008569464  0.0004585552  0.0179790952 -0.0796394028
##  [91]  0.0111112830 -0.0308614053  0.0234918221  0.0109588871  0.0126338027
##  [96] -0.0096811310 -0.0435626249  0.0054425970  0.0136281059 -0.0377065951
## [101]  0.0226812801 -0.0343167565  0.0387229048  0.0100338599  0.0224094523
## [106] -0.0153378742  0.0496024704  0.0127671772 -0.0275670009  0.0195991278
## [111]  0.0080966108 -0.0365117583  0.0075434650  0.0154431319 -0.0061224418
## [116]  0.0535357294  0.0100700462 -0.0146361088  0.0173961520  0.0140060711
# 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.01 
##  4   1.03 
##  5   1.01 
##  6   0.976
##  7   0.982
##  8   1.00 
##  9   1.02 
## 10   1.02 
## # … 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.00
##  3   1.02
##  4   1.05
##  5   1.06
##  6   1.03
##  7   1.01
##  8   1.02
##  9   1.04
## 10   1.05
## # … with 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 2.443517

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   368.
## 2   369.
## 3   371.
## 4   375.
## 5   371.
## 6   374.
dump(list = c("simulate_accumulation"),
     file = "../00_scripts/simulate_accumulation.R")

7 Running multiple simulations

sims <- 51
starts <- rep(1, sims) %>%
    set_names(paste0("sim", 1:sims))

monte_carlo_sim_51 <- starts %>%
    
    map_dfc(.x = .,
            .f =~ simulate_accumulation(initial_value = .x, N = 120, mean_return = mean_port_return, sd_return = stddev_port_return)) %>%
    
    mutate(month = 1:nrow(.)) %>%
    select(month, everything()) %>%
    
    set_names(c("month", names(starts))) %>%
    
    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
monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    ungroup() %>%
    pull(growth) %>%
    
    quantile(probs = c(0, 0.25, 0.50, 0.75, 1)) %>%
    round(2)
##   0%  25%  50%  75% 100% 
## 1.19 1.58 1.96 2.44 2.89

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

sim_summary <- monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    ungroup() %>%
    
    summarise(max = max(growth), median = median(growth), min = min(growth))
   

monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    filter(last(growth) == sim_summary$max |
               last(growth) == sim_summary$median |
               last(growth) == sim_summary$min) %>%
    ungroup() %>%
    
    
    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")