Backtesting Function

Here is a description of the backtest function and all of its parameters. This is true for any kind of backtesting that you will be doing.

lumibot.strategies.strategy.Strategy.run_backtest(datasource_class, backtesting_start: <module 'datetime' from '/opt/homebrew/Cellar/python@3.13/3.13.3/Frameworks/Python.framework/Versions/3.13/lib/python3.13/datetime.py'> = None, backtesting_end: <module 'datetime' from '/opt/homebrew/Cellar/python@3.13/3.13.3/Frameworks/Python.framework/Versions/3.13/lib/python3.13/datetime.py'> = None, minutes_before_closing=5, minutes_before_opening=60, sleeptime=1, stats_file=None, risk_free_rate=None, logfile=None, config=None, auto_adjust=False, name=None, budget=None, benchmark_asset: str | ~lumibot.entities.asset.Asset | None = 'SPY', analyze_backtest: bool = True, plot_file_html=None, trades_file=None, settings_file=None, pandas_data: ~typing.List | ~typing.Dict[~lumibot.entities.asset.Asset, ~lumibot.entities.data.Data] = None, quote_asset=USD, starting_positions=None, show_plot=None, tearsheet_file=None, save_tearsheet=True, show_tearsheet=None, parameters={}, buy_trading_fees=[], sell_trading_fees=[], polygon_api_key=None, use_other_option_source=False, thetadata_username=None, thetadata_password=None, indicators_file=None, show_indicators=None, save_logfile=False, use_quote_data=False, show_progress_bar=True, quiet_logs=False, trader_class=<class 'lumibot.traders.trader.Trader'>, include_cash_positions=False, save_stats_file=True, **kwargs)

Backtest a strategy.

Parameters:
  • datasource_class (class) – The datasource class to use. For example, if you want to use the yahoo finance datasource, then you would pass YahooDataBacktesting as the datasource_class.

  • backtesting_start (datetime) – The start date of the backtesting period.

  • backtesting_end (datetime) – The end date of the backtesting period.

  • minutes_before_closing (int) – The number of minutes before closing that the minutes_before_closing strategy method will be called.

  • minutes_before_opening (int) – The number of minutes before opening that the minutes_before_opening strategy method will be called.

  • sleeptime (int) – The number of seconds to sleep between each iteration of the backtest.

  • stats_file (str) – The file to write the stats to.

  • risk_free_rate (float) – The risk-free rate to use.

  • logfile (str) – The file to write the log to.

  • config (dict) – The config to use to set up the brokers in live trading.

  • auto_adjust (bool) – Whether to automatically adjust the strategy.

  • name (str) – The name of the strategy.

  • budget (float) – The initial budget to use for the backtest.

  • benchmark_asset (str or Asset or None) – The benchmark asset to use for the backtest to compare to. If it is a string then it will be converted to a stock Asset object. If it is None, no benchmarking will occur.

  • analyze_backtest (bool = True) – Run the backtest_analysis method on the strategy.

  • plot_file_html (str) – The file to write the plot html to.

  • trades_file (str) – The file to write the trades to.

  • pandas_data (list) – A list of Data objects that are used when the datasource_class object is set to PandasDataBacktesting. This contains all the data that will be used in backtesting.

  • quote_asset (Asset (crypto)) – An Asset object for the cryptocurrency that will get used as a valuation asset for measuring overall porfolio values. Usually USDT, USD, USDC.

  • starting_positions (dict) – A dictionary of starting positions for each asset. For example, if you want to start with $100 of SPY, and $200 of AAPL, then you would pass in starting_positions={‘SPY’: 100, ‘AAPL’: 200}.

  • show_plot (bool) – Whether to show the plot.

  • show_tearsheet (bool) – Whether to show the tearsheet.

  • save_tearsheet (bool) – Whether to save the tearsheet.

  • parameters (dict) – A dictionary of parameters to pass to the strategy. These parameters must be set up within the initialize() method.

  • buy_trading_fees (list of TradingFee objects) – A list of TradingFee objects to apply to the buy orders during backtests.

  • sell_trading_fees (list of TradingFee objects) – A list of TradingFee objects to apply to the sell orders during backtests.

  • polygon_api_key (str) – The polygon api key to use for polygon data. Only required if you are using PolygonDataBacktesting as the datasource_class.

  • indicators_file (str) – The file to write the indicators to.

  • show_indicators (bool) – Whether to show the indicators plot.

  • save_logfile (bool) – Whether to save the logfile. Defaults to False. If True, the logfile will be saved to the logs directory. Turning on this option will slow down the backtest.

  • use_quote_data (bool) – Whether to use quote data for the backtest. Defaults to False. If True, the backtest will use quote data for the backtest. (Currently this is specific to ThetaData) When set to true this requests Quote data in addition to OHLC which adds time to backtests.

  • show_progress_bar (bool) – Whether to show the progress bar during the backtest. Defaults to True.

  • quiet_logs (bool) – Whether to quiet the logs during the backtest. Defaults to True.

  • trader_class (class) – The class to use for the trader. Defaults to Trader.

Returns:

A tuple of the analysis dictionary and the strategy object. The analysis dictionary contains the analysis of the strategy returns. The strategy object is the strategy object that was backtested, where you can access the strategy returns and other attributes.

Return type:

tuple of (dict, Strategy)

Examples

>>> from datetime import datetime
>>> from lumibot.backtesting import YahooDataBacktesting
>>> from lumibot.strategies import Strategy
>>>
>>> # A simple strategy that buys AAPL on the first day
>>> class MyStrategy(Strategy):
>>>    def on_trading_iteration(self):
>>>        if self.first_iteration:
>>>            order = self.create_order("AAPL", quantity=1, side="buy")
>>>            self.submit_order(order)
>>>
>>> # Create a backtest
>>> backtesting_start = datetime(2018, 1, 1)
>>> backtesting_end = datetime(2018, 1, 31)
>>>
>>> # The benchmark asset to use for the backtest to compare to
>>> benchmark_asset = Asset(symbol="QQQ", asset_type="stock")
>>>
>>> backtest = MyStrategy.backtest(
>>>     datasource_class=YahooDataBacktesting,
>>>     backtesting_start=backtesting_start,
>>>     backtesting_end=backtesting_end,
>>>     benchmark_asset=benchmark_asset,
>>> )