# 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("XOM", "SHEL", "BP", "CVX")
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()
weights <- c(0.30,0.10,0.20,0.40)
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 4 × 2
## symbols weights
## <chr> <dbl>
## 1 BP 0.3
## 2 CVX 0.1
## 3 SHEL 0.2
## 4 XOM 0.4
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 2013-03-28 0.0289
## 2 2013-06-28 0.00194
## 3 2013-09-30 0.00124
## 4 2013-12-31 0.138
## 5 2014-03-31 -0.00748
## 6 2014-06-30 0.0825
## 7 2014-09-30 -0.0971
## 8 2014-12-31 -0.0706
## 9 2015-03-31 -0.0444
## 10 2015-06-30 -0.00815
## 11 2015-09-30 -0.169
## 12 2015-12-31 0.0452
## 13 2016-03-31 0.0499
## 14 2016-06-30 0.144
## 15 2016-09-30 -0.0393
## 16 2016-12-30 0.0753
## 17 2017-03-31 -0.0642
## 18 2017-06-30 0.00698
## 19 2017-09-29 0.0883
## 20 2017-12-29 0.0725
portfolio_returns_tbl %>%
ggplot(mapping = aes(x = portfolio.returns)) +
geom_histogram(fill = "wheat4", binwidth = 0.01) + geom_density() +
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? In any typical quarter you should expect a return of approximately 2%