Reputation: 311
I am trying to implement the linear Regression curve mentioned at this link in R and need help.
Link: Linear Regression Curve
I found the following ThinkScript code that implements what I am looking for. Any help in converting it to R?
script inertiaTS {
input y = close;
input n = 20;
rec x = x[1] + 1;
def a = (n * Sum(x * y, n) - Sum(x, n) * Sum(y, n) ) / ( n * Sum(Sqr(x), n) - Sqr(Sum(x, n)));
def b = (Sum(Sqr(x), n) * Sum(y, n) - Sum(x, n) * Sum(x * y, n) ) / ( n * Sum(Sqr(x), n) - Sqr(Sum(x, n)));
plot InertiaTS = a * x + b;
}
Here is what I have so far..
Sqr <- function(x) {
return (x^2)
}
inertiaTS <- function(y, n) {
x <- x + 1;
a <- (n * rollapply( x*y, n, sum) - rollapply( x, n, sum ) * rollapply( y, n, sum )) / ( n * rollapply( Sqr(x), n, sum ) - Sqr(rollapply( x, n, sum )))
b <- (rollapply( Sqr(x), n, sum) * rollapply( y, n, sum ) - rollapply( x, n, sum ) * rollapply( x*y, n, sum ) ) / ( n * rollapply( Sqr(x), n, sum ) - Sqr
(rollapply( x, n, sum )))
return (a * x + b)
}
When I make a call to the function with
lrc <- inertiaTS(Cl(stockData$AAPL), 20)
I get the following error. Any help with this?
Error in seq.default(start.at, NROW(data), by = by) : wrong sign in 'by' argument
Thanks.
Upvotes: 1
Views: 1233
Reputation: 5152
The rollapply
and lm
do the task:
library(zoo)
inertiaTS <- function(y, n) {
x <- 1:n;
c.ab=rollapply(y,n,function(yt){
coef(lm(yt~x))
},align = "right")
plot(y,col=2)
lines(c.ab[ ,2]*x[n]+c.ab[ ,1],col=4,lwd=2)
list(axpb=c.ab[ ,2]*x[n]+c.ab[ ,1],rolcoef=c.ab)
}
#simulate any ts series
set.seed(123)
y=ts(10+sort(rnorm(150,sd=.8))+runif(150))
plot(y)
res<-inertiaTS(y,20)
[1] 11.84216 11.95979 12.06342 12.05539 12.06578 12.19312
Upvotes: 1