Skip to content

Running a Backtest

Replay an SMA crossover strategy against historical data and read the stats out.

Build / install

pip install lrvx

Or build from source: cmake -B build -DLRVX_BUILD_PYTHON=ON -DLRVX_ENABLE_BACKTEST=ON && cmake --build build and put build/python on PYTHONPATH.

npm install @lrvx/lrvx

Build lrvx with -DLRVX_BUILD_CAPI=ON -DLRVX_ENABLE_BACKTEST=ON, then point Codon at codon/lrvx.

cmake -B build -DLRVX_ENABLE_BACKTEST=ON -DCMAKE_BUILD_TYPE=Release
cmake --build build -j

Strategy

A 10/20 SMA crossover. Buy when fast crosses above slow, sell on the reverse.

import lrvx
from collections import deque

class SmaCrossover(lrvx.Strategy):
    def __init__(self, symbols, fast=10, slow=20, size=1.0):
        super().__init__(symbols)
        self.fast, self.slow, self.size = fast, slow, size
        self.prices = deque(maxlen=slow)
        self.prev_above = False

    def on_trade(self, ctx, trade):
        self.prices.append(trade.price)
        if len(self.prices) < self.slow:
            return
        fast_sma = sum(list(self.prices)[-self.fast:]) / self.fast
        slow_sma = sum(self.prices) / self.slow
        above = fast_sma > slow_sma
        if above and not self.prev_above and ctx.is_flat():
            self.market_buy(self.size)
        elif not above and self.prev_above and ctx.is_long():
            self.market_sell(self.size)
        self.prev_above = above
const lrvx = require('@lrvx/lrvx');

class SmaCrossover {
  constructor(symbols, fast = 10, slow = 20, size = 1.0) {
    this.symbols = symbols;
    this.fast = fast; this.slow = slow; this.size = size;
    this.prices = []; this.prevAbove = false;
  }
  onTrade(ctx, trade, emit) {
    this.prices.push(trade.price);
    if (this.prices.length > this.slow) this.prices.shift();
    if (this.prices.length < this.slow) return;
    const fastSma = this.prices.slice(-this.fast).reduce((a,b)=>a+b)/this.fast;
    const slowSma = this.prices.reduce((a,b)=>a+b)/this.slow;
    const above = fastSma > slowSma;
    if (above && !this.prevAbove && ctx.position === 0) emit.marketBuy(this.size);
    else if (!above && this.prevAbove && ctx.position > 0) emit.marketSell(this.size);
    this.prevAbove = above;
  }
}
from lrvx.strategy import Strategy
from lrvx.context import SymbolContext
from lrvx.types import TradeData
from lrvx.indicators import SMA

class SmaCrossover(Strategy):
    fast: SMA
    slow: SMA
    size: float
    prev_above: bool

    def __init__(self, symbols: List[int], fast_n: int = 10, slow_n: int = 20, size: float = 1.0):
        super().__init__(symbols)
        self.fast = SMA(fast_n)
        self.slow = SMA(slow_n)
        self.size = size
        self.prev_above = False

    def on_trade(self, ctx: SymbolContext, trade: TradeData):
        f = self.fast.update(trade.price.to_double())
        s = self.slow.update(trade.price.to_double())
        if not self.slow.ready:
            return
        above = f > s
        if above and not self.prev_above and self.position() == 0.0:
            self.market_buy(self.size)
        elif not above and self.prev_above and self.position() > 0.0:
            self.market_sell(self.size)
        self.prev_above = above
#include "lrvx/strategy/strategy.h"
#include <deque>

using namespace lrvx;

class SmaCrossover : public Strategy {
public:
  SmaCrossover(SymbolId symbol, size_t fast, size_t slow, Quantity size,
               const SymbolRegistry& registry)
      : Strategy(1, symbol, registry), _fast(fast), _slow(slow), _size(size) {}

