Pandas and Finance: Make Candlestick Plot

What will we cover in this tutorial?

A quick way to make a candlestick plot using the mplfinance library on financial data in Pandas DataFrames.

The code

It is straight forward to achieve by using the new matplotlib finance API. The data can be collected by using Pandas-datareader with the open Yahoo! Finance API.

import pandas_datareader as pdr
import datetime as dt
import mplfinance as mpf


df = pdr.get_data_yahoo("AAPL", dt.datetime(2020,6,1), dt.datetime.now())

mpf.plot(df, type='candle', style='charles',
            title='Apple',
            ylabel='Price',
            ylabel_lower='Volume',
            volume=True,
            mav=(1,3,6))

The mav-argument is the Moving Averages, I have also included the 1, which is the actual price.

2 Replies to “Pandas and Finance: Make Candlestick Plot”

  1. This code does not work any more. I get the following error

    Traceback (most recent call last):
    File “mpl.py”, line 3, in
    import mplfinance as mpf
    File “D:\Python\lib\site-packages\mplfinance\__init__.py”, line 2, in
    from mplfinance.plotting import plot, make_addplot
    File “D:\Python\lib\site-packages\mplfinance\plotting.py”, line 2, in
    import matplotlib.pyplot as plt
    File “D:\Python\lib\site-packages\matplotlib\pyplot.py”, line 2349, in
    switch_backend(rcParams[“backend”])
    File “D:\Python\lib\site-packages\matplotlib\pyplot.py”, line 221, in switch_backend
    backend_mod = importlib.import_module(backend_name)
    File “D:\Python\lib\importlib\__init__.py”, line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    File “D:\Python\lib\site-packages\matplotlib\backends\backend_tkagg.py”, line 1, in
    from . import _backend_tk
    File “D:\Python\lib\site-packages\matplotlib\backends\_backend_tk.py”, line 6, in
    import tkinter as tk
    File “S:\perl64\lambda\scripts\tkinter.py”, line 2, in
    import _tkinter
    ModuleNotFoundError: No module named ‘_tkinter’

    1. Hi Amol,

      It should work – I just tested it.

      It says in your error that you do not have the module Tkinter installed.

      ModuleNotFoundError: No module named ‘_tkinter’

      As far I know, it is part of most new installations. Try to see if you can import it. Make the following program and see if it has it available.

      import tkinter
      print(tkinter.TkVersion)

      Cheers,
      Rune

Leave a Reply