How to plot simple and Candlestick chart using Python – pandas matplotlib

Pandas and Matplotlib can be used to plot various types of graphs. Simple timeseries plot and candlestick are basic graphs used by technical analyst for identifying the trend.

Simple time Series Chart using Python – pandas matplotlib

Here is the simplest graph. It uses close price of HDFCBANK for last 24 months to plot normal graph

################################################################################################
# name: timeseries_simple.py
# desc: Plots line chart using 'Close Price'
# date: 2018-06-15
# Author: conquistadorjd
################################################################################################
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
print('*** Program Started ***')
df = pd.read_csv('15-06-2016-TO-14-06-2018HDFCBANKALLN.csv')
# ensuring only equity series is considered
df = df.loc[df['Series'] == 'EQ']
# Converting date to pandas datetime format
df['Date'] = pd.to_datetime(df['Date'])
# Using matplotlib to add required columns
plt.plot(df['Date'], df['Close Price'])
# Adding labels
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.title('Simple time series plot for HDFC')
# Saving image
plt.savefig('Simple time series plot for HDFC.png')
# In case you dont want to save image but just displya it
#plt.show()
print('*** Program ended ***')

view raw
timeseries_simple.py
hosted with ❤ by GitHub

Here is the sample output

Candlestick chart using Python – pandas matplotlib

As per this link, module matplotlib.finance is deprecated in 2.0 and has been moved to a module called mpl_finance. This is still working when I have motplotlib version 2.1.2. This may stop working in any future releases, however, you can use mpl_finance module to use this feature. Please note that mpl_finance is no longer maintained.

 

################################################################################################
# name: timeseries_OHLC.py
# desc: creates OHLC graph
# date: 2018-06-15
# Author: conquistadorjd
################################################################################################
import pandas as pd
# import pandas_datareader as datareader
import matplotlib.pyplot as plt
import datetime
from matplotlib.finance import candlestick_ohlc
# from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
print('*** Program Started ***')
df = pd.read_csv('15-06-2016-TO-14-06-2018HDFCBANKALLN.csv')
# ensuring only equity series is considered
df = df.loc[df['Series'] == 'EQ']
# Converting date to pandas datetime format
df['Date'] = pd.to_datetime(df['Date'])
df["Date"] = df["Date"].apply(mdates.date2num)
# Creating required data in new DataFrame OHLC
ohlc= df[['Date', 'Open Price', 'High Price', 'Low Price','Close Price']].copy()
# In case you want to check for shorter timespan
# ohlc =ohlc.tail(60)
f1, ax = plt.subplots(figsize = (10,5))
# plot the candlesticks
candlestick_ohlc(ax, ohlc.values, width=.6, colorup='green', colordown='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# Saving image
plt.savefig('OHLC HDFC.png')
# In case you dont want to save image but just displya it
#plt.show()
print('*** Program ended ***')

view raw
simple2.py
hosted with ❤ by GitHub

Here is the output

Candlestick chart with SMA overlay using Python – pandas matplotlib

################################################################################################
# name: timeseries_OHLC_with_SMA.py
# desc: creates OHLC graph with overlay of simple moving averages
# date: 2018-06-15
# Author: conquistadorjd
################################################################################################
import pandas as pd
# import pandas_datareader as datareader
import matplotlib.pyplot as plt
import datetime
from matplotlib.finance import candlestick_ohlc
# from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
print('*** Program Started ***')
df = pd.read_csv('15-06-2016-TO-14-06-2018HDFCBANKALLN.csv')
# ensuring only equity series is considered
df = df.loc[df['Series'] == 'EQ']
# Converting date to pandas datetime format
df['Date'] = pd.to_datetime(df['Date'])
df["Date"] = df["Date"].apply(mdates.date2num)
# Creating required data in new DataFrame OHLC
ohlc= df[['Date', 'Open Price', 'High Price', 'Low Price','Close Price']].copy()
# In case you want to check for shorter timespan
# ohlc =ohlc.tail(60)
ohlc['SMA50'] = ohlc["Close Price"].rolling(50).mean()
f1, ax = plt.subplots(figsize = (10,5))
# plot the candlesticks
candlestick_ohlc(ax, ohlc.values, width=.6, colorup='green', colordown='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# Creating SMA columns
ohlc['SMA5'] = ohlc["Close Price"].rolling(5).mean()
ohlc['SMA10'] = ohlc["Close Price"].rolling(10).mean()
ohlc['SMA20'] = ohlc["Close Price"].rolling(20).mean()
ohlc['SMA50'] = ohlc["Close Price"].rolling(50).mean()
ohlc['SMA100'] = ohlc["Close Price"].rolling(100).mean()
ohlc['SMA200'] = ohlc["Close Price"].rolling(200).mean()
#Plotting SMA columns
# ax.plot(ohlc['Date'], ohlc['SMA5'], color = 'blue', label = 'SMA5')
# ax.plot(ohlc['Date'], ohlc['SMA10'], color = 'blue', label = 'SMA10')
# ax.plot(ohlc['Date'], ohlc['SMA20'], color = 'blue', label = 'SMA20')
ax.plot(ohlc['Date'], ohlc['SMA50'], color = 'green', label = 'SMA50')
# ax.plot(ohlc.index, df['SMA100'], color = 'blue', label = 'SMA100')
ax.plot(ohlc['Date'], ohlc['SMA200'], color = 'blue', label = 'SMA200')
# Saving image
plt.savefig('OHLC with SMA HDFC.png')
# In case you dont want to save image but just displya it
# ohlc.to_csv('ohlc.csv')
# plt.show()
print('*** Program ended ***')

view raw
simple3.py
hosted with ❤ by GitHub

here is the output

5 Replies to “How to plot simple and Candlestick chart using Python – pandas matplotlib”

  1. hi, thanks for this post.
    if only I knew what was in ’15-06-2016-TO-14-06-2018HDFCBANKALLN.csv’ or how you got it it would be very helpful!
    cheers!

  2. Hi Pravin – Thanks for sharing. It looks wonderful. However – It would tremendously help me if we can have volume overlay at the bottom of the chart…Is that simple enough to do? Any pointer or help will be greatly appreciated. Once again Thank You for sharing

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.