获取超过100天的数据网络抓取雅虎

时间:2018-02-05 23:36:16

标签: python screen-scraping finance stockquotes

与许多其他人一样,我一直在寻找替代的股票价格来源,因为雅虎和谷歌API已经不复存在。我决定尝试网络抓取雅虎网站,从中仍然可以获得历史价格。我设法将以下代码组合在一起,几乎可以满足我的需求:

import urllib.request as web
import bs4 as bs

def yahooPrice(tkr):
    tkr=tkr.upper()
    url='https://finance.yahoo.com/quote/'+tkr+'/history?p='+tkr

    sauce=web.urlopen(url)
    soup=bs.BeautifulSoup(sauce,'lxml')
    table=soup.find('table')
    table_rows=table.find_all('tr')

    allrows=[]
    for tr in table_rows:
        td=tr.find_all('td')
        row=[i.text for i in td]
        if len(row)==7:
            allrows.append(row)

    vixdf= pd.DataFrame(allrows).iloc[0:-1]
    vixdf.columns=['Date','Open','High','Low','Close','Aclose','Volume']
    vixdf.set_index('Date',inplace=True)

    return vixdf

生成包含我想要的信息的数据框。不幸的是,即使实际的网页显示了一整年的价格,我的例程也只返回100条记录(包括股息记录)。知道如何获得更多吗?

3 个答案:

答案 0 :(得分:0)

我没有确切解决你的问题,但我有一个解决方法(我有同样的问题,因此使用这种方法)....基本上,你可以使用Bday()方法 - 'import pandas.tseries .offset'并查找x个用于收集数据的businessDays。在我的情况下,我运行循环三次以获得300个businessDays数据 - 知道100是我默认获得的最大值。

基本上,你运行循环三次并设置Bday()方法,以便第一次迭代从现在开始抓取100天数据,然后是接下来的100天(从现在起200天),最后是过去100天(300从现在开始的几天)。使用它的全部意义在于,在任何给定的点上,人们只能抓取100天的数据。所以基本上,即使你一次性循环300天,你也可能无法得到300天的数据 - 你原来的问题(可能雅虎限制了一次性提取的数据量)。我的代码在这里:https://github.com/ee07kkr/stock_forex_analysis/tree/dataGathering

注意,由于某些原因,csv文件在我的情况下不能使用/ t分隔符...但基本上你可以使用数据框。我目前还有一个问题是'Volume'是一个字符串而不是float ....解决方法是:

apple = pd.DataFrame.from_csv('AAPL.csv',sep ='\ t') apple ['Volume'] = apple ['Volume']。str.replace(',','')。astype(float)

答案 1 :(得分:0)

首先-运行以下代码以获取100天的时间。 然后-使用SQL将数据插入到一个小数据库中(Sqlite3非常易于与python一起使用)。 最后-修改下面的代码,然后获取每日价格,您可以添加这些每日价格来扩展数据库。

from pandas import DataFrame
import bs4
import requests

def function():
    url = 'https://uk.finance.yahoo.com/quote/VOD.L/history?p=VOD.L'
    response = requests.get(url)
    soup=bs4.BeautifulSoup(response.text, 'html.parser')
    headers=soup.find_all('th')
    rows=soup.find_all('tr')
    ts=[[td.getText() for td in rows[i].find_all('td')] for i in range (len(rows))]
    date=[]
    days=(100)
    while days > 0:
        for i in ts:
            data.append (i[:-6])
        now=data[num]
        now=DataFrame(now)
        now=now[0]

        now=str(now[0])
        print now, item
        num=num-1

答案 2 :(得分:-1)

雅虎财经API于17年5月被贬值,我相信。现在,有许多选项可以免费下载时间序列数据,至少我知道。然而,总会有某种替代方案。请查看以下网址,找到下载历史价格的工具。

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

enter image description here

也能看到这一点。

https://blog.quandl.com/api-for-stock-data

相关问题