library(pacman)
pacman::p_load(data.table, fixest, BatchGetSymbols, finreportr, ggplot2, lubridate, esquisse)
Download stock price data
## Set parameters
first.date <- Sys.Date() - 2500
last.date <- Sys.Date()
freq.data <- "monthly"
tickers <- c("TSLA", "NIO", "PRPL", "AAPL", "SNAP", "MU", "AMD",
"NVDA", "TWTR")
## Get Stock Prices
stocks <- BatchGetSymbols(tickers = tickers,
first.date = first.date,
last.date = last.date,
freq.data = freq.data,
do.cache = FALSE,
thresh.bad.data = 0)
head(stocks)
## $df.control
## # A tibble: 9 × 6
## ticker src download.status total.obs perc.benchmark.dates threshold.decision
## <chr> <chr> <chr> <int> <dbl> <chr>
## 1 TSLA yahoo OK 1725 1 KEEP
## 2 NIO yahoo OK 1057 0.613 KEEP
## 3 PRPL yahoo OK 1725 1 KEEP
## 4 AAPL yahoo OK 1725 1 KEEP
## 5 SNAP yahoo OK 1443 0.837 KEEP
## 6 MU yahoo OK 1725 1 KEEP
## 7 AMD yahoo OK 1725 1 KEEP
## 8 NVDA yahoo OK 1725 1 KEEP
## 9 TWTR yahoo OK 1708 0.990 KEEP
##
## $df.tickers
## # A tibble: 700 × 10
## ticker ref.date volume price…¹ price…² price…³ price…⁴ price…⁵ ret.ad…⁶
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2016-01-19 2494882400 24.6 25.4 23.1 24.3 22.3 NA
## 2 AAPL 2016-02-01 3243450400 24.1 24.7 23.1 24.2 22.2 -0.00129
## 3 AAPL 2016-03-01 2984198400 24.4 27.6 24.4 27.2 25.1 0.127
## 4 AAPL 2016-04-01 3489534800 27.2 28.1 23.1 23.4 21.6 -0.140
## 5 AAPL 2016-05-02 3602686000 23.5 25.2 22.4 25.0 23.1 0.0718
## 6 AAPL 2016-06-01 3117990800 24.8 25.5 22.9 23.9 22.1 -0.0427
## 7 AAPL 2016-07-01 2743118400 23.9 26.1 23.6 26.1 24.1 0.0901
## 8 AAPL 2016-08-01 2520514000 26.1 27.6 26 26.5 24.7 0.0237
## 9 AAPL 2016-09-01 3872062400 26.5 29.0 25.6 28.3 26.3 0.0655
## 10 AAPL 2016-10-03 2747657200 28.2 29.7 28.1 28.4 26.4 0.00433
## # … with 690 more rows, 1 more variable: ret.closing.prices <dbl>, and
## # abbreviated variable names ¹price.open, ²price.high, ³price.low,
## # ⁴price.close, ⁵price.adjusted, ⁶ret.adjusted.prices
## Verify Returns
stocks_DT <- stocks$df.tickers %>% setDT() %>% # Convert to data.table
.[order(ticker, ref.date)] # Order by ticker and date
library(ggplot2)
ggplot(stocks_DT) +
aes(x = ref.date, y = ret.adjusted.prices, fill = ticker, colour = ticker) +
geom_line(size = 0.5) +
scale_fill_hue(direction = 1) +
scale_color_hue(direction = 1) +
theme_minimal() +
facet_wrap(vars(ticker))
## Warning: Removed 9 row(s) containing missing values (geom_path).
ggplot(stocks_DT) +
aes(x = ref.date, y = price.close, fill = ticker) +
geom_line(size = 0.5, colour = "#112446") +
scale_fill_manual(values = c(AAPL = "#F8766D", AMD = "#D39200", MU = "#93AA00", NIO = "#00BA38",
NVDA = "#00C19F", PRPL = "#00B9E3", SNAP = "#619CFF", TSLA = "#DB72FB", TWTR = "#FF61C3")) +
theme_minimal() +
facet_wrap(vars(ticker), scales = "free_y")