DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Matplotlib Candlestick Chart in Python | Matplotlib Tutorial | Chapter 11

  • 5 minutes read
  • 81906 Views
Matplotlib Candlestick Chart in Python | Matplotlib Tutorial | Chapter 11

    Table of Contents

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.

  1. 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.
  2. We are using the style ‘ggplot’.
  3. 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.
  4. There after we have create a simple Python Subplot.
  5. 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.
  6. Thereafter, we have set the labels and title to our Python Subplot.
  7. Finally, we have formatted the date to our liking (read more from here ) and used plt.show() to plot the Python Candlestick Chart.

candlestick_chart_in_python.png

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()

candlestick_chart_in_python_.png

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.


Related Posts

Python unittest module - How to test your python code?
By Udit Vashisht

Python unittest module

Why to unit test your python source code?

All programmers want their code to be impeccable, but as the saying goes, to err is human, we make mistakes and leave bugs in our source code. Here is where the unit testing comes to our rescue. If you ...

Read More
If __name__ == '__main__' in Python
By Udit Vashisht

What does if __name__ == ‘__main__‘in python means?

In python, you must have come accross the following code :-

if __name__ == '__main__': main() 

In this tutorial, we will learn in detail what does the above statement means. As per official documentation:

‘__main__‘ is the name of the ...

Read More
Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3
By Udit Vashisht

Matplotlib Tutorial in Python

Chapter 3 | Creating Pie Charts in Python

In this chapter, we will learn to create Pie Charts in Matplotlib in Python. Pie Charts are an intiutive way of showing data, wherein each category is shown as a portion of the pie. Let ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python