Reproducible Finance with R — Chapter 1

Major Takeaways

tq_get

Get stock prices

AAPL <- tq_get("AAPL", get = "stock.prices", from = "2010-01-01")
AAPL
## # A tibble: 4,204 × 8
##    symbol date        open  high   low close    volume adjusted
##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
##  1 AAPL   2010-01-04  7.62  7.66  7.59  7.64 493729600     6.40
##  2 AAPL   2010-01-05  7.66  7.70  7.62  7.66 601904800     6.41
##  3 AAPL   2010-01-06  7.66  7.69  7.53  7.53 552160000     6.31
##  4 AAPL   2010-01-07  7.56  7.57  7.47  7.52 477131200     6.30
##  5 AAPL   2010-01-08  7.51  7.57  7.47  7.57 447610800     6.34
##  6 AAPL   2010-01-11  7.60  7.61  7.44  7.50 462229600     6.28
##  7 AAPL   2010-01-12  7.47  7.49  7.37  7.42 594459600     6.21
##  8 AAPL   2010-01-13  7.42  7.53  7.29  7.52 605892000     6.30
##  9 AAPL   2010-01-14  7.50  7.52  7.47  7.48 432894000     6.26
## 10 AAPL   2010-01-15  7.53  7.56  7.35  7.35 594067600     6.16
## # ℹ 4,194 more rows

Get economic data from FRED

To find a series symbol, search the data series name on the St. Louis Fed’s FRED website (fred.stlouisfed.org) and copy the symbol shown next to the series title. The example below uses the national unemployment rate (UNRATE) — swap in whatever series symbol you need.

unemployment <- tq_get("UNRATE", get = "economic.data")
## Warning: x = 'UNRATE', get = 'economic.data': Error in getSymbols.FRED(Symbols = "UNRATE", env = <environment>, verbose = FALSE, : Unable to import "UNRATE".
## Stream error in the HTTP/2 framing layer [fred.stlouisfed.org]:
## HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2)
## getSymbols.FRED: requests without an API key are not guaranteed to succeed.
## Register for a free key at https://fredaccount.stlouisfed.org/apikeys and set it with
## setDefaults(getSymbols.FRED, api.key = "your key").
unemployment
## [1] NA

Charting with tidyquant

Line chart

AAPL %>%
  ggplot(aes(x = date, y = close)) +
  geom_line() +
  labs(title = "AAPL Line Chart", y = "Closing Price", x = "") +
  theme_tq()

Bar chart

AAPL %>%
  tail(30) %>%
  ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close)) +
  geom_barchart() +
  labs(title = "AAPL Bar Chart (last 30 days)", y = "Price", x = "") +
  theme_tq()

Candlestick chart

AAPL %>%
  tail(30) %>%
  ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close)) +
  geom_candlestick() +
  labs(title = "AAPL Candlestick Chart (last 30 days)", y = "Price", x = "") +
  theme_tq()

Performance Analysis with tidyquant

Quick example: Capital Asset Pricing Model

Step 1: Get stock prices and convert to returns

symbols <- c("AAPL", "GOOG", "NFLX")

RA <- symbols %>%
  tq_get(get = "stock.prices", from = "2010-01-01") %>%
  group_by(symbol) %>%
  tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = "monthly",
               col_rename = "Ra")
RA
## # A tibble: 603 × 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
## # ℹ 593 more rows

Step 2: Get baseline and convert to returns

RB <- "XLK" %>%
  tq_get(get = "stock.prices", from = "2010-01-01") %>%
  tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = "monthly",
               col_rename = "Rb")
RB
## # A tibble: 201 × 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
## # ℹ 191 more rows

Step 3: Join the two return tables

RAb <- left_join(RA, RB, by = "date")
RAb
## # A tibble: 603 × 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
## # ℹ 593 more rows

Step 4: Calculate performance metrics (CAPM)

RAb %>%
  tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM)
## Registered S3 method overwritten by 'robustbase':
##   method          from     
##   hatvalues.lmrob RobStatTM
## # A tibble: 3 × 18
## # Groups:   symbol [3]
##   symbol ActivePremium  Alpha AlphaRobust AnnualizedAlpha  Beta `Beta-`
##   <chr>          <dbl>  <dbl>       <dbl>           <dbl> <dbl>   <dbl>
## 1 AAPL          0.0687 0.006       0.006           0.0739 1.01    0.811
## 2 GOOG          0.0062 0.0036     -0.0004          0.0444 0.890   1.17 
## 3 NFLX          0.114  0.0215      0.0158          0.290  0.765   0.743
## # ℹ 11 more variables: `Beta-Robust` <dbl>, `Beta+` <dbl>, `Beta+Robust` <dbl>,
## #   BetaRobust <dbl>, Correlation <dbl>, `Correlationp-value` <dbl>,
## #   InformationRatio <dbl>, `R-squared` <dbl>, `R-squaredRobust` <dbl>,
## #   TrackingError <dbl>, TreynorRatio <dbl>