0

I want to plot a candlestick graph with data that keeps getting updated but I'm facing some trouble. So I have successfully used mplfinance to plot the candlestick but I can't find a way to clear the plot and update the plot every time new data point gets included. Currently a new graph gets created every time the new data points get included instead of being updated on one graph.

import mplfinance as fplt

df=pd.DataFrame({'time':date_list,'Open':open_price,'High':high_price,'Low':low_price,'Close':close_price})
df.index=date_list

fplt.plot(df,type='candle',title='EUR_USD',ylabel='Price ($)')

This code will run everytime the df is updated. I tried fplt.cla() and fplt.clf() but does not seem to be the correct attribute.

ScottC
  • 3,941
  • 1
  • 6
  • 20
Cho
  • 1
  • 1

2 Answers2

1

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:

original



Here is the plot after about 20 minutes:

20mins

ScottC
  • 3,941
  • 1
  • 6
  • 20
0

You need to use mplfinance in animation mode. Here are some links to some examples:

Daniel Goldfarb
  • 6,937
  • 5
  • 29
  • 61