# Load packages
library(tidyverse)
library(tidyquant)

1 Import stock prices of your choice

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

prices <- tq_get(x    = symbols,
                 get  = "stock.prices",
                 from = "2012-01-01",
                 to   = "2026-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") %>%
    ungroup() %>%
    
    set_names(c("asset", "date", "return"))
asset_returns_tbl
## # A tibble: 223 × 3
##    asset date        return
##    <chr> <date>       <dbl>
##  1 META  2012-06-29 -0.206 
##  2 META  2012-09-28 -0.362 
##  3 META  2012-12-31  0.206 
##  4 META  2013-03-28 -0.0399
##  5 META  2013-06-28 -0.0277
##  6 META  2013-09-30  0.703 
##  7 META  2013-12-31  0.0843
##  8 META  2014-03-31  0.0974
##  9 META  2014-06-30  0.111 
## 10 META  2014-09-30  0.161 
## # ℹ 213 more rows

3 Make plot

asset_returns_tbl %>%
    
    ggplot(aes(x = return))  +
    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 monthly returns, 2012-2025",
         y     = "Frequency",
         x     = "Rate of returns",
         caption = "A typical monthly return is higher for META and NKE than for AAPL, VOO, and TSLA")

4 Interpret the plot

The plot displays the distribution of monthly returns for five assets (AGG, EEM, EFA, IJS, and SPY) from 2012 to 2016. AGG shows a narrow, low-volatility return distribution, while EEM and EFA have wider, more dispersed return ranges. Overall, typical monthly returns were higher for SPY and IJS compared to AGG, EEM, and EFA during this period.

5 Change the global chunck options

Hide the code, messages, and warnings