# Load packages
# Core
library(tidyverse)
library(tidyquant)
Collect individual returns into a portfolio by assigning a weight to each stock
five stocks: “TTWO”, “ADBE”, “CAT”, “NVDA”, “NOK”
from 2012-12-31 to 2017-12-31
symbols <- c("TTWO", "ADBE", "CAT", "NVDA", "NOK")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-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 <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "ADBE" "CAT" "NOK" "NVDA" "TTWO"
# 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 ADBE 0.2
## 2 CAT 0.2
## 3 NOK 0.2
## 4 NVDA 0.2
## 5 TTWO 0.2
# ?tq_portfolio
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
rebalence_on = "months")
portfolio_returns_tbl
## # A tibble: 20 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2013-03-28 0.0726
## 2 2013-06-28 0.0204
## 3 2013-09-30 0.193
## 4 2013-12-31 0.0872
## 5 2014-03-31 0.0792
## 6 2014-06-30 0.0651
## 7 2014-09-30 0.00850
## 8 2014-12-31 0.0448
## 9 2015-03-31 -0.0354
## 10 2015-06-30 0.0245
## 11 2015-09-30 0.0246
## 12 2015-12-31 0.162
## 13 2016-03-31 0.0245
## 14 2016-06-30 0.0856
## 15 2016-09-30 0.210
## 16 2016-12-30 0.161
## 17 2017-03-31 0.101
## 18 2017-06-30 0.212
## 19 2017-09-29 0.198
## 20 2017-12-29 0.0797
Histogram & Density Plot
portfolio_returns_tbl %>%
ggplot(mapping = aes(x = portfolio.returns)) +
geom_histogram(fill = "cornflowerblue", binwidth = 0.01, color = "tomato") +
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 your portfolio in a typical quarter?
Based on my histogram, I should have an average of around a 5% gain every quarter. This is because that is where the apex shows on the density line. The minimum quarter was around -4%, where the maximum quarter is around 22%.