  void start() override { _running = true; }
  void stop() override  { _running = false; }

protected:
  void onSymbolTrade(SymbolContext& /*ctx*/, const TradeEvent& ev) override
  {
    if (!_running) return;
    _prices.push_back(ev.trade.price.toDouble());
    if (_prices.size() > _slow) _prices.pop_front();
    if (_prices.size() < _slow) return;

    double fast_sma = sma(_fast), slow_sma = sma(_slow);
    bool above = fast_sma > slow_sma;
    if (above && !_prev_above && !_long) { emitMarketBuy(symbol(), _size); _long = true; _short = false; }
    else if (!above && _prev_above && !_short) { emitMarketSell(symbol(), _size); _short = true; _long = false; }
    _prev_above = above;
  }

private:
  double sma(size_t n) const {
    double sum = 0; auto it = _prices.end();
    for (size_t i = 0; i < n; ++i) sum += *--it;
    return sum / n;
  }
  size_t _fast, _slow;
  Quantity _size;
  std::deque<double> _prices;
  bool _running{false}, _prev_above{false}, _long{false}, _short{false};
};

Run the backtest

reg = lrvx.SymbolRegistry()
btc = reg.add_symbol("binance", "BTCUSDT", tick_size=0.01)

strat = SmaCrossover([btc])
bt = lrvx.BacktestRunner(reg, fee_rate=0.0004, initial_capital=10_000)
bt.set_strategy(strat)

stats = bt.run_csv("data/btcusdt_1m.csv", "BTCUSDT")
print(f"Final ${stats['final_capital']:.2f}  return {stats['return_pct']:.2f}%  "
      f"trades {stats['total_trades']}  Sharpe {stats['sharpe_ratio']:.2f}  "
      f"DD {stats['max_drawdown_pct']:.2f}%")
const reg = new lrvx.SymbolRegistry();
const btc = reg.addSymbol("binance", "BTCUSDT", 0.01);

const strat = new SmaCrossover([btc]);
const bt = new lrvx.BacktestRunner(reg, 0.0004, 10000);
bt.setStrategy(strat);

const stats = bt.runCsv("data/btcusdt_1m.csv", "BTCUSDT");
console.log(`Final $${stats.finalCapital.toFixed(2)}  return ${stats.returnPct.toFixed(2)}%  ` +
            `trades ${stats.totalTrades}  Sharpe ${stats.sharpeRatio.toFixed(2)}  ` +
            `DD ${stats.maxDrawdownPct.toFixed(2)}%`);
from lrvx.runner import BacktestRunner

reg = ...                                # see lrvx.engine in your runner code
btc = reg.add_symbol("binance", "BTCUSDT", 0.01)

strat = SmaCrossover([btc])
bt = BacktestRunner(reg, fee_rate=0.0004, initial_capital=10_000.0)
bt.set_strategy(strat)
stats = bt.run_csv("data/btcusdt_1m.csv", "BTCUSDT")
print(f"Final ${stats.final_capital:.2f}  return {stats.return_pct:.2f}%")
#include "lrvx/backtest/backtest_runner.h"
#include "lrvx/replay/abstract_event_reader.h"

int main() {
  replay::ReaderFilter filter;
  filter.symbols = {1};
  auto reader = replay::createMultiSegmentReader("/data/btcusdt", filter);

  BacktestConfig config{ .initialCapital = 10000.0, .feeRate = 0.0004 };
  BacktestRunner runner(config);

  SymbolRegistry registry;
  SymbolInfo info{ .exchange = "binance", .symbol = "BTCUSDT",
                    .tickSize = Price::fromDouble(0.01) };
  registry.registerSymbol(info);

  SmaCrossover strat(1, 10, 20, Quantity::fromDouble(1.0), registry);
  runner.setStrategy(&strat);

  auto result = runner.run(*reader);
  auto stats = result.computeStats();
  std::cout << "Final " << stats.finalCapital
            << "  return " << stats.returnPct << "%\n";
}

Bars from a tape in one call

A bar strategy over a recorded .lrvx tape is one call: run_tape_bars aggregates the tape's trades into time bars while it streams and hands each closed bar to on_bar. The trades never reach Python, so a three-month tape runs in the memory its bars need.

bt = lrvx.BacktestRunner(reg, fee_rate=0.0004, initial_capital=10_000,
                         slippage_model="fixed_bps", slippage_bps=1.0)
bt.set_strategy(strat)
stats = bt.run_tape_bars("data/tape", interval_seconds=300, symbol="BTCUSDT")
const bt = new lrvx.BacktestRunner(reg, 0.0004, 10000,
    {slippageModel: "fixed_bps", slippageBps: 1.0});
bt.setStrategy(strat);
const stats = bt.runTapeBars("data/tape", 300, "BTCUSDT");
bt = BacktestRunner(reg, 0.0004, 10_000.0,
                    slippage_model="fixed_bps", slippage_bps=1.0)
