【问题标题】:R - Executing a function columnwise across two matricesR - 跨两个矩阵按列执行函数
【发布时间】:2020-03-28 04:07:54
【问题描述】:

我有两个时间序列矩阵:
A:由 500 列组成,包含标准普尔成分股的回报
B:由一列组成,持有指数(S&P500)的回报

我想执行这个函数:

beta_function <- function(stock, index1)  cov(stock, index1)/var(index1)

R 应该在 12 个月内应用它。

总结一下:
我希望 R 执行每只股票每 12 个月窗口计算每只股票的 beta 的函数。

我试过了:
- 将 S&P500 指数回报的值重复 500 次,以获得与股票回报矩阵相同维度的矩阵。

如果我通过

应用我的功能
apply.rolling(c(returns_constituents, returns_index), 
                   width = 12, by = 12, FUN = beta_function)

它返回错误:

 Error in is.data.frame(y) : argument "index1" is missing, with no default 

甚至在执行apply.rolling函数之前赋值

index1 <- returns_index

没有解决我的问题。

你能帮帮我吗?

非常感谢。

例子:

stock <- matrix(c(runif(n = 84000, min = -1, max = 1)), ncol = 500, nrow = 168)
index1 <- matrix(c(runif(n = 168, min = -1, max = 1)), ncol = 1, nrow = 168)

我的尝试是“扩展”索引:

index1_ext <- matrix(c(runif(n = 8400, min = -1, max = 1)), ncol = 500, nrow = 168)

【问题讨论】:

    标签: r matrix xts


    【解决方案1】:

    数据,不仅仅是代码,应该是最小的,所以我们将数据缩减为 15x2(见最后的注释)。此外,我们使用set.seed 使其可重现,并使用 3 而不是 12。

    这里的关键是迭代索引而不是数据。不使用任何包。

    sq <- seq_along(index1)
    bfun <- function(ix) apply(stock[ix, ], 2, beta_function, index1[ix])
    t(sapply(split(sq, (sq - 1) %/% 3), bfun))
    

    给予:

            [,1]       [,2]
    0  0.1369903  2.5808410
    1 -0.2041141 -0.7671860
    2 -0.4868275 -0.1372993
    3 -1.5786697 -0.6059759
    4  2.1902241  1.3766969
    

    注意

    set.seed(123)
    stock <- matrix(c(runif(n = 30, min = -1, max = 1)), ncol = 2, nrow = 15)
    index1 <- matrix(c(runif(n = 15, min = -1, max = 1)), ncol = 1, nrow = 15)
    

    【讨论】:

    • 感谢您的帮助!你能解释一下为什么前两行包含 NA 吗?最后,我应该有 14 个 beta 值(每个窗口一个),并且每个公司(列)都有这个值。我该如何考虑这一点?
    • 好的。已修改。此外,现在它在示例中使用 15x2。
    猜你喜欢
    • 2019-12-09
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多