# 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
# Choose stocks
symbols <- c("GM", "PLUG", "AAPL")
# Using tq_get() ----
prices <- tq_get(x = symbols,
get = "stock.prices",
from = "2002-12-31",
to = "2024-12-31")
asset_returns_tbl <- prices %>%
# Calculate monthly returns
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "quarterly",
type = "log") %>%
slice(-1) %>%
ungroup() %>%
# remane
set_names(c("asset", "date", "returns"))
# period_returns = c("yearly", "quarterly", "monthly", "weekly")
symbols <- asset_returns_tbl %>% distinct(asset) %>% pull()
weights <- c(0.4, 0.35, 0.25)
w_tbl <- tibble(symbols, weights)
portfolio_returns_rebalanced_monthly_tbl <- asset_returns_tbl %>%
tq_portfolio(assets_col = asset,
returns_col = returns,
weights = w_tbl,
col_rename = "returns",
rebalance_on = "quarters")
portfolio_returns_rebalanced_monthly_tbl
## # A tibble: 88 × 2
## date returns
## <date> <dbl>
## 1 2003-03-31 0.0245
## 2 2003-06-30 0.0994
## 3 2003-09-30 0.0569
## 4 2003-12-31 0.0988
## 5 2004-03-31 0.110
## 6 2004-06-30 0.0662
## 7 2004-09-30 0.0313
## 8 2004-12-31 0.191
## 9 2005-03-31 0.122
## 10 2005-06-30 -0.0403
## # ℹ 78 more rows
# write_rds(portfolio_returns_rebalanced_monthly_tbl,
# "00_data/Ch03_portfolio_returns_rebalanced_monthly_tbl.rds")
portfolio_returns_rebalanced_monthly_tbl %>%
ggplot(aes(x = date, y = returns)) +
geom_point(color = "cornflower blue") +
# Formatting
scale_x_date(breaks = scales::breaks_pretty(n = 6)) +
labs(title = "Portfolio Returns Scatter",
y = "monthly return")
portfolio_returns_rebalanced_monthly_tbl %>%
ggplot(aes(returns)) +
geom_histogram(fill = "cornflower blue",
binwidth = 0.005) +
labs(title = "Portfolio Returns Distribution",
y = "count",
x = "Quarterly returns")
portfolio_returns_rebalanced_monthly_tbl %>%
ggplot(aes(returns)) +
geom_histogram(fill = "cornflower blue",
binwidth = 0.01) +
geom_density(aes(returns)) +
labs(title = "Portfolio Histogram and Density",
y = "distribution",
x = "Quarterly returns")
What return should you expect from the portfolio in a typical quarter?
Quarterly returns can range from -37% to 42%. But, I expect the returns
to be from -13% to 18%.