# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Take raw prices of five individual stocks and transform them into monthly returns

1 Import stock prices

# Choose stocks
symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")
# Using tq_get() ----
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") %>%
    slice(-1) %>%
    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) +
    guides(fill = "none") +
    labs(title = "Monthly Returns since 2013",
         x = "distribution",
         y = "monthly returns") +
    theme_update(plot.title = element_text(hjust = 0.5))

4 Custom function

convert_prices_to_returns <- function(data, period_returns) {
    asset_returns_tbl <- data %>%
        # Calculate monthly returns
        group_by(symbol) %>%
        tq_transmute(select = adjusted,
                     mutate_fun = periodReturn,
                     period = period_returns,
                     type = "log") %>%
        slice(-1) %>%
        ungroup() %>%
        # remane
        set_names(c("asset", "date", "returns"))
    return(asset_returns_tbl)
}
asset_returns_long_tbl <- convert_prices_to_returns(prices, period_returns = "monthly")
asset_returns_long_tbl
## # A tibble: 300 × 3
##    asset date         returns
##    <chr> <date>         <dbl>
##  1 AGG   2013-01-31 -0.00623 
##  2 AGG   2013-02-28  0.00589 
##  3 AGG   2013-03-28  0.000986
##  4 AGG   2013-04-30  0.00964 
##  5 AGG   2013-05-31 -0.0202  
##  6 AGG   2013-06-28 -0.0158  
##  7 AGG   2013-07-31  0.00269 
##  8 AGG   2013-08-30 -0.00830 
##  9 AGG   2013-09-30  0.0111  
## 10 AGG   2013-10-31  0.00829 
## # … with 290 more rows
dump("convert_prices_to_returns", file = "../00_scripts/convert_prices_to_returns.R")
# Save data
# write_rds(asset_returns_long_tbl, "00_data/Ch02_asset_returns_long_tbl.rds")