Skip to content

Instantly share code, notes, and snippets.

@yellowflash
Created October 8, 2019 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yellowflash/2cd253f8509ee6e09e081760a559b043 to your computer and use it in GitHub Desktop.
Save yellowflash/2cd253f8509ee6e09e081760a559b043 to your computer and use it in GitHub Desktop.
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