Principle:51bitquant Ai hedge fund crypto Backtest Simulation Loop
| Knowledge Sources | |
|---|---|
| Domains | Backtesting, Workflow_Orchestration |
| Last Updated | 2026-10-28 14:00 GMT |
Overview
A backtesting pattern that iterates historical bars one at a time, invoking the decision pipeline per bar with only past-available data, executing simulated trades, and accumulating a portfolio value series for performance analysis.
Description
The backtest simulation loop replays history bar-by-bar to evaluate a strategy as if it were trading live. It pre-fetches the full historical window once (for speed), validates data alignment across tickers, then for each bar: reads the current prices from the pre-fetched klines, invokes the agent (passing the bar's close time as "now" so the agent only sees data up to that point), executes the returned decisions, revalues the portfolio, and records the value + exposures. After the loop, performance metrics and the equity curve are produced.
This avoids look-ahead bias by feeding the agent only data up to each bar's close time, and it amortizes DAG construction by compiling the graph once before the loop.
Usage
Use this pattern to evaluate a strategy on historical data. Ensure the agent's `end_date` is set to each bar's close time so it cannot see the future. Compile the DAG once; invoke per bar. Track portfolio values in a list for post-loop analysis.
Theoretical Basis
Given a historical series of bars and a decision function , the loop is:
with the no-look-ahead constraint that contains only information available up to 's close. The portfolio value series feeds performance analytics.
Pseudo-code:
# Abstract pattern
data = prefetch(symbol, timeframe, start, end)
agent = compile_dag(strategies)
for bar in data:
prices = close_prices(bar)
decisions = agent.run(end_date=bar.close_time, portfolio=portfolio)
for ticker: execute_trade(decisions[ticker], prices[ticker])
portfolio_values.append(value(portfolio, prices))
analyze(portfolio_values)
Practical Guide
- Pre-fetch once; reading per bar from the API would be far slower and rate-limited.
- Validate all tickers have equal-length, aligned DataFrames before the loop — a mismatch means a data gap.
- Pass the bar's close time (not `now`) as the agent's `end_date` to avoid look-ahead bias.
- Compile the DAG once before the loop; reconstructing it per bar wastes time.
- Update performance metrics incrementally (when enough bars exist) so the table shows live progress.