Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. 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

Kernel Density Estimation of Nifty – Data Visualization using Seaborn Python Library

1 min read

Kernel Density Estimation is an elegant way to visualize the price distribution. KDE plots are widely used to visualize and explore the distribution of data. They provide a smooth representation of the underlying probability density, making it easier to identify patterns, modes, and outliers in the data.

KDE Plot on the stock/index price is very similar to the Price distribution plot using the Market Profile. However, the difference here is the smooth distribution plot as the market profile distribution plot comes with rough edges. The peak value of the KDE Plot is very similar to the point of control concept where the maximum time price is spent horizontally.

Installation of Python Libraries

pip install seaborn
pip install yfinance
pip install pandas
pip install matplotlib
pip install ipywidgets

Python Code to Generate KDE Plot using Seaborn Library with Interactive Ipython Widgets which offers slider control for the year and the bandwidth

import yfinance as yf
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from ipywidgets import interactive, FloatSlider, IntSlider
from IPython.display import display

# Function to get Nifty data using yfinance
def get_data(start_date, end_date):
    data = yf.download('^NSEI', start=start_date, end=end_date)
    return data['Adj Close']

# Function to plot KDE for Nifty with adjustable bandwidth
def plot_nifty_kde(data, year, bandwidth):
    sns.set(style="whitegrid")
    plt.figure(figsize=(12, 6))

    # Plot KDE using seaborn with adjustable bandwidth
    sns.kdeplot(data, fill=True, color='blue', label=f'Nifty KDE - {year}', bw_method=bandwidth)

    # Find peak value
    peak_value = data.values[sns.kdeplot(data, bw_method=bandwidth).get_lines()[0].get_data()[1].argmax()].round(2)

    
    # Set plot labels and title
    plt.title(f'Kernel Density Estimate (KDE) Plot for Nifty - {year} - Peak Value {peak_value}')
    plt.xlabel('Nifty Index')
    plt.ylabel('Density')

    # Show legend
    plt.legend()

    # Show the plot
    plt.show()

# Function to create an interactive plot
def interactive_plot(bandwidth, year):
    start_date = f'{year}-01-01'
    end_date = f'{year}-12-31'

    # Get Nifty data for the selected year
    data = get_data(start_date, end_date)

    # Plot KDE for Nifty for the selected year with adjustable bandwidth
    plot_nifty_kde(data, year, bandwidth)

# Set the date range for Nifty data
start_year = 2010
end_year = 2023  # Change this to the current year

# Create interactive sliders for bandwidth and year
bandwidth_slider = FloatSlider(min=0.01, max=1.0, step=0.01, value=0.1, description='Bandwidth:')
year_slider = IntSlider(min=start_year, max=end_year, step=1, value=start_year, description='Year:')

# Create interactive plot
interactive_plot_widget = interactive(interactive_plot, bandwidth=bandwidth_slider, year=year_slider)

# Display the interactive plot widget
display(interactive_plot_widget)

Output

This code uses Seaborn’s kdeplot function to create a kernel density estimate (KDE) plot for the given data. The argmax method returns the index of the maximum y-value in the KDE curve, effectively giving the position of the peak.

KDE plots offer a powerful and flexible tool for visualizing price distributions, enabling traders/investors to uncover patterns and characteristics within financial data.

Learn the Basics about Kernel Density Function

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. 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

How to Speed Up a 1 Billion Iterations Loop…

Python is a versatile and user-friendly programming language, but it’s often criticized for being slow compared to compiled languages like C or C++. A...
Rajandran R
9 min read

Mastering Pydantic for Traders: A Step-by-Step Guide

Trading in India, whether in stocks, commodities, or cryptocurrencies, revolves around data. From NSE tickers to API responses from brokers handling structured and...
Rajandran R
3 min read

SketchMaker AI: Create Stunning AI Visuals and Your Own…

SketchMaker AI is an open-source tool that transforms text into art, allowing you to create stunning AI images, blog banners, Instagram and YouTube thumbnails...
Rajandran R
3 min read

Leave a Reply

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