You can update the plot through the use of the matplotlib.animation.FuncAnimation()
function.
In the code below:
get_data()
is used to retrieve the latest data from the data source. You can use your own method to retrieve the relevant data.
- the
animation.FuncAnimation()
is responsible for calling the animate()
function every 5 minutes.
- the
animate()
function makes use of the get_data()
function to retrieve the latest data, and then clears and updates the plot.
If you are using Jupyter Notebook or similar, then you may want to add this to the top of your notebook.
%matplotlib widget
# %matplotlib widget: requires ipympl: pip install ipympl : https://matplotlib.org/ipympl/
# enables using the interactive features of matplotlib in Jupyter Notebooks, Jupyter Lab, Google Colab, VSCode notebooks, Google Colab
Code:
import pandas as pd
import mplfinance as mpf
import matplotlib.animation as animation
import yfinance as yf
def get_data():
# valid periods: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
# valid intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
TICKER = "AAPL"
df = yf.download(tickers=TICKER, period='5d', interval='5m')
return df
df = get_data() # download the data to produce the original plot
fig, axes = mpf.plot(df,returnfig=True,volume=True,
figsize=(11,8),panel_ratios=(2,1),
title='\n\nAAPL',type='candle',mav=(10,20))
ax1 = axes[0]
ax2 = axes[2]
def animate(ival):
data = get_data() # retrieve latest data
ax1.clear() # clear ax1 and ax2 before replotting the latest data
ax2.clear()
mpf.plot(data,ax=ax1,volume=ax2, type='candle',mav=(10,20)) # plot the new data
ani = animation.FuncAnimation(fig, animate, interval=300000) # update plot every 5 minutes = 300000 secs
mpf.show() # display the plot
Output:
Here is the first / original plot:

Here is the plot after about 20 minutes:
