# Load packages

# Core
library(tidyverse)
library(tidyquant)

Goal

Collect individual returns into a portfolio by assigning a weight to each stock

Choose your stocks.

from 2021-01-21 to 2025-01-21

1 Import stock prices

symbols <- c("UNH", "LLY", "JNJ", "PFE", "MRK")

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

2 Convert prices to returns (quarterly)

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 (change the weigting scheme)

# Symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "JNJ" "LLY" "MRK" "PFE" "UNH"
# weights
weights <- c(0.3, 0.25, 0.20, 0.13, 0.12)
weights
## [1] 0.30 0.25 0.20 0.13 0.12
w_tbl <-tibble(symbols, weights)
w_tbl
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 JNJ        0.3 
## 2 LLY        0.25
## 3 MRK        0.2 
## 4 PFE        0.13
## 5 UNH        0.12

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: 59 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2010-06-30         -0.0927  
##  2 2010-09-30          0.106   
##  3 2010-12-31          0.000621
##  4 2011-03-31          0.0269  
##  5 2011-06-30          0.0916  
##  6 2011-09-30         -0.0549  
##  7 2011-12-30          0.114   
##  8 2012-03-30          0.0313  
##  9 2012-06-29          0.0506  
## 10 2012-09-28          0.0590  
## # ℹ 49 more rows

5 Plot: Portfolio Histogram and Density

portfolio_returns_tbl %>%
    
    ggplot(mapping = aes(x = portfolio.returns)) +
    geom_histogram(fill = "cornflowerblue", binwidth = 0.015) +
    geom_density() +
    
    # Formatting
    scale_x_continuous(labels = scales::percent_format()) +

    # Labeling
    labs(x = "returns",
         y = "distribution",
         title = "Portfolio Histogram and Density")

What return should you expect from the portfolio in a typical quarter?

I would expect a typical quarterly return of approximately 0% to 6%, based on the peak of the density curve and the central tendency of the distribution. I would also expect some volatility as the histogram depicts large historical quarterly losses and gains.