The TaLib's code: https://sourceforge.net/p/ta-lib/code/HEAD/tree/trunk/ta-lib/c/src/ta_func/ta_LINEARREG_SLOPE.c#l331
I want a JavaScript function like this:
functuin linearRegressionSlope(arr, range) {
return [...slopeVal]
}
I tried to implement one according to the above source code, but found that the result is inconsistent with it:
const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
let today = 0
const optInTimePeriod = 5
const SumX = optInTimePeriod * (optInTimePeriod - 1) * 0.5
const SumXSqr =
(optInTimePeriod * (optInTimePeriod - 1) * (2 * optInTimePeriod - 1)) / 6
const Divisor = SumX * SumX - optInTimePeriod * SumXSqr
const outReal = []
while (today <= data.length - 1) {
let SumXY = 0
let SumY = 0
for (let i = optInTimePeriod; i > 0; i--) {
SumY += data[today - i]
SumXY += i * data[today - i]
}
outReal.push((optInTimePeriod * SumXY - SumX * SumY) / Divisor)
today++
}
console.log(outReal)
And you can test it by talib-binding
const {LINEARREG_SLOPE} = require('talib-binding')
console.log(LINEARREG_SLOPE(data, optInTimePeriod))
The original code has for
loop is like
for(int i = 5; i-- != 0; )
printf("%d ", i);
which prints out: 4 3 2 1 0
and your loop iterates 5 4 3 2 1. perhaps it's the reason.