【问题标题】:Scraping Yahoo finance historical stock prices抓取雅虎财经的历史股价
【发布时间】:2018-04-21 20:14:35
【问题描述】:

我正在尝试使用 BeautifulSoup 和 Python 来解析 Yahoo Finance 的各种股票的历史股价表。代码如下:

import requests
import pandas as pd
import urllib
from bs4 import BeautifulSoup

tickers = ['HSBA.L', 'RDSA.L', 'RIO.L', 'BP.L', 'GSK.L', 'DGE.L', 'AZN.L', 'VOD.L', 'GLEN.L', 'ULVR.L']
url = 'https://uk.finance.yahoo.com/quote/HSBA.L/history?period1=1478647619&period2=1510183619&interval=1d&filter=history&frequency=1d'

request = requests.get(url)

soup = BeautifulSoup(request.text, 'lxml')

table = soup.find_all('table')[0]




n_rows = 0
n_columns = 0
column_name = []

for row in table.find_all('tr'):

    data = row.find_all('td')
    if len(data) > 0:
        n_rows += 1
        if n_columns == 0:
            n_columns = len(data)


    headers = row.find_all('th')
    if len(headers) > 0 and len(column_name) == 0:
        for header_names in headers:
            column_name.append(header_names.get_text())


new_table = pd.DataFrame(columns = column_name, index = range(0,n_rows))


row_index = 0
for row in table.find_all('tr'):
    column_index = 0
    columns = row.find_all('td')

    for column in columns:
        new_table.iat[row_index, column_index] = column.get_text()
        column_index += 1

    if len(columns) > 0:
        row_index += 1    

我第一次运行代码时,我将时间间隔设置为从 2015 年 11 月 7 日起正好两年(每周价格)。问题是生成的数据框有 101 行长,但我知道事实上它应该更多(106 行)。然后我尝试在页面打开时(每天)将间隔完全更改为默认间隔,但我仍然得到相同的 101 行,而实际数据要大得多。代码有什么问题,还是雅虎财务正在做的事情?

感谢任何帮助,我真的被困在这里。

【问题讨论】:

  • 我也一直在收集一些历史数据,但这些数据通常仅限于 API 提供的数据。它不像您可以检索自 2015 年以来发生的每一分钟的数据。只是说,我尚未验证,但这是我所期望的。
  • 但您实际上可以手动下载每周股票价格并获得超过 101 个每周观察值。我只是想确保是 API 限制了数据,或者代码是否有问题。
  • 您可以使用为此目的构建的库:pandas-datareader.readthedocs.io/en/latest/…
  • 感谢您的建议,这似乎可以解决问题。你知道我是否可以使用 data_reader 下载每周价格。我尝试使用 as 频率进行重采样,但结果与从 yahoo Finance 手动下载的结果不匹配。谢谢

标签: python-3.x


【解决方案1】:

AFAIK,API 已于 2017 年 5 月关闭。您可以使用 Google 金融吗?如果您可以接受 Excel 作为解决方案,这里有一个文件链接,您可以下载该文件以下载各种历史时间序列数据。

http://investexcel.net/multiple-stock-quote-downloader-for-excel/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多