bt.set_strategy(strat)
stats = bt.run_tape_bars("data/tape", 300.0, "BTCUSDT")
BacktestRunner runner(config);
runner.setStrategy(&strat);
auto result = runner.runTapeBars("data/tape", std::chrono::minutes(5), btcId);

What it does, exactly:

  • Bars are wall-clock aligned (a 300 s bar starts on a multiple of five minutes, UTC), built by the same time-bar policy as aggregate_time_bars: a trade later than its bar's bucket is dropped, and the last bar, still open when the tape ends, is not delivered. An interval with no trades has no bar.
  • The executor is fed the bars, not the ticks, so the fill rules are run_bars' rules: an order sent from on_bar fills at that symbol's next bar open, and resting and conditional orders walk open, low, high, close. on_trade does not fire, and book records in the tape are not used.
  • One symbol per run. symbol names the registered symbol whose registry id is the tape's symbol id; it may be left out only when the tape holds a single symbol, and a tape with more than one raises instead of mixing them.
  • Each bar carries bar_type 0 (time), bar_type_param = the interval in nanoseconds, and its buy volume, as a live time aggregator would set them.

The result is the result of the explicit route -- DataReader.read_trades, aggregate_time_bars, run_bars -- for the same interval: same fills, same trades(), same equity_curve(). This example runs both and checks it:

"""A bar strategy over a .lrvx tape: the one-call route and the explicit one.

run_tape_bars aggregates the tape into time bars while it streams and replays
them with run_bars' fill rules. The explicit route -- read_trades,
aggregate_time_bars, run_bars -- lands on the same fills, trades and equity
curve for the same interval.
"""
import tempfile

import numpy as np

import lrvx

INTERVAL = 300.0
SEC = 10**9


def write_tape(path: str) -> None:
    """Six hours of synthetic BTCUSDT trades, symbol id 1."""
    rng = np.random.default_rng(1)
    n = 20_000
    ts = 1_767_225_600 * SEC + np.cumsum(rng.integers(1, 2 * SEC, n))
    px = np.round(60_000 + np.cumsum(rng.integers(-50, 51, n)) * 0.1, 1)
    qty = np.round(rng.uniform(0.001, 0.5, n), 3)
    w = lrvx.DataWriter(path)
    w.write_trades(ts, ts, px, qty, np.arange(n, dtype=np.uint64),
                   np.ones(n, np.uint32), rng.integers(0, 2, n).astype(np.uint8))
    w.close()


class Breakout(lrvx.Strategy):
    """Buys a close above the previous high, exits a close below the previous low."""

    def __init__(self, symbols):
        super().__init__(symbols)
        self.prev = None

    def on_bar(self, ctx, bar):
        if self.prev is not None:
            if ctx.is_flat() and bar.close > self.prev.high:
                self.market_buy(0.1)
            elif not ctx.is_flat() and bar.close < self.prev.low:
                self.close_position()
        self.prev = bar


def runner():
    reg = lrvx.SymbolRegistry()
    btc = reg.add_symbol("bybit", "BTCUSDT", tick_size=0.1)
    bt = lrvx.BacktestRunner(reg, fee_rate=0.00055, initial_capital=10_000.0,
                             slippage_model="fixed_bps", slippage_bps=1.0)
    bt.set_strategy(Breakout([btc]))
    return bt


def one_call(tape: str):
    bt = runner()
    stats = bt.run_tape_bars(tape, interval_seconds=INTERVAL, symbol="BTCUSDT")
    return stats, bt.trades(), bt.equity_curve()


def explicit(tape: str):
    trades = lrvx.DataReader(tape).read_trades()
    bars = lrvx.aggregate_time_bars(
        trades["exchange_ts_ns"], trades["price_raw"] / lrvx.PRICE_SCALE,
        trades["qty_raw"] / lrvx.VOLUME_SCALE, (trades["side"] == 0).astype(np.uint8),
        interval_seconds=INTERVAL)
    bt = runner()
    stats = bt.run_bars(
        start_time_ns=bars["start_time_ns"], end_time_ns=bars["end_time_ns"],
        open=bars["open_raw"] / lrvx.PRICE_SCALE, high=bars["high_raw"] / lrvx.PRICE_SCALE,
        low=bars["low_raw"] / lrvx.PRICE_SCALE, close=bars["close_raw"] / lrvx.PRICE_SCALE,
        volume=bars["volume_raw"] / lrvx.VOLUME_SCALE, symbol="BTCUSDT",
        bar_type=0, bar_type_param=int(INTERVAL * SEC))
    return stats, bt.trades(), bt.equity_curve()


