Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError Cannot import name 'warnings' from 'matplotlib.dates

Alpaca backtrader plot issue: I ran into this import issue and found this article, so I applied the code, but same issue not resolved. any one can help please?

My installed matplotlib version is 3.3.1 backtrader 1.9.76.123 python 3.8.5

the entire code posted below:

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 alpaca_backtrader_api

import backtrader as bt

from datetime import datetime

#import matplotlib
ALPACA_API_KEY = "XXXXX"

ALPACA_SECRET_KEY = "XXXX"

ALPACA_PAPER = True

class SmaCross(bt.SignalStrategy):

def init(self):

sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)

crossover = bt.ind.CrossOver(sma1, sma2)

self.signal_add(bt.SIGNAL_LONG, crossover)

cerebro = bt.Cerebro()

cerebro.addstrategy(SmaCross)

store = alpaca_backtrader_api.AlpacaStore( key_id=ALPACA_API_KEY,secret_key=ALPACA_SECRET_KEY,paper=ALPACA_PAPER)

if not ALPACA_PAPER:
  
  broker = store.getbroker() # or just alpaca_backtrader_api.AlpacaBroker()
  
  cerebro.setbroker(broker)
  
  DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData
  
  data0 = DataFactory(dataname='AAPL', historical=True, fromdate=datetime(2015, 1, 1), timeframe=bt.TimeFrame.Days)
  
  cerebro.adddata(data0)
  
  print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
  
  cerebro.run()
  
  print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
  
  cerebro.plot()
like image 982
G Chu Avatar asked Aug 18 '20 15:08

G Chu


2 Answers

Downgrade to matplotlib 3.2.2 until the bug in backtrader is fixed.

Here is the fix pull request: https://github.com/mementum/backtrader/pull/418.

pip uninstall matplotlib  # or conda
pip install matplotlib==3.2.2
like image 151
cambunctious Avatar answered Oct 21 '22 12:10

cambunctious


I suffered the same problem like you did, your link provided has the perfect solution. just get rid of warnings from locator.py

https://community.backtrader.com/topic/981/importerror-cannot-import-name-min_per_hour-when-trying-to-plot/8

like image 21
pepCoder Avatar answered Oct 21 '22 14:10

pepCoder