Search code examples
pythonmatplotlibmplfinance

How to add separate lines to mplfinance plot?


TL;DR

Is there any way to add separate lines to an mplfinance plot, like the image below, to show how a trade went? I know how to add points, but I can't figure out how to add separate lines.

enter image description here

Replication

Say you have a pandas dataframe that looks like this:

Date Open High Low Close
20190608 9586.35 9586 9586 9586.35
20190609 9586.35 9586 9586 9586.35
20190610 9586.35 9586 9586 9586.35
20190611 9586.35 9586 9586 9586.35
20190612 9586.35 9586 9586 9586.35
20190701 9595.94 9873 9596 9674.55
20190702 9588.27 9692 9556 9576.77

Using mplfinance it's possible to plot and save an OHLC chart with something like this where df is the said dataframe:

import mplfinance as mpf

# plot
fig, axlist = mpf.plot(
    df, type="candle", style='yahoo', ylabel='',
    xrotation=30, returnfig=True, figsize=(6,4))
# save
fig.savefig(filename, bbox_inches='tight',
    pad_inches=0.1, dpi=96, transparent='True')

Solution

  • Additional lines include a vertical line, a horizontal line, a line connecting two or more pairs of dates and prices, and a trend line. Here is an example of simply drawing a line with date and price. Please refer to this page for more details.

    import datetime
    import pandas as pd
    import pandas_datareader.data as web
    import mplfinance as mpf
    
    import yfinance as yf
    data = yf.download("AAPL", start="2021-01-01", end="2021-07-01")
    
    two_points = [('2021-06-04', 128),('2021-06-30', 138)]
    mpf.plot(data, figratio=(8,4), type='candle', alines=two_points, volume=True, mav=(5, 25), style='yahoo')
    

    enter image description here