在使用backtrader 做回测时,发现只要是运行到 cerebro.plot()
就会出现如下的一堆错误:ImportError: cannot import name ‘warnings’ from ‘matplotlib.dates’
cerebro.plot()File "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\cerebro.py", line 974, in plotfrom . import plotFile "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\plot\__init__.py", line 42, in <module>from .plot import Plot, Plot_OldSyncFile "C:\ProgramData\Anaconda3\lib\site-packages\backtrader\plot\plot.py", line 44, in <module>from . import locator as locFile "C:\ProgramData\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' from 'matplotlib.dates' (C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\dates.py)
搜索网上,发现原因竟然是由于matplotlib 版本太高,需要降配到3.2.2
pip uninstall matplotlibpip install matplotlib=3.2.2
然而这个自然会出现几个问题:
1、这种卸载重装往往不成功,因为matplotlib 已经被默认安装,
2、降配自然可能引起其他的问题
后来发现一种简单的办法:
找到出错的地方:
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader\plot\locator.py”, line 35, in
from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
发现这个文件中的语法如下:
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)
既然是warning出了问题,而warning 是python的标准库,所以直接修改这行代码如下即可:
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
运行后一切正常。