# Load packages
library(tidyverse)
library(tidyquant)

1 Import stock prices of your choice

symbols <- c("X", "CMC", "ZEUS")

prices <- tq_get(x   = symbols,
                 get = "stock.prices", 
                from = "2018-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: 81 × 3
## # Groups:   asset [3]
##    asset date        returns
##    <chr> <date>        <dbl>
##  1 X     2018-03-29 -0.0600 
##  2 X     2018-06-29 -0.0111 
##  3 X     2018-09-28 -0.130  
##  4 X     2018-12-31 -0.512  
##  5 X     2019-03-29  0.0685 
##  6 X     2019-06-28 -0.238  
##  7 X     2019-09-30 -0.278  
##  8 X     2019-12-31 -0.00857
##  9 X     2020-03-31 -0.591  
## 10 X     2020-06-30  0.136  
## # ℹ 71 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 = .3, binwidth = 0.01) +
    facet_wrap(~asset, ncol = 1) + 
    labs(title = "Distribution of Quarterly Returns 2018-Today", 
     y     = "Frequency",
     x     = "Rate of Return", 
     caption = "A typical Quarterly return is higher for CMC, than for X, and ZEUS ")

4 Interpret the plot

# "A typical Quarterly return is higher for CMC, than for X, and ZEUS" I would also say that CMC is a less risky stock with more of the frequency arpund the 0.0 and less spread out while the other two seem much more pread out and have lower lows and higher highs.

5 Change the global chunck options

Hide the code, messages, and warnings