Sweep parameters over bars¶
Run one bar strategy over many parameter combinations fast enough to iterate on the grid, not wait for it.
A single run over a recorded tape does not need the arrays at all:
run_tape_bars(path, interval_seconds=..., symbol=...) aggregates the tape
while it streams and gives the same result as the explicit route (see
Bars from a tape in one call).
A sweep repeats the run many times over the same bars, so it pays to build the
bars once and reuse them, which is what this page does.
A bar sweep fills on bars: an order from on_bar at the next bar's open, a
stop at the bar's low. Once the grid has narrowed to a few candidates, run
those on the tape itself with run_tape_bars_on_ticks, which shows the
strategy the same bars but fills its orders on the tape's prints; the table in
Decide on bars, fill on ticks sets
the three modes side by side. That run reads the whole tape each time, so it
is the check on a shortlist, not the sweep itself.
Load the bars once¶
run_bars takes the bar arrays and nothing else: no file, no parsing, no conversion. Load them once and hand the same arrays to every run. Timestamps are nanoseconds and the call does no unit guessing, so a file with millisecond timestamps is multiplied by 1 000 000 at load time, once.
- From CSV:
numpy.loadtxtinto one array, then one column per field. - From Parquet:
pandas.read_parquet(path), then.to_numpy()on each column. - From a recorded tape: aggregate bars once and keep the result.
run_csv and run_ohlcv read and parse their file on every call, which is the right tool for one run and the wrong one for a sweep.
Run on bars¶
A bar strategy implements on_bar(ctx, bar) and reads bar.open, bar.high, bar.low, bar.close, bar.volume, bar.start_time_ns and bar.end_time_ns. The engine walks each bar (open, low, high, close) before the callback, holds every order the callback submits, and fills it at the next bar's open. The full set of rules, with pinned numbers, is on the reference backtest page.
Two exits that look alike are not: market_sell(qty) is a plain sell of qty, which reduces a long by that much and goes short past it; close_position() sells exactly the open position, reduce-only, and submits nothing when flat.
Keep the work per bar small. The streaming indicators (lrvx.SMA, lrvx.EMA, lrvx.ATR and the rest) keep no history: update() advances a fixed-size state by one step without allocating, at a cost set by the indicator's period (O(1) for the moving averages, RSI and ATR, O(period) for the rolling statistics) and independent of how many bars came before. A strategy that keeps only its indicators and its state costs the same on bar 3000 as on bar 40.
The sweep¶
A combination is a fresh registry, runner and strategy; only the bar arrays are shared. The example below runs a small grid over the data file that ships in docs/examples/data/.
"""
Sweep strategy parameters over bars that each worker loads once.
The grid is parameters only. A worker process reads the bar arrays the first
time it runs a combination and keeps them; every later combination in that
process reuses them, so the cost per run is the strategy and nothing else.
Processes rather than threads: a Python strategy runs under the GIL, so two
threads would take turns rather than run at once.
Usage:
cd /path/to/lrvx
PYTHONPATH=build/python python3 docs/examples/python_sweep_over_bars.py
"""
import os
from concurrent.futures import ProcessPoolExecutor
import numpy as np
import lrvx
DATA = os.path.join(os.path.dirname(__file__), "data", "btcusdt_1m.csv")
_BARS = None
def bars_for(path):
"""The bar arrays run_bars takes, loaded once per process."""
global _BARS
if _BARS is None:
raw = np.loadtxt(path, delimiter=",", skiprows=1)
# The file carries millisecond timestamps; run_bars takes nanoseconds
# and does no unit guessing.
start_ns = raw[:, 0].astype(np.int64) * 1_000_000
_BARS = {
"start_time_ns": start_ns,
"end_time_ns": start_ns + 60_000_000_000,
"open": raw[:, 1],
"high": raw[:, 2],
"low": raw[:, 3],
"close": raw[:, 4],
"volume": raw[:, 5],
}
return _BARS
class SmaCross(lrvx.Strategy):
"""Long when the fast SMA is above the slow one, flat otherwise."""
def __init__(self, symbols, fast, slow, qty=0.01):
super().__init__(symbols)
self.fast = lrvx.SMA(fast)
self.slow = lrvx.SMA(slow)
self.qty = qty
def on_bar(self, ctx, bar):
f = self.fast.update(bar.close)
s = self.slow.update(bar.close)
if f is None or s is None or not self.slow.ready:
return
if f > s and ctx.is_flat():
# Held until the next bar opens: nothing fills on the bar that
# produced the signal.
self.market_buy(self.qty)
elif f < s and ctx.is_long():
# Sells exactly the open position, reduce-only.
self.close_position()
def run_one(task):
"""One combination: a fresh registry, runner and strategy every time."""
fast, slow, path = task
registry = lrvx.SymbolRegistry()
btc = registry.add_symbol("exchange", "BTCUSDT", tick_size=0.01)
bt = lrvx.BacktestRunner(registry, fee_rate=0.0004, initial_capital=10_000.0)
bt.set_strategy(SmaCross([btc], fast, slow))
stats = bt.run_bars(symbol="BTCUSDT", **bars_for(path))
return {
"fast": fast,
"slow": slow,
"trades": stats["total_trades"],
"return_pct": stats["return_pct"],
"sharpe": stats["sharpe_ratio"],
}
def main():
grid = [(fast, slow, DATA) for fast in (5, 10, 20) for slow in (30, 60) if fast < slow]
with ProcessPoolExecutor(max_workers=2) as pool:
rows = list(pool.map(run_one, grid))
rows.sort(key=lambda r: r["sharpe"], reverse=True)
for r in rows:
print(
f"fast={r['fast']:2d} slow={r['slow']:2d} trades={r['trades']:3d} "
f"return={r['return_pct']:+.4f}% sharpe={r['sharpe']:+.3f}"
)
if __name__ == "__main__":
main()
Processes, not threads: a Python strategy runs under the GIL, so two threads take turns on the callbacks rather than run at once. Each worker process loads the bars the first time it runs a combination and keeps them; the tasks it receives are parameters only.
From C++, BacktestOptimizer::runLocal(numThreads) and GridSearch::run(numThreads) run the combinations on threads, with the bar vector loaded once and shared read-only; see grid search.
After the sweep¶
The result list is unsorted. Rank it on the caller side, then:
- hold out time with walk-forward,
- separate luck from edge with the statistical tests, and
- prefer a parameter point with good neighbours over an isolated peak.