We can plot a year's worth of stock quotes data with the matplotlib.finance
package. This requires a connection to Yahoo Finance, which is the data source.
from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator from matplotlib.finance import quotes_historical_yahoo from matplotlib.finance import candlestick import sys from datetime import date import matplotlib.pyplot as plt today = date.today() start = (today.year - 1, today.month, today.day)
matplotlib.dates
package locate months and days on the x
axis:alldays = DayLocator() months = MonthLocator()
x
axis. This formatter creates a string containing the short name of a month and the year:month_formatter = DateFormatter("%b %Y")
quotes = quotes_historical_yahoo(symbol, start, today)
matplotlib
Figure
object—this is a top-level container for plot components:fig = plt.figure()
ax = fig.add_subplot(111)
x
axis to the months locator. This locator is responsible for the big ticks on the x
axis:ax.xaxis.set_major_locator(months)
x
axis to the days locator. This locator is responsible for the small ticks on the x
axis:ax.xaxis.set_minor_locator(alldays)
x
axis to the months formatter. This formatter is responsible for the labels of the big ticks on the x
axis:ax.xaxis.set_major_formatter(month_formatter)
matplotlib.finance
package allows us to display candlesticks. Create the candlesticks using the quotes data. It is possible to specify the width of the candlesticks. For now, use the default value:candlestick(ax, quotes)
x
axis as dates. This rotates the labels on the x
axis so that they fit better:fig.autofmt_xdate() plt.show()
The candlestick chart for DISH (Dish Network Corp) appears as follows:
We downloaded a year's worth of data from Yahoo Finance. We charted this data using candlesticks (see candlesticks.py
):
from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator from matplotlib.finance import quotes_historical_yahoo from matplotlib.finance import candlestick import sys from datetime import date import matplotlib.pyplot as plt today = date.today() start = (today.year - 1, today.month, today.day) alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo(symbol, start, today) fig = plt.figure() ax = fig.add_subplot(111) ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) candlestick(ax, quotes) fig.autofmt_xdate() plt.show()