python-3.xmatplotlibvisualizationtradingmplfinance

How to plot a horizontal line starting from a specific date in a Japanese Candlestick chart using MatPlotLibFinance on Python3?


I recently decided to code a small program in Python3 that plots the OHLC prices stored in a dataframe and also highlights a horizontal line for a specific price on said graph. For this work, the MatPlotLibFinance library and the very famous Pandas library were used.

The dataframe used (named in this program as df_trading_pair_date_time_index) was the following:

                      Open   High    Low  Close   Volume                End Date
Start Date                                                                      
2022-09-25 07:15:00  5.473  5.495  5.473  5.490  11186.8 2022-09-25 07:17:59.999
2022-09-25 07:18:00  5.491  5.522  5.491  5.517  14063.3 2022-09-25 07:20:59.999
2022-09-25 07:21:00  5.518  5.518  5.499  5.508   5728.8 2022-09-25 07:23:59.999
2022-09-25 07:24:00  5.508  5.511  5.496  5.501   3691.7 2022-09-25 07:26:59.999
2022-09-25 07:27:00  5.499  5.505  5.498  5.500   1146.3 2022-09-25 07:29:59.999
2022-09-25 07:30:00  5.498  5.501  5.491  5.491   2743.0 2022-09-25 07:32:59.999
2022-09-25 07:33:00  5.490  5.494  5.489  5.492   1670.0 2022-09-25 07:35:59.999
2022-09-25 07:36:00  5.494  5.497  5.492  5.496   1341.0 2022-09-25 07:38:59.999
2022-09-25 07:39:00  5.500  5.502  5.491  5.492   1750.0 2022-09-25 07:41:59.999
2022-09-25 07:42:00  5.490  5.492  5.477  5.477   4139.7 2022-09-25 07:44:59.999
2022-09-25 07:45:00  5.476  5.484  5.473  5.484   2292.4 2022-09-25 07:47:59.999
2022-09-25 07:48:00  5.483  5.492  5.480  5.491   2312.6 2022-09-25 07:50:59.999
2022-09-25 07:51:00  5.492  5.500  5.491  5.499   2372.2 2022-09-25 07:53:59.999
2022-09-25 07:54:00  5.500  5.505  5.498  5.502   2511.2 2022-09-25 07:56:59.999
2022-09-25 07:57:00  5.502  5.504  5.500  5.500   1696.4 2022-09-25 07:59:59.999
2022-09-25 08:00:00  5.500  5.507  5.499  5.507   1742.7 2022-09-25 08:02:59.999
2022-09-25 08:03:00  5.506  5.512  5.502  5.512   1276.9 2022-09-25 08:05:59.999
2022-09-25 08:06:00  5.511  5.512  5.505  5.508   3885.8 2022-09-25 08:08:59.999
2022-09-25 08:09:00  5.507  5.509  5.503  5.507   1209.7 2022-09-25 08:11:59.999
2022-09-25 08:12:00  5.507  5.510  5.504  5.510   1270.1 2022-09-25 08:14:59.999

The data types contained in the df_trading_pair_date_time_index columns when executing df_trading_pair_date_time_index.dtypes are as follows:

Open               float64
High               float64
Low                float64
Close              float64
Volume             float64
End Date    datetime64[ns]
dtype: object

And when executing df_trading_pair_date_time_index.index.dtype, the data type of the index column is as follows (it is the same as the End Date column):

dtype('<M8[ns]')

Finally, the code in charge of plotting said data and highlighting a horizontal line for a specific price was the following:

import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Plotting
# Create my own `marketcolors` style:
mc = mpf.make_marketcolors(up='#2fc71e',down='#ed2f1a',inherit=True)
# Create my own `MatPlotFinance` style:
s  = mpf.make_mpf_style(base_mpl_style=['bmh', 'dark_background'],marketcolors=mc, y_on_right=True)    

# Plot it
trading_plot, axlist = mpf.plot(df_trading_pair_date_time_index,
                    figratio=(10, 6),
                    type="candle",
                    style=s,
                    tight_layout=True,
                    datetime_format = '%H:%M',
                    ylabel = "Precio ($)",
                    returnfig=True,
                    show_nontrading=True,
                    hlines=dict(hlines=[df_trading_pair_date_time_index['Open'].iat[-5]],colors=['#06FF44'],linestyle='-.', linewidths=3)
                    )
# Add Title
symbol = trading_pair.replace("BUSD","")+"/"+"BUSD"
axlist[0].set_title(f"{symbol} - 3m", fontsize=25, style='italic', fontfamily='fantasy')

# Find which times should be shown every 6 minutes starting at the last row of the df
x_axis_minutes = []
for i in range (1,len(df_trading_pair_date_time_index),2):
    x_axis_minutes.append(df_trading_pair_date_time_index.index[-i].minute)

# Set the main "ticks" to show at the x axis
axlist[0].xaxis.set_major_locator(mdates.MinuteLocator(byminute=x_axis_minutes))

# Set the x axis label
axlist[0].set_xlabel('Zona Horaria UTC')

trading_plot.savefig('asdf.png',dpi=600, bbox_inches = "tight")

Note: What the horizontal line highlights on the graph itself is the parameter hlines used inside the .plot() method

Which returned the following graph:

initial graph

However, I am interested in learning how someone can specify the start date from which the horizontal line in the figure above would be drawn, so that this horizontal line does not go over the entire graph but only over those values after the start date, that is, a graph like the following:

desired graph

If it's not too much trouble, I would also like to know how I could add a small label to said horizontal line as shown in the image.

I appreciate anyone who can help me out.


Solution

  • The mplfinance kwarg hlines is by definition all the way from one side of the plot to the other. To plot a horizontal line that does not stretch from one side to the other, use kwarg alines.

    To add text or an annotation near the line, use axlist[0].text() or axlist[0].annotate()