Environment:AI4Finance Foundation FinRobot BackTrader
| Knowledge Sources | |
|---|---|
| Domains | Infrastructure, Quantitative_Trading, Backtesting |
| Last Updated | 2026-10-19 00:00 GMT |
Overview
Python 3.11+ environment with the optional BackTrader backtesting library and matplotlib (Agg backend) for equity-curve chart rendering, required only by the backtest adapter.
Description
This environment layers the Python_3_11 base stack with the `backtrader` package — a synchronous, callback-heavy event-driven backtesting framework. BackTrader is an optional extra (`finrobot[backtest]`) rather than a core dependency, because the rest of FinRobot (valuation, data, RAG, server) has no need for it.
The BackTraderAdapter wraps BackTrader's synchronous API into an async interface via `asyncio.to_thread`, configures the SharpeRatio analyzer for daily bars (annualized, factor=252) to avoid the default yearly-resample bug that yields `None` on ~1yr windows, forces the matplotlib `Agg` backend (so `cerebro.plot()` cannot pop a GUI window from a server/headless process), and generates an equity-curve PNG base64-encoded into the typed `BacktestResult`.
Usage
Use this environment only when running the BackTraderAdapter_run implementation — i.e. the Strategy_Backtest workflow (deterministic mode via `BackTraderAdapter.run(config)` or auto mode via `run_strategy_selection`). No other workflow or compute operator requires BackTrader. Install it with `pip install 'finrobot[backtest]'`.
System Requirements
| Category | Requirement | Notes |
|---|---|---|
| OS | Linux / macOS / Windows | Same as base Python env |
| Hardware | Any modern CPU | Backtest is CPU-bound; no GPU needed |
| Disk | +50MB for backtrader + matplotlib | On top of the base Python env |
| Display | None (headless-safe) | matplotlib `Agg` backend is forced; no GUI window |
Dependencies
System Packages
- All packages from Python_3_11
Python Packages
- `backtrader` >= 1.9 (optional extra: `finrobot[backtest]`)
- `matplotlib` >= 3.8 (core dep, but load-bearing here for `Agg` equity-curve PNG)
Credentials
No additional credentials beyond the base Python_3_11 environment. Price bars come from the injected `DataLayer` (which uses yfinance/FMP), not a BackTrader-specific data feed.
Quick Install
# Install the backtest extra on top of the base environment
pip install 'finrobot[backtest]'
# Or from source (editable dev install with backtest extra)
cd finrobot_desktop
pip install -e '.[backtest]'
Code Evidence
Optional-extra declaration from `pyproject.toml:44-45`:
[project.optional-dependencies]
backtest = ["backtrader>=1.9"]
Import guard raising a helpful message from `backtrader_adapter.py:72-80`:
def _check_backtrader() -> None:
"""Raise ImportError with a helpful message if backtrader is not installed."""
try:
import backtrader # noqa: F401
except ImportError:
raise ImportError(
"backtrader is required for backtesting. "
"Install it with: pip install 'finrobot[backtest]'"
) from None
Forced Agg backend to prevent a GUI window from a server process from `backtrader_adapter.py:38-48`:
try:
import matplotlib
# force=True so we win even if another module already imported
# matplotlib.pyplot and locked in an interactive backend (e.g. macosx on
# macOS). Without force a plain use("Agg") is a no-op once pyplot is loaded,
# letting cerebro.plot() pop up a GUI window (BUG-069).
matplotlib.use("Agg", force=True)
except ImportError:
pass
Daily SharpeRatio configuration (annualized) avoiding the default yearly-resample `None` bug from `backtrader_adapter.py:157-161`:
cerebro.addanalyzer(
bt.analyzers.SharpeRatio,
_name="sharpe",
riskfreerate=config.risk_free_rate,
# timeframe=Days, annualize=True, factor=252 — see BUG-019
timeframe=bt.TimeFrame.Days, compression=1,
annualize=True, factor=252,
)
Common Errors
| Error Message | Cause | Solution |
|---|---|---|
| `backtrader is required for backtesting. Install it with: pip install 'finrobot[backtest]'` | `backtrader` not installed | `pip install 'finrobot[backtest]'` |
| `SMA crossover requires fast (X) < slow (Y)` | Strategy params have `fast >= slow` | Swap the values so `fast < slow` |
| `Backtest models US-equity T+0 zero-friction execution only; A-share/HK tickers ... are rejected` | Non-US-equity ticker passed (BUG-068) | Use a US-equity ticker; A-share/HK constraints (T+1, price limits, stamp duty, halts) are unmodeled |
| SharpeRatio returns `None` | Default `timeframe=Years` resamples daily returns to yearly → ~1 point (BUG-019) | Adapter already sets `timeframe=Days, annualize=True, factor=252`; do not override |
| GUI window pops up during `cerebro.plot()` | Interactive matplotlib backend locked in before import (BUG-069) | Adapter calls `matplotlib.use("Agg", force=True)`; ensure no earlier `pyplot` import in your process |
Compatibility Notes
- Optional install: BackTrader is NOT a core dependency. The base `pip install finrobot` works for all valuation/RAG/server workflows; only backtesting needs the extra.
- mypy strict: BackTrader exposes `Strategy` as `Any`, so `disallow_subclassing_any = false` is configured for `finrobot.engine.backtest.backtrader_adapter` (`pyproject.toml:124-126`); the adapter otherwise runs under `strict = true`.
- US-equity only: The adapter rejects A-share/HK tickers (BUG-068) because T+1 settlement, price limits, stamp duty, and halts are unmodeled — it raises rather than warn to avoid producing untrustworthy equity curves.
- Coverage exclusion: `backtrader_adapter.py` is omitted from coverage runs (`pyproject.toml:89`) as an optional-extra surface exercised via integration tests.
- Headless-safe: matplotlib `Agg` is forced with `force=True` so a server/headless process never attempts to open a display.