Open ProgrammingLife opened 6 years ago
here's a pretty rough implementation that mimics tradingview's linreg(), you can figure it out from this. I might make a pull request and include my other implementations if I proceed with the technicalindicators package.
// Working, exactly matches pinescript implementation
// time order of series: [t-0, t-1, t-2 ] // reverse for ease of use later
let close = [5609.7, 5655.7, 5749.6].reverse();
close = [25.500000, 26.921875,29.531250].reverse();
console.log(
linreg(close, 3, 0)
);
function linreg(source, length, offset)
{
let begin = 0, end = length-1;
let sumX = 0.0;
let sumY = 0.0;
let sumXSqr = 0.0;
let sumXY = 0.0;
for (let i=0; i<length; ++i)
{
// must calculate across X-axis => x-3, x-2, x-1, x = 0
// hence the quick and dirty reverse() above.
let val = source[begin+i];
let per = i + 1;
sumX += per;
sumY += val;
sumXSqr += per * per;
sumXY += val * per;
}
var m = (length*sumXY - sumX*sumY) / (length*sumXSqr - sumX*sumX);
var b = (sumY/length) - (m*sumX)/length +m ;
return b + m * (length - 1 - offset);
}
Is any chance to calculate a linear regression with TechnicalIndicators? If not, maybe in the future some time? :)