codeplayr / alphacate

Node.js toolkit for the technical and quantitative stock analysis
MIT License
13 stars 3 forks source link

Wrong RSI calculations due to rounding errors #1

Open stefankirchfeld opened 4 years ago

stefankirchfeld commented 4 years ago

Hi,

thanks for providing this library! Great API.

While using it I noticed though that at least the RSI indicator does not calculate 100% accurate results. I believe this is due to rounding in lines 61 and 62:

avg_gain: NumberUtil.isNumeric(avg_gain) ? NumberUtil.roundTo( avg_gain, 2 ) : null, avg_loss: NumberUtil.isNumeric(avg_loss) ? NumberUtil.roundTo( avg_loss, 2 ) : null,

Since these fields are not only result fields but are also used internally for the i+1 calculations for the next period, and they are rounded, the average gain remains the same for a lot of periods over time, although smaller gains/losses occurred, which actually do affect the RSI. Hence the indicator tends to deliver values that are too low.

I did not check if similar rounding errors happen for other indicators as well, maybe it's worth going over your code again and double check this.

I would suggest to not round any fields that are used for in-between calculations. Only at the very end, just when the data is returned to the caller, fields can be rounded.

I noticed the discrepancies when comparing your RSI values with RSIs for example on tradingview.com or results delivered from another node library (@d3fc/d3fc-technical-indicator).

Best regards, Stefan

mdkrieg commented 3 years ago

Hello @stefankirchfeld

I've forked this repository and fixed the issue you mentioned. I increased the rounding to 10 decimals and fixed a problem with the intial averages including the first bar which is always zero gain & loss (and thus dropping one bar after initial average).

See here: https://github.com/mdkrieg/alphacate

@codeplayr , big thanks and nice work on this repository!

Regards, -Matt