# 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", "NKE")
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] "NKE" "TSLA"
# weights
weights <- c(0.50,0.50)
weights
## [1] 0.5 0.5
w_tbl <- tibble(symbols, weights)
w_tbl
## # A tibble: 2 × 2
## symbols weights
## <chr> <dbl>
## 1 NKE 0.5
## 2 TSLA 0.5
#?tq_portfolio
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "quarters")
portfolio_returns_tbl
## # A tibble: 60 × 2
## date returns
## <date> <dbl>
## 1 2013-01-31 0.0742
## 2 2013-02-28 -0.0325
## 3 2013-03-28 0.0822
## 4 2013-04-30 0.215
## 5 2013-05-31 0.319
## 6 2013-06-28 0.0736
## 7 2013-07-31 0.106
## 8 2013-08-30 0.128
## 9 2013-09-30 0.139
## 10 2013-10-31 -0.0739
## # ℹ 50 more rows
portfolio_returns_tbl %>%
ggplot(mapping = aes(x = returns)) +
geom_histogram(fill = "cornflower blue", bindwith = 0.01) +
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 the portfolio in a typical
quarter?
should expect 5% return from stocks