# Load packages
# Core
library(tidyverse)
library(tidyquant)
Collect individual returns into a portfolio by assigning a weight to each stock
Choose your stocks.
from 2012-12-31 to 2017-12-31
symbols <- c("TSLA", "NVDA", "GOOGL", "ORCL", "JNJ")
prices <- tq_get(x = symbols,
from = "2019-12-31",
to = "2024-12-31")
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"))
# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "GOOGL" "JNJ" "NVDA" "ORCL" "TSLA"
# weights
weight <- c(0.25, 0.25, 0.2, 0.2, 0.1)
weight
## [1] 0.25 0.25 0.20 0.20 0.10
w_tbl <- tibble(symbols, weight)
w_tbl
## # A tibble: 5 × 2
## symbols weight
## <chr> <dbl>
## 1 GOOGL 0.25
## 2 JNJ 0.25
## 3 NVDA 0.2
## 4 ORCL 0.2
## 5 TSLA 0.1
# ?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: 20 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2020-03-31 -0.0327
## 2 2020-06-30 0.242
## 3 2020-09-30 0.180
## 4 2020-12-31 0.120
## 5 2021-03-31 0.0691
## 6 2021-06-30 0.149
## 7 2021-09-30 0.0627
## 8 2021-12-31 0.138
## 9 2022-03-31 -0.0226
## 10 2022-06-30 -0.257
## 11 2022-09-30 -0.105
## 12 2022-12-30 0.0208
## 13 2023-03-31 0.217
## 14 2023-06-30 0.212
## 15 2023-09-29 -0.0128
## 16 2023-12-29 0.0450
## 17 2024-03-28 0.145
## 18 2024-06-28 0.128
## 19 2024-09-30 0.0673
## 20 2024-12-30 0.0751
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? In A typical quarter, you should expect a return from right around 0% to about 21%. There are some outlier quarters, the worst being less than -20%, and the best being close to 25%.