【问题标题】:Scraping live stock prices from yahoo Finance and plotting live prices从 yahoo Finance 抓取实时股票价格并绘制实时价格
【发布时间】: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


【解决方案1】:

代码仍有改进的空间。作为流程的一部分,我们将在图形动画函数中调用获取数据到 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()

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2020-07-08
    • 2020-04-21
    • 1970-01-01
    • 2021-12-12
    • 2017-01-08
    • 2015-06-20
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多