title: “Apply it 4” author: “Takeru Ito” date: “2022-09-24” output: html_document editor_options: chunk_output_type: console —
symbols <- c("WMT", "TGT", "NKE", "DELL", "AAPL")
# Using tq_get() ----
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")
asset_returns_tbl <- prices %>%
# Calculate monthly returns
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
# remane
set_names(c("asset", "date", "returns"))
# period_returns = c("yearly", "quarterly", "monthly", "weekly")
asset_returns_tbl %>%
ggplot(aes(x = returns)) +
geom_density(aes(col = asset), alpha = 1, show.legend = FALSE) +
geom_histogram(aes(fill = asset), alpha = 0.45, binwidth = 0.01) +
facet_wrap(~asset, ncol = 1, scales = "free_y") +
guides(fill = "none") +
labs(title = "Monthly Returns since 2013",
x = "distribution",
y = "monthly returns") +
theme_update(plot.title = element_text(hjust = 0.5))