# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Take raw prices of five individual stocks and transform them into monthly returns two stocks “NKE”, “TSLA”.

1 Import stock prices

# Choose stocks
symbols <- c("NKE", "TSLA")

prices <- tq_get(x = symbols, 
                 get  = "stock.prices", 
                 from = "2012-01-01", 
                 to   = "2017-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() %>%
    
    set_names(c("asset", "date", "returns"))

asset_returns_tbl
## # A tibble: 40 × 3
##    asset date       returns
##    <chr> <date>       <dbl>
##  1 NKE   2012-03-30  0.117 
##  2 NKE   2012-06-29 -0.208 
##  3 NKE   2012-09-28  0.0818
##  4 NKE   2012-12-31  0.0880
##  5 NKE   2013-03-28  0.138 
##  6 NKE   2013-06-28  0.0795
##  7 NKE   2013-09-30  0.135 
##  8 NKE   2013-12-31  0.0825
##  9 NKE   2014-03-31 -0.0596
## 10 NKE   2014-06-30  0.0519
## # ℹ 30 more rows

3 Make a 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 Quarterly Returns, 2012-2016", 
         y     = "Frequency",
         x     = "Rate of Returns",
         caption = "A typical quarterly return is higher for NKE and TSLA")

4 Interpret the plot

Both stocks that I have chosen are volatile but TSLA looks more volatile then NKE.

5 Change the global chunk options