项目场景:
通过Backtrader框架对tushare获取的股票数据做回测调用cerebro.plot()时报错:
ImportError:cannot import name 'warnings'
问题描述
详细报错信息如下:
Traceback (most recent call last):
File "D:\Anaconda3\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "D:\Desktop\新建文件夹 (2)\cfc-validation\SimTrade\gui_simtrade.py", line 338, in execOpTradebackDay
cerebro.plot()
File "D:\Anaconda3\lib\site-packages\backtrader\cerebro.py", line 974, in plot
from . import plot
File "D:\Anaconda3\lib\site-packages\backtrader\plot\__init__.py", line 43, in <module>
from .plot import Plot, Plot_OldSync
File "D:\Anaconda3\lib\site-packages\backtrader\plot\plot.py", line 44, in <module>
from . import locator as loc
File "D:\Anaconda3\lib\site-packages\backtrader\plot\locator.py", line 35, in <module>
from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
ImportError: cannot import name 'warnings'
原因分析:
认真看这里的报错信息,定位到
D:\Anaconda3\lib\site-packages\backtrader\plot\locator.py
from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
MONTHS_PER_YEAR, DAYS_PER_WEEK,
SEC_PER_HOUR, SEC_PER_DAY,
num2date, rrulewrapper, YearLocator,
MicrosecondLocator, warnings)
是这里的warnings不能被引用,查阅相关文档后发现:
- matplotlib 3.2后的版本不在支持warnings
- Backtrader所支持的matplotlib版本为3.2.2
- 我安装的matplotlib是3.4.5
- 由此可以得出两种解决方案:
解决方案:
1、回退matplotlib版本为3.2.2
pip uninstall matplotlib
pip install matplotlib==3.2.2
2、将locator.py错误定位语句修改为:
from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
MONTHS_PER_YEAR, DAYS_PER_WEEK,
SEC_PER_HOUR, SEC_PER_DAY,
num2date, rrulewrapper, YearLocator,
MicrosecondLocator)
import warnings