Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Using Plotly and Pandas TA to Plot Technical Indicators – Python Tutorial

6 min read

To plot technical indicators with Plotly and pandas_ta in Python, download OHLC data with yfinance, compute indicators such as RSI, ATR and Supertrend with one line each using the pandas_ta DataFrame extension, and draw them in Plotly subplots: a candlestick chart with Supertrend on top and the oscillators in panels below. This tutorial walks through the original 2023 code and an updated 2026 version tested with yfinance 1.x and pandas-ta 0.4.

Key Takeaways

  • df.ta.rsi(), df.ta.atr() and df.ta.supertrend() add indicator columns directly to your DataFrame with append=True.
  • make_subplots() with row_heights gives the price chart most of the space and stacks indicators underneath.
  • Newer yfinance versions return adjusted, multi-level columns by default; pass auto_adjust=False, multi_level_index=False to keep the old layout.
  • pandas-ta 0.4 names Supertrend columns SUPERT_7_3 instead of SUPERT_7_3.0.
  • Tata Motors trades under the NSE symbol TMPV since 24 October 2025, so TATAMOTORS.NS needs replacing.

Why Use Plotly and pandas_ta for Technical Indicators?

Plotly combined with pandas_ta is a great tool for visualizing technical indicators and Plotly python library comes with better customization in creating various chart visualization types. Plotly brings a powerful library for creating interactive charts and visually appealing plots.

Whereas, pandas_ta brings 130+ classical technical indicators like supertrend, moving averages, macd, rsi, atr, and various oscillators. It provides an effortless way to compute and calculate technical indicators.

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls

Installing yfinance, pandas_ta and Plotly

pip install yfinance
pip install pandas_ta
pip install plotly

Note: the second and third pip commands above install the versions current in 2023. Today pip install pandas-ta installs the rewritten 0.4.x series (0.4.71b0 at the time of writing), which depends on NumPy 2, pandas and Numba (pandas-ta installation docs). The older 0.3.14b release fails to import with NumPy 2, so upgrade if you see an error about NaN from numpy.

Download Stock Data from Yahoo Finance and Compute RSI, ATR and Supertrend

import yfinance as yf
import plotly.subplots as sp
import plotly.graph_objects as go
import pandas_ta as ta
import numpy as np

# Fetch stock data
symbol = 'TATAMOTORS.NS'
start_date = '2022-01-01'
end_date = '2023-01-01'
stock_data = yf.download(symbol, start=start_date, end=end_date)

# Calculate technical indicators
stock_data.ta.atr(length=14, append=True)
stock_data.ta.rsi(length=14, append=True)
stock_data.ta.supertrend(append=True, atr_length=7, multiplier=3)

stock_data

Output

[*********************100%***********************]  1 of 1 completed
Open	High	Low	Close	Adj Close	Volume	ATRr_14	RSI_14	SUPERT_7_3.0	SUPERTd_7_3.0	SUPERTl_7_3.0	SUPERTs_7_3.0
Date												
2022-06-01	445.100006	446.000000	439.600006	444.600006	443.218628	11930669	NaN	NaN	0.000000	1	NaN	NaN
2022-06-02	445.000000	445.600006	435.649994	439.149994	437.785553	12742438	NaN	NaN	NaN	1	NaN	NaN
2022-06-03	444.899994	445.049988	430.500000	431.899994	430.558075	12780122	NaN	NaN	NaN	1	NaN	NaN
2022-06-06	427.899994	433.950012	424.600006	432.350006	431.006683	11896105	NaN	NaN	NaN	1	NaN	NaN
2022-06-07	432.500000	438.200012	429.100006	435.850006	434.495819	11153869	NaN	NaN	NaN	1	NaN	NaN
...	...	...	...	...	...	...	...	...	...	...	...	...
2023-12-04	716.000000	717.000000	704.799988	705.599976	705.599976	9348036	13.684554	69.059318	669.040471	1	669.040471	NaN
2023-12-05	705.900024	714.900024	705.000000	708.950012	708.950012	9601509	13.414231	70.206895	669.827554	1	669.827554	NaN
2023-12-06	709.049988	724.799988	709.000000	722.450012	722.450012	12148825	13.588212	74.337551	675.716468	1	675.716468	NaN
2023-12-07	725.000000	727.500000	716.000000	721.950012	721.950012	10451801	13.439054	73.928726	681.521264	1	681.521264	NaN
2023-12-08	722.049988	727.599976	707.500000	714.549988	714.549988	8554990	13.914834	67.970747	681.521264	1	681.521264	NaN
378 rows × 12 columns

The first rows show NaN because ATR and RSI need 14 bars of history before they produce a value. SUPERTd_7_3.0 is the direction (1 for uptrend, -1 for downtrend), while SUPERTl and SUPERTs hold the long and short trailing stop values. (The sample output above was captured over a longer date range than the code’s 2022 window.)

