@@ -38,7 +38,7 @@ def relative_strength_index(
3838 # validating levels
3939 if oversold >= overbought :
4040 raise ValueError ("oversold level should be < overbought level" )
41- if not (0 < oversold < 100 ) or not (0 < overbought < 100 ):
41+ if not (0 < oversold < 100 ) or not (0 < overbought < 100 ):
4242 raise ValueError ("levels should be > 0 and < 100" )
4343 # converting data to pd.DataFrame if it is a pd.Series (for subsequent function calls):
4444 if isinstance (data , pd .Series ):
@@ -56,12 +56,21 @@ def relative_strength_index(
5656 data ["avg_gain" ] = data ["gain" ].rolling (window = wl , min_periods = wl ).mean ()
5757 data ["avg_loss" ] = data ["loss" ].rolling (window = wl , min_periods = wl ).mean ()
5858 # calculate WMS (wilder smoothing method) averages
59- lambda_wsm = lambda avg_gain_loss , gain_loss , window_length : (avg_gain_loss * (window_length - 1 ) + gain_loss ) / window_length
59+ lambda_wsm = (
60+ lambda avg_gain_loss , gain_loss , window_length : (
61+ avg_gain_loss * (window_length - 1 ) + gain_loss
62+ )
63+ / window_length
64+ )
6065 # ignore SettingWithCopyWarning for the below operation
61- with pd .option_context (' mode.chained_assignment' , None ):
66+ with pd .option_context (" mode.chained_assignment" , None ):
6267 for gain_or_loss in ["gain" , "loss" ]:
63- for i , row in enumerate (data [f"avg_{ gain_or_loss } " ].iloc [wl + 1 :]):
64- data [f"avg_{ gain_or_loss } " ].iloc [i + wl + 1 ] = lambda_wsm (data [f"avg_{ gain_or_loss } " ].iloc [i + wl ], data [gain_or_loss ].iloc [i + wl + 1 ], wl )
68+ for i , row in enumerate (data [f"avg_{ gain_or_loss } " ].iloc [wl + 1 :]):
69+ data [f"avg_{ gain_or_loss } " ].iloc [i + wl + 1 ] = lambda_wsm (
70+ data [f"avg_{ gain_or_loss } " ].iloc [i + wl ],
71+ data [gain_or_loss ].iloc [i + wl + 1 ],
72+ wl ,
73+ )
6574 # calculate RS values
6675 data ["rs" ] = data ["avg_gain" ] / data ["avg_loss" ]
6776 # calculate RSI
0 commit comments