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 = "monthly",
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"))
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(
assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "months"
)
risk_free_rate <- 0.0003
portfolio_sharpe_ratio_tbl <- portfolio_returns_tbl %>%
tq_performance(
Ra = returns,
performance_fun = SharpeRatio,
Rf = risk_free_rate,
FUN = "StdDev"
) %>%
as_tibble()
portfolio_sharpe_ratio_tbl
## # A tibble: 1 × 1
## `SharpeRatio(Rf=0%,p=95%)`
## <dbl>
## 1 0.154
window <- 24
calculate_rolling_sharpe_ratio <- function(data) {
rolling_sr <- SharpeRatio(
R = data,
Rf = risk_free_rate,
FUN = "StdDev"
)
return(rolling_sr)
}
rolling_sharpe_ratio_tbl <- portfolio_returns_tbl %>%
tq_mutate(
select = returns,
mutate_fun = rollapply,
width = window,
FUN = calculate_rolling_sharpe_ratio,
col_rename = "rolling_sharpe_ratio"
) %>%
select(-returns) %>%
na.omit()
rolling_sharpe_ratio_tbl
## # A tibble: 36 × 2
## date rolling_sharpe_ratio
## <date> <dbl>
## 1 2014-01-31 0.227
## 2 2014-02-28 0.233
## 3 2014-03-31 0.250
## 4 2014-04-30 0.274
## 5 2014-05-30 0.512
## 6 2014-06-30 0.488
## 7 2014-07-31 0.441
## 8 2014-08-29 0.448
## 9 2014-09-30 0.283
## 10 2014-10-31 0.329
## # ℹ 26 more rows
rolling_sharpe_ratio_tbl %>%
ggplot(aes(x = date, y = rolling_sharpe_ratio)) +
geom_line(color = "cornflowerblue") +
scale_x_date(breaks = scales::pretty_breaks(n = 7)) +
labs(x = "", y = "Rolling Sharpe Ratio",
title = paste0("Rolling ", window, " Month Sharpe Ratio")) +
theme(plot.title = element_text(hjust = 0.5))
How has your portfolio performed over time? Provide dates of the structural breaks, if any.
(Write after you knit and look at the plot. Describe where the line sits near or below zero, where it rises, and the month/year of the break.)
What might be the reason for it?
(Name 1-2 economic events near your break date, e.g., the early-2016 global selloff tied to China growth fears and oil prices, the Fed pause after the December 2015 hike, Brexit in June 2016, or the November 2016 election.)