# Load Packages

# Core
library(tidyverse)
library(tidyquant)

1 Import stock prices

symbols <- c("LULU", "NKE", "UA")
prices <- tq_get(x    = symbols, 
                 from = "2021-12-31",
                 to   = "2024-12-31")

2 Convert prices to returns

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

3 Assign a weight to each asset

# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "LULU" "NKE"  "UA"
# weights
weights <- c(0.25, 0.2, 0.1)
weights
## [1] 0.25 0.20 0.10
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 3 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 LULU       0.25
## 2 NKE        0.2 
## 3 UA         0.1

4 Build a portfolio

# ?tq_portfolio
portfolio_returns_tbl <- asset_returns_tbl %>%
    
    tq_portfolio(assets_col = asset,
                 returns_col = returns,
                 weights = w_tbl, 
                 rebalance_on = "quarters")
portfolio_returns_tbl
## # A tibble: 12 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2022-03-31           -0.0745
##  2 2022-06-30           -0.200 
##  3 2022-09-30           -0.0585
##  4 2022-12-30            0.143 
##  5 2023-03-31            0.0375
##  6 2023-06-30           -0.0348
##  7 2023-09-29           -0.0284
##  8 2023-12-29            0.124 
##  9 2024-03-28           -0.111 
## 10 2024-06-28           -0.119 
## 11 2024-09-30            0.0335
## 12 2024-12-30            0.0414

5 Plot

Histogram & Density Plot

portfolio_returns_tbl %>%
    ggplot(mapping = aes(x = portfolio.returns)) +
    geom_histogram(fill = "cornflowerblue", binwidth = 0.01) +
    geom_density() +
    
    # Formatting
    scale_x_continuous(labels = scales::percent_format()) +
    labs(x="returns",
         y = "distribution",
         title = "Portfolio Histogram & Density")

Expected Return

What return should you expect from the portfolio in a typical quarter? The graph shows a peak at about -4% returns from all three companies