Python: pandas_datareader 获取 Yahoo Finance Data 报错 RemoteDataError: Unable to read URL / TypeError: string indices must be integers
1. 问题概述:
pandas_datareader 获取 Yahoo Finance Data:
import pandas_datareader.data as web df = web.get_data_yahoo('GE', start='2019-09-10', end='2019-10-09') # 或 df = web.DataReader('GE', 'yahoo', start='2019-09-10', end='2019-10-09')
报错1:
RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/GE/history?period1=1568059200&period2=1570651199&interval=1d&frequency=1d&filter=history
报错2:
TypeError: string indices must be integers
2. 相关原因:
报错1原因:
2021 年 11 月 1 日起,用户将无法从中国大陆使用 Yahoo 的产品与服务。这并不影响 Yahoo 在全球其他地方的产品及服务。我们感谢你一直以來的支持。
报错2原因:
略
3. 解决办法:
报错1解决办法:
略
报错2解决办法:
1. 安装 yfinance (原fix-yahoo-finance):
参考:https://github.com/ranaroussi/yfinance
$ pip install yfinance --upgrade --no-cache-dir
2. Call the pdr_override()
method and keep the code as it was:
from pandas_datareader import data as web import yfinance as yf yf.pdr_override() # <== that's all it takes :-) # download dataframe using pandas_datareader df = web.get_data_yahoo('GE', start='2019-09-10', end='2019-10-09')
如果仍然无法获取数据:
Failed to get ticker 'GE' reason: Expecting value: line 1 column 1 (char 0) [*********************100%%**********************] 1 of 1 completed 1 Failed download: ['GE']: Exception('%ticker%: No timezone found, symbol may be delisted')
原因也是因为无法从中国大陆使用 Yahoo 的产品与服务,解决办法略。
注意:
调用yfinance的pdr_override()
方法后,pandas_datareader只能使用方法get_data_yahoo()
df = web.get_data_yahoo('GE', start='2019-09-10', end='2019-10-09')
若使用方法DataReader()
df = web.DataReader('GE', 'yahoo', start='2019-09-10', end='2019-10-09')
会报错:
TypeError: download() got multiple values for argument 'start'
原因是方法DataReader()
把参数'yahoo'当成了'start',后面又有start='2019-09-10',因此报错多个'start'。