如何使用 Python 显示实时数据

How to display Live Data using Python

我想在 Python 3 项目中显示股票价格和平均值的时间序列数据。

数据当前存储在 CSV 文件中,该文件定期更新,我的解释器是 Anaconda。

我试过使用

Matplotlib.animation.FuncAnimation()

但是 图形 window 弹出时没有任何轴 并且 然后无法响应并崩溃 s。

这是我在项目中的图表Class

class Chart:

    import matplotlib.pyplot
    import matplotlib.animation as animation
    plt = matplotlib.pyplot

    @classmethod
    def __init__(cls):
        fig = cls.plt.figure(figsize=(5, 5))
        global ax1
        ax1 = fig.add_subplot(1, 1, 1)
        ani = cls.animation.FuncAnimation(fig, cls.animate, interval=1000, blit=True)
        cls.plt.show()

    @classmethod
    def animate(cls, i):
        xs = []
        ys = []
        ax1.clear()
        data = pd.read_csv('chart_values.csv')
        date = data['timestamp']
        last = data['last']
        short_ma = data['short_ma']
        long_ma = data['long_ma']

        xs.append(date)
        ys.append(last)
        ax1.clear()
        ax1.plot(xs, ys)
        ax1.set_title('Trade data')
注意 *

我遇到的另一个问题是我需要在我的anaconda中设置一个指向/library/plugins的环境PATH变量解决获取此错误消息问题的目录:

this application failed to start because it could not find or load the qt platform plugin "windows" in "".

但是,如果我想使用任何其他需要 PyQt 的程序,就需要尽快删除它

* 编辑 *

我已经根据响应更改了代码,但尚未让图表连续加载和显示数据。

class Chart:

    import matplotlib.pyplot
    import matplotlib.animation as animation
    plt = matplotlib.pyplot

    def __init__(self):
        fig = self.plt.figure(figsize=(5, 5))
        self.ax1 = fig.add_subplot(1, 1, 1)
        self.line, = self.ax1.plot([], [])
        ani = self.animation.FuncAnimation(fig, self.update, interval=1000, blit=True)
        self.plt.show()

    def update(self, i):
# I don't think its essential to pass the loc as a param just yet.
        data = pd.read_csv('chart_values.csv', header=0) 
        self.line.set_data(data['timestamp'], data['last'])
        self.ax1.set_title('Trade data')

我在 KeyboardInterrupt 程序后得到以下错误:

ValueError: could not convert string to float: '2020-05-21T17:04:13.645Z'

以及:

RuntimeError: The animation function must return a sequence of Artist objects.

我有办法!

注意几点:

  • Matlotlib 的 Funcanimation 库在 类 中不起作用。
  • 将主要项目和图表功能放在单独的文件中,您可以随时 运行 或在单独的线程上实例化它们。
  • Matplotlib 有 2 种方式与他们的库接口。建议使用 OOP API。
  • 需要轴日期格式化程序才能在 x 轴上使用时间戳。

更新后的代码

chart.py:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import dateutil.parser
import matplotlib.dates as mdates
import numpy as np


def init():  # only required for blitting to give a clean slate.
    plt.ion()
    line = ax1.set_ydata([np.nan] * 1000)
    return line,


def update(i):
    ax1.clear()  # necessary to stop plots from being redrawn on canvas
    ax1.set_title('Trade data')
    ax1.set_xlabel('Date & Time')
    my_fmt = mdates.DateFormatter('%H:%M')  
    ax1.xaxis.set_major_formatter(my_fmt) # Display Hour and Min on X axis 
    data = pd.read_csv('D:/Development applications/Trading Bot/Foxbot_v0.1/main/sources/ticker_history.csv',
                       header=0, index_col=0)
    line = []  # Different MA Lines to be placed onto the figure
    dates = data['timestamp'].iloc[-1000:]  # selecting last 1000 timestamp points to be displayed at any given time
    x = []  # empty list to store dates
    types = {  # dict: keys = features I wish to plot & values = color of the line

        'last': 'cyan',
        'short_ma': 'r',
        'long_ma': 'k',
        'base_ma': 'green', }

    for date in dates:
        x.append(dateutil.parser.parse(str(date)))

    for t in types.keys():  # iterate through dict keys
        y = data[t].iloc[-1000:]  # select last 1000 points where column = dict key
        line.append(ax1.plot(x, y, lw=1.5, ls='-', color=types[t], label=t))  # append the col pts to the line
        ax1.legend(types.keys(), loc='upper right')

    return line[0], line[1], line[2], line[3],  # return last and short, base, long moving avg


fig = plt.figure(figsize=(5, 5))
ax1 = fig.add_subplot(1, 1, 1)
ani = animation.FuncAnimation(fig, update, interval=3000)
plt.show()


对我有用!

错误:

我认为错误可能与 update() 方法中的 i 变量有关。我认为 selfcls 参数妨碍了将间隔传递给 i