# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Calculate and visualize your portfolio’s beta.

Choose your stocks and the baseline market.

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 Calculate CAPM Beta

5.1 Get market returns

market_returns_tbl <- tq_get(x = "SPY", 
                 get = "stock.prices", 
                 from = "2012-12-31", 
                 to = "2017-12-31") %>%
    
    # Convert prices to returns
    tq_transmute(select = adjusted, 
                 mutate_fun = periodReturn,
                 period = "monthly",
                 type = "log", 
                 col_rename = "returns") %>%
    
    slice(-1)

5.2 Join Returns

portfolio_market_returns_tbl <- left_join(market_returns_tbl, portfolio_returns_tbl, "date") %>%
    
    set_names("date", "market_returns", "portfolio_returns")

5.3 CAPM Beta

portfolio_market_returns_tbl %>%
    
    tq_performance(Ra = portfolio_returns, 
                   Rb = market_returns,
                   performance_fun = CAPM.beta)
## # A tibble: 1 × 1
##   CAPM.beta.1
##         <dbl>
## 1       0.687

6 Plot: Scatter with regression line

portfolio_market_returns_tbl %>%
    
    ggplot(aes(x = market_returns, 
               y = portfolio_returns)) +
    geom_point(color = "cornflowerblue") +
    geom_smooth(method = "lm", se = FALSE, size = 1.5, color = tidyquant::palette_light()[3]) +
    
    labs(y = "Portfolio Returns", 
         x = "Market Returns")

How sensitive is your portfolio to the market? Discuss in terms of the beta coefficient. Does the plot confirm the beta coefficient you calculated?

The beta coefficient of 0.687 indicates that the portfolio is moderately sensitive to movements in the market. Specifically, for every 1% change in market returns, the portfolio is expected to move approximately 0.687%. This suggests that the portfolio has less volatility than the overall market, meaning it is relatively defensive and would typically decline less than the market in a downturn, but also rise less during an upturn. The scatter plot of portfolio returns versus market returns confirms this beta estimate. The upward-sloping trend line illustrates a positive relationship. While the data points are somewhat dispersed around the trend line, they generally follow the direction of the market, which supports the conclusion that the portfolio is positively but not strongly correlated with market movements. This is consistent with the beta coefficient provided.