Search code examples
pandasmplfinance

mplfinance moving average gaps and exponential moving averages


I am printing moving averages on a mplfinance plot, as expected there are gaps.

On most charting software, i.e. TradingView etc, they do not have gaps on the moving averages - and presume they are pulling the data from previous -n elements (even with a discontinuous jump they accept this).

I have two questions please:

  1. How can I run a moving average without a gap (understanding it would be skewed within n elements of the discontinuity)... i.e. pull in the day prior and use this for moving average calculation but do not display that day (so that the moving average will already be running on the left hand side of the plot - for below that would be startng at Dec 21st)?

  2. If i wanted to calculate this moving average outside of mplfinance internal function (or change to exponential moving average etc) how would I go about adding this as a separate plot on top of the candlesticks?

And my code is below:

import mplfinance as mpf
import pandas as pd
from polygon import RESTClient
import yfinance as yf
import datetime

start = datetime.date(2021,12,21)
end = datetime.date(2021,12,23)
yfResults = yf.download("AAPL", start=start, end=end, period='1d', interval='5m')
mpf.plot(yfResults, type='candlestick', xrotation=0, style='yahoo', tight_layout=True, volume=True, mav=(9, 20), figratio=(48,24))

plot


Solution

    1. As you have implied, those systems that show no gap at the beginning of the moving average do so by using data prior to the data displayed as part of the moving average calculation. You can accomplish the same thing by setting kwarg xlim=(min,max) in your call to mpf.plot() by setting min equal to one less than your largest moving average, and max=len(data) ... so for example given your code above, do:
    mpf.plot( yfResults, type='candlestick', xrotation=0, style='yahoo',
             tight_layout=True, volume=True, mav=(9, 20), figratio=(48,24),
             xlim=(19,len(yfResults)) )
    
    1. You can calculate and plot any additional data using the mpf.make_addplot() api and the addplot kwarg. For further details, see https://github.com/matplotlib/mplfinance/blob/master/examples/addplot.ipynb