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:AI4Finance Foundation FinRobot BackTraderAdapter run

From Leeroopedia
Knowledge Sources
Domains Finance, Quantitative_Trading, External_Library_Wrapper
Last Updated 2026-10-18 00:00 GMT

Overview

Concrete BacktestEngine implementation that runs BackTrader in a thread pool with DataLayer-sourced price bars and analyzer-based metrics, provided by the FinRobot backtest adapter.

Description

The BackTraderAdapter is a Wrapper Doc for the external BackTrader library. It implements the BacktestEngine ABC and provides:

  • DataLayer integration: Price bars come from the injected DataLayer (not direct yfinance), sharing the provider fallback chain, circuit-breaker, and cache like every other data path. Degraded bars (close-only feed) fall back OHLC = close.
  • Strategy resolution: Built-in strategies (s.g. "sma_crossover") are resolved from an allow-list registry. User-supplied strategy strings can only reach vetted, zero-argument factories — no importlib on untrusted input.
  • Analyzer pipeline: SharpeRatio (annualized, factor=252), DrawDown, Returns, TradeAnalyzer — all BackTrader analyzers feeding into the typed BacktestResult.
  • Thread pool execution: BackTrader is synchronous; run wraps _run_sync in asyncio.to_thread.
  • Chart rendering: Equity curve PNG via matplotlib (Agg backend), base64-encoded into BacktestResult.chart_base64.
  • Non-US equity rejection: Rejects non-US equity tickers (via is_us_equity_ticker).

The companion run_strategy_selection provides LLM-guided auto mode: it splits the window into in-sample/out-of-sample, asks the LLM to pick and tune strategy parameters on IS only, then runs the winning parameters ONCE on the untouched OOS tail.

Usage

  • Strategy_Backtest workflow (Step 3): Deterministic mode via BackTraderAdapter.run(config); auto mode via run_strategy_selection.
  • Import this when you need to execute a backtest using BackTrader. Pass a DataLayer to the constructor for shared data access.

Code Reference

Source Location

  • Repository: FinRobot
  • File: finrobot_desktop/finrobot/engine/backtest/backtrader_adapter.py (BackTraderAdapter), finrobot_desktop/finrobot/engine/backtest/strategy_agent.py (run_strategy_selection)

Signature

class BackTraderAdapter(BacktestEngine):
    """BacktestEngine implementation using BackTrader.

    Price bars come from the injected DataLayer — the backtest shares the
    provider fallback chain, circuit-breaker and cache like every other data path.
    """

    def __init__(self, data_layer: DataLayer) -> None:
        self._data_layer = data_layer

    async def run(self, config: BacktestConfig) -> BacktestResult:
        """Execute backtest using BackTrader in a thread pool."""
        _check_backtrader()
        _reject_non_us_equity(config.ticker)
        return await asyncio.to_thread(self._run_sync, config)

async def run_strategy_selection(
    settings: FinRobotSettings,
    ticker: str,
    start_date: str,
    end_date: str,
    data_layer: DataLayer,
    initial_cash: float = 100_000.0,
) -> BacktestResult:
    """Run LLM-guided strategy selection with in-sample/out-of-sample validation.

    Splits the window IS (first 70%) / OOS (last 30%), tunes on IS only,
    runs the winner ONCE on the untouched OOS tail. Degrades to single-window
    tuning with an overfit warning when the window is too short.
    """

Import

from finrobot.engine.backtest.backtrader_adapter import BackTraderAdapter
from finrobot.engine.backtest.strategy_agent import run_strategy_selection

I/O Contract

Inputs

Name Type Required Description
data_layer DataLayer Yes Injected for price bar access (constructor)
config BacktestConfig Yes Validated backtest configuration
settings FinRobotSettings Yes (auto) For LLM model creation (run_strategy_selection)

Outputs

Name Type Description
BacktestResult BacktestResult All computed metrics + chart_base64 + warnings

Usage Examples

Deterministic Backtest

from finrobot.engine.backtest.backtrader_adapter import BackTraderAdapter
from finrobot.engine.backtest.engine import BacktestConfig

engine = BackTraderAdapter(data_layer=deps.data_layer)
config = BacktestConfig(
    ticker="AAPL",
    start_date="2023-01-01",
    end_date="2024-01-01",
    strategy_params={"fast": 10, "slow": 30},
)
result = await engine.run(config)
print(result.format_summary())

LLM-Guided Auto Mode

from finrobot.engine.backtest.strategy_agent import run_strategy_selection

result = await run_strategy_selection(
    settings=deps.settings,
    ticker="AAPL",
    start_date="2022-01-01",
    end_date="2024-01-01",
    data_layer=deps.data_layer,
    initial_cash=100_000.0,
)
# LLM tuned parameters on in-sample (2022-2023), validated on out-of-sample (2023-2024)

Related Pages

Implements Principle

Requires Environment

Page Connections

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