# Load packages
# Core
library(tidyverse)
library(tidyquant)
Collect individual returns into a portfolio by assigning a weight to each stock
Choose your stocks.
I looked at the fast food chains McDonald’s(MCD), Wendy’s(WEN), Taco Bell(YUM), Domino’s Pizza(DPZ), and Starbucks(SBUX).
from 2012-12-31 to 2017-12-31
symbols <- c("MCD", "WEN", "YUM", "DPZ", "SBUX")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2015-12-31",
to = "2020-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] "DPZ" "MCD" "SBUX" "WEN" "YUM"
# 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 DPZ 0.2
## 2 MCD 0.2
## 3 SBUX 0.2
## 4 WEN 0.2
## 5 YUM 0.2
# ?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 2016-03-31 0.0756
## 2 2016-06-30 -0.0354
## 3 2016-09-30 0.0561
## 4 2016-12-30 0.0692
## 5 2017-03-31 0.0598
## 6 2017-06-30 0.120
## 7 2017-09-29 -0.0204
## 8 2017-12-29 0.0585
## 9 2018-03-29 0.0514
## 10 2018-06-29 -0.0123
## 11 2018-09-28 0.0866
## 12 2018-12-31 -0.00966
## 13 2019-03-29 0.0988
## 14 2019-06-28 0.100
## 15 2019-09-30 0.00446
## 16 2019-12-31 0.0210
## 17 2020-03-31 -0.227
## 18 2020-06-30 0.199
## 19 2020-09-30 0.113
## 20 2020-12-30 0.0519
portfolio_returns_tbl %>%
ggplot(mapping = aes(x = portfolio.returns)) +
geom_histogram(fill = "violet", 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?