Applying a rolling window regression to an XTS series in R

前端 未结 2 1737
悲哀的现实
悲哀的现实 2021-02-04 13:52

I have an xts of 1033 daily returns points for 5 currency pairs on which I want to run a rolling window regression, but rollapply is not working for my defined function which us

2条回答
  •  没有蜡笔的小新
    2021-02-04 13:53

    There are several problems here:

    • rollapply passes a matrix but lm requires a data.frame.
    • rollapply applies the function to each column separately unless we specify by.column=FALSE.
    • you may or may not want the result to be right aligned with the dates but if you do use rollapplyr :

    1) Incorporating the above we have:

    dolm <- function(x) coef(lm(USDZAR ~ ., data = as.data.frame(x))))
    rollapplyr(fxr, 62, dolm, by.column = FALSE)
    

    2) An alternative to the lm in the dolm above is to use lm.fit which directly works with matrices and is also faster:

    dolm <- function(x) coef(lm.fit(cbind(Intercept = 1, x[,-1]), x[,1]))
    

提交回复
热议问题