How to create a candlestick chart with Matplotlib (Python 2.7) and your own data

Matteo NNZ picture Matteo NNZ · Jan 14, 2014 · Viewed 19.4k times · Source

I would like to create a candlestick chart on Matplotlib. I have found many examples on the web but so far they are all using connections to yahoo finance or other kind of data, while not explaining well how to get the same result when you have a list of tuples containing the date, the open, the close, the high and the low prices. Often, indeed, it happens that you already have historical values, or estimated values, or more in general you just don't want to use the numbers coming from a provider such as Yahoo Finance. What I would like to know is the very basic code to make something like create a candlestick chart with your own list of values. Assume that I have a list of tuples with all the data I need for two days:

Prices = [('01/01/2010', 1.123 (open), 1.212 (close), 1.463 (high), 1.056(low)),
          ('02/01/2010', 1.121 (open), 1.216 (close), 1.498 (high), 1.002(low))] 

What should I code exactly to get a candlestick plot (that means a plot where every element of the list "Prices" is creating a candlestick) with these two data points? I can of course manipulate the data (example the date string to be converted in a float day etc.), but I cannot get the simple commands to create the chart. Anyone can help?

Answer

Matteo NNZ picture Matteo NNZ · Jan 14, 2014

Following the matplotlib example I have got to the following solution:

from pylab import *
import matplotlib.pyplot as plt
from datetime import datetime
import time
from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
     DayLocator, MONDAY
from matplotlib.finance import candlestick,\
     plot_day_summary, candlestick2


mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays    = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')      # e.g., 12

#starting from dates expressed as strings...
Date1 = '01/01/2010'
Date2 = '02/01/2010'
#...you convert them in float numbers....
Date1 = date2num(datetime.strptime(Date1, "%d/%m/%Y"))
Date2 = date2num(datetime.strptime(Date2, "%d/%m/%Y"))
#so redefining the Prices list of tuples...
Prices = [(Date1, 1.123, 1.212, 1.463, 1.056), (Date2,1.121, 1.216, 1.498, 1.002)]
#and then following the official example. 
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
candlestick(ax, Prices, width=0.6)

ax.xaxis_date()
ax.autoscale_view()
plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

plt.show()