# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Take raw prices of five individual stocks and transform them into monthly returns five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”

1 Import stock prices

# Choose stocks

symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")

prices <- tq_get(x = symbols,
                 get = "stock.prices",
                 from = "2012-12-31",
                 to = "2017-12-31")

2 Convert prices to returns

asset_returns_tbl <- prices %>%

    # Calculate monthly returns
    group_by(symbol) %>%
    tq_transmute(select = adjusted,
                 mutate_fun = periodReturn,
                 period = "monthly",
                 type = "log") %>%
    ungroup() %>%

    # remane
    set_names(c("asset", "date", "returns"))

# period_returns = c("yearly", "quarterly", "monthly", "weekly")

3 Make plot

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))