# 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("COST", "LOW", "HD", "KR")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2019-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"))
asset_returns_tbl
## # A tibble: 124 × 3
## asset date returns
## <chr> <date> <dbl>
## 1 COST 2019-06-28 0.0901
## 2 COST 2019-09-30 0.0886
## 3 COST 2019-12-31 0.0221
## 4 COST 2020-03-31 -0.0283
## 5 COST 2020-06-30 0.0638
## 6 COST 2020-09-30 0.160
## 7 COST 2020-12-31 0.0873
## 8 COST 2021-03-31 -0.0647
## 9 COST 2021-06-30 0.118
## 10 COST 2021-09-30 0.129
## # ℹ 114 more rows
# symbols
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "COST" "HD" "KR" "LOW"
# weights
weights <- c(0.25, 0.2, 0.2, 0.1)
weights
## [1] 0.25 0.20 0.20 0.10
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 4 × 2
## symbols weights
## <chr> <dbl>
## 1 COST 0.25
## 2 HD 0.2
## 3 KR 0.2
## 4 LOW 0.1
portfolio_retuns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
rebalance_on = "quarters")
portfolio_retuns_tbl
## # A tibble: 31 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2019-06-28 0.00841
## 2 2019-09-30 0.0901
## 3 2019-12-31 0.0284
## 4 2020-03-31 -0.0609
## 5 2020-06-30 0.146
## 6 2020-09-30 0.0839
## 7 2020-12-31 -0.000895
## 8 2021-03-31 0.0563
## 9 2021-06-30 0.0550
## 10 2021-09-30 0.0557
## # ℹ 21 more rows
Histogram & Density Plot
portfolio_retuns_tbl %>%
ggplot(mapping = aes(x = portfolio.returns)) +
geom_histogram(color = "black", fill = "cornflowerblue", binwidth = 0.03) +
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 most common return from this portfolio would be around 0-2% return. The portfolio leans more to a positive return than a loss.