Search code examples
pythonmatplotlibmplfinance

How to add multiple dataframe columns to the basic mplfinance plot()


import yfinance as yf
msft = yf.Ticker('MSFT')
data = msft.history(period='6mo')
import mplfinance as mpf

data['30 Day MA'] = data['Close'].rolling(window=20).mean()
data['30 Day STD'] = data['Close'].rolling(window=20).std()
data['Upper Band'] = data['30 Day MA'] + (data['30 Day STD'] * 2)
data['Lower Band'] = data['30 Day MA'] - (data['30 Day STD'] * 2)

apdict = (
        mpf.make_addplot(data['Upper Band'])
        , mpf.make_addplot(data['Lower Band'])
        )
mpf.plot(data, volume=True, addplot=apdict)

I tried the above code. But I got the following error, which I don't understand what is wrong. Could anybody show me how to fix the bug? Thanks.

>>> mpf.plot(data, volume=True, addplot=apdict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mplfinance/plotting.py", line 293, in plot
    config = _process_kwargs(kwargs, _valid_plot_kwargs())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mplfinance/_arg_validators.py", line 292, in _process_kwargs
    raise TypeError('kwarg "'+key+'" validator returned False for value: "'+str(value)+'"\n    '+v)
TypeError: kwarg "addplot" validator returned False for value: "({'data': Date
2020-12-15           NaN
2020-12-16           NaN
2020-12-17           NaN
2020-12-18           NaN
2020-12-21           NaN
                 ...
2021-06-08    255.290610
2021-06-09    256.115131
2021-06-10    256.886620
2021-06-11    258.091432
2021-06-14    259.828890
Name: Upper Band, Length: 124, dtype: float64, 'scatter': False, 'type': 'line', 'mav': None, 'panel': 0, 'marker': 'o', 'markersize': 18, 'color': None, 'linestyle': None, 'width': None, 'bottom': 0, 'alpha': 1, 'secondary_y': 'auto', 'y_on_right': None, 'ylabel': None, 'ylim': None, 'title': None, 'ax': None, 'yscale': None, 'stepwhere': 'pre'}, {'data': Date
2020-12-15           NaN
2020-12-16           NaN
2020-12-17           NaN
2020-12-18           NaN
2020-12-21           NaN
                 ...
2021-06-08    239.371960
2021-06-09    239.340165
2021-06-10    240.447735
2021-06-11    240.784914
2021-06-14    240.278626
Name: Lower Band, Length: 124, dtype: float64, 'scatter': False, 'type': 'line', 'mav': None, 'panel': 0, 'marker': 'o', 'markersize': 18, 'color': None, 'linestyle': None, 'width': None, 'bottom': 0, 'alpha': 1, 'secondary_y': 'auto', 'y_on_right': None, 'ylabel': None, 'ylim': None, 'title': None, 'ax': None, 'yscale': None, 'stepwhere': 'pre'})"
    'Validator'   : lambda value: isinstance(value,dict) or (isinstance(value,list) and all([isinstance(d,dict) for d in value])) },

Solution

    • As per Adding plots to the basic mplfinance plot(), section Plotting multiple additional data sets
      • Aside from the example below, for two columns from a dataframe, the documentation shows a number of ways to configure an appropriate object for the addplot parameter.
      • apdict = [mpf.make_addplot(data['Upper Band']), mpf.make_addplot(data['Lower Band'])] works as well. Note it's a list, not a tuple.
    • mplfinance/examples
    # add multiple additional data sets
    apdict = mpf.make_addplot(data[['Upper Band', 'Lower Band']])
    
    # plot
    mpf.plot(data, volume=True, addplot=apdict)
    

    enter image description here