按组滚动时间序列回归并提取回归Beta

时间:2019-06-22 18:14:57

标签: r group-by lm rollapply

关于滚动时间序列回归,已经有很多问题,但是由于我对R相当陌生,所以我一直受困。我需要对不同的isins进行滚动时间序列回归,并将每个isin的beta添加到数据框中。我需要为每个isin回归y〜market + cds,滚动窗口为4。

在下面的文章中,我已经找到了一些有用的代码,但是它仅包含一个自变量,我不知道如何针对我的问题进行调整:

rolling regression by group in the tidyverse?

数据如下:

mydata = data_frame('isin' = c('a','a', 'a','a','a','a', 'a','a','b', 'b', 'b', 'b','b', 'b', 'b', 'b','C','c','c','C','c','c','C','c','c'),
                    'y' = c(1,2,3,4,2,3,4,5,1,2,3,4,2,3,4,5,1,2,3,4,2,3,4,5,5),
                    'market' = c(2,4,6,8,6,9,12,15,2,4,6,8,6,9,12,15,2,4,6,8,6,9,12,15,15),
                    'cds' = c(2,4,6,8,6,9,12,15,2,4,6,8,6,9,12,15,2,4,6,8,6,9,12,15,2),
                    'date' = c(ymd('2016-06-01', '2016-06-02', '2016-06-03', '2016-06-04','2016-06-05', '2016-06-06', '2016-06-07', '2016-06-08',
                                   '2016-06-03', '2016-06-04', '2016-06-05','2016-06-06', '2016-06-07', '2016-06-08', '2016-06-09', '2016-06-06', '2016-06-07',
                                   '2016-06-08', '2016-06-09','2016-06-10', '2016-06-11','2016-06-12', '2016-06-13', '2016-06-14','2016-06-15')))

有用的代码

mydata %>% 
       group_by(isin) %>% 
       do(select(., date, y, market, cds) %>% 
          read.zoo %>% 
          rollapplyr(2, Coef, by.column = FALSE, fill = NA) %>%
          fortify.zoo(names = "date")
       ) %>% 
       ungroup

最后,我需要一个数据框,其中包含原始数据以及市场和CD的滚动beta。当然,对于每个isin的前4个观测值,由于滚动窗口而没有可用的值。非常感谢您的帮助!

0 个答案:

没有答案