UNPKG

trading-signals

Version:

Technical indicators to run technical analysis with JavaScript / TypeScript.

62 lines 1.9 kB
import { TechnicalIndicator } from '../../base/Indicator.js'; import { pushUpdate } from '../../util/pushUpdate.js'; export class LinearRegression extends TechnicalIndicator { prices = []; interval; constructor(interval) { super(); this.interval = interval; } getRequiredInputs() { return this.interval; } #calculateRegression(prices) { const n = prices.length; const isPerfectLinearTrend = prices.every((price, i) => { if (i === 0) { return true; } return Math.abs(price - prices[i - 1] - 1) < 1e-10; }); if (isPerfectLinearTrend) { const slope = 1; const intercept = prices[0] - slope; const nextX = n; const prediction = slope * nextX + intercept; return { intercept, prediction, slope }; } const sumX = ((n - 1) * n) / 2; const sumY = prices.reduce((a, b) => a + b, 0); let sumXY = 0; let sumXX = 0; for (let i = 0; i < n; i++) { sumXY += i * prices[i]; sumXX += i * i; } const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX); const intercept = (sumY - slope * sumX) / n; const prediction = slope * n + intercept; return { intercept, prediction, slope, }; } update(price, replace) { pushUpdate(this.prices, replace, price, this.interval); if (this.prices.length < this.interval) { return null; } return (this.result = this.#calculateRegression(this.prices)); } get isStable() { try { this.getResultOrThrow(); return true; } catch { return false; } } } //# sourceMappingURL=LinearRegression.js.map