# Load packages
# Core
library(tidyverse)
library(tidyquant)
Collect individual returns into a portfolio by assigning a weight to each stock
five stocks: “SPY”, “EFA”, “IJS”, “EEM”, “AGG”
from 2012-12-31 to 2017-12-31
symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")
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 = "monthly",
type = "log"
) %>%
slice(-1) %>% # remove first row of each group
rename(returns = monthly.returns)
# Get unique stock symbols from asset_returns_tbl
symbols <- asset_returns_tbl %>%
distinct(symbol) %>%
pull()
# Assign custom weights
weights <- c(0.25, 0.25, 0.20, 0.20, 0.10)
# Create weights table
w_tbl <- tibble(symbol = symbols, weights = weights)
portfolio_returns_tbl <- asset_returns_tbl %>%
tq_portfolio(
assets_col = symbol,
returns_col = returns,
weights = w_tbl,
col_rename = "portfolio.returns",
rebalance_on = "months"
)
portfolio_returns_tbl %>%
ggplot(aes(x = date, y = portfolio.returns)) +
geom_point(color = "cornflowerblue") +
labs(title = "Portfolio Returns: Scatter Plot",
x = "Date", y = "Monthly Return")
portfolio_returns_tbl %>%
ggplot(aes(x = portfolio.returns)) +
geom_histogram(fill = "cornflowerblue", binwidth = 0.005) +
labs(title = "Portfolio Returns: Histogram",
x = "Monthly Return", y = "Frequency")
portfolio_returns_tbl %>%
ggplot(aes(x = portfolio.returns)) +
geom_histogram(aes(y = ..density..), fill = "cornflowerblue", binwidth = 0.01) +
geom_density(color = "darkblue", size = 1) +
labs(title = "Portfolio Returns: Histogram + Density",
x = "Monthly Return", y = "Density")