# Load packages
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidyquant) 
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend
## 
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo

1 Get stock prices and convert to returns

Ra <- c("AAPL", "GOOG", "NFLX") %>%
  tq_get(get  = "stock.prices",
         from = "2010-01-01",
         to   = "2015-12-31") %>%
  group_by(symbol) %>%
  tq_transmute(select     = adjusted,
               mutate_fun = periodReturn,
               perio      = "monthly",
               col_rename = "Ra")
Ra
## # A tibble: 216 × 3
## # Groups:   symbol [3]
##    symbol date            Ra
##    <chr>  <date>       <dbl>
##  1 AAPL   2010-01-29 -0.103 
##  2 AAPL   2010-02-26  0.0654
##  3 AAPL   2010-03-31  0.148 
##  4 AAPL   2010-04-30  0.111 
##  5 AAPL   2010-05-28 -0.0161
##  6 AAPL   2010-06-30 -0.0208
##  7 AAPL   2010-07-30  0.0227
##  8 AAPL   2010-08-31 -0.0550
##  9 AAPL   2010-09-30  0.167 
## 10 AAPL   2010-10-29  0.0607
## # ℹ 206 more rows

2 Get baseline and convert to returns

Rb <- "XLK" %>%
  tq_get(get  = "stock.prices",
         from = "2010-01-01",
         to   = "2015-12-31") %>%
  tq_transmute(select    = adjusted,
              mutate_fun = periodReturn,
              period     = "monthly",
              col_rename = "Rb")
Rb
## # A tibble: 72 × 2
##    date            Rb
##    <date>       <dbl>
##  1 2010-01-29 -0.0993
##  2 2010-02-26  0.0348
##  3 2010-03-31  0.0684
##  4 2010-04-30  0.0126
##  5 2010-05-28 -0.0748
##  6 2010-06-30 -0.0540
##  7 2010-07-30  0.0745
##  8 2010-08-31 -0.0561
##  9 2010-09-30  0.117 
## 10 2010-10-29  0.0578
## # ℹ 62 more rows

3 Join the two tables

RaRb <- left_join(Ra, Rb, by = c("date" = "date"))
RaRb
## # A tibble: 216 × 4
## # Groups:   symbol [3]
##    symbol date            Ra      Rb
##    <chr>  <date>       <dbl>   <dbl>
##  1 AAPL   2010-01-29 -0.103  -0.0993
##  2 AAPL   2010-02-26  0.0654  0.0348
##  3 AAPL   2010-03-31  0.148   0.0684
##  4 AAPL   2010-04-30  0.111   0.0126
##  5 AAPL   2010-05-28 -0.0161 -0.0748
##  6 AAPL   2010-06-30 -0.0208 -0.0540
##  7 AAPL   2010-07-30  0.0227  0.0745
##  8 AAPL   2010-08-31 -0.0550 -0.0561
##  9 AAPL   2010-09-30  0.167   0.117 
## 10 AAPL   2010-10-29  0.0607  0.0578
## # ℹ 206 more rows

4 Calculate CAPM

RaRb_capm <- RaRb %>%
  tq_performance(Ra = Ra,
                 Rb = Rb,
                 performance_fun = table.CAPM)
RaRb_capm
## # A tibble: 3 × 13
## # Groups:   symbol [3]
##   symbol ActivePremium  Alpha AnnualizedAlpha  Beta `Beta-` `Beta+` Correlation
##   <chr>          <dbl>  <dbl>           <dbl> <dbl>   <dbl>   <dbl>       <dbl>
## 1 AAPL           0.119 0.0089           0.112 1.11    0.578  1.04        0.659 
## 2 GOOG           0.034 0.0028           0.034 1.14    1.39   1.16        0.644 
## 3 NFLX           0.447 0.053            0.859 0.384  -1.52   0.0045      0.0817
## # ℹ 5 more variables: `Correlationp-value` <dbl>, InformationRatio <dbl>,
## #   `R-squared` <dbl>, TrackingError <dbl>, TreynorRatio <dbl>