Algorithmic Trading & Indicators
Beginner
Automated RSI Calculation & Overbought/Oversold Reversal Signals in Python
Calculate Wilder's Relative Strength Index (RSI) in Python Pandas and detect automated bullish and bearish reversal crossovers at 30 and 70 thresholds.
#pandas#numpy
Problem Statement
Using simple rolling averages for RSI produces inaccurate readings during sharp momentum spikes. This script implements Wilder's exact reciprocal smoothing and flags fresh exits from oversold (<30) and overbought (>70) zones.
Formula / Core Logic
RS = Wilder_EMA(Gains, 14) / Wilder_EMA(Losses, 14)
RSI = 100 - [100 / (1 + RS)]
Installation
pip install pandas numpy
rsi-divergence-detection-script-python.py
import pandas as pd
import numpy as np
def calculate_rsi_signals(df, period=14):
df = df.copy()
delta = df['Close'].diff()
gain = delta.clip(lower=0)
loss = -1 * delta.clip(upper=0)
avg_gain = gain.ewm(alpha=1/period, min_periods=period, adjust=False).mean()
avg_loss = loss.ewm(alpha=1/period, min_periods=period, adjust=False).mean()
rs = avg_gain / avg_loss
df['RSI'] = 100 - (100 / (1 + rs))
# Signal 1 when RSI crosses back above 30, -1 when RSI crosses below 70
df['Signal'] = np.where((df['RSI'] > 30) & (df['RSI'].shift(1) <= 30), 1, np.where((df['RSI'] < 70) & (df['RSI'].shift(1) >= 70), -1, 0))
return df
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: Why wait for RSI to cross back above 30 instead of buying below 30?
In strong downtrends, RSI can stay below 30 for dozens of candles. Waiting for the cross back above 30 confirms momentum inflection.