def main() -> None:
    with tempfile.TemporaryDirectory() as tape:
        write_tape(tape)
        a = one_call(tape)
        b = explicit(tape)
    assert a[0] == b[0], "stats differ"
    for got, want in ((a[1], b[1]), (a[2], b[2])):
        for key in got:
            assert np.array_equal(got[key], want[key]), key
    stats = a[0]
    print(f"trades {stats['total_trades']}  net pnl {stats['net_pnl']:.2f}  "
          f"max dd {stats['max_drawdown_pct']:.2f}%  (both routes identical)")


if __name__ == "__main__":
    main()

Two differences a strategy can see, neither of which reaches a fill: the explicit route passes no buy volume (run_bars takes none), and it carries each bar's volume through a float, so a bar whose notional exceeds about 9e7 quote units arrives rounded to the nearest representable value where the one-call route delivers it exact. Use the explicit form when the bars are reused across many runs -- load or aggregate them once and hand the same arrays to every run, as in Sweep parameters over bars.

Slippage and latency arguments are covered in Realistic backtest fills and Add latency to a backtest. On bars, any positive submit latency moves a fill to a later bar's open: Latency on bar replay.

Decide on bars, fill on ticks

A tape holds every print, and a bar hides them: on bar replay a stop that triggers inside a bar fills at the bar's low, while the tape says it filled a tick or two past its trigger. run_tape_bars_on_ticks keeps both: the strategy is shown the bars run_tape_bars builds, and the simulated executor is fed the tape's own trades and book records, as run_tape feeds it.

stats = bt.run_tape_bars_on_ticks("data/tape", interval_seconds=300, symbol="BTCUSDT")
const stats = bt.runTapeBarsOnTicks("data/tape", 300, "BTCUSDT");
stats = bt.run_tape_bars_on_ticks("data/tape", 300.0, "BTCUSDT")
auto result = runner.runTapeBarsOnTicks("data/tape", std::chrono::minutes(5), btcId);

The three ways to run a strategy over a tape, side by side:

run_tape run_tape_bars run_tape_bars_on_ticks
The strategy sees every trade (on_trade) and book record closed time bars (on_bar) closed time bars (on_bar)
The executor matches against every trade and book record each bar's open, low, high, close every trade and book record
An order sent from the callback first trades at the current market (the record just shown) the next bar's open the first trade stamped at or after the bar's end
A stop triggered inside a bar fills at the print that crossed it the bar's low (high for a buy stop) the print that crossed it
Submit latency of L moves the fill to the first record at or after now + L moves the fill to a later bar's open moves the fill to the first record at or after the bar's end + L
Use it for strategies that react to prints or the book fast sweeps of a bar strategy, and parity with bar data a bar strategy whose fills should be the tape's

The rules of run_tape_bars_on_ticks, exactly:

  • Bar n reaches on_bar when the first trade stamped at or after its end arrives, and before that trade reaches the executor. The bar is over by then, and nothing it contains is new to the strategy. The callback runs on a clock set to the bar's end, or later when book records stamped past the end came first.
  • An order sent from that callback is submitted then, through the full submit path (rate limits, reduce-only, the sampled latency), and is not matched inside the call. With no latency it can first match against that trade: the first trade stamped at or after the end of bar n, a trade stamped exactly at the end included. With a submit latency L it waits for the first record at or after the bar's end + L: 5 ms of latency moves a fill by milliseconds, not by a bar.
  • Stops, take-profits, trailing stops and limits already working are matched by the trades inside the following bars, by run_tape's rules. A conditional order never fills better than its trigger.
  • The bars are the bars run_tape_bars delivers for the same interval, bit for bit, and the last bar, still open when the tape ends, is not delivered. A trade later than its bar's bucket is left out of the bar and still reaches the executor.
  • on_trade and on_book_update do not fire.
  • One symbol per run, as for run_tape_bars: symbol names it, and without it a trade or book record of a second symbol raises.
  • The result has the same shape as the other runners' (stats, trades(), equity_curve()); the stats also carry skipped_option_quotes and skipped_pool_states, as run_tape's do. The tape is streamed: memory does not grow with the number of trades.

