We can plot a year’s worth of stock quotes data with the matplotlib.finance
package. This will require a connection to Yahoo Finance, which will be the data source.
1
year from today.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 are needed to locate months and days on the x-axis.alldays = DayLocator() months = MonthLocator()
month_formatter = DateFormatter("%b %Y")
quotes = quotes_historical_yahoo(symbol, start, today)
figure
object—this is a top-level container for plot components.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)
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)
fig.autofmt_xdate() plt.show()
The candlestick chart for DISH (Dish Network Corp.) would appear 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()
18.217.5.86