I want to be able to make a weight vector for every period, in the example here the weight vector is fixed at the beginning and there are no changes, I want to be able to change the weights. I also have changing number of stocks, so it is possible in my case that for example "GOOG" disappears after a couple of years and is replaced by one or more different stocks, f.e. "TSLA" (I also have thousands of stocks.) Is this possible to do in tidyquant or is there another option?
library(tidyquant)
library(tidyverse)
# Asset Period Returns
stock_returns_monthly <- c("AAPL", "GOOG", "NFLX") %>%
tq_get(get = "stock.prices",
from = "2010-01-01",
to = "2015-12-31") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Ra")
stock_returns_monthly
# Baseline Period Returns
baseline_returns_monthly <- "XLK" %>%
tq_get(get = "stock.prices",
from = "2010-01-01",
to = "2015-12-31") %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "Rb")
baseline_returns_monthly
# scaling a single portfolio to many, 3 in this case
stock_returns_monthly_multi <- stock_returns_monthly %>%
tq_repeat_df(n = 3)
stock_returns_monthly_multi
# Create Vector of Weights
# not all symbols need to be specified. Any symbol not specified by default gets a weight of zero.
weights <- c(
0.50, 0.25, 0.25,
0.25, 0.50, 0.25,
0.25, 0.25, 0.50
)
stocks <- c("AAPL", "GOOG", "NFLX")
weights_table <- tibble(stocks) %>%
tq_repeat_df(n = 3) %>%
bind_cols(tibble(weights)) %>%
group_by(portfolio)
weights_table
# Aggregate a Portfolio using Vector of Weights
portfolio_returns_monthly_multi <-
stock_returns_monthly_multi %>%
tq_portfolio(assets_col = symbol,
returns_col = Ra,
weights = weights_table,
col_rename = "Ra")
portfolio_returns_monthly_multi
# Merging Ra and Rb
RaRb_single_portfolio <- left_join(portfolio_returns_monthly_multi ,
baseline_returns_monthly,
by = "date")
RaRb_single_portfolio
#Step 4: Computing the CAPM Table
RaRb_single_portfolio %>%
tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) %>%
t()