【问题标题】:How can I animate Pandas histogram from stock data?如何根据股票数据为 Pandas 直方图制作动画?
【发布时间】:2021-12-26 02:29:45
【问题描述】:

我的目标是查看股票的直方图如何随时间变化。所以我想在指定时间为差异设置动画。根据网络上的一些文章,我尝试了以下方法。但我没有得到一些直方图数据。我对 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()

【问题讨论】:

    标签: python pandas animation histogram stock


    【解决方案1】:

    我制作了股票的 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多