# 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("UNH", "LLY", "JNJ", "PFE", "MRK")

prices <- tq_get(x = symbols, 
                 get = "stock.prices", 
                 from = "2000-12-31", 
                 to = "2025-06-11")

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"))

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

# Symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "JNJ" "LLY" "MRK" "PFE" "UNH"
# weights
weights <- c(0.3, 0.25, 0.20, 0.13, 0.12)
weights
## [1] 0.30 0.25 0.20 0.13 0.12
w_tbl <-tibble(symbols, weights)
w_tbl
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 JNJ        0.3 
## 2 LLY        0.25
## 3 MRK        0.2 
## 4 PFE        0.13
## 5 UNH        0.12

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: 293 × 2
##    date        returns
##    <date>        <dbl>
##  1 2001-02-28  0.0181 
##  2 2001-03-30 -0.0633 
##  3 2001-04-30  0.0746 
##  4 2001-05-31 -0.0211 
##  5 2001-06-29 -0.0516 
##  6 2001-07-31  0.0677 
##  7 2001-08-31 -0.0268 
##  8 2001-09-28  0.0323 
##  9 2001-10-31 -0.00428
## 10 2001-11-30  0.0495 
## # ℹ 283 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.148

6 Plot: Rolling Sharpe Ratio

# Create a Custom Function to Calculate Rolling SR
Calculate_rolling_SharpeRatio <- function(data) {
    
    rolling_SR <- SharpeRatio(R = data,
                Rf = rfr,
                FUN = "StdDev")
    
    return(rolling_SR)
}

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: 270 × 2
##    date       rolling_sr
##    <date>          <dbl>
##  1 2003-01-31    -0.0708
##  2 2003-02-28    -0.120 
##  3 2003-03-31    -0.0129
##  4 2003-04-30    -0.0541
##  5 2003-05-30    -0.0596
##  6 2003-06-30     0.0402
##  7 2003-07-31    -0.0492
##  8 2003-08-29    -0.0570
##  9 2003-09-30    -0.109 
## 10 2003-10-31    -0.0925
## # ℹ 260 more rows
rolling_sr_tbl %>%
    
    ggplot(aes(x = date, y = rolling_sr)) +
    geom_line(color = "cornflowerblue") +
    
    # Labeling
    labs(x = NULL, y = "Rolling Sharpe Ratio") +
    
    annotate(geom = "text",
             x = as.Date("2015-06-01"), y = 0,
             label = str_glue(""),
             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 November 2016. What do you think the reason is?

The 24-month rolling Sharpe ratio of the portfolio shows several clear structural shifts in performance over time. From 2002 to 2008, the Sharpe ratio remained volatile and hovered around zero, indicating inconsistent risk-adjusted returns. A noticeable structural break occurs around 2008–2009, where the Sharpe ratio drops sharply into negative territory, reflecting the impact of the Global Financial Crisis on the broader market, including the healthcare sector. Following the crisis, a significant upward break occurs beginning in 2010, with the Sharpe ratio rising steadily and peaking around 2014–2015. This period of strong performance likely reflects the post-crisis economic recovery, increased demand for healthcare services, and policy tailwinds from the Affordable Care Act. From 2016 to 2020, the Sharpe ratio fluctuates but remains positive. This stability may have been influenced by ongoing innovation in pharmaceuticals, although partially offset by political uncertainty around healthcare regulation and drug pricing. During the 2020 COVID-19 pandemic, the Sharpe ratio dipped initially but rebounded quickly, likely because of the health sectors strong preformance following the creation of COVID vaccines. However, a gradual structural decline is visible from 2023 onward, with the Sharpe ratio trending downward and dipping and dipping slightly negative in 2025. This decline could be attributed to rising interest rates compressing valuations, investor rotation out of defensive sectors like healthcare, and underperformance from traditional pharmaceutical companies due to pricing pressures and fewer blockbuster drug developments. Overall, the portfolio’s Sharpe ratio reflects major macroeconomic and policy-driven shifts in the healthcare sector over the last two decades.

The portfolio in the Code Along 9 Assignment likely had a strong sharpe ratio after 2016 due to a combination of strong economic growth, supportive monetary policy, and high corporate earnings. During this period, the U.S. economy experienced consistent GDP growth, low unemployment, and rising consumer confidence, which helped drive demand across sectors. Corporate tax reform, particularly the Tax Cuts and Jobs Act of 2017, significantly reduced the corporate tax rate, boosting after-tax profits and increasing shareholder returns through stock buybacks and dividends. In addition, the Federal Reserve maintained relatively low interest rates for most of this period, creating a favorable environment for equities by keeping borrowing costs low and encouraging investment. Technology stocks, which make up a large portion of broad market indices like the S&P 500, also delivered exceptional returns during these years, driven by rapid innovation, increased digital adoption, and strong earnings growth. The combination of low inflation, accommodative policy, and robust corporate fundamentals contributed to a period of strong risk-adjusted returns for broadly diversified portfolios.