I was wondering if someone could guide me through the rollapply function in R. I want to conduct a 1 year rolling regression with fama-french factors. The dataset is prepared in Excel and contains weekly data from 2011-2017. Therefore the time window is set to 52 weeks. I want to compute 1 year rolling beta coefficients for the time period 2012-2017, so the time window will move from [1:52] to [2:53] starting from the first week in 2011. I have several pricing factors, this means that I have to run a multiple linear regression.
This is what I have tried so far:
Rollingregression <- read_excel("C:/Users/neri_/Desktop/Fama French Regression.xlsx", col_names = TRUE, sheet = 1)
Rollingregression <- xts(Rollingregression[,2:7],order.by = Rollingregression[,1])
coeffs <- rollapply(Rollingregression, width=52, FUN = function(Z) coef(lm(Rollingregression$`Excess Return` ~ Rollingregression$OBX + Rollingregression$SMB + Rollingregression$HML + Rollingregression$PR1YR + Rollingregression$LIQ, data = as.data.frame(Z))), by.column=FALSE, align="right")
However, I dont get the 5 years weekly rolling betas, but instead the regression over the full period:
(Intercept) Rollingregression$OBX Rollingregression$SMB
[1,] 0.0001511391 0.7529416 -0.007408397
[2,] 0.0001511391 0.7529416 -0.007408397
[3,] 0.0001511391 0.7529416 -0.007408397
[4,] 0.0001511391 0.7529416 -0.007408397
[5,] 0.0001511391 0.7529416 -0.007408397
The output also gives me the same betas for the other fama-french factors throughout the period.
2011-01-04
2011-01-11
2011-01-18
2011-01-25
2011-02-01
I thought this xts code would make sure that R understood that the dataset is a time-series.
I also tried this:
coeffs <- (rollapply(zoo(Rollingregression), width=52, FUN = function(Z){t = lm(Rollingregression$`Excess Return` ~ Rollingregression$OBX + Rollingregression$SMB + Rollingregression$HML + Rollingregression$PR1YR + Rollingregression$LIQ, data = as.data.frame(Z), model = TRUE); return(t$coef)}, by.column = FALSE, align = "right"))
Still gives me the same output.
I am fairly new with R, so any help is much appreciated.
Thanks!