【发布时间】:2020-11-28 22:41:48
【问题描述】:
大家好,我真的需要帮助。 我正在尝试绘制实时股票价格,这些价格是使用 Python 中的 BeautifulSoup 从 yahoo Finance 中检索的。 代码的网页美化部分有效,因为我可以看到每秒都在流动的价格:
import lxml as lxml
import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import numpy as np
def real_time_price(stock_code):
url = ('https://finance.yahoo.com/quote/' + stock_code + '?p=' + stock_code + '&.tsrc=fin-srch')
r = requests.get(url)
web_content = BeautifulSoup(r.text, 'lxml')
web_content = web_content.find('div', {"class":'My(6px) Pos(r) smartphone_Mt(6px)'})
web_content = web_content.find('span').text
if web_content ==[]:
web_content = '99999999999'
return web_content
HSI = ['AAPL','AMZN','IBM', 'CSCO']
for step in range(1,101):
price =[]
col =[]
time_stamp = datetime.datetime.now()
time_stamp = time_stamp.strftime("%Y-%m-%d-%H:%M:%S")
for stock_code in HSI:
price.append(real_time_price(stock_code))
col = [time_stamp]
col.extend(price)
df = pd.DataFrame(col)
df = df.T
df.to_csv('real time stock data.csv', mode='a', header=False)
print(col)
但是,我似乎无法绘制实时流数据:
# plotting
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
def animate(i):
df = pd.read_csv('real time stock data.csv')
ys = df.iloc[1:, 2].values
xs = list(range(1, len(ys) + 1))
ax1.clear()
ax1.plot(xs, ys)
ax1.set_title('Apple Stock Price', fontsize=12)
ys = df.iloc[1:, 3].values
ax2.clear()
ax2.plot(xs, ys)
ax2.set_title('Amazon Stock Price', fontsize=12)
ys = df.iloc[1:, 4].values
ax3.clear()
ax3.plot(xs, ys)
ax3.set_title('IBM Stock Price', fontsize=12)
ys = df.iloc[1:, 5].values
ax4.clear()
ax4.plot(xs, ys)
ax4.set_title('Cisco Stock Price', fontsize=12)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.tight_layout()
plt.show()
我在 Pycharm 和 Jupyter notebook 中尝试过。 我不知道该怎么办!
【问题讨论】:
-
我认为你需要每隔 N 秒调用一次动画函数来重绘绘图
标签: python matplotlib