# Load packages
# Core
library(tidyverse)
library(tidyquant)
Collect individual returns into a portfolio by assigning a weight to each stock
Choose your stocks.
from 2021-01-21 to 2025-01-21
symbols <- c("UNH", "LLY", "JNJ", "PFE", "MRK")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2010-01-01",
to = "2025-01-01")
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] "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
# ?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
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")