# 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 2012-12-31 to 2017-12-31

1 Import stock prices

symbols <- c("SOXX", "TKR", "VUG", "AMZN", "GOOG")
prices <- tq_get(x = symbols, 
                 from = "2020-01-01",
                 to = "2025-12-31")

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] "AMZN" "GOOG" "SOXX" "TKR"  "VUG"
# weights
weights <- c(0.2, 0.2, 0.2, 0.2, 0.2)
weights
## [1] 0.2 0.2 0.2 0.2 0.2
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 5 × 2
##   symbols weights
##   <chr>     <dbl>
## 1 AMZN        0.2
## 2 GOOG        0.2
## 3 SOXX        0.2
## 4 TKR         0.2
## 5 VUG         0.2

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: 23 × 2
##    date       portfolio.returns
##    <date>                 <dbl>
##  1 2020-06-30            0.285 
##  2 2020-09-30            0.119 
##  3 2020-12-31            0.180 
##  4 2021-03-31            0.0593
##  5 2021-06-30            0.0950
##  6 2021-09-30           -0.0385
##  7 2021-12-31            0.0917
##  8 2022-03-31           -0.0857
##  9 2022-06-30           -0.271 
## 10 2022-09-30           -0.0163
## # ℹ 13 more rows

5 Plot: Portfolio Histogram and Density

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")

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

Given these 5 stocks, you can more often than not expect a positive quarterly return from 2020-2025. However, the maximum potential loss and gain is the same, around 30%. This is indicative of an aggressive, high risk growth portfolio. The most common return is between 5-15% profit, although its almost as common to take a 3-10% loss. 2020-2025 is a decent bull market for technology and adjacent sectors, but there were notable dips from AI bubbles, circular expectations and geopolitical conflict.