fix: handle RSI NaN when gain and loss are both zero - return neutral 50

This commit is contained in:
阳虎 2026-03-18 03:24:15 +08:00
parent 774b1ed3d3
commit 78ad76876d
1 changed files with 7 additions and 1 deletions

View File

@ -60,9 +60,15 @@ class MomentumIndicator:
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
# Handle division by zero and NaN values
loss = loss.replace(0, np.nan)
# When both gain and loss are zero (no price change), return neutral RSI of 50
# Otherwise compute RS and RSI
rs = gain / loss
# When loss is 0 (no downtrends), RSI = 100
rsi = 100 - (100 / (1 + rs))
# Fill NaN values:
# - When loss was NaN (no downtrends), RSI should be 100
# - When gain and loss were both 0 (no price change), RSI should be 50
return rsi.fillna(100 if loss.isna().any() else 50)