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

I would like to create a candlestick chart on Matplotlib. I found many examples on the Internet, but so far they all use links to yahoo finances or other data, without explaining how to get the same result when you have a list of tuples containing a date, open, close, high and low prices. Often, indeed, it happens that you already have historical values ​​or estimated values ​​or more in general, you simply do not want to use numbers from a supplier such as Yahoo Finance. What I would like to know is the simplest code to do something like creating a candlestick chart with its own list of values. Suppose 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 must I code exactly to get a candlestick chart (this means a chart in which each item in the Prices list creates a candlestick) with these two data points? I can, of course, manipulate the data (an example of a date string that needs to be converted to a floating point day, etc.), but I cannot get simple commands to create a chart. Can anybody help?

+4
source share
1 answer

Following the matplotlib example , I came up with 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()
+5
source

All Articles