Plotting the Technical Indicators with Plotly Subplots


# Create subplots in a separate plane with different row heights
fig = sp.make_subplots(rows=3, cols=1, shared_xaxes=True,
                       subplot_titles=[f'{symbol} Stock Prices', 'Technical Indicators'],
                       vertical_spacing=0.1,
                       row_heights=[0.7, 0.15, 0.15])

# Add Stock Prices subplot
fig.add_trace(go.Candlestick(x=stock_data.index,
                open=stock_data['Open'],
                high=stock_data['High'],
                low=stock_data['Low'],
                close=stock_data['Close'],
                name='Stock Prices'), row=1, col=1)

# Add Supertrend subplot with dynamic colors and smaller marker dots
fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['SUPERT_7_3.0'],
                mode='lines+markers',
                marker=dict(color=np.where(stock_data['Close'] > stock_data['SUPERT_7_3.0'], 'green', 'red'),
                            size=3),  # Set the size of the marker dots
                line=dict(color='rgba(0,0,0,0)'),  # This line is added to hide the line connecting markers
                name='Supertrend'), row=1, col=1)

# Add ATR subplot
fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['ATRr_14'],
                mode='lines',
                line=dict(color='blue'),  # Set the color to blue
                name='ATR'), row=2, col=1)

# Add RSI subplot
fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['RSI_14'],
                mode='lines',
                name='RSI'), row=3, col=1)

# Update layout to set figure size
fig.update_layout(xaxis_rangeslider_visible=False,
                  template='plotly_dark',
                  title_text=f'{symbol} Stock Analysis',
                  xaxis=dict(type='category'),  # Set x-axis type to category which removes the sat and sun gap
                  xaxis_title_text='Date',
                  yaxis_title_text='Price',
                  yaxis2_title_text='ATR',  # Add y-axis title for ATR subplot
                  yaxis3_title_text='RSI',  # Add y-axis title for RSI subplot
                  height=800,  # Set the height of the figure
                  width=1200)  # Set the width of the figure

# Show the figure
fig.show()

Here the sp.make_subplots function is from the plotly.subplots module and it is used to create a subplot grid. The Subplots are divided into 3 rows – the first row is used to plot candlestick charts with supertrend indicators and second row to plot ATR levels and the third row to plot RSI levels. The row_heights=[0.7, 0.15, 0.15] implies that the first row consumes 70% of the canvas so that the candlestick plot will have a larger space to plot, and the 2nd and 3rd row utilizes 15% of each of the total canvas.

In Plotly, the add_trace function is used to add one or more traces to a plot. A trace represents a single set of data in a plot, such as a line, scatter plot, bar chart, etc. The add_trace function is part of the Figure class in Plotly, and it allows you to build up complex plots by adding multiple traces to a single figure. A total of 4 traces are added to plot the candlestick charts, supertrend, ATR, and RSI indicator.

The Supertrend markers are added in such a way as to plot dynamic colors according to buy/sell mode. The supertrend is plotted with green color if the close of the candle is above supertrend else a red color is plotted to the trace.

The update_layout method in Plotly to customize the layout and appearance of the plot. For a dark theme, the template parameter is set to plotly_dark. And to remove the Saturday and Sunday or any holiday gap xaxis=dict(type=’category’) is added. The height and width of the canvas are set as 800 and 1200 respectively.

Finally fig.show() is used to display the final figure with all the computed technical indicators in one figure.

Updated Version (2026): Tested with yfinance 1.x and pandas-ta 0.4

Three things have changed since this tutorial was written:

  • yfinance defaults: yf.download() now adjusts prices by default and returns multi-level column names (price, ticker). Passing auto_adjust=False, multi_level_index=False gives the flat Open/High/Low/Close/Adj Close/Volume columns this code expects.
  • pandas-ta 0.4: Supertrend takes length and multiplier (the old atr_length argument was not a Supertrend parameter, so the original code was silently using the default length of 7), and the column is now SUPERT_7_3.
  • Symbol change: after the demerger of its commercial vehicles business, Tata Motors Ltd became Tata Motors Passenger Vehicles and its NSE symbol changed from TATAMOTORS to TMPV effective 24 October 2025 (HDFC Sky).

I ran the script below with yfinance 1.x, pandas-ta 0.4.71b0 and Plotly 7 on Python 3.13. It picks up the Supertrend column name automatically, adds 70/30 guide lines to the RSI panel and hides weekends and NSE holidays with rangebreaks, which keeps a real date axis (unlike type='category', which turns dates into labels).

import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas_ta as ta
import numpy as np
import pandas as pd

# Tata Motors now trades as Tata Motors Passenger Vehicles (NSE: TMPV)
symbol = 'TMPV.NS'

