# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Visualize and examine changes in the underlying trend in the performance of your portfolio in terms of Sharpe Ratio.

Choose your stocks.

from 2012-12-31 to present

1 Import stock prices

symbols <- c("BABA", "LLY", "JPM", "UNH") 

prices <- tq_get(x = symbols,
                 get = "stock.prices",
                 from = "2012-12-31")
symbols
## [1] "BABA" "LLY"  "JPM"  "UNH"
prices
## # A tibble: 12,475 × 8
##    symbol date        open  high   low close    volume adjusted
##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
##  1 BABA   2014-09-19  92.7  99.7  89.9  93.9 271879400     89.2
##  2 BABA   2014-09-22  92.7  92.9  89.5  89.9  66657800     85.4
##  3 BABA   2014-09-23  88.9  90.5  86.6  87.2  39009800     82.8
##  4 BABA   2014-09-24  88.5  90.6  87.2  90.6  32088000     86.0
##  5 BABA   2014-09-25  91.1  91.5  88.5  88.9  28598000     84.4
##  6 BABA   2014-09-26  89.7  90.5  88.7  90.5  18340000     85.9
##  7 BABA   2014-09-29  89.6  89.7  88.0  88.8  25302000     84.3
##  8 BABA   2014-09-30  89    90.9  88.5  88.8  24419400     84.4
##  9 BABA   2014-10-01  88.7  88.9  86.0  86.1  24029600     81.8
## 10 BABA   2014-10-02  86.3  88.2  85.6  87.1  21469700     82.7
## # ℹ 12,465 more rows

2 Convert prices to returns (monthly)

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"))
asset_returns_tbl
## # A tibble: 595 × 3
##    asset date       returns
##    <chr> <date>       <dbl>
##  1 BABA  2014-10-31  0.104 
##  2 BABA  2014-11-28  0.124 
##  3 BABA  2014-12-31 -0.0715
##  4 BABA  2015-01-30 -0.154 
##  5 BABA  2015-02-27 -0.0455
##  6 BABA  2015-03-31 -0.0223
##  7 BABA  2015-04-30 -0.0237
##  8 BABA  2015-05-29  0.0942
##  9 BABA  2015-06-30 -0.0822
## 10 BABA  2015-07-31 -0.0489
## # ℹ 585 more rows

3 Assign a weight to each asset (change the weigting scheme)

# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "BABA" "JPM"  "LLY"  "UNH"
# weights
weights <- c(0.3, 0.3, 0.25, 0.15)
weights
## [1] 0.30 0.30 0.25 0.15
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 4 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 BABA       0.3 
## 2 JPM        0.3 
## 3 LLY        0.25
## 4 UNH        0.15

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: 154 × 2
##    date        returns
##    <date>        <dbl>
##  1 2013-01-31  0.0462 
##  2 2013-02-28  0.0136 
##  3 2013-03-28  0.0112 
##  4 2013-04-30  0.0122 
##  5 2013-05-31  0.0309 
##  6 2013-06-28 -0.0225 
##  7 2013-07-31  0.0540 
##  8 2013-08-30 -0.0376 
##  9 2013-09-30  0.00184
## 10 2013-10-31 -0.00840
## # ℹ 144 more rows

5 Compute Sharpe Ratio

# Define risk free rate
rfr <- 0.0003

portfolio_SharpeRatio_tbl <- portfolio_returns_tbl %>%
    tq_performance(Ra = returns,
                   performance_fun = SharpeRatio,
                   Rf = rfr,
                   FUN = "StdDev")
portfolio_SharpeRatio_tbl
## # A tibble: 1 × 1
##   `StdDevSharpe(Rf=0%,p=95%)`
##                         <dbl>
## 1                       0.264

6 Plot: Rolling Sharpe Ratio

# Create custom function to calculate rolling SR
Calculate_rolling_SharpeRatio <- function(data) {
    rolling_SR <- SharpeRatio(R = data, 
                Rf = rfr,
                FUN = "StdDev")
    return(rolling_SR)
}
#Define window
window <- 24
# Transform data: Calculate rolling sharpe ratio
rolling_sr_tbl <- portfolio_returns_tbl %>%
    tq_mutate(select = returns,
              mutate_fun = rollapply, 
              width = window,
              FUN = Calculate_rolling_SharpeRatio,
              col_rename = "rolling_sr") %>%
    select(-returns) %>%
    na.omit()

rolling_sr_tbl
## # A tibble: 131 × 2
##    date       rolling_sr
##    <date>          <dbl>
##  1 2014-12-31      0.561
##  2 2015-01-30      0.332
##  3 2015-02-27      0.349
##  4 2015-03-31      0.340
##  5 2015-04-30      0.317
##  6 2015-05-29      0.349
##  7 2015-06-30      0.386
##  8 2015-07-31      0.319
##  9 2015-08-31      0.231
## 10 2015-09-30      0.171
## # ℹ 121 more rows
rolling_sr_tbl %>% 
    ggplot(aes(x = date, y = rolling_sr)) +
    geom_line(color = "cornflowerblue") +
    labs(x = NULL, y = "Rolling Sharpe Ratio") +
    annotate(geom = "text",
             x = as.Date("2020-06-01"), y = 0.5,
             label = "This portfolio has had 
             lots of movement and many structural breaks",
             color = "red", size = 4)

How has your portfolio performed over time? Provide dates of the structural breaks, if any. The Code Along Assignment 9 had one structural break in early 2016. What do you think the reason is?
The portfolio has had a positive rolling sharpe ratio from 2015 to the middle of 2022. It came back to positive shortly after. The structural breaks occur around 2018 and 2023. The drop around 2018 is likely due to the volatile market because of trade tension between US and China and economic slowdown concerns. The market was also coming off of record highs in the previous quarter. In 2023 it is likely due to the stock market having the worst 6-month start to a year since 1970.