Python Candlestick Chart in Matplotlib
Python Candlestick Chart | Chapter 11
A candlestick chart or Japanese candlestick chart is a financial chart used to depict the price movement of securities, derivatives etc. in financial market. In this tutorial we will use Python to plot Candlestick Chart.
A Candlestick Chart essentialy have an Open, High, Low and Close (also called OHLC). Matplotlib has a moudule called matplotlib.finance which has a method to create candlestick chart in Python, but the same has been deprecated. However, plotting a Candlestick chart in Python and Matplotlib is still possible with the help of module mpl_finance, which consists of code extracted from the deprecated matplotlib.finance module.
Python Candlestick Plot in Matplotlib
Now, we will create a Candlestick chart in Python. For that we will have to install mpl_finance module and we will be using candlestick_ohlc method to plot the data.
First of all, we will install mpl_finance:-
pip install mpl_finance
We will be creating Candlestick Chart/Plot for NIFTY 50 data for the period from 01.08.2019 to 13.09.2019, which I have downloaded from here and named it as ‘candlestick_python_data.csv’. We will be using pandas’ read_csv() method to read the csv files. Quickly create a Python file ‘python_candlestick_chart.py’ and start coding:
# 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 candlestick chart, pandas to extract data using read_csv method, matplotlib.dates for formatting the dates.
- We are using the style ‘ggplot’. You can read more about styles in our Chapter 1.
- Then we are extracting the 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 from here.
- There after we have create a simple Python Subplot. Read more about subplots in Python from here.
- Then we have used candlestick_ohlc method to plot the 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. Learn more about it from here.
- Finally, we have formatted the date to our liking (read more from here ) and used plt.show() to plot the Python Candlestick Chart.
Python Candlestick Plot with SMA Overlay in Matplotlib
We can also overlay the Simple Moving Average(SMA) on the Python Candlestick Plot. Let us calculate the SMA for 5 days (Since, we started with data of only 30-40 days in beginning) and overlay it on the existing Python Candlestick Plot in Matplotlib.
# 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()
Table of Contents of Matplotlib Tutorial in Python
In case of any query, you can leave the comment below.
If you want to support our work. You can do it using Patreon.