Moving Regressions, from Steve Ellison
Dr. Rafter discussed smoothing some time ago. One of his techniques was to take a regression and project the regression line forward at each point in the time series. I have been interested in trying this technique, but have found it very time-consuming to implement in E****, in which one must go to a dialog window to run a single regression. I looked for a better way.
Below is a rough piece of R code that calculates a "moving regression projection" for a daily price series (in this case a 20-period regression projected 2 periods forward). For input, I use a CSV file with date, open, high, low, and close prices, plus a sequence number (1 for the first row, 2 for the second row, etc.) to be used as the independent variable in the regression.
require(gregmisc)
dailyPrices<-read.csv('cotton.csv',header=TRUE,sep=",",quote="\"") arrSize<-dim(dailyPrices) numrows<-arrSize[1] regressCol<-array(0,c(numrows,1)) combined<-cbind(dailyPrices, regressCol)
for (i in 20:numrows)
{
Get a regression of the last 20 closes last20<-subset(dailyPrices[(i-19):i,]) regression<-lm(Close ~ X, last20) # Extend the regression line by 2 additional points predictedValues<-predict(regression) combined[i,7]<-(2*predictedValues[20])-predictedValues[18]
}
write.csv(combined,file="cottonRegression.csv")
The output looks like:
Date Open High Low Close X RegressCol
5/3/2007 48.59 48.95 48.35 48.4 84 47.98565
5/4/2007 48.4 48.65 48.21 48.28 85 47.73247
5/7/2007 48.58 48.75 48.45 48.6 86 47.50965
5/8/2007 48.6 49.19 48.45 48.7 87 47.37444
5/9/2007 49.1 49.24 48.65 48.82 88 47.36022
5/10/2007 48.9 49.15 48.9 49.03 89 47.37723
5/11/2007 48.35 48.7 47.58 48.11 90 47.29259
5/14/2007 48.15 48.2 46.9 46.92 91 46.91736
5/15/2007 47.1 47.9 47.1 47.75 92 46.75521
5/16/2007 48.8 50.2 48.4 49.19 93 47.05242