# 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("AMZN", "TSLA", "TM")
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
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
symbols
## [1] "AMZN" "TM" "TSLA"
# weights
weights <- c(0.5, 0.25, 0.25)
weights
## [1] 0.50 0.25 0.25
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 3 × 2
## symbols weights
## <chr> <dbl>
## 1 AMZN 0.5
## 2 TM 0.25
## 3 TSLA 0.25
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
rebalance_on = "months")
portfolio_returns_tbl
## # A tibble: 20 × 2
## date portfolio.returns
## <date> <dbl>
## 1 2013-03-28 0.0853
## 2 2013-06-28 0.321
## 3 2013-09-30 0.223
## 4 2013-12-31 0.0467
## 5 2014-03-31 -0.0182
## 6 2014-06-30 0.0323
## 7 2014-09-30 -0.00272
## 8 2014-12-31 -0.0246
## 9 2015-03-31 0.0804
## 10 2015-06-30 0.154
## 11 2015-09-30 0.0338
## 12 2015-12-31 0.142
## 13 2016-03-31 -0.108
## 14 2016-06-30 0.0583
## 15 2016-09-30 0.110
## 16 2016-12-30 -0.0411
## 17 2017-03-31 0.131
## 18 2017-06-30 0.101
## 19 2017-09-29 0.0136
## 20 2017-12-29 0.0914
portfolio_returns_tbl %>%
ggplot(mapping = aes(x = date, y = portfolio.returns)) +
geom_point(color = "cornflowerblue") +
# formatting
scale_x_date(date_breaks = "1 year",
date_labels = "%Y") +
# labeling
labs(y = "quarterly returns",
x = NULL,
title = "Portfolio Returns Scatter")