# 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 ("LULU", "NKE", "UA")
prices <- tq_get(x = symbols,
from = "2019-12-31",
to = "2025-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
symbol <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbol
## [1] "LULU" "NKE" "UA"
# weights
weights <- c(0.35, 0.45, 0.20)
#combine tibble
w_tbl <- tibble(symbol, weights)
#view result
w_tbl
## # A tibble: 3 × 2
## symbol weights
## <chr> <dbl>
## 1 LULU 0.35
## 2 NKE 0.45
## 3 UA 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: 22 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2020-03-31 -0.333
## 2 2020-06-30 0.270
## 3 2020-09-30 0.153
## 4 2020-12-31 0.157
## 5 2021-03-31 -0.0284
## 6 2021-06-30 0.131
## 7 2021-09-30 -0.00255
## 8 2021-12-31 0.0570
## 9 2022-03-31 -0.149
## 10 2022-06-30 -0.369
## # ℹ 12 more rows
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? The stocks are pretty even across the board in terms of distribution with an exception at about 6% of returns earning twice as much distribution as the other percentages.