# auto_adjust=False keeps raw OHLC; multi_level_index=False gives flat column names
stock_data = yf.download(symbol, start='2025-01-01', end='2026-06-30',
                         auto_adjust=False, multi_level_index=False)

# Calculate technical indicators (pandas-ta 0.4.x)
stock_data.ta.atr(length=14, append=True)
stock_data.ta.rsi(length=14, append=True)
stock_data.ta.supertrend(length=7, multiplier=3, append=True)

# Column names changed in pandas-ta 0.4: SUPERT_7_3 instead of SUPERT_7_3.0
st_col = [c for c in stock_data.columns if c.startswith('SUPERT_')][0]

fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
                    subplot_titles=[f'{symbol} Stock Prices', 'ATR (14)', 'RSI (14)'],
                    vertical_spacing=0.08,
                    row_heights=[0.7, 0.15, 0.15])

fig.add_trace(go.Candlestick(x=stock_data.index,
                             open=stock_data['Open'], high=stock_data['High'],
                             low=stock_data['Low'], close=stock_data['Close'],
                             name='Stock Prices'), row=1, col=1)

fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data[st_col],
                         mode='markers',
                         marker=dict(color=np.where(stock_data['Close'] > stock_data[st_col], 'green', 'red'),
                                     size=3),
                         name='Supertrend'), row=1, col=1)

fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['ATRr_14'],
                         mode='lines', line=dict(color='blue'), name='ATR'), row=2, col=1)

fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['RSI_14'],
                         mode='lines', name='RSI'), row=3, col=1)

# Overbought / oversold guides on the RSI panel
fig.add_hline(y=70, line_dash='dot', line_color='grey', row=3, col=1)
fig.add_hline(y=30, line_dash='dot', line_color='grey', row=3, col=1)

# Hide weekends and exchange holidays (dates with no data) using rangebreaks
all_days = pd.date_range(stock_data.index.min(), stock_data.index.max(), freq='D')
missing_days = all_days.difference(stock_data.index)
fig.update_xaxes(rangebreaks=[dict(values=missing_days.strftime('%Y-%m-%d').tolist())])

fig.update_layout(xaxis_rangeslider_visible=False,
                  template='plotly_dark',
                  title_text=f'{symbol} Stock Analysis',
                  yaxis_title_text='Price',
                  yaxis2_title_text='ATR',
                  yaxis3_title_text='RSI',
                  height=800, width=1200)

fig.show()

How to Add More Indicators

Any pandas_ta indicator follows the same pattern. For example, to overlay a 20 and 50 EMA on the price panel, add these lines after the indicator calculations and before fig.show():

stock_data.ta.ema(length=20, append=True)
stock_data.ta.ema(length=50, append=True)

fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['EMA_20'],
                         mode='lines', name='EMA 20'), row=1, col=1)
fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['EMA_50'],
                         mode='lines', name='EMA 50'), row=1, col=1)

For MACD, Bollinger Bands or ADX, call stock_data.ta.macd(), stock_data.ta.bbands() or stock_data.ta.adx() with append=True, print stock_data.columns to see the exact column names, and add a new subplot row for oscillators. You can also call help(ta.supertrend) or stock_data.ta.indicators() to see what is available.

Common Errors and Fixes

ErrorCauseFix
KeyError: 'SUPERT_7_3.0'pandas-ta 0.4 column namingUse SUPERT_7_3 or detect the column as in the updated code
ImportError: cannot import name 'NaN' from 'numpy'Old pandas-ta 0.3.14b with NumPy 2pip install -U pandas-ta
Empty DataFrame for TATAMOTORS.NSSymbol renamed after the 2025 demergerUse TMPV.NS
Indicator functions fail on Closeyfinance multi-level columnsPass multi_level_index=False

For more on the data side, see Mastering yfinance and my introduction to Pandas DataFrame for traders. If you want another indicator to try with this charting template, the Halftrend indicator Python code is a good next step, and visualizing Nifty 50 market capitalisation with a Plotly treemap shows a different Plotly chart type.

Frequently Asked Questions

What is pandas_ta used for?

pandas_ta is a Python library that adds 130+ technical indicators to pandas DataFrames, so you can calculate RSI, MACD, ATR, Supertrend and more with one line each.

How do I install pandas_ta?

Run pip install pandas-ta. Current versions (0.4.x) need NumPy 2 and Numba; use a recent Python version in a virtual environment.

How do I remove weekend gaps in a Plotly candlestick chart?

Either set the x-axis to type='category' as in the original code, or use fig.update_xaxes(rangebreaks=...) with the missing dates, which keeps a true date axis.

Can I plot Supertrend in Plotly?

Yes. Compute it with df.ta.supertrend(length=7, multiplier=3, append=True) and add the SUPERT_7_3 column as a Scatter trace on the price panel, coloured by whether the close is above or below it.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More