Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Visualizing the Market Strength Using a Gauge Chart: Python Tutorial

2 min read

In this tutorial, we’ll explore how to visualize the RSI using a gauge chart in Python, leveraging the capabilities of the Plotly library, “Guage Chart” visually represents a single value within a given scale, resembling the dashboard gauge of a car. In the context of stock market indicators, such as the Relative Strength Index (RSI), it is used to depict how overbought or oversold a security is. The chart typically has a semicircular scale with a needle or pointer indicating the current value.

In this tutorial, we will be fetching the historical data from yfinance and computing the latest RSI value using the pandas_ta library. We will be creating the gauge chart quadrant values as follows

0-20 Levels – Extremely Oversold
20-40 – Over Sold
40-60 – Neutral
60-80 – Momentum Zone
80-100 – Extreme Overbought

Importing the Library and Computing the RSI Value

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

# Fetch data from Yahoo Finance
ticker = "^NSEI"  # Example ticker
data = yf.download(ticker, start="2023-01-01", end="2024-01-12")


# Calculate RSI using pandas_ta
data['RSI'] = ta.rsi(data['Close'], length=14)

# Latest RSI value
latest_rsi = data['RSI'].iloc[-1]

Plot the Guage Chart Showing RSI Strength Reading

For the visual representation, we’ll create a gauge chart using plotly.graph_objects. This type of chart will allow us to illustrate the RSI level like a car’s speedometer:

The below code snippet sets up the quadrant, colors, and text for the different RSI levels and calculates the angle of the needle based on the latest RSI value.

# Gauge chart setup

plot_bgcolor = "#def"
quadrant_colors = [plot_bgcolor, "#f25829", "#f2a529", "#eff229", "#85e043", "#2bad4e"] 
quadrant_text = ["", "<b>Extreme Overbought</b>", "<b>Momentum Zone</b>", "<b>Neutral</b>", "<b>Over Sold</b>", "<b>Extremely Oversold</b>"]
n_quadrants = len(quadrant_colors) - 1

min_value = 0
max_value = 100  # RSI ranges from 0 to 100
hand_length = np.sqrt(2) / 4
hand_angle =  360 * (-latest_rsi/2 - min_value) / (max_value - min_value) - 180

# Create gauge chart
fig = go.Figure(
    data=[
        go.Pie(
            values=[0.5] + (np.ones(n_quadrants) / 2 / n_quadrants).tolist(),
            rotation=90,
            hole=0.5,
            marker_colors=quadrant_colors,
            text=quadrant_text,
            textinfo="text",
            hoverinfo="skip",
            sort=False
        ),
    ],
    layout=go.Layout(
        showlegend=False,
        margin=dict(b=0,t=10,l=10,r=10),
        width=800,
        height=800,
        paper_bgcolor=plot_bgcolor,
        annotations=[
            go.layout.Annotation(
                text=f"<b>Nifty RSI Level:</b><br>{latest_rsi:.2f}",
                x=0.5, xanchor="center", xref="paper",
                y=0.25, yanchor="bottom", yref="paper",
                showarrow=False,
                font=dict(size=14)
            )
        ],
        shapes=[
            go.layout.Shape(
                type="circle",
                x0=0.48, x1=0.52,
                y0=0.48, y1=0.52,
                fillcolor="#333",
                line_color="#333",
            ),
            go.layout.Shape(
                type="line",
                x0=0.5, x1=0.5 + hand_length * np.cos(np.radians(hand_angle)),
                y0=0.5, y1=0.5 + hand_length * np.sin(np.radians(hand_angle)),
                line=dict(color="#333", width=4)
            )
        ]
    )
)
fig.show()

This visual tool can be particularly useful when presenting market data, offering a clear and immediate interpretation of the market’s momentum. By following this tutorial, you’ve learned how to fetch market data, calculate RSI, and create a dynamic gauge chart to visualize market strength. Happy trading, and may your analysis be as sharp as your visualizations!

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Voice Commands to Trade on OpenAlgo Platform Using Google…

Trading platforms are always getting better by using the newest technologies to make things easier and more efficient for users. A great example of...
Rajandran R
5 min read

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

How to Place Orders Concurrently using ThreadPoolExecutor – Python…

Creating concurrent orders is essential for active traders, especially those handling large funds, as it allows for executing multiple trade orders simultaneously, thereby maximizing...
Rajandran R
2 min read

Leave a Reply

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