{"id":7971,"library":"backtrader","title":"Backtrader","description":"backtrader is a powerful and flexible Python framework for backtesting trading strategies, analyzing financial data, and live trading. It provides a robust engine for simulating market conditions, managing portfolios, and executing trades based on defined rules. The current stable version is 1.9.78.123, with a major 2.x release under active development that introduces significant changes. Its release cadence is sporadic but active, with bug fixes and minor features released as needed.","status":"active","version":"1.9.78.123","language":"en","source_language":"en","source_url":"https://github.com/mementum/backtrader","tags":["backtesting","trading","financial analysis","quantitative finance","market simulation"],"install":[{"cmd":"pip install backtrader","lang":"bash","label":"Install stable version"},{"cmd":"pip install backtrader[plotting,pandas]","lang":"bash","label":"Install with common optional dependencies"}],"dependencies":[{"reason":"Required for the cerebro.plot() method to visualize results.","package":"matplotlib","optional":true},{"reason":"Commonly used for creating data feeds (e.g., bt.feeds.PandasData).","package":"pandas","optional":true}],"imports":[{"symbol":"bt","correct":"import backtrader as bt"},{"note":"While direct imports sometimes work, the standard and recommended practice is 'import backtrader as bt' and then access components via 'bt.<component>'.","wrong":"from backtrader import Cerebro","symbol":"Cerebro","correct":"import backtrader as bt\ncerebro = bt.Cerebro()"},{"note":"See note for Cerebro; prefer accessing via the 'bt' alias.","wrong":"from backtrader.strategy import Strategy","symbol":"Strategy","correct":"import backtrader as bt\nclass MyStrategy(bt.Strategy):"},{"note":"See note for Cerebro; prefer accessing via the 'bt' alias.","wrong":"from backtrader.feeds import CSVData","symbol":"CSVData","correct":"import backtrader as bt\ndata = bt.feeds.CSVData(...)"}],"quickstart":{"code":"import backtrader as bt\nimport datetime\nimport os\n\n# Dummy CSV data for demonstration. In a real scenario, this would be a file.\ndummy_csv_content = (\n    \"Date,Open,High,Low,Close,Volume,OpenInterest\\n\"\n    \"2020-01-01,100,102,99,101,1000,0\\n\"\n    \"2020-01-02,101,103,100,102,1200,0\\n\"\n    \"2020-01-03,102,104,101,103,1100,0\\n\"\n    \"2020-01-06,103,105,102,104,1300,0\\n\"\n)\n\n# Create a dummy CSV file\ndummy_csv_path = 'dummy_data.csv'\nwith open(dummy_csv_path, 'w') as f:\n    f.write(dummy_csv_content)\n\nclass SmaCross(bt.Strategy):\n    params = (('fast_period', 10), ('slow_period', 30),)\n\n    def __init__(self):\n        self.sma_fast = bt.indicators.SMA(self.data.close, period=self.p.fast_period)\n        self.sma_slow = bt.indicators.SMA(self.data.close, period=self.p.slow_period)\n        self.crossover = bt.indicators.CrossOver(self.sma_fast, self.sma_slow)\n\n    def next(self):\n        if not self.position:  # Not in the market\n            if self.crossover > 0:  # fast crosses slow upwards\n                self.buy()\n        elif self.crossover < 0:  # fast crosses slow downwards\n            self.close()\n\ncerebro = bt.Cerebro()\ncerebro.addstrategy(SmaCross)\n\n# Add data feed\ndata = bt.feeds.CSVData(\n    dataname=dummy_csv_path,\n    datetimeformat='%Y-%m-%d',\n    fromdate=datetime.datetime(2020, 1, 1),\n    todate=datetime.datetime(2020, 1, 31)\n)\ncerebro.adddata(data)\n\ncerebro.broker.setcash(100000.0)\ncerebro.broker.setcommission(commission=0.001)\n\nprint(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}')\ncerebro.run()\nprint(f'Final Portfolio Value: {cerebro.broker.getvalue():.2f}')\n\n# Clean up dummy file\nos.remove(dummy_csv_path)\n\n# To plot results (requires matplotlib):\n# cerebro.plot()","lang":"python","description":"This quickstart demonstrates how to set up a basic backtesting strategy with backtrader. It involves defining a strategy with two moving averages, adding a CSV data feed (a dummy one created for demonstration), setting initial cash and commission, running the backtest, and printing the portfolio value. The `cerebro.plot()` line is commented out but shows how to visualize results if `matplotlib` is installed."},"warnings":[{"fix":"Refer to the official 2.0 documentation for updated import paths and API usage when migrating. For current projects, stick to 1.x.","message":"The upcoming backtrader 2.0 release (currently in pre-release/beta) introduces significant breaking changes, including module restructuring and API renames (e.g., `bt.Cerebro` moves to `bt.core.Cerebro`).","severity":"breaking","affected_versions":"2.x (pre-release) and later"},{"fix":"Use `datetimeformat='%Y-%m-%d %H:%M:%S'` and `tz='UTC'` or ensure your input data is already UTC. For pandas feeds, use `pd.to_datetime(..., utc=True)` before creating the feed.","message":"backtrader internally processes all datetime objects as UTC. If your input data feed contains timezone-aware datetimes or is in a local timezone, ensure you convert it to UTC or set the correct timezone conversion parameters in your data feed (`dtformat`, `tz`, `tzislocal`).","severity":"gotcha","affected_versions":"1.x, 2.x"},{"fix":"Install matplotlib: `pip install matplotlib` or `pip install backtrader[plotting]`.","message":"Calling `cerebro.plot()` will raise a `ModuleNotFoundError` or similar error if `matplotlib` is not installed in your environment.","severity":"gotcha","affected_versions":"1.x, 2.x"},{"fix":"Define `params = (('my_param', default_value),)` at the class level. Access them within the strategy via `self.p.my_param`.","message":"Strategy and indicator parameters must be defined within a `params` tuple in the class, not as instance attributes in `__init__`.","severity":"gotcha","affected_versions":"1.x, 2.x"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Always use `import backtrader as bt` and then refer to components as `bt.Cerebro`, `bt.Strategy`, etc.","cause":"Attempting to access a backtrader component directly (e.g., `backtrader.Cerebro`) without importing backtrader with the standard alias.","error":"AttributeError: 'module' object has no attribute 'Cerebro'"},{"fix":"Install `matplotlib`: `pip install matplotlib` or `pip install backtrader[plotting]`.","cause":"The `cerebro.plot()` method was called, but the `matplotlib` library is not installed.","error":"ModuleNotFoundError: No module named 'matplotlib'"},{"fix":"Verify the `dataname` path, `datetimeformat` string, and ensure the `fromdate`/`todate` range correctly overlaps with available data. Check the content of your data file for correctness and headers.","cause":"This usually indicates that the data feed could not be loaded correctly, or the specified `fromdate`/`todate` range for the data is empty/invalid. Common reasons include incorrect file path, wrong `datetimeformat`, or an empty data file.","error":"ValueError: No data points left to run a strategy (fromdate/todate problem?)\nTypeError: object of type 'NoneType' has no len()"},{"fix":"Double-check the file path. Ensure it's either an absolute path or a path relative to where your script is being run. Use `os.path.abspath()` for debugging if unsure.","cause":"The path provided to a data feed (e.g., `bt.feeds.CSVData(dataname='your_data.csv')`) is incorrect or the file does not exist at that location.","error":"FileNotFoundError: [Errno 2] No such file or directory: 'your_data.csv'"}]}