Wenjie Yu
Wenjie Yu

Reputation: 71

How to fill color using mplfinance?

I plotted the candlestick chart for the stock price along with some indicators using the mplfinance package. I bought and sold the stock at different prices for many times. Sometimes I win and somethimes I lose. I want to fill the region where I win with green color and the regin where I lose with red color on the main plot. How can I do it?

For instance, how to fill the region between 2022-04-07 and 2022-04-21 with red and the region between 2022-04-27 and 2022-05-10 with green? enter image description here

import mplfinance as mpf

kwargs = dict(
type='candle', 
mav=(5,10,30), 
volume=True, 
title='%s'%(stock_df.iloc[0,0]),    
ylabel='Price', 
ylabel_lower='Volume', 
#figratio=(1200/72,480/60), 
figscale=3,
datetime_format='%Y-%m-%d',
xrotation=0
)

add_plot = [
mpf.make_addplot(rsi.tail(60),panel=2,ylabel='RSI'),
mpf.make_addplot(slowk.tail(60),panel=3,color='darkslateblue',ylabel='KDJ'),
mpf.make_addplot(slowd.tail(60),panel=3,color='limegreen'),
mpf.make_addplot(slowj.tail(60),panel=3,color='orangered')
]

mpf.plot(
        stock_df.tail(60),  # the stock price 
        **kwargs,
        addplot=add_plot,
        style='yahoo'
    )

Upvotes: 1

Views: 2364

Answers (1)

Daniel Goldfarb
Daniel Goldfarb

Reputation: 7714

You can use kwarg fill_between when calling mpf.plot() or when calling mpf.make_addplot(). Both methods accept fill_between.

Do whichever is more convenient. The difference is that, when passing a dict for you fill_between value, mpf.plot() will accept panel as one of the keys in the dict (to place the fill_between on a particular panel), whereas, since mpf.make_addplot() has its own panel kwarg, there is no need to include it in the fill_between dict.

To accomplish what you want, coloring only between particular dates, you must pass, a where value within the fill_between dict. This where value must be a boolean list, equal in length to your dataframe, where True indicates that color should be placed at that point, and False indicates no color.

For specific examples, see the fill_between tutorial in the mplfinance documentation.

Note: kwarg fill_between was recently enhanced with version 0.12.9b0, adding support for make_addplot and allowing a list of fill_between dicts to be passed. Make sure you have the latest version of mplfinance: pip install --upgrade mplfinance.

Upvotes: 1

Related Questions