This tutorial shows how to find every RSI crossing above 80 in Python and measure what the market did next. The code downloads Nifty 50 data with yfinance, calculates the 14 period RSI, flags the days when RSI moves from 80 or below to above 80, and prints the next 5, 10 and 20 day returns, so you can judge whether an overbought reading was a sell signal or a sign of strength.
Here is a simple Python code that filters the dates when the RSI crosses above 80 and also computes the next 5-day, 10-day, and 20-day return. To calculate the RSI – the pandas_ta and yfinance libraries are used.

Key Takeaways
- A cross above 80 is defined as RSI above 80 today and at or below 80 on the previous bar, which avoids counting every overbought day.
- Forward returns are calculated with
pct_change(n).shift(-n)so each signal row shows what happened over the following n days. - Signals that occur within five bars of each other overlap, so the second script skips them (the “interleaving” fix).
- On Nifty 50 from 2010, the median 20 day return after a cross above 80 was positive: an RSI above 80 has more often marked strong momentum than an immediate top.
- Library changes since 2023 (pandas_ta packaging, yfinance auto adjustment) break parts of the original code; an updated, tested version is included below.
What is pandas_ta library?
The pandas_ta (Technical Analysis) library is an extension of the popular pandas library in Python. It provides additional functionality for performing technical analysis and provides more than 130 Indicators and Utility functions and more than 60 TA Lib Candlestick Patterns
Installing the necessary libraries
pip install yfinance
pip install pandas_ta
Update for 2026: the pandas_ta package on PyPI has changed. Only the 0.4.x beta releases are listed on the pandas-ta PyPI page now, and they require Python 3.12 or newer, so pip install pandas_ta fails on older Python versions. If you cannot upgrade Python, use the plain pandas RSI function in the updated version further down, which needs only pandas and yfinance.
Simple RSI Crossing Above 80 Python Code
import yfinance as yf
import pandas as pd
import pandas_ta as ta
# Download historical data for a stock/index (e.g., ^NSEI. - Nifty 50)
ticker = '^NSEI'
df = yf.download(ticker, start="2010-01-01",end="2023-12-31", multi_level_index=False)
# Calculate RSI
df['RSI'] = ta.rsi(df['Close'], length=14)
# Identify the dates where RSI crosses above 80
cross_above_80 = (df['RSI'] > 80) & (df['RSI'].shift(1) <= 80)
# Calculate returns for next 5, 10, and 20 days
df['Return_5d'] = df['Close'].pct_change(5).shift(-5)*100
df['Return_10d'] = df['Close'].pct_change(10).shift(-10)*100
df['Return_20d'] = df['Close'].pct_change(20).shift(-20)*100
# Filter rows where RSI crossed above 80
cross_above_80_df = df[cross_above_80][['RSI', 'Return_5d', 'Return_10d', 'Return_20d']]
# Round the returns to two decimals
cross_above_80_df = cross_above_80_df.round(2)
# Display the results in table format
print(cross_above_80_df)
How the code works
yf.download()fetches daily Nifty 50 (^NSEI) prices.multi_level_index=Falsekeeps simple column names likeClose.ta.rsi()calculates the 14 period RSI using Wilder’s smoothing.- The boolean series
cross_above_80is True only on the bar where RSI moves from 80 or below to above 80. pct_change(5).shift(-5)computes the return from today’s close to the close five bars later and moves it back to today’s row. The same is done for 10 and 20 bars.- The final DataFrame keeps only the signal rows, rounded to two decimals.
Output
RSI Return_5d Return_10d Return_20d
Date
2010-09-15 80.01 2.21892 2.224035 6.363298
2014-04-02 80.23 0.649386 0.964082 -1.480922
2014-05-19 81.07 1.314784 1.362284 3.717191
2014-06-09 80.59 -1.581406 -2.106576 1.731636
2018-01-23 82.11 -0.505246 -5.47651 -6.324603
2020-12-17 80.77 0.062222 2.02173 5.043411
2021-01-12 80.92 -0.290452 -4.092095 3.728854
2021-08-31 82.49 1.34192 2.260364 3.380194
2022-08-12 80.48 -1.172163 -2.176781 2.101352
2023-07-20 80.57 -1.597916 -2.990618 -3.348491
2023-12-04 81.84 <NA> <NA> <NA>
Avoiding Interleaving issue to fix the t+5 return issue
If within 5 days any RSI value crosses above 80 again it will be ignored. That will fix the interleaving issues. Here is the updated Python code for the same.
import yfinance as yf
import pandas as pd
import pandas_ta as ta
# Download historical data for a stock/index (e.g., ^NSEI - NIFTY 50)
ticker = '^NSEI'
df = yf.download(ticker, start="2010-01-01", multi_level_index=False)
# Calculate RSI using 'Adj Close'
df['RSI'] = ta.rsi(df['Adj Close'], length=14)
# Identify the dates where RSI crosses above 80
cross_above_80 = (df['RSI'] > 80) & (df['RSI'].shift(1) <= 80)
# Initialize columns for returns
df['Return_5d'] = pd.NA
df['Return_10d'] = pd.NA
df['Return_20d'] = pd.NA
skip_days = 0 # Days to skip after finding a cross above 80
# Calculate returns for next 5, 10, and 20 days with non-interleaving for 5-day returns
for i in range(len(df)):
if skip_days > 0:
# If any crossover happens interleaving then convert it to False
cross_above_80.iloc[i] = False
# Skip this day and decrement skip_days
skip_days -= 1
continue
if (cross_above_80.iloc[i]):
# Found a cross above 80, set skip_days
skip_days = 5
# Calculate returns
if i + 5 < len(df):
df.at[df.index[i], 'Return_5d'] = (df['Adj Close'].iloc[i + 5] / df['Adj Close'].iloc[i] - 1) * 100
if i + 10 < len(df):
df.at[df.index[i], 'Return_10d'] = (df['Adj Close'].iloc[i + 10] / df['Adj Close'].iloc[i] - 1) * 100
if i + 20 < len(df):
df.at[df.index[i], 'Return_20d'] = (df['Adj Close'].iloc[i + 20] / df['Adj Close'].iloc[i] - 1) * 100
# Filter rows where RSI crossed above 80
cross_above_80_df = df[cross_above_80][['RSI', 'Return_5d', 'Return_10d', 'Return_20d']]
# Round the returns to two decimals
cross_above_80_df = cross_above_80_df.round(2)
# Display the results in table format
print(cross_above_80_df)
Output
[*********************100%***********************] 1 of 1 completed
RSI Return_5d Return_10d Return_20d
Date
2010-09-15 80.01 2.21892 2.224035 6.363298
2014-04-02 80.23 0.649386 0.964082 -1.480922
2014-05-19 81.07 1.314784 1.362284 3.717191
2014-06-09 80.59 -1.581406 -2.106576 1.731636
2018-01-23 82.11 -0.505246 -5.47651 -6.324603
2020-12-17 80.77 0.062222 2.02173 5.043411
2021-01-12 80.92 -0.290452 -4.092095 3.728854
2021-08-31 82.49 1.34192 2.260364 3.380194
2022-08-12 80.48 -1.172163 -2.176781 2.101352
2023-07-20 80.57 -1.597916 -2.990618 -3.348491
2023-12-04 81.84 <NA> <NA> <NA>
The 4 December 2023 row shows <NA> because the post was written before the next 20 sessions existed. Using Nifty 50 daily closes from Yahoo Finance, that signal returned +1.50% after 5 days, +3.54% after 10 days and +4.73% after 20 days. A second cross followed on 14 December 2023 (RSI 82.27). There has been no fresh daily cross above 80 on Nifty 50 since then; the highest daily RSI(14) from 2024 to 9 November 2026 was about 78.7. I discuss what these readings mean for the index in Nifty RSI indicator above 80: is the index overbought?.
Updated version (2026)
Current yfinance releases return auto adjusted prices by default, so there is no Adj Close column and the second script stops with KeyError: 'Adj Close' (see the yfinance project on GitHub). The version below uses Close with auto_adjust=True, calculates Wilder’s RSI in plain pandas (no pandas_ta needed), replaces the row by row loop with a simple signal filter, and prints summary statistics. I tested it with yfinance 1.8 and pandas 3.0 in November 2026.
import yfinance as yf
import pandas as pd
# Download Nifty 50 daily data (auto_adjust=True is the default in yfinance 1.x,
# so there is no separate 'Adj Close' column; 'Close' is already adjusted)
ticker = '^NSEI'
df = yf.download(ticker, start="2010-01-01", auto_adjust=True,
multi_level_index=False, progress=False)
# Wilder's RSI(14) in plain pandas (same smoothing as pandas_ta and TradingView)
def rsi(close, length=14):
delta = close.diff()
gain = delta.clip(lower=0).ewm(alpha=1/length, min_periods=length, adjust=False).mean()
loss = (-delta.clip(upper=0)).ewm(alpha=1/length, min_periods=length, adjust=False).mean()
return 100 - 100 / (1 + gain / loss)
df['RSI'] = rsi(df['Close'], 14)
# RSI crossing above 80 today, after being at or below 80 yesterday
cross = (df['RSI'] > 80) & (df['RSI'].shift(1) <= 80)
# Forward returns in percent
for n in (5, 10, 20):
df[f'Return_{n}d'] = (df['Close'].shift(-n) / df['Close'] - 1) * 100
# Skip any new signal that appears within 5 bars of the previous one
signals, last = [], None
for i in df.index[cross]:
pos = df.index.get_loc(i)
if last is None or pos - last > 5:
signals.append(i)
last = pos
result = df.loc[signals, ['Close', 'RSI', 'Return_5d', 'Return_10d', 'Return_20d']].round(2)
print(result)
print(result[['Return_5d', 'Return_10d', 'Return_20d']].describe().round(2))
Output (run on 10 November 2026)
Close RSI Return_5d Return_10d Return_20d
Date
2010-09-15 5860.95 80.01 2.22 2.22 6.36
2014-04-02 6752.55 80.23 0.65 0.96 -1.48
2014-05-19 7263.55 81.07 1.31 1.36 3.72
2014-06-09 7654.60 80.59 -1.58 -2.11 1.73
2018-01-23 11083.70 82.11 -0.51 -5.48 -6.32
2020-12-17 13740.70 80.77 0.06 2.02 5.04
2021-01-12 14563.45 80.92 -0.29 -4.09 3.73
2021-08-31 17132.20 82.49 1.34 2.26 3.38
2022-08-12 17698.15 80.48 -1.17 -2.18 2.10
2023-07-20 19979.15 80.57 -1.60 -2.99 -3.35
2023-12-04 20686.80 81.84 1.50 3.54 4.73
2023-12-14 21182.70 82.27 0.34 2.59 3.36
Return_5d Return_10d Return_20d
count 12.00 12.00 12.00
mean 0.19 -0.16 1.92
std 1.26 3.03 3.76
min -1.60 -5.48 -6.32
25% -0.68 -2.38 0.93
50% 0.20 1.16 3.37
75% 1.32 2.23 3.98
max 2.22 3.54 6.36
The signal dates and returns match the original output exactly, which confirms the plain pandas RSI gives the same values as pandas_ta. The extra 14 December 2023 signal appears because it is more than five bars after 4 December.
How to Read the Results
- Across these 12 signals the median 20 day return was +3.37% and 9 of 12 were positive. That argues against shorting Nifty just because RSI crossed 80.
- The 5 and 10 day returns are close to zero on average, so a cross above 80 tends to be followed by a pause before the trend resumes.
- Twelve events is a small sample. Use it to form a hypothesis, then test it on more instruments (Bank Nifty, sector indices, stocks) before trading it.
- Returns here ignore costs and are close to close. For a tradeable version, enter on the next day’s open and include brokerage, STT and slippage.
Ways to Extend This RSI Filter
- Change
tickerto any Yahoo symbol, for example^NSEBANKorRELIANCE.NS. - Test the opposite case, RSI crossing below 20 or 30, by changing the condition to
(df['RSI'] < 30) & (df['RSI'].shift(1) >= 30). - Loop over a list of tickers and collect the results in one DataFrame to see which stocks continue higher after overbought readings.
- Plot the RSI with the signals marked; using Plotly and pandas TA to plot technical indicators shows how.
If you are new to yfinance, my yfinance guide for stock market data in Python covers downloads, intervals and common errors. For an AmiBroker take on RSI signals, see the simple smoothed RSI crossover strategy.
Frequently Asked Questions
How do I calculate RSI in Python without pandas_ta?
Take the daily price change, separate gains and losses, smooth each with an exponential average using alpha = 1/14 (Wilder’s method), and compute RSI = 100 – 100 / (1 + average gain / average loss). The rsi() function in the updated code does exactly this.
Why does my code give KeyError: ‘Adj Close’?
Newer yfinance versions adjust prices by default and drop the Adj Close column. Use df[‘Close’], or pass auto_adjust=False to yf.download() if you need both columns.
Is RSI above 80 a sell signal?
Not on its own. On Nifty 50 since 2010, returns 20 days after a cross above 80 were positive in most cases. RSI above 80 shows strong momentum; combine it with price structure or a trend filter before acting.
Does RSI in Python match TradingView?
Yes, if both use Wilder’s smoothing and the same price data. Small differences can appear in the first few hundred bars because the smoothing needs time to settle, and because index data from different vendors can differ slightly.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.


Hi Raja, Can you share me the code which works. Currently this code not work in python
try now it works. recently yfinance upgrade with multi index column in the latest library