backtesting.lib module provides utility functions for common signal detection, quantile analysis, multi-timeframe resampling, statistical recomputation, and synthetic data generation.
crossover(series1, series2)
True if series1 just crossed above series2 on the most recent bar. Specifically, checks that series1[-2] < series2[-2] and series1[-1] > series2[-1].
First data series. Accepts a pandas
Series, NumPy array, or a scalar (which is treated as a constant).Second data series. Same types accepted as
series1.True if series1 just crossed above series2. Returns False if the series is too short (fewer than 2 elements).Use
cross() if you want to detect a crossover in either direction (above or below).cross(series1, series2)
True if series1 and series2 just crossed in either direction (above or below). Equivalent to crossover(series1, series2) or crossover(series2, series1).
First data series.
Second data series.
True if the two series just crossed in either direction.barssince(condition, default=np.inf)
condition was last True. If condition has never been True, returns default.
A boolean sequence (e.g. the result of a comparison against a data array). The most recent bar is the last element.
Value to return if
condition has never been True.Number of bars since
condition was last True, or default if it never was.The condition sequence is evaluated over the full history up to the current bar. When used inside
Strategy.next(), this is automatically the slice seen so far.quantile(series, quantile=None)
quantile is provided:
- Rank mode (
quantile=None): returns the quantile rank of the last value inseriesrelative to all prior values. Result is a float between 0 and 1. - Value mode (
quantileis a float 0–1): returns the value ofseriesat the given quantile (equivalent to a percentile, but in[0, 1]scale).
The data series to analyze. Typically a slice of a price array.
When
None, returns the rank of the last value. When a float between 0 and 1, returns the value at that quantile. To convert from percentile notation, divide by 100 (e.g. 10th percentile → 0.1).Quantile rank (0–1) of the last value, or the value at the requested quantile. Returns
np.nan if the series is too short.resample_apply(rule, func, series, *args, agg=None, **kwargs)
func (such as an indicator) to series after resampling it to the time frame specified by rule. When called from inside Strategy.init(), the result is automatically wrapped in self.I() so it behaves like any other indicator.
A Pandas offset string specifying the target time frame (e.g.
'D' for daily, 'W' for weekly, '4H' for four-hourly).The indicator function to apply to the resampled series. Pass
None to skip applying a function and just resample.The input data series to resample. Must have a
DatetimeIndex. You can pass a Strategy.data.* array (e.g. self.data.Close) — it will be converted to a pd.Series automatically.*args
Additional positional arguments passed to
func after the resampled series.Aggregation function used when grouping bars into the target time frame. Defaults to
OHLCV_AGG for DataFrames and 'last' for Series (or the appropriate OHLCV rule if the series name matches a column in OHLCV_AGG).**kwargs
Additional keyword arguments passed to
func.An indicator array aligned to the original data index, forward-filled from the resampled time frame. When called from
Strategy.init(), the array is wrapped with self.I() automatically.compute_stats(*, stats, data, trades=None, risk_free_rate=0.)
A statistics series as returned by
Backtest.run(). Used to obtain the equity curve, strategy instance, and full trade list.The OHLC DataFrame that was used in the original
Backtest. Must be the same data that produced stats.A subset of
stats._trades to compute stats for (e.g. only rows where Size > 0 for long trades). When None, all trades in stats._trades are used.Annual risk-free rate used in the Sharpe and Sortino ratio calculations.
A performance statistics series with the same fields as
Backtest.run(), computed over the provided trade subset.plot_heatmaps(heatmap, agg='max', *, ncols=3, plot_width=1200, filename='', open_browser=True)
heatmap. Used for visualizing optimization results across multiple parameter dimensions.
A
pd.Series as returned by Backtest.optimize(return_heatmap=True). The index is a MultiIndex of all tested parameter combinations; values are the optimization scores.Aggregation function used to project n-dimensional (n > 2) heatmap data onto 2D slices. Accepts any value that pandas
.agg() accepts (e.g. 'max', 'mean', np.median).Number of heatmap columns in the grid layout.
Total width of the combined heatmap grid in pixels.
Output HTML file path. When empty, a default filename is generated in the current directory.
When
True, the generated HTML file is opened automatically in the default web browser.random_ohlc_data(example_data, *, frac=1., random_state=None)
example_data. Each call to next() on the generator yields a new independently sampled DataFrame.
Useful for Monte Carlo simulations, robustness testing, and significance testing.
A DataFrame with
Open, High, Low, and Close columns used as the reference distribution. Must include all four OHLCV columns.Fraction of
example_data rows to sample per generated DataFrame. Values greater than 1 oversample (with replacement), producing a longer series.Integer seed for reproducibility. Pass the same seed to get identical generated sequences.
An infinite generator. Each
next() call returns a new random OHLC DataFrame with the same index as example_data.Constants
OHLCV_AGG
OrderedDict mapping standard OHLCV column names to their corresponding aggregation functions. Used with pd.DataFrame.resample(...).agg(OHLCV_AGG) to correctly downsample price data.
TRADES_AGG
OrderedDict mapping trades DataFrame column names to aggregation functions. Designed for use with stats._trades to aggregate trade records over time windows.