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.

Starting cash and currency conversion

budget is starting cash in quote_asset units. Without an explicit budget, the existing default is 100,000 quote units: a BTC quote wallet means BTC, not dollars. starting_positions contains quantities that are already denominated in their assets; it does not convert a starting cash amount.

To declare a different input denomination, pass an explicit budget amount and an optional budget_conversion record. The rate is quote-wallet units per one input-budget unit. For example, this illustrative caller-supplied assumption converts USD 10,000 into 0.2 BTC; it is not a fresh or independently verified price:

MyStrategy.backtest(
    datasource_class=MyDataSource,
    backtesting_start=start,
    backtesting_end=end,
    budget=10000,
    quote_asset=Asset("BTC", "crypto"),
    budget_conversion={
        "budget_currency": "USD",
        "quote_currency": "BTC",
        "quote_per_budget": "0.00002",
        # Optional provenance; use the observation actually available to you.
        "as_of": start.isoformat(),
        "source": "prepared historical conversion assumption",
        "note": "illustrative approximation",
    },
)

The required conversion fields are budget_currency, quote_currency and a positive finite quote_per_budget. The target must match quote_asset. An amount must be explicitly supplied through budget or BACKTESTING_BUDGET. There is no currency allowlist, automatic rate lookup, live ticker fallback or assumption that USD and USDT have equal value. A supplied multi-currency rate must already include the needed conversion legs.

as_of, source and note are optional. Missing values remain explicitly unspecified. Approximate or unparseable dates remain usable. Known later dates are flagged, so they cannot be mistaken for an exact simulation-start observation; they are not a runtime refusal. The caller chooses and owns that approximation. No provenance label independently verifies the supplied rate.

BACKTESTING_BUDGET keeps its existing priority over the Python amount. BACKTESTING_BUDGET_CONVERSION accepts the same record as JSON and replaces the Python record as a whole, rather than merging it. Without a conversion record, all existing numeric-budget units and defaults are unchanged. This only initializes backtest cash; live broker balances and wallets are never converted.

strategy.budget_conversion and the optional budget_conversion field in settings.json retain the input amount, source and target currencies, supplied rate and metadata, resulting quote cash, conversion-record argument/environment origin and date relation to the simulation start. initial_budget and settings budget remain the resulting starting cash in quote units. Legacy runs add no conversion field.

lumibot.strategies.strategy.Strategy.run_backtest(datasource_class=None, backtesting_start: <module 'datetime' from '/opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/datetime.py'> = None, backtesting_end: <module 'datetime' from '/opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/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 | Asset | None = 'SPY', analyze_backtest: bool = True, plot_file_html=None, trades_file=None, settings_file=None, pandas_data: Asset, ~lumibot.entities.Data]=None, quote_asset=<object object>, starting_positions=None, show_plot=None, tearsheet_file=None, tearsheet_metrics_file=None, save_tearsheet=True, show_tearsheet=None, parameters={}, buy_trading_fees=[], sell_trading_fees=[], buy_trading_slippages=[], sell_trading_slippages=[], 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=None, include_cash_positions=False, save_stats_file=True, budget_conversion=None, **kwargs)

Backtest a strategy.

Parameters:
  • datasource_class (class, optional) – 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. When BACKTESTING_DATA_SOURCE is configured in the environment, you may leave this as None and let the runtime resolve the effective backtesting data source from the environment instead.

  • 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.

  • budget_conversion (dict, optional) – Explicit starting-capital conversion. Required fields are budget_currency, quote_currency (matching quote_asset), and positive finite quote_per_budget. The existing budget amount is in budget_currency and is multiplied by that caller-supplied rate to initialize quote-wallet cash. Optional as_of, source, note and other metadata remain visible in settings.json. No prices are fetched; missing, approximate and known later dates are disclosed, not blocked. BACKTESTING_BUDGET_CONVERSION JSON replaces this record when configured.

  • 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.

  • buy_trading_slippages (list of TradingSlippage objects) – Slippage amounts to apply to buy SMART_LIMIT fills when no per-order slippage is provided.

  • sell_trading_slippages (list of TradingSlippage objects) – Slippage amounts to apply to sell SMART_LIMIT fills when no per-order slippage is provided.

  • 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=None,
>>>     backtesting_start=backtesting_start,
>>>     backtesting_end=backtesting_end,
>>>     benchmark_asset=benchmark_asset,
>>> )