# 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("MSFT", "AAPL", "GOOG")
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2012-12-31",
to = "2017-12-31")
prices
## # A tibble: 3,780 × 8
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 MSFT 2012-12-31 26.6 26.8 26.4 26.7 42749500 21.6
## 2 MSFT 2013-01-02 27.2 27.7 27.1 27.6 52899300 22.3
## 3 MSFT 2013-01-03 27.6 27.6 27.2 27.2 48294400 22.0
## 4 MSFT 2013-01-04 27.3 27.3 26.7 26.7 52521100 21.6
## 5 MSFT 2013-01-07 26.8 26.9 26.6 26.7 37110400 21.5
## 6 MSFT 2013-01-08 26.8 26.8 26.5 26.5 44703100 21.4
## 7 MSFT 2013-01-09 26.7 26.8 26.6 26.7 49047900 21.5
## 8 MSFT 2013-01-10 26.6 27.0 26.3 26.5 71431300 21.3
## 9 MSFT 2013-01-11 26.5 26.9 26.3 26.8 55512100 21.6
## 10 MSFT 2013-01-14 26.9 27.1 26.8 26.9 48324400 21.7
## # ℹ 3,770 more rows
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: 60 × 3
## asset date returns
## <chr> <date> <dbl>
## 1 AAPL 2013-03-28 -0.178
## 2 AAPL 2013-06-28 -0.103
## 3 AAPL 2013-09-30 0.191
## 4 AAPL 2013-12-31 0.169
## 5 AAPL 2014-03-31 -0.0383
## 6 AAPL 2014-06-30 0.198
## 7 AAPL 2014-09-30 0.0858
## 8 AAPL 2014-12-31 0.0956
## 9 AAPL 2015-03-31 0.124
## 10 AAPL 2015-06-30 0.0122
## # ℹ 50 more rows
symbols <- asset_returns_tbl %>%
distinct(asset) %>%
pull()
weights <- c(0.3, 0.4, 0.3)
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 3 × 2
## symbols weights
## <chr> <dbl>
## 1 AAPL 0.3
## 2 GOOG 0.4
## 3 MSFT 0.3
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.0159
## 2 2013-06-28 0.0688
## 3 2013-09-30 0.0462
## 4 2013-12-31 0.187
## 5 2014-03-31 0.0162
## 6 2014-06-30 0.0795
## 7 2014-09-30 0.0608
## 8 2014-12-31 -0.00581
## 9 2015-03-31 0.0154
## 10 2015-06-30 0.0108
## 11 2015-09-30 0.0279
## 12 2015-12-31 0.145
## 13 2016-03-31 0.00545
## 14 2016-06-30 -0.0878
## 15 2016-09-30 0.136
## 16 2016-12-30 0.0308
## 17 2017-03-31 0.114
## 18 2017-06-30 0.0538
## 19 2017-09-29 0.0680
## 20 2017-12-29 0.107
portfolio_returns_tbl %>%
ggplot(mapping = aes(x = portfolio.returns)) +
geom_histogram(fill = "maroon", binwidth = 0.0175) +
geom_density() +
# Formatting
scale_x_continuous(labels = scales::percent_format()) +
labs(x = "returns",
y = "distribution",
title = "Portfolio Histogram and Density")
This portfolio can expect returns of about 2% in a typical quarter.