user6771241 user6771241 - 2 months ago 23
R Question

Linear Regression Analysis - rolling across rows

I need a suggestion on how I get the results
of my regression analysis into an object.

I wan't to perform the regression analysis row wise and
with a window of 20 days.
The object Slope should save the results (slopes) of each days regressions analysis over the window.

#Loading Library
require(quantmod)
#Initiation of Example
mc_result <- matrix(sample(c(1:200)), ncol = 200, nrow =1)
mc_result1 <- matrix(sample(c(1:200)), ncol =200, nrow =1)
mc_result <- rbind(mc_result, mc_result1)
a <- c(1:200)


Slope <- matrix(ncol=2, nrow=181)


Caution this Loop that does not work.
The Loop should apply Rollapply row wise
and save the results for each day in the object Slope.

However, this is how the result should look like, but with changing Slope values. At the moment the Slope Value is stable and I don't know why.

for (i in 1:2) {

Slope[,i] <- rollapply(data =mc_result[i,], width=20,
FUN = function(z)
summary(lm(mc_result[i,] ~ a, data = as.data.frame(z)))$coefficients[2], by.column = FALSE)
}

Answer

I think what you want is the following (in your code none of mc_result[i,] or a is rolling over the indices in the data, that's why the linear regression coefficients are not changing, since you are training on the same dataset, only z is changing, you need to change the code to something like the following):

#Loading Library 
require(quantmod)
#Initiation of Example
mc_result  <- matrix(sample(c(1:200)), ncol = 200, nrow =1)
mc_result1 <- matrix(sample(c(1:200)), ncol =200, nrow =1)
mc_result <- rbind(mc_result, mc_result1)
a <- c(1:200)          
Slope <- matrix(ncol=2, nrow=181)

for (i in 1:2) { 

  Slope[,i] <- rollapply(data = 1:200, width=20, 
                         FUN = function(z) {
                           summary(lm(mc_result[i,z]  ~ a[z]))$coefficients[2]
                         }, by.column = FALSE) 
}

head(Slope)
          [,1]      [,2]
[1,] 1.3909774 2.0278195
[2,] 1.0315789 2.8421053
[3,] 1.5082707 2.8571429
[4,] 0.0481203 1.6917293
[5,] 0.2969925 0.2060150
[6,] 1.3526316 0.6842105
Comments