Python pandas datareader不再为雅虎财经工作

vyswwuz2  于 2023-02-17  发布在  Python
关注(0)|答案(8)|浏览(136)

由于雅虎停止了他们的API支持Pandas数据读取器现在失败

import pandas_datareader.data as web
import datetime
start = datetime.datetime(2016, 1, 1)
end = datetime.datetime(2017, 5, 17)
web.DataReader('GOOGL', 'yahoo', start, end)

HTTPError: HTTP Error 401: Unauthorized

有没有非官方的图书馆可以让我们暂时解决这个问题?2也许有关于Quandl的资料?

ekqde3dh

ekqde3dh1#

我发现https://pypi.python.org/pypi/fix-yahoo-finance中的“fix-yahoo-finance”解决方案很有用,例如:

from pandas_datareader import data as pdr
import fix_yahoo_finance

data = pdr.get_data_yahoo('APPL', start='2017-04-23', end='2017-05-24')

请注意,最后2列数据的顺序是“调整收盘价”和“成交量”,即不是以前的格式。要重新编制索引:

cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
data.reindex(columns=cols)
rhfm7lfc

rhfm7lfc2#

fix_yahoo_finance包的名称已经更改为yfinance。

import yfinance as yf
data = yf.download('MSFT', start = '2012-01-01', end='2017-01-01')
zkure5ic

zkure5ic3#

所以他们已经改变了他们的网址,现在使用cookie保护(可能还有javascript),所以我用dryscrape修复了我自己的问题,它模拟了一个浏览器,这只是一个FYI,因为这肯定违反了他们的条款和条件...所以使用风险自担?我正在寻找Quandl的替代EOD价格来源。
我无法用cookie浏览CookieJar,所以我最终使用dryscrape来“伪造”用户下载

import dryscrape
from bs4 import BeautifulSoup
import time
import datetime
import re

#we visit the main page to initialise sessions and cookies
session = dryscrape.Session()
session.set_attribute('auto_load_images', False)
session.set_header('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95     Safari/537.36')    

#call this once as it is slow(er) and then you can do multiple download, though there seems to be a limit after which you have to reinitialise...
session.visit("https://finance.yahoo.com/quote/AAPL/history?p=AAPL")
response = session.body()

#get the dowload link
soup = BeautifulSoup(response, 'lxml')
for taga in soup.findAll('a'):
    if taga.has_attr('download'):
        url_download = taga['href']
print(url_download)

#now replace the default end date end start date that yahoo provides
s = "2017-02-18"
period1 = '%.0f' % time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())
e = "2017-05-18"
period2 = '%.0f' % time.mktime(datetime.datetime.strptime(e, "%Y-%m-%d").timetuple())

#now we replace the period download by our dates, please feel free to improve, I suck at regex
m = re.search('period1=(.+?)&', url_download)
if m:
    to_replace = m.group(m.lastindex)
    url_download = url_download.replace(to_replace, period1)        
m = re.search('period2=(.+?)&', url_download)
if m:
    to_replace = m.group(m.lastindex)
    url_download = url_download.replace(to_replace, period2)

#and now viti and get body and you have your csv
session.visit(url_download)
csv_data = session.body()

#and finally if you want to get a dataframe from it
import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd
df = pd.read_csv(StringIO(csv_data), index_col=[0], parse_dates=True)
df
os8fio9y

os8fio9y4#

我从雅虎换到谷歌财经,它对我很有效,所以从

data.DataReader(ticker, 'yahoo', start_date, end_date)

data.DataReader(ticker, 'google', start_date, end_date)

并改编了我的“旧”雅虎符号:

tickers = ['AAPL','MSFT','GE','IBM','AA','DAL','UAL', 'PEP', 'KO']

tickers = ['NASDAQ:AAPL','NASDAQ:MSFT','NYSE:GE','NYSE:IBM','NYSE:AA','NYSE:DAL','NYSE:UAL', 'NYSE:PEP', 'NYSE:KO']
zpgglvta

zpgglvta5#

试试这个:

import fix_yahoo_finance as yf
data = yf.download('SPY', start = '2012-01-01', end='2017-01-01')
0yg35tkg

0yg35tkg6#

雅虎财经和Pandas合作得很好,这样用吧:

import pandas as pd
import pandas_datareader as pdr
from pandas_datareader import data as wb

ticker='GOOGL'
start_date='2019-1-1'
data_source='yahoo'

ticker_data=wb.DataReader(ticker,data_source=data_source,start=start_date)
df=pd.DataFrame(ticker_data)
ijxebb2r

ijxebb2r7#

让线程在每次阅读数据后都处于睡眠状态。可能大部分时间都能工作,所以尝试5-6次并将数据保存在csv文件中,以便下次你可以从文件中读取。

### code is here ###
import pandas_datareader as web
import time
import datetime as dt
import pandas as pd

symbols = ['AAPL', 'MSFT', 'AABA', 'DB', 'GLD']
webData = pd.DataFrame()
for stockSymbol in symbols:
    webData[stockSymbol] = web.DataReader(stockSymbol, 
    data_source='yahoo',start= 
               startDate, end= endDate, retry_count= 10)['Adj Close']   
    time.sleep(22) # thread sleep for 22 seconds.
wydwbb8l

wydwbb8l8#

这个问题已经很老了,但我还是来了。我在yfinancepypi.org项目页面上找到了一个标题为“panda_datareader override”的部分。它写道:
“如果你的代码使用了panda_datareader,而你又想更快地下载数据,你可以“劫持”panda_datareader.data.get_data_yahoo()方法来使用yfinance,同时确保返回的数据格式与panda_datareader的get_data_yahoo()相同。”
他们还提供了以下代码示例,该示例目前正在运行。

from pandas_datareader import data as pdr

import yfinance as yf
yf.pdr_override() # <== that's all it takes :-)

# download dataframe
data = pdr.get_data_yahoo("SPY", start="2017-01-01", end="2017-04-30")

相关问题