# Load packages
library(tidyverse)
library(tidyquant)
# Choose stocks
symbols <- c("MSFT", "NVDA", "JPM")
prices <- tq_get( x = symbols,
get = "stock.prices",
from = "2012-01-01")
asset_returns_tbl <- prices %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "quarterly",
type = "log") %>%
ungroup() %>%
set_names(c("asset", "date", "returns"))
asset_returns_tbl
## # A tibble: 144 × 3
## asset date returns
## <chr> <date> <dbl>
## 1 MSFT 2012-03-30 0.193
## 2 MSFT 2012-06-29 -0.0466
## 3 MSFT 2012-09-28 -0.0209
## 4 MSFT 2012-12-31 -0.0999
## 5 MSFT 2013-03-28 0.0770
## 6 MSFT 2013-06-28 0.195
## 7 MSFT 2013-09-30 -0.0301
## 8 MSFT 2013-12-31 0.125
## 9 MSFT 2014-03-31 0.0989
## 10 MSFT 2014-06-30 0.0242
## # ℹ 134 more rows
asset_returns_tbl %>%
ggplot(aes(x = returns)) +
geom_density(aes(color = asset), show.legend = FALSE, 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-Present",
y = "frequency",
x = "rate of returns",
capition = "")
JPM and MSFT both are clustered close together making them less volatile, and NVDA was more spaced out making it a more volatile stock. JPM and MSFT both seem like good investments.
Hide the code, messages, and warnings