我刚刚得到了类似的工作。为了更简单地说明该方法,我修改了 matplotlib 站点上的 finance_demo 示例。
#!/usr/bin/env python
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \
DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo, candlestick,\
plot_day_summary, candlestick2
# make plot interactive in order to update
plt.ion()
class Candleplot:
def __init__(self):
fig, self.ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
def update(self, quotes, clear=False):
if clear:
# clear old data
self.ax.cla()
# axis formatting
self.ax.xaxis.set_major_locator(mondays)
self.ax.xaxis.set_minor_locator(alldays)
self.ax.xaxis.set_major_formatter(weekFormatter)
# plot quotes
candlestick(self.ax, quotes, width=0.6)
# more formatting
self.ax.xaxis_date()
self.ax.autoscale_view()
plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
# use draw() instead of show() to update the same window
plt.draw()
# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
date1 = ( 2004, 2, 1)
date2 = ( 2004, 4, 12 )
date3 = ( 2004, 5, 1 )
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # e.g., Jan 12
dayFormatter = DateFormatter('%d') # e.g., 12
quotes = quotes_historical_yahoo('INTC', date1, date2)
plot = Candleplot()
plot.update(quotes)
raw_input('Hit return to add new data to old plot')
new_quotes = quotes_historical_yahoo('INTC', date2, date3)
plot.update(new_quotes, clear=False)
raw_input('Hit return to replace old data with new')
plot.update(new_quotes, clear=True)
raw_input('Finished')
基本上,我使用 plt.ion() 打开交互模式,以便在程序继续运行时更新绘图。要更新数据,似乎有两种选择。(1) 您可以使用新数据再次调用烛台(),这会将其添加到绘图中,而不会影响先前绘制的数据。这对于在末尾添加一根或多根新蜡烛可能更可取;只需传递一个包含新蜡烛的列表。(2) 使用 ax.cla() (清除轴)在传递新数据之前删除所有以前的数据。如果您想要一个移动窗口,这将是更可取的,例如只绘制最后 50 根蜡烛,因为仅在末尾添加新蜡烛会导致越来越多的蜡烛在图中累积。同样,如果您想在最后一根蜡烛关闭之前更新它,您应该先清除旧数据。
目前不确定该问题是否仍与原始海报相关,但希望这对某人有所帮助。