我正在尝试为股票生成滚动beta,我的滚动函数不起作用。到目前为止我所尝试的:
library(tidyquant)
library(tidyverse)
library(tibbletime)
ticker_data <- tq_get(c("AAPL", "SPY"))
daily_returns <- ticker_data %>%
group_by(symbol) %>%
tq_transmute(select = close,
mutate_fun = periodReturn,
period = "daily",
col_rename = "daily_return") %>%
ungroup
all_returns_df <- left_join(daily_returns %>% filter(symbol == "AAPL"),
daily_returns %>% filter(symbol == "SPY") %>%
select(-symbol) %>%
rename(mkt_daily_return = daily_return))
# Can generate one Beta for all dates
all_returns_df %>%
tq_performance(Ra = daily_return,
Rb = mkt_daily_return,
scale = 252,
performance_fun = table.CAPM)
# Rolling Beta is not working
#Function that is not working
roll_beta <- rollify(.f = function(xy){ tq_performance(data = xy,
Ra = daily_return,
Rb = mkt_daily_return,
scale = 252,
performance_fun = table.CAPM)},
window = 40)
# This fails
all_returns_df %>% roll_beta()
关于如何使这个工作为我有什么想法吗?
我的主要目的是用"整洁"的方式来做这件事。方式。
注意:tibbletime已退役。你应该看看时刻表。
现在timek的slidify
函数取代了rollify
函数。但是我不能让它正常工作,因为它一直抱怨月经。但回到zoo::rollapply
是可行的。由于某些原因,获取整个表也是一个问题。
下面的代码将为给出的示例工作并返回测试版。我使用函数CAPM.beta
来返回beta值。
CAPM_beta_roll <- function(data, width = 40) {
data <- timetk::tk_xts(data, date_var = date)
beta <- zoo::rollapply(data = data[, 1],
FUN = CAPM.beta,
Rb = data[, 2],
width = width,
by = 1,
align = "right",
by.column = TRUE)
names(beta) <- "beta"
out <- timetk::tk_tbl(beta, preserve_index = FALSE)
out$beta
}
all_returns_df %>%
mutate(beta = CAPM_beta_roll(.))
# A tibble: 2,680 x 5
symbol date daily_return mkt_daily_return beta
<chr> <date> <dbl> <dbl> <dbl>
1 AAPL 2011-01-03 0 0 NA
2 AAPL 2011-01-04 0.00522 -0.000551 NA
3 AAPL 2011-01-05 0.00818 0.00520 NA
4 AAPL 2011-01-06 -0.000808 -0.00196 NA
5 AAPL 2011-01-07 0.00716 -0.00196 NA
6 AAPL 2011-01-10 0.0188 -0.00126 NA
7 AAPL 2011-01-11 -0.00237 0.00354 NA
8 AAPL 2011-01-12 0.00814 0.00902 NA
9 AAPL 2011-01-13 0.00366 -0.00163 NA
10 AAPL 2011-01-14 0.00810 0.00724 NA
# ... with 2,670 more rows
Warning message:
Problem with `mutate()` column `beta`.
i `beta = CAPM.beta_roll(.)`.
i Non-numeric columns being dropped: symbol, date
您可以忽略警告消息。这些来自time_tk::tk_xts
为了更快地实现这个函数,你可以在这篇文章中找到几个例子。