You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux 18.04下yfinance获取^BVSP数据时报时区错误求助

问题:Linux下yfinance获取巴西IBOVESPA指数(^BVSP)数据报错

全新安装Linux 18.04.6 LTS(Bionic Beaver)后,原Windows上正常运行的Python脚本无法获取巴西IBOVESPA指数(代码^BVSP)的数据,但其他巴西股票(如AALR3.SA)、美股(如AAPL)、加密货币(如BTC-USD)均可正常获取。

测试代码:

df = web.get_data_yahoo('^BVSP', progress=False,show_errors=False)
print(df)

报错信息:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.6/dist-packages/multitasking/__init__.py", line 104, in _run_via_pool
    return callee(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/yfinance/multi.py", line 201, in _download_one_threaded
    keepna, timeout)
  File "/usr/local/lib/python3.6/dist-packages/yfinance/multi.py", line 218, in _download_one
    timeout=timeout)
  File "/usr/local/lib/python3.6/dist-packages/yfinance/base.py", line 315, in history
    df.index = _pd.to_datetime(df.index.date).tz_localize(tz_exchange, ambiguous=True)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/datetimes.py", line 235, in tz_localize
    arr = self._data.tz_localize(tz, ambiguous, nonexistent)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/arrays/datetimes.py", line 972, in tz_localize
    self.asi8, tz, ambiguous=ambiguous, nonexistent=nonexistent
  File "pandas/_libs/tslibs/tzconversion.pyx", line 319, in pandas._libs.tslibs.tzconversion.tz_localize_to_utc
pytz.exceptions.NonExistentTimeError: 1997-10-06 00:00:00

解决方案

1. 缩小数据时间范围

报错源于1997年10月6日巴西时区调整导致该时间点不存在,指定一个较近的起始日期即可避开问题:

df = web.get_data_yahoo('^BVSP', start='2000-01-01', progress=False, show_errors=False)
print(df)

2. 修改yfinance源码处理时区问题

找到yfinance/base.py中第315行左右的代码,为tz_localize添加nonexistent参数,指定时区冲突时的处理逻辑:

# 原代码
df.index = _pd.to_datetime(df.index.date).tz_localize(tz_exchange, ambiguous=True)
# 修改后
df.index = _pd.to_datetime(df.index.date).tz_localize(tz_exchange, ambiguous=True, nonexistent='shift_forward')

3. 升级相关依赖库

新版本的pandas、yfinance和pytz可能已修复该时区处理问题,执行以下命令更新:

pip install --upgrade pandas yfinance pytz

内容的提问来源于stack exchange,提问作者Capuccino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:10:26