# 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("UAL", "AAL", "LUV")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2020-01-01",
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] "AAL" "LUV" "UAL"
# weights
weights <- c(0.4, 0.3, 0.3)
weights
## [1] 0.4 0.3 0.3
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 3 × 2
## symbols weights
## <chr> <dbl>
## 1 AAL 0.4
## 2 LUV 0.3
## 3 UAL 0.3
# ?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: 19 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2020-06-30 0.0434
## 2 2020-09-30 0.00441
## 3 2020-12-31 0.231
## 4 2021-03-31 0.333
## 5 2021-06-30 -0.118
## 6 2021-09-30 -0.0511
## 7 2021-12-31 -0.133
## 8 2022-03-31 0.0436
## 9 2022-06-30 -0.298
## 10 2022-09-30 -0.0937
## 11 2022-12-30 0.0926
## 12 2023-03-31 0.100
## 13 2023-06-30 0.176
## 14 2023-09-29 -0.298
## 15 2023-12-29 0.0418
## 16 2024-03-28 0.0938
## 17 2024-06-28 -0.121
## 18 2024-09-30 0.0569
## 19 2024-12-30 0.382
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?