Created
October 8, 2019 11:02
-
-
Save yellowflash/2cd253f8509ee6e09e081760a559b043 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Line { | |
constructor(m, c) { | |
this.m = m; | |
this.c = c | |
} | |
apply(x) { | |
return this.m * x + this.c; | |
} | |
invert(y) { | |
return this.m != 0 ? (y - this.c) / this.m : 0; | |
} | |
} | |
class LeastSquares { | |
constructor(n, sumX, sumY, sumXY, sumXX) { | |
this.n = n || 0; | |
this.sumX = sumX || 0; | |
this.sumY = sumY || 0; | |
this.sumXY = sumXY || 0; | |
this.sumXX = sumXX || 0; | |
} | |
line() { | |
if(n == 0) throw "No data point added."; | |
const m = (this.sumXY - (this.sumX * this.sumY) / this.n) / (this.sumXX - (this.sumX * this.sumX) / n); | |
const c = (this.sumY - m * this.sumX) / n; | |
return new Line(m, c); | |
} | |
add(x, y) { | |
return new LeastSquares ( | |
this.n + 1, | |
this.sumX + x, | |
this.sumY + y, | |
this.sumXY + x*y, | |
this.sumXX + x * x | |
); | |
} | |
} | |
class DickeyFuller { | |
constructor(n, yprev, linearmodel, drift, trend) { | |
this.n = n || 0; | |
this.yprev = yprev || 0; | |
this.linearmodel = linearmodel || new LeastSquares(); | |
this.drift = drift || 0; | |
this.trend = trend || 0; | |
} | |
add(y) { | |
if(n == 0) return new DickeyFuller( | |
1, | |
y, | |
this.linearmodel, | |
this.drift, | |
this.trend); | |
else new DickeyFuller( | |
this.n + 1, | |
y, | |
this.linearmodel.add(this.yprev, y - this.yprev), | |
this.drift, | |
this.trend); | |
} | |
predict() { | |
return this.linearmodel.line().m == 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment