使用Matplotlib绘制动画股票的价格

问题描述 投票:1回答:1

我正在尝试使用Matplotlib为时间序列图制作动画,但是该图总是空白。我在下面附加了我的代码。任何帮助,将不胜感激

import yfinance as yf
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt

# loading the data
indices = ["^GSPC","TLT", ]
data = yf.download(indices,start='2020-01-01')
data = data['Adj Close']
inv_growth = (data.pct_change().dropna() + 1).cumprod()

# plotting the data

fig, ax = plt.subplots()

ax.set_xlim(inv_growth.index[0], inv_growth.index[-1])
ax.set_ylim(940, 1100)

line, = ax.plot(inv_growth.index[0], 1000)

x_data = []
y_data = []

def animation_frame(date):
    x_data.append(date)
    y_data.append(inv_growth.loc[date])
    
    line.set_xdata(x_data)
    line.set_ydata(y_data)
    
    return line,

animation = FuncAnimation(fig, 
                          func=animation_frame, 
                          frames=list(inv_growth.index), 
                          interval = 100)
plt.show()
python matplotlib animation
1个回答
2
投票

您的问题是,您试图同时绘制两个值。如果需要两行,则必须创建两行并更新它们各自的数据。这是您的代码的稍微简化的版本(而且,您的y比例似乎减少了1000倍)。

import yfinance as yf
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt

# loading the data
indices = ["^GSPC","TLT", ]
data = yf.download(indices,start='2020-01-01')
data = data['Adj Close']
inv_growth = (data.pct_change().dropna() + 1).cumprod()

# plotting the data

fig, ax = plt.subplots()

ax.set_xlim(inv_growth.index[0], inv_growth.index[-1])
ax.set_ylim(0.940, 1.100)

line1, = ax.plot([], [])
line2, = ax.plot([], [])


def animation_frame(i):
    temp = inv_growth.iloc[:i]
    line1.set_data(temp.index, temp[0])
    line2.set_data(temp.index, temp[1])

    return line1,line2,

animation = FuncAnimation(fig, 
                          func=animation_frame, 
                          frames=range(inv_growth.index.size),
                          interval = 100)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.