Correctly port from Python code
Return 0 instead of NaN for the situation of no any changes compared to historical average