0

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

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

我试过使用

Matplotlib.animation.FuncAnimation()

然而,图形窗口弹出没有任何轴然后无法响应并 crashe

这是我在项目中的图表类

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 变量,这解决了收到此错误消息的问题:

此应用程序无法启动,因为它无法在“”中找到或加载 qt 平台插件“windows”。

但是,一旦 id 喜欢使用任何其他需要 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')

键盘中断程序后出现以下错误:

ValueError:无法将字符串转换为浮点数:'2020-05-21T17:04:13.645Z'

也:

RuntimeError:动画函数必须返回一系列 Artist 对象。

4

1 回答 1

1

我有办法!

需要注意的几点:

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

更新的代码

图表.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()


这对我有用!

错误:

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

于 2020-05-25T06:39:58.457 回答