# 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.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]  1.896632e-02  1.217248e-02  1.227409e-02  1.972233e-02  1.822330e-02
##   [6] -4.635837e-02  1.717932e-02 -3.935831e-02 -1.719429e-02  3.526530e-02
##  [11] -3.429227e-03 -4.488644e-02  2.528200e-03  2.176082e-03  7.100882e-03
##  [16] -9.948643e-03  3.245354e-02 -4.977288e-02  5.950456e-04  2.094340e-02
##  [21]  8.083819e-03 -2.763552e-02  2.793377e-02  5.809844e-03  1.014520e-02
##  [26]  1.538351e-02  2.566174e-02  2.423042e-02 -3.445707e-02 -1.067754e-02
##  [31] -1.184030e-02  1.172586e-02 -3.708744e-02  1.255980e-02 -4.232571e-03
##  [36]  1.472817e-02  2.730568e-02 -2.810319e-03 -3.505774e-03  3.736269e-02
##  [41]  8.489400e-02  2.221951e-02  9.875509e-03 -2.581638e-02  2.496742e-02
##  [46]  7.736401e-03  3.310179e-02  3.269904e-02  2.717708e-02  1.080437e-02
##  [51] -8.298816e-03  1.660676e-02  1.652941e-02  1.211156e-02  4.593890e-02
##  [56]  7.148112e-03  1.285800e-02 -1.923936e-02  4.934753e-02  1.993897e-02
##  [61]  5.933093e-03 -1.850021e-02  3.340416e-02  4.037769e-02  2.577244e-02
##  [66] -3.938341e-02  2.370417e-02  1.024807e-02  2.467560e-02  1.294410e-02
##  [71]  2.808241e-02 -6.250369e-03  1.473310e-02 -1.092611e-02 -2.138732e-02
##  [76]  5.430369e-03  3.032100e-02  6.048285e-02 -2.992604e-02 -2.803205e-02
##  [81]  6.790042e-03  2.686514e-02 -2.827298e-03  1.211727e-02  1.026275e-02
##  [86] -2.324359e-03  1.534780e-02  2.861937e-02 -7.310854e-05  4.753847e-03
##  [91] -7.610177e-03  6.062740e-03 -3.366456e-02 -9.190583e-03 -1.573936e-02
##  [96]  4.092573e-02  2.766869e-03  4.038860e-03  3.786570e-03 -2.141061e-02
## [101]  2.560926e-02  1.176251e-02  9.116095e-03 -8.108084e-02 -3.661285e-02
## [106]  7.673238e-04 -1.033495e-02  2.971205e-02 -5.980100e-03 -6.417144e-03
## [111] -8.264396e-03  1.982093e-02  2.113696e-02 -1.426928e-02  2.143803e-02
## [116] -3.770224e-04  2.665681e-02 -1.621586e-02 -2.665350e-02 -7.989413e-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.02 
##  3   1.01 
##  4   1.01 
##  5   1.02 
##  6   1.02 
##  7   0.954
##  8   1.02 
##  9   0.961
## 10   0.983
## # … 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.02 
##  3  1.03 
##  4  1.04 
##  5  1.06 
##  6  1.08 
##  7  1.03 
##  8  1.05 
##  9  1.01 
## 10  0.993
## # … with 111 more rows
# Check the compound annual growth rate
cagr <- ((simulated_growth$growth[nrow(simulated_growth)]^(1/10)) - 1) * 100
cagr
## [1] 6.227308

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 = .005,sd_return = .01) %>% tail()
## # A tibble: 6 × 1
##   growth
##    <dbl>
## 1   290.
## 2   292.
## 3   292.
## 4   298.
## 5   304.
## 6   304.
dump(list = c("simulate accumulation"), 
     file = "../00_scripts/simulate accumulation.R")

7 Running multiple simulations

# Create a vector a starting function
sims <- 100
starts <- rep(100, sims) %>%
    set_names(paste0("sim", 1:sims))
starts
##   sim1   sim2   sim3   sim4   sim5   sim6   sim7   sim8   sim9  sim10  sim11 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim12  sim13  sim14  sim15  sim16  sim17  sim18  sim19  sim20  sim21  sim22 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim23  sim24  sim25  sim26  sim27  sim28  sim29  sim30  sim31  sim32  sim33 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim34  sim35  sim36  sim37  sim38  sim39  sim40  sim41  sim42  sim43  sim44 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim45  sim46  sim47  sim48  sim49  sim50  sim51  sim52  sim53  sim54  sim55 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim56  sim57  sim58  sim59  sim60  sim61  sim62  sim63  sim64  sim65  sim66 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim67  sim68  sim69  sim70  sim71  sim72  sim73  sim74  sim75  sim76  sim77 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim78  sim79  sim80  sim81  sim82  sim83  sim84  sim85  sim86  sim87  sim88 
##    100    100    100    100    100    100    100    100    100    100    100 
##  sim89  sim90  sim91  sim92  sim93  sim94  sim95  sim96  sim97  sim98  sim99 
##    100    100    100    100    100    100    100    100    100    100    100 
## sim100 
##    100
# 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: 12,100 × 3
##    month sim   growth
##    <int> <chr>  <dbl>
##  1     1 sim1     100
##  2     1 sim2     100
##  3     1 sim3     100
##  4     1 sim4     100
##  5     1 sim5     100
##  6     1 sim6     100
##  7     1 sim7     100
##  8     1 sim8     100
##  9     1 sim9     100
## 10     1 sim10    100
## # … with 12,090 more rows
# Find Quantiles
monte_carlo_sim_51 %>%
    group_by(sim) %>%
    summarise(growth = last(growth)) %>%
    ungroup() %>%
    pull(growth) %>%
    quantile(Probs = c(0, .25, .5, .75, 1)) %>%
    round(2)
##     0%    25%    50%    75%   100% 
##  78.20 165.78 198.88 227.84 336.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 = .5))+
    labs(title = "Simulating the growth of 1 dollar over 120 months")

New Line plot with max, median, and minimum

# Step one Summarized data into maximum medium and minimum
sim_summary <- monte_carlo_sim_51 %>%
    
    group_by(sim) %>%
    summarize(growth = last(growth)) %>%
    ungroup() %>%
    summarize(max = max(growth),
              median = median(growth),
              min = min(growth))

sim_summary
## # A tibble: 1 × 3
##     max median   min
##   <dbl>  <dbl> <dbl>
## 1  336.   199.  78.2
# Step 2 plot 
monte_carlo_sim_51 %>%
    
    # Filter for max, median, and 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 = .5)) + 
    theme(plot.subtitle = element_text(hjust = .5)) +
    labs(title = "Simulating the growth of 1 dollar over 120 months",      subtitle = "Max, Medium, and Min Simulation")