It looks like you're new here. If you want to get involved, click one of these buttons!
if len(df) >= rolling_window + 7: # Ensure at least 14 rows are available for the initial incomplete window
df['DIFF'] = df['CLOSE'].diff()
df['GAIN'] = np.where(df['DIFF'] > 0, df['DIFF'], 0)
df['LOSS'] = np.where(df['DIFF'] < 0, -df['DIFF'], 0)
# Calculate average gains and losses for the initial incomplete window
df['AVG_GAIN'] = df['GAIN'].rolling(window=rolling_window, min_periods=1).mean()
df['AVG_LOSS'] = df['LOSS'].rolling(window=rolling_window, min_periods=1).mean()
df['RS'] = np.where(df['AVG_LOSS'] != 0, df['AVG_GAIN'] / df['AVG_LOSS'], np.inf)
df['RS'] = np.where(df['AVG_GAIN'] != 0, df['RS'], np.finfo(float).max)
df['RSI'] = 100 - (100 / (1 + np.minimum(df['RS'], 100)))
stochastic_window = 7
df['StochRSI'] = (df['RSI'] - df['RSI'].rolling(window=stochastic_window).min()) / \
(df['RSI'].rolling(window=stochastic_window).max() - df['RSI'].rolling(window=stochastic_window).min())
# Continue calculations for the rest of the rows
df['AVG_GAIN'][rolling_window:] = df['GAIN'][rolling_window:].rolling(window=rolling_window, min_periods=1).mean()
df['AVG_LOSS'][rolling_window:] = df['LOSS'][rolling_window:].rolling(window=rolling_window, min_periods=1).mean()
df['RS'][rolling_window:] = np.where(df['AVG_LOSS'][rolling_window:] != 0, df['AVG_GAIN'][rolling_window:] / df['AVG_LOSS'][rolling_window:], np.inf)
df['RS'][rolling_window:] = np.where(df['AVG_GAIN'][rolling_window:] != 0, df['RS'][rolling_window:], np.finfo(float).max)
df['RSI'][rolling_window:] = 100 - (100 / (1 + np.minimum(df['RS'][rolling_window:], 100)))
df['StochRSI'][rolling_window:] = (df['RSI'][rolling_window:] - df['RSI'][rolling_window:].rolling(window=stochastic_window).min()) / \
(df['RSI'][rolling_window:].rolling(window=stochastic_window).max() - df['RSI'][rolling_window:].rolling(window=stochastic_window).min())