Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:51bitquant Ai hedge fund crypto Backtester run backtest

From Leeroopedia
Knowledge Sources
Domains Backtesting, Workflow_Orchestration
Last Updated 2026-10-28 14:00 GMT

Overview

Concrete tool for running a bar-by-bar historical backtest that pre-fetches data, invokes the trading agent per bar, executes trades, and tracks performance provided by the `Backtester` class.

Description

Backtester.run_backtest orchestrates the full backtest loop. It calls `prefetch_data()` to load all klines, validates that all tickers have equal-length DataFrames, constructs an `Agent` once (compiling the DAG), then iterates each bar: fetches current prices, calls Agent.run with the bar's `close_time`, parses decisions, calls execute_trade per ticker, computes portfolio value via calculate_portfolio_value, records exposures, builds table rows, and updates performance metrics when more than 3 portfolio values exist. Returns the `performance_metrics` dict.

Usage

Call this once after constructing a `Backtester` with validated `Settings`. It is the primary entry point for the backtest workflow, invoked from `main.py` or `backtest.py`.

Code Reference

Source Location

Signature

class Backtester:
    def run_backtest(self) -> Dict:
        # 1. prefetch_data()
        # 2. Validate equal-length DataFrames
        # 3. Construct Agent (compile DAG)
        # 4. For each bar:
        #    a. Get current_prices from klines
        #    b. agent.run(...) -> decisions
        #    c. execute_trade per ticker
        #    d. calculate_portfolio_value
        #    e. Record portfolio_values + exposures
        #    f. Build/print table rows
        #    g. _update_performance_metrics (if >3 values)
        # 5. Store self.performance_metrics; return performance_metrics

Import

from src.backtest.backtester import Backtester

I/O Contract

Inputs

Name Type Required Description
self Backtester Yes Instance with `primary_interval`, `intervals`, `tickers`, `start_date`, `end_date`, `initial_capital`, `strategies`, `model_name/provider/base_url`, `portfolio`

Outputs

Name Type Description
return Dict `performance_metrics` with `sharpe_ratio`, `sortino_ratio`, `max_drawdown`, `max_drawdown_date`, `long_short_ratio`, `gross_exposure`, `net_exposure`
side effect self.portfolio_values List of per-bar dicts (Date, Portfolio Value, exposures)
side effect self.portfolio Mutated by trades throughout the run

Usage Examples

Full Backtest Run

from src.backtest.backtester import Backtester
from src.utils.settings import settings

bt = Backtester(
    primary_interval=settings.primary_interval,
    intervals=settings.signals.intervals,
    tickers=settings.signals.tickers,
    start_date=settings.start_date,
    end_date=settings.end_date,
    initial_capital=settings.initial_cash,
    strategies=settings.signals.strategies,
    model_name=settings.model.name,
    model_provider=settings.model.provider,
    model_base_url=settings.model.base_url,
    initial_margin_requirement=settings.margin_requirement,
    show_reasoning=settings.show_reasoning,
    show_agent_graph=settings.show_agent_graph,
)

metrics = bt.run_backtest()
print("Sharpe:", metrics["sharpe_ratio"])
print("Max DD:", metrics["max_drawdown"])

Analyze After Run

performance_df = bt.analyze_performance()
# Prints summary stats and plots equity curve

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment