Alok kumar
2006-Aug-31 08:08 UTC
[R] Moving Window regressions with corrections for Heteroscedasticity and Autocorrelations(HAC)
# Using Moving/Rolling Windows, here we do an OLS Regression with corrections for #Heteroscedasticity and Autocorrelations (HAC) using Newey West Method. This code is a #extension of Ajay Shah?s code for moving windows simple OLS regression. # The easiest way to adjust for Autocorrelations and Heteroscedasticity in the OLS residuals is to #use the coeftest function that is included in the ?lmtest? packages. # The ?lmtest? package includes the coeftest (model, NeweyWest) command which returns # the ?HAC? consistent estimators along with its standard error, t-stat and pvalue. # To implement the corrections for Heteroscedasticity and Autocorrelations for a moving/rolling # window OLS regression, here is the actual function: #--------------------------------------------------------------------------------------------------------->movingWindowRegression <- function(data, T, width, model, K) {results = matrix(nrow=T, ncol=4*K) for (i in width:T) { details <-coeftest(lm(model,data[(i-width+1):i,]),NeweyWest) n=1; for (j in 1:K) { results[i,n:(n+3)] = details[j, 1:4] n=n+4 } } return(results) } #------------------------------------------------------------------------------------------------------ #STEP1: Install ?lmtest? package using library (lmtest). #STEP 2: Copy and paste the function defined above into the console and submit it. # The function returns a matrix with T rows (You will find ?NA ?values on all rows less than width.) #The columns are organized as : beta1 se1 tstat1 pvalue1 beta2 se2 tstat2 pvalue2 # i.e. we have each coefficient followed by its s,e., t-stat and p-value. Note that K is the no of #variables in the regression. #STEP3: Get the results using> r= movingWindowRegression(CAPM, 240, 60,Y~X1+X2,3)# Here CAPM is the data set, T=240 monthly data, K =60 as we want to find the 5 year #(5*12=60) rolling regression with adjustment to Autocorrelations and Heteroscedasticity #and the model is Y~X1+X2. # Note that if you want only the ?Heteroscedasticity-Consistent (HC) standard errors? in the #moving/rolling window framework then install ?sandwich? package and change the ?NeweyWest? # to ?sandwich? in the ?details? of the function. # Please send your comments/suggestions to <alok@igidr.ac.in>alok@igidr.ac.in. # www.igidr.ac.in [[alternative HTML version deleted]]