# 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("TSLA", "AMZN", "GOOG", "JNJ", "MSFT", "AAPL")
prices <- tq_get(x = symbols,
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"))
asset_returns_tbl
## # A tibble: 120 × 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
## # … with 110 more rows
#Symbols
symbols <- asset_returns_tbl %>%
distinct(asset) %>%
pull()
symbols
## [1] "AAPL" "AMZN" "GOOG" "JNJ" "MSFT" "TSLA"
#Weights
weights <- c(0.5, 0.1, 0.1, 0.1, 0.1, 0.1)
weights
## [1] 0.5 0.1 0.1 0.1 0.1 0.1
w_tbl <- tibble(symbols, weights)
# 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: 20 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2013-03-28 -0.0367
## 2 2013-06-28 0.0923
## 3 2013-09-30 0.164
## 4 2013-12-31 0.127
## 5 2014-03-31 0.0136
## 6 2014-06-30 0.122
## 7 2014-09-30 0.0574
## 8 2014-12-31 0.0256
## 9 2015-03-31 0.0519
## 10 2015-06-30 0.0582
## 11 2015-09-30 -0.0403
## 12 2015-12-31 0.0588
## 13 2016-03-31 0.00711
## 14 2016-06-30 -0.0539
## 15 2016-09-30 0.120
## 16 2016-12-30 0.0140
## 17 2017-03-31 0.175
## 18 2017-06-30 0.0592
## 19 2017-09-29 0.0419
## 20 2017-12-29 0.0899
Portfolio Histogram and Density
portfolio_returns_tbl %>%
ggplot(mapping = aes(portfolio.returns)) +
geom_histogram(fill = "cornflowerblue", binwidth = 0.02) +
geom_density() +
#Formatting
scale_x_continuous(labels = scales::percent_format()) +
labs(x = "Returns",
y = "Density",
title = "Portfolio Histogram & Density")
What return should you expect from the portfolio in a typical quarter?
In a typical quarter return I can expect between 5%-6% returns.