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.

How to Plot Candlestick Charts, Moving Averages, Drawdown using Python and Pandas Library

1 min read

How to Plot Candlestick Charts, Moving Averages, Drawdown using Python and Pandas Library

In one of the past tutorials, we learned how to import data from NSEindia using NSEpy library and how to compute co-integration. Now let us plot candlestick charts in Python using the same NSE data.

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

Python for traders, the quick way in

BEGINNER FRIENDLY · RATED 5.0

Python for traders, the quick way in

A crash course that gets you from zero to writing your own market data scripts.

  • Python basics with market examples
  • Fetch, clean and chart price data
  • Lifetime access
Start learning →by Marketcalls
pip install nsepy
pip install mplfinance
pip install matplotlib
pip install pandas

Python Code for Plotting Candlestick 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()
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.

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