我正在尝试实现R中此链接中提到的线性回归曲线,需要帮助。
我找到了以下ThinkScript代码来实现我正在寻找的东西。有什么帮助将它转换为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;
}
这是我到目前为止所拥有的......
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)
}
当我用
调用该函数时lrc&lt; - inertiaTS(Cl(stockData $ AAPL),20)
我收到以下错误。对此有何帮助?
seq.default(start.at,NROW(data),by = by)出错: 错误的登录&#39;由&#39;参数
感谢。
答案 0 :(得分:0)
rollapply
和lm
执行任务:
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