How to create a Matplotlib Candlestick Chart in Python?

A candlestick chart or Japanese candlestick chart is a financial chart used to depict the price movement of securities, derivatives etc. in financial market. We can create a Matplotlib Candlestick Chart using a module called mpl_finance, which consists of code extracted from the deprecated matplotlib.finance() module. A Candlestick Chart essentialy have an Open, High, Low and Close (also called OHLC). Earlier, Matplotlib had a moudule called matplotlib.finance which had a method to create candlestick chart in Matplotlib, but the same has been deprecated.

Installing mpl_finance module (alternative to matplotlib.finance)

As discussed earlier you can not install/use matplotlib.finance in Matplotlib 3 as the same has been deprecated. To create a Matplotlib Candlestick (OHLC) chart, we will be installing mpl_finance using the following code:-

pip install mpl_finance

Downloading and reading datetime data for creating Matplotlib Candlestick Chart

We will be creating Matplotlib Candlestick Chart from Datetime data for NIFTY 50 data for the period from 01.08.2019 to 13.09.2019, which I have downloaded from NSE and named it as ‘candlestick_python_data.csv’. We will be using Pandas’ read_csv() method to read the csv file containing the datetime data. Create a Python file ‘python_candlestick_chart.py’ and start coding:

Python code for creating Matplotlib Candlestick Chart using Pandas

# python_candlestick_chart.py import matplotlib.pyplot as plt from mpl_finance import candlestick_ohlc import pandas as pd import matplotlib.dates as mpl_dates plt.style.use('ggplot') # Extracting Data for plotting data = pd.read_csv('candlestick_python_data.csv') ohlc = data.loc[:, ['Date', 'Open', 'High', 'Low', 'Close']] ohlc['Date'] = pd.to_datetime(ohlc['Date']) ohlc['Date'] = ohlc['Date'].apply(mpl_dates.date2num) ohlc = ohlc.astype(float) # Creating Subplots fig, ax = plt.subplots() candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8) # Setting labels & titles ax.set_xlabel('Date') ax.set_ylabel('Price') fig.suptitle('Daily Candlestick Chart of NIFTY50') # Formatting Date date_format = mpl_dates.DateFormatter('%d-%m-%Y') ax.xaxis.set_major_formatter(date_format) fig.autofmt_xdate() fig.tight_layout() plt.show()

Let me quickly walk you through the code.

Firstly, we have made the necessary imports, we will be using matplotlib.pyplot() to plot the chart, candlestick_ohlc() from mpl_finance to plot the Matplotlib Candlestick chart, Pandas to extract datetime-CSV data using read_csv() method, matplotlib.dates for formatting the datetime data in Matplotlib. We are using the style ‘ggplot’. Then, we are extracting the datetime data from the downloaded CSV using pandas.read_csv(). Thereafter, we have converted the date to pandas.to_datetime and finally we have converted all the data to float using pandas.astype().You can read more about extracting data from CSV using Pandas. There after we have create a simple Python Subplot. Then we have used candlestick_ohlc of mpl_finance method to plot the matplotlib candlestick chart in Python. We can pass arguments, like width, colorup, colordown, alpha etc. to this method. Thereafter, we have set the labels and title to our Python Subplot. Finally, we have formatted the date to our liking (read more from here ) and used plt.show() to plot the Python Candlestick Chart.

Matplotlib Candlestick chart with SMA Overlay in Python

We can also overlay the Simple Moving Average(SMA) on the Matplotlib Candlestick chart. Let us calculate the SMA for 5 days (Since, we started with datetime data of only 30-40 days in beginning) and overlay it on the existing Matplotlib Candlestick Chart.

# python_candlestick_chart.py ohlc['SMA5'] = ohlc['Close'].rolling(5).mean() ax.plot(ohlc['Date'], ohlc['SMA5'], color='green', label='SMA5') fig.suptitle('Daily Candlestick Chart of NIFTY50 with SMA5') plt.legend() plt.show()

Matplotlib Video Tutorial Series

We are glad to inform you that we are coming up with the Video Tutorial Series of Matplotlib on Youtube. Check it out below.

Table of Contents of Matplotlib Tutorial in Python

Matplotlib Tutorial in Python | Chapter 1 | Introduction

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter 6

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Chart | Matplotlib Tutorial | Chapter 11

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

In case of any query, you can leave the comment below.

If you want to support our work. You can do it using Patreon.