# A thought on Linear Models on Stocks

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**DataPunks.com » R**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Timely Portfolio has a nice post about linear models sytems for stock.

The idea follows from the steps below:

- Get the weekly closing values of the S&P 500.
- Choose a time window (i.e. 25 weeks) and for each window, linearly regress the subset of closing values
- Choose an investment strategy based on the residuals, the running average of slope coefficients, or the running average of correlation with data points

The idea is quite simple, and so far, from Timely Portfolio’s post, it looks like the drawdown is behaving nicely.

It seems like the idea could be extended to a non-linear method. The residuals are getting larger and larger, and this indicates that linear methods are less reliable as time goes by.

# code from Timely Portfolio # http://timelyportfolio.blogspot.ca/2011/08/unrequited-lm-love.html require(PerformanceAnalytics) require(quantmod) getSymbols("^GSPC",from="1896-01-01",to=Sys.Date()) GSPC <- to.weekly(GSPC)[,4] width = 25 for (i in (width+1):NROW(GSPC)) { linmod <- lm(GSPC[((i-width):i),1]~index(GSPC[((i-width):i)])) ifelse(i==width+1,signal <- coredata(linmod$residuals[length(linmod$residuals)]), signal <- rbind(signal,coredata(linmod$residuals[length(linmod$residuals)]))) } signal <- as.xts(signal,order.by=index(GSPC[(width+1):NROW(GSPC)])) plot(signal, main="Residuals through time") plot(log(signal), main="Log of Residuals through time") |

To

**leave a comment**for the author, please follow the link and comment on their blog:**DataPunks.com » R**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.