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

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. 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

[Course] Designing a Stock Market Trading Dashboard App using…

Designing a Stock Market App using Python is a hands-on course that guides you through the development of a functional stock market application. Over...
Rajandran R
1 min read

Exploring the Essential Python Libraries for Data Analytics

Python has emerged as a powerhouse due to its versatility, ease of use, and extensive library support. Whether you're manipulating data, visualizing trends, performing...
Rajandran R
3 min read

Integrating Tradingview Lightweight Charts with Yahoo Finance Data –…

Hey traders! If you’re looking for a way to visualize your stock data dynamically and interactively, you’re in for a treat. Today, we’ll explore...
Rajandran R
2 min read

Leave a Reply

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