问题描述
我希望能够为每个时期制作一个权重向量,在此处的示例中,权重向量在开始时是固定的并且没有变化,我希望能够更改权重。 我的股票数量也在不断变化,因此在我的情况下,例如“GOOG”可能会在几年后消失,并被一种或多种不同的股票所取代,例如“特斯拉” (我也有成千上万的股票。) 这可以在 tidyquant 中进行还是有其他选择?
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",to = "2015-12-31") %>%
tq_transmute(select = adjusted,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.50,0.50
)
stocks <- c("AAPL","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()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)