I am trying to build a graph that displays candlesticks of a datafeed. Below the code is provided. The graph is supposed to be animated but it does not update. Can anybode help please?
class Graph(object):
def __init__(self, ticker_name):
self.datafeed = self.get_datafeed(ticker_name)
self.figure = plt.figure()
self.ax1 = self.figure.add_subplot(211)
self.ax2 = self.figure.add_subplot(212)
animation.FuncAnimation(self.figure, self.animate, interval=10000, init_func=self.init_figure)
plt.show()
def get_datafeed(self, ticker_name):
self.parameters = {"ticker_name": ticker_name,
"history": 100}
return DataFeed(self.parameters)
def init_figure(self):
self.ax1.xaxis.set_major_formatter(DateFormatter('%H:%M'))
self.ax1.grid()
self.ax2.grid()
self.ax1.set_title(self.parameters["ticker_name"].upper())
def animate(self, i):
time.sleep(2)
self.datafeed.refresh()
data = self.datafeed.query(10)
self.ax1.clear()
self.ax2.clear()
self.plot_candles(data[["time", "open", "high", "low", "close"]])
def plot_candles(self, df):
df.loc[:, "time"] = df.time.apply(date2num)
mpf.candlestick_ohlc(self.ax1, df.values.tolist(), width=0.0005, colordown="r", colorup="g")
self.ax1.set_ylim(df["low"].min() - 5, df["high"].max() + 5)
Don't use time.sleep()
in an animation. Instead use the interval
argument of FuncAnimation
to control the updating speed.
You also need to retain a reference to the FuncAnimation
. Use
self.ani = animation.FuncAnimation( ... )
Otherwise the FuncAnimation will be garbage collected as soon as the figure is shown.
(Note that if this does not solve the problem, you need to provide a
Minimal, Complete, and Verifiable example of the issue)