Implementation:24mlight A Share investment Agent Backtester
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Finance, Backtesting |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Concrete tool for systematic backtesting that iterates over business days calling the full analysis workflow with rate limiting, trade execution, and performance reporting, provided by the A_Share_investment_Agent repository.
Description
The Backtester class orchestrates the backtesting loop. Key methods:
__init__: Initializes portfolio, logging, validates inputs (requires agent callable)_rate_limit: Window-based rate limiter (max 8 calls/60s, 6s min interval)_get_agent_decision: Callsrun_hedge_fundwith rate limiting and retry (3 attempts)_execute_trade: Executes buy/sell with cash constraint checkingrun_backtest: Main loop over business days with look-ahead bias preventionanalyze_performance: Computes returns, generates matplotlib charts
Usage
Import when you need to:
- Backtest the full investment analysis workflow over historical data
- Measure portfolio performance with realistic execution constraints
Code Reference
Source Location
- Repository: A_Share_investment_Agent
- File: src/backtester.py
- Lines: L53-605 (class), L54-76 (__init__), L155-176 (_rate_limit), L178-243 (_get_agent_decision), L257-278 (_execute_trade), L280-452 (run_backtest), L455-523 (analyze_performance)
Signature
class Backtester:
def __init__(
self,
config: BacktestConfig,
*,
agent: Optional[Callable[..., Any]] = None,
) -> None:
"""Initialize backtester with config and agent callable."""
def _rate_limit(self) -> None:
"""Window-based rate limiter: max 8 calls/60s, 6s min interval."""
def _get_agent_decision(self, current_date: str, lookback_start: str) -> Dict[str, Any]:
"""Call agent with rate limiting and retry. Returns {decision, analyst_signals, raw_response}."""
def _execute_trade(self, action: str, quantity: int, current_price: float) -> int:
"""Execute buy/sell with cash constraint checking. Returns executed quantity."""
def run_backtest(self) -> None:
"""Main backtest loop over business days."""
def analyze_performance(self) -> pd.DataFrame:
"""Compute returns and generate performance charts."""
Import
from src.backtester import Backtester, BacktestConfig
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| config | BacktestConfig | Yes | Frozen config dataclass |
| agent | Callable | Yes | Typically run_hedge_fund |
Outputs
| Name | Type | Description |
|---|---|---|
| portfolio_values | list[dict] | {Date, Portfolio Value, Daily Return} per trading day |
| performance_df | DataFrame | Indexed by Date with Portfolio Value, Daily Return, Cumulative Return |
| backtest_plot.png | File | Saved chart in backtest run directory |
Usage Examples
Full Backtest Run
from src.backtester import Backtester, BacktestConfig
from src.main import run_hedge_fund
config = BacktestConfig(
ticker="002848",
start_date="2025-01-01",
end_date="2025-06-01",
initial_capital=100000.0,
initial_position=0,
num_of_news=5,
decision_interval=1,
)
backtester = Backtester(config, agent=run_hedge_fund)
backtester.run_backtest()
performance = backtester.analyze_performance()
print(f"Total return: {performance['Cumulative Return'].iloc[-1]:.2f}%")
CLI Execution
# From command line:
# uv run python src/backtester.py --ticker 002074 --start-date 2025-10-01 --end-date 2025-11-15
Related Pages
Implements Principle
Requires Environment
Uses Heuristics
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment