symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")
prices <- tq_get(
x = symbols,
get = "stock.prices",
from = "2012-01-01",
to = "2017-01-01"
)
asset_returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(
select = adjusted,
mutate_fun = periodReturn,
period = "quarterly",
type = "log"
) %>%
slice(-1) %>%
ungroup() %>%
set_names(c("asset", "date", "returns"))
symbols_vec <- asset_returns_tbl %>%
distinct(asset) %>%
pull()
weights <- c(0.25, 0.25, 0.20, 0.20, 0.10)
w_tbl <- tibble(symbols_vec, weights) %>%
set_names(c("asset", "weights"))
w_tbl
## # A tibble: 5 × 2
## asset weights
## <chr> <dbl>
## 1 AGG 0.25
## 2 EEM 0.25
## 3 EFA 0.2
## 4 IJS 0.2
## 5 SPY 0.1
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(
assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "quarters"
)
## Warning in check_weights(weights, assets_col, map, x): Sum of weights does not
## equal 1.
portfolio_sd_tbl <- portfolio_returns_tbl %>%
tq_performance(Ra = returns, performance_fun = table.Stats) %>%
select(Stdev) %>%
mutate(tq_sd = round(Stdev, 4) * 100) %>%
select(tq_sd)
portfolio_sd_tbl
## # A tibble: 1 × 1
## tq_sd
## <dbl>
## 1 3.85
asset_sd_mean_tbl <- asset_returns_tbl %>%
group_by(asset) %>%
tq_performance(Ra = returns, performance_fun = table.Stats) %>%
ungroup() %>%
select(asset, Stdev, ArithmeticMean) %>%
set_names(c("asset", "stdev", "mean"))
portfolio_mean <- mean(portfolio_returns_tbl$returns)
portfolio_row <- tibble(
asset = "Portfolio",
stdev = portfolio_sd_tbl$tq_sd / 100,
mean = portfolio_mean
)
sd_mean_table <- asset_sd_mean_tbl %>%
add_row(portfolio_row) %>%
mutate(
stdev = stdev * 100,
mean = mean * 100
)
sd_mean_table
## # A tibble: 6 × 3
## asset stdev mean
## <chr> <dbl> <dbl>
## 1 AGG 1.67 0.54
## 2 EEM 6.97 -0.53
## 3 EFA 5.56 1.07
## 4 IJS 6.13 3.43
## 5 SPY 4.05 2.95
## 6 Portfolio 3.85 1.20
sd_mean_table %>%
ggplot(aes(x = stdev, y = mean, color = asset)) +
geom_point() +
geom_text_repel(aes(label = asset)) +
labs(
title = "Expected Quarterly Return vs. Risk",
x = "Standard Deviation (Risk)",
y = "Mean Return"
) +
theme_tq() +
theme(legend.position = "none")
Based on the plot above, (name the asset(s) with the highest standard deviation) carries the most risk in this portfolio, with an expected quarterly return of (fill in). The portfolio as a whole sits at (describe its position relative to the individual assets), which shows the effect of diversification: combining assets with different risk/return profiles typically produces a portfolio with lower overall risk than its riskiest individual components, without necessarily sacrificing much expected return.