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 Plot Candlestick Charts, Moving Averages, Drawdown using Python and Pandas Library

2 min read

In one of the past tutorials, we learned how to import data from NSEindia using NSEpy library and how to compute co-integration.

In this tutorial, we use the nsepy library to get historical data for the RELIANCE stock from the National Stock Exchange (NSE) in India. The data is then used to create a candlestick chart using the matplotlib library. Also, yfinance to plot the candle data with volume using mplfinance library and plot the drawdown below the line charts

Installing Libraries using pip command

pip install nsepy
pip install mplfinance
pip install matplotlib
pip install pandas

Python Code for Plotting Candle Stick Charts

import nsepy
from nsepy import get_history
from datetime import date
import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpl_dates

# Set the start and end dates
start_date = date(2022, 10, 1)
end_date = date(2023, 2, 28)

# Get the historical data for the stock
data = get_history(symbol='RELIANCE', start=start_date, end=end_date)

# Reset the index and convert the date to a column
data = data.reset_index()
data['Date'] = pd.to_datetime(data['Date'])
data['Date'] = data['Date'].apply(mpl_dates.date2num)

# Create a new DataFrame with the necessary columns for the Candlestick chart
ohlc = data[['Date', 'Open', 'High', 'Low', 'Close']].copy()

# Create a subplot
fig, ax = plt.subplots()

# Plot the Candlestick chart
candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8)


# Set the x-axis tick format
date_format = mpl_dates.DateFormatter('%d %b %Y')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()

# Set the chart title and axis labels
plt.title('RELIANCE Candlestick Chart')
plt.xlabel('Date')
plt.ylabel('Price')

# Show the chart
plt.show()

Output

Plotting Simple Moving Average on Top of the Charts

ticker = "RELIANCE"
plt.plot(data["Close"], label="Close")
plt.plot(data["Close"].rolling(window=10).mean(), label="10-day Moving Average")
plt.plot(data["Close"].rolling(window=20).mean(), label="20-day Moving Average")
plt.title(f"{ticker} Stock Price")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.show()

Plotting Moving Averages using yfinance and mplfinance library

import yfinance as yf
import mplfinance as mpf

# Set the ticker symbol and timeframe
ticker = "RELIANCE.NS"
start_date = "2021-01-01"
end_date = "2022-02-25"

# Fetch the stock data using yfinance
data = yf.download(ticker, start=start_date, end=end_date)


# Plot a candlestick chart with 10-day SMA and 20-day EMA
mpf.plot(data, type="candle", mav=(10, 20), volume=True)

Plotting Drawdown in Percentage Terms

import yfinance as yf
import matplotlib.pyplot as plt

# Download historical data for the stock
ticker = "RELIANCE.NS"
stock = yf.download(ticker)

# Calculate the drawdown
running_max = stock['Adj Close'].cummax()
drawdown = (stock['Adj Close'] - running_max) / running_max *100

# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(12, 8))

# Plot the stock price on the first subplot
ax1.plot(stock.index, stock['Adj Close'], label='Price')

# Plot the drawdown on the second subplot
ax2.fill_between(drawdown.index, drawdown, 0, alpha=0.3)
ax2.set_ylim(-100, 0)
ax2.set_ylabel('Drawdown (%)')

# Add a title and legend
plt.suptitle(f"{ticker} Stock Price and Drawdown")
ax1.legend()

# Show the chart
plt.show()
Reliance Drawdown %
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

Introduction to Backtrader – Creating your First Trading Strategy…

Backtrader is a powerful Python library designed to facilitate the backtesting of trading strategies. It allows traders to test their strategies against historical market...
Rajandran R
4 min read

A Comprehensive Guide to Python Linters: Pylint, Black, and…

Python linters are tools that analyze Python code for potential errors, style violations, and improvements in code quality. They help enforce coding standards, identify...
Rajandran R
8 min read

Introduction to Hidden Markov Models (HMM) for Traders: Python…

Trading the financial markets can be challenging, especially when price movements are unpredictable. One of the techniques traders use to understand and anticipate market...
Rajandran R
8 min read

One Reply to “How to Plot Candlestick Charts, Moving Averages, Drawdown using…”

Leave a Reply

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