Candlestick plot in matplotlib.finance

As you have seen in the first part of this chapter, our dataset contains the opening and closing prices as well as the highest and lowest price per trading day. None of the plots we have described thus far are able to describe the trend of all these variables in a single plot.

In the financial world, the candlestick plot is almost the default choice for describing price movements of stocks, currencies, and commodities over a time period. Each candlestick consists of the body, describing the opening and closing prices, and extended wicks illustrating the highest and lowest prices of a particular trading day. If the closing price is higher than the opening price, the candlestick is often colored black. Conversely, the candlestick is colored red if the closing price is lower. The trader can then infer the opening and closing prices based on the combination of color and the boundary of the candlestick body.

In the following example, we are going to prepare a candlestick chart of Apple Incorporation in the last 50 trading days of our DataFrame. We will also apply the tick formatter to label the ticks as dates:

import matplotlib.pyplot as plt
from matplotlib.dates import date2num, WeekdayLocator, DayLocator, DateFormatter, MONDAY
from matplotlib.finance import candlestick_ohlc


# Extract stocks data for AAPL.
# candlestick_ohlc expects Date (in floating point number), Open, High, Low,
# Close columns only
# So we need to select the useful columns first using DataFrame.loc[]. Extra
# columns can exist,
# but they are ignored. Next we get the data for the last 50 trading only for
# simplicity of plots.
candlestick_data = stock_df[stock_df["Company"]=="AAPL"]
.loc[:, ["Datetime", "Open", "High", "Low", "Close",
"Volume"]]
.iloc[-50:]

# Create a new Matplotlib figure
fig, ax = plt.subplots()

# Prepare a candlestick plot
candlestick_ohlc(ax, candlestick_data.values, width=0.6)

ax.xaxis.set_major_locator(WeekdayLocator(MONDAY)) # major ticks on the mondays
ax.xaxis.set_minor_locator(DayLocator()) # minor ticks on the days
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.xaxis_date() # treat the x data as dates
# rotate all ticks to vertical
plt.setp(ax.get_xticklabels(), rotation=90, horizontalalignment='right')

ax.set_ylabel('Price (US $)') # Set y-axis label
plt.show()
Starting from Matplotlib 2.0, matplotlib.finance is deprecated. Readers should use mpl_finance (https://github.com/matplotlib/mpl_finance) in the future instead. However, as of writing this chapter, mpl_finance is not yet available on PyPI, so let's stick to matplotlib.finance for the time being.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset