大家好,我真的需要一些帮助。 我正在尝试绘制实时股票价格,这些价格是使用Python中的BeautifulSoup从Yahoo财务获取的。 该代码的webscaping部分有效,因为我可以看到每秒的价格流:
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笔记本中尝试过。 我不确定该怎么办!
答案 0 :(得分:0)
该代码仍有改进的空间。作为该过程的一部分,我们将在图形动画功能中调用将数据获取到Yahoo Finance的功能。我们将累积到那里的数据并将其绘制出来。
由于animate(i)
中的'i'是循环计数,因此数据由'i'引用。另外,Funcanimation()
指定帧数,并且不重复。
import lxml as lxml
from numpy.core.fromnumeric import repeat
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
HSI = ['AAPL', 'AMZN', 'IBM', 'CSCO']
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
# style.use('fivethirtyeight')
fig = plt.figure()
fig.subplots_adjust(wspace=1.0, hspace=1.0)
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)
df = pd.DataFrame(columns=['date',*HSI])
def animate(i):
global df
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 = df.append(pd.Series(col, index=df.columns, name=1), ignore_index=True)
ys = df.iloc[i:, 1].values
xs = df.iloc[i:,0].values
ax1.plot(xs, ys, marker='o', color='r')
ax1.set_title('Apple Stock Price', fontsize=12)
ys = df.iloc[i:, 2].values
ax2.plot(xs, ys, marker='o', color='r')
ax2.set_title('Amazon Stock Price', fontsize=12)
ys = df.iloc[i:, 3].values
ax3.plot(xs, ys, marker='o', color='r')
ax3.set_title('IBM Stock Price', fontsize=12)
ys = df.iloc[i:, 4].values
ax4.plot(xs, ys, marker='o', color='r')
ax4.set_title('Cisco Stock Price', fontsize=12)
ani = animation.FuncAnimation(fig, animate, frames=10, interval=100, repeat=False)
plt.tight_layout()
plt.show()