如何根据股票数据制作 Pandas 直方图的动画?

How can I animate Pandas histogram from stock data?

我的目标是查看股票的直方图如何随时间变化。所以我想为指定时间的差异设置动画。根据网络上的一些文章,我尝试了以下方法来制作它。但我没有得到一些直方图数据。我理解matplotlib中动画方式的问题是什么?

import pandas_datareader as web
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
stock = 'ALB'

df = web.DataReader(stock, 'yahoo', "01.01.2021", "14.11.2021")

def update_hist(step):
    plt.cla()
    df_step = df[:][step:step+30]
    df_step.hist(column=stock)

animation.FuncAnimation(fig, update_hist, fargs=([1, 30, 60, 90, 120]))
plt.show()

我制作了一个股票的 NumPy 数组并绘制了它。这是我的代码。我认为有一个更直接的方法只使用上面的 df。

##
# generates an animation of histograms of the stocks in the file
##
def histogram_builder(filename):
    df = pd.read_csv(f"Webscrapper/{filename}_DailyChanges.csv", index_col="Date")
    fig = plt.figure()
    stock = 'ALB'

    data = np.empty((0, 30), float)

    for index, val in enumerate(df[stock][:-30]):
        array_buffer = np.array(df[stock][index: index + 30])
        array_buffer = np.reshape(array_buffer, (1, 30))
        data = np.append(data, array_buffer, axis=0)

    iterations = data.shape[0]
    print(iterations)

    def update_hist(step):
        plt.cla()
        df_step = df[:][step:step+30]
        stock_data = df_step.loc[:, stock]
        plt.hist(data[step])

        # calculates the expected value of the histogram
        n, bins = np.histogram(stock_data.values)
        mid = 0.5 * (bins[1:] + bins[:-1])
        mean = np.average(mid, weights=n)
    update_hist(1)
    anim = animation.FuncAnimation(fig, update_hist, frames=iterations)
    plt.show()