A strategy that sends only market orders from on_bar gets exactly the fills run_tape gives the same orders sent from on_trade of the first trade at or after each bar's end. Choose run_tape_bars when bars are all the data there is, or to sweep many parameters fast; choose run_tape_bars_on_ticks for the fills of a bar strategy that the tape can actually support.

Output

Final $10245.30  return 2.45%  trades 47  Sharpe 1.23  DD 3.21%

Two stats shapes, one set of key names

Every producer names the risk ratios the same way: sharpe_ratio / sortino_ratio / calmar_ratio in Python and Codon, sharpeRatio / sortinoRatio / calmarRatio in Node. The C++ BacktestStats field name is the source both are derived from, so the snake_case to camelCase rule holds with no exceptions.

What still differs between producers is the field set, not the names:

Producer Field set
BacktestRunner.run_csv / run_ohlcv / run_bars / run_tape / run_tapes / run_tape_bars / run_tape_bars_on_ticks Headline metrics plus all three risk ratios; the tape runs run_tape, run_tapes and run_tape_bars_on_ticks add skipped_option_quotes and skipped_pool_states (Node: skippedOptionQuotes / skippedPoolStates on every run)
BacktestResult.stats() The full set
GridSearch.run()[i]["stats"] Python: whatever the factory returned (normally the run_* shape). Node: the fold shape
WalkForwardRunner fold stats The fold shape: the run_* set minus avg_win / avg_loss

BacktestResult.stats() is the only one carrying the full metric set: time_weighted_return, avg_win_loss_ratio, max_consecutive_wins / max_consecutive_losses, avg_trade_duration_ns / median_trade_duration_ns / max_trade_duration_ns, start_time_ns and end_time_ns. In Node these three shapes are the BacktestStats, RunnerStats and FoldStats interfaces in index.d.ts.

Fees: one rate, or one per side

fee_rate charges every fill the same. That is a maker/taker average, and it understates any strategy that mostly posts on a venue where making is cheaper than taking — sometimes a rebate.

Fills carry is_maker, so both sides can be priced separately:

r = lrvx.BacktestResult(
    initial_capital=10_000.0,
    fee_rate=0.0004,          # still the fallback for either side
    maker_fee_rate=0.0001,    # charged when the fill provided liquidity
    taker_fee_rate=0.0005,    # charged when it took liquidity
)
BacktestConfig config{};
config.feeRate = 0.0004;
config.makerFeeRate = 0.0001;
config.takerFeeRate = 0.0005;

Both default to unset (None in Python, an empty std::optional in C++), in which case fee_rate applies to both sides and results are unchanged. A rate you set is used as given, sign and all: zero is a real maker rate, and a negative one is a rebate the venue pays you for posting. Fixed-fee mode (use_percentage_fee=False) ignores the side entirely.

r = lrvx.BacktestResult(
    initial_capital=10_000.0,
    fee_rate=0.0004,
    maker_fee_rate=-0.00005,  # the venue pays 0.5 bp for posting
    taker_fee_rate=0.0005,
)
BacktestConfig config{};
config.feeRate = 0.0004;
config.makerFeeRate = -0.00005;
config.takerFeeRate = 0.0005;

is_maker is also on every fill in fills_list() and in the fills() numpy dtype, so a fee model of your own can read it directly. What this does not give you is a venue's 30-day volume tiering — for that see Realistic backtest in one call.

Pre-aggregated bars (faster replay)

For repeated parameter sweeps over the same data, pre-aggregate bars once and replay them. Python (run_bars), Node.js (runBars) and Codon (run_bars) all take closed OHLC bars; C++ has dedicated mmap storage.

runBars is implemented by the Node addon but is not declared in index.d.ts, so TypeScript callers need a cast.

import numpy as np
bt.run_bars(
    start_time_ns = ts_start_arr.astype(np.int64),
    end_time_ns   = ts_end_arr.astype(np.int64),
    open  = opens,  high = highs, low = lows, close = closes, volume = vols,
    symbol = "BTCUSDT",
)
// startNs / endNs are BigInt64Array; OHLCV arrays are Float64Array.
bt.runBars(startNs, endNs, opens, highs, lows, closes, vols, "BTCUSDT");

Pre-aggregate offline with the preagg_bars tool, then replay via MmapBarReplaySource:

MmapBarStorage storage("/data/BTCUSDT/bars");
MmapBarReplaySource source(storage, symbol_id);
source.replay([&](const BarEvent& ev) { strat.onBar(ev); });

See Also