# Load packages
# Core
library(tidyverse)
library(tidyquant)
1 Import stock prices
# Choose stocks
symbols <- c("LULU", "UA", "NKE", "AMZN", "GOOG")
prices <- tq_get(x= symbols,
get = "stock.prices",
from = "2017-01-01",
to = "2021-01-01")
2 Convert prices to returns
asset_returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "quarterly",
type = "log") %>%
ungroup() %>%
rename(asset = symbol,
returns = quarterly.returns)
set_names(c("asset", "date", "returns"))
## asset date returns
## "asset" "date" "returns"
asset_returns_tbl
## # A tibble: 80 × 3
## asset date returns
## <chr> <date> <dbl>
## 1 LULU 2017-03-31 -0.254
## 2 LULU 2017-06-30 0.140
## 3 LULU 2017-09-29 0.0423
## 4 LULU 2017-12-29 0.233
## 5 LULU 2018-03-29 0.126
## 6 LULU 2018-06-29 0.337
## 7 LULU 2018-09-28 0.264
## 8 LULU 2018-12-31 -0.290
## 9 LULU 2019-03-29 0.298
## 10 LULU 2019-06-28 0.0950
## # ℹ 70 more rows
3 Make plot
asset_returns_tbl %>%
ggplot(aes(x = returns)) +
geom_density(aes(color = asset), alpha = 1) +
geom_histogram(aes(fill = asset), show.legend = FALSE, alpha = 0.3, binwidth = 0.01) +
facet_wrap(~asset, ncol = 1)

# labeling
labs(title = "Distribution of Monthly Returns, 2012-2016",
y = "Frequency",
x = "Rate of Returns",
caption = "A typical monthly return is higher for AMZN, GOOG, and NKE than for LULU and UA.")
## $y
## [1] "Frequency"
##
## $x
## [1] "Rate of Returns"
##
## $title
## [1] "Distribution of Monthly Returns, 2012-2016"
##
## $caption
## [1] "A typical monthly return is higher for AMZN, GOOG, and NKE than for LULU and UA."
##
## attr(,"class")
## [1] "labels"