vendredi 22 février 2019

Loop through specific number of rows in R

I am doing data analysis in R to get the pre-ranking betas of Fama-French CAPM model. In order to calculate the pre-ranking betas, I have to regress a minimum of 24 and a maximum of 60 monthly returns (R) on market returns (M) and save the betas (first coefficient of the regression analysis) for EACH month (I have 342 months). In order to achieve this, I created the following loop:

mydata <- read.csv("Austria.csv", header = T, sep = ";")

Betas <- matrix(nrow = 342, ncol = 1)

for(k in 1:282){
  M <- mydata[k:59+k,3]
  R <- mydata[k:59+k,5] - mydata[k:59+k,2]
  criteria <- length(!is.na(R))
  if (criteria >= 24) {
    result <- lm(R ~ M, na.action = na.omit)
  } else {
    result <- "NA"
  } 
  if (any(result != "NA")) {
    coefficients <- coef(summary(result))
  } else {
    coefficients <- "NA"
  } 
  if (any(coefficients != "NA")) {
    Betas[k,1] <- coefficients[2,1]
  } else {
    Betas[k,1] <- "NA"
  }
}

But the betas generated through this procedure do not match the regression betas in excel. Can anyone please help me?

Aucun commentaire:

Enregistrer un commentaire