# Load packages

# Core
library(tidyverse)
library(tidyquant)

1 Import stock prices

symbols <- c("TSLA", "F", "STLA", "GM")

prices <- tq_get(x = symbols,
                 get = "stock.prices", 
                 from = "2018-01-01",
                 to = "2024-01-01")

2 Convert prices to returns by quarterly

asset_returns_tbl <- prices %>%
    
    group_by(symbol) %>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "quarterly",
                 type       = "log") %>% 
    set_names(c("asset", "date", "returns"))

asset_returns_tbl
## # A tibble: 96 × 3
## # Groups:   asset [4]
##    asset date       returns
##    <chr> <date>       <dbl>
##  1 TSLA  2018-03-29 -0.186 
##  2 TSLA  2018-06-29  0.254 
##  3 TSLA  2018-09-28 -0.259 
##  4 TSLA  2018-12-31  0.229 
##  5 TSLA  2019-03-29 -0.173 
##  6 TSLA  2019-06-28 -0.225 
##  7 TSLA  2019-09-30  0.0750
##  8 TSLA  2019-12-31  0.552 
##  9 TSLA  2020-03-31  0.225 
## 10 TSLA  2020-06-30  0.723 
## # ℹ 86 more rows

3 Make plot

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 quarterly returns, 2018-2024",
         y = "Frequency",
         x = "Rate of return")

Interpret the plot

Return tends to be higher for TSLA than for F, GM and, STLA which are all very similar in ruturns

Change the global chunk options

Hide the code, messages, and warnings