Initial commit of RSI indicator

This commit is contained in:
moshferatu 2024-12-03 08:43:43 -08:00
parent ddab52ca4f
commit 23c96cdc9a

18
indicators/rsi.py Normal file
View File

@ -0,0 +1,18 @@
from numpy import where
from pandas import DataFrame, Series
def rsi(data: DataFrame, period: int = 2) -> Series:
"""
Calculate the RSI and return it as a Series.
"""
delta = data['Close'].diff().fillna(0)
gain = where(delta > 0, delta, 0)
loss = where(delta < 0, -delta, 0)
alpha = 1 / period
avg_gain = Series(gain).ewm(alpha = alpha, adjust = False).mean()
avg_loss = Series(loss).ewm(alpha = alpha, adjust = False).mean()
rs = avg_gain / avg_loss
rs = rs.fillna(0)
return 100 - (100 / (1 + rs))