Skip to content

Running Backtests

Overview

Item Description
Goal Master the three backtest interfaces
Prerequisite Writing Strategies

1. Running Backtests

One-stop backtest execution with automatic report generation.

result = run_strategy(
    initialize,
    start_date='2024-01-01',
    end_date='2024-12-31',
    starting_cash=100000,
    benchmark='000300.XSHG',
    securities=['601390', '600519'],
    report_dir='reports',
)

1.2 run_backtest (Fine-grained Control)

Runs the backtest only, without generating reports.

result = run_backtest(
    initialize,
    start_date='2024-01-01',
    end_date='2024-12-31',
    starting_cash=100000,
)

1.3 run_portfolio_backtest (Portfolio Backtest)

High-level interface for multi-stock portfolio backtesting.

from eqlib import (
    StrategyConfig, run_portfolio_backtest,
    attribute_history, order_value, order_target,
)

config = StrategyConfig(
    starting_cash=200000,
    securities=["601390", "600519", "000858"],
    benchmark="000300.XSHG",
    position_pct=0.33,
    start_date="2024-01-01",
    end_date="2024-12-31",
    report_suffix="momentum_v1",
)

def my_strategy(context):
    for sec in context.universe:
        hist = attribute_history(sec, 25, "1d", ["close"])
        if hist.empty:
            continue
        ma20 = hist["close"].tail(20).mean()
        price = hist["close"].iloc[-1]
        if price > ma20 * 1.02:
            order_value(sec, context.portfolio.available_cash)
        elif price < ma20 * 0.98 and context.portfolio.positions.get(sec):
            order_target(sec, 0)

result = run_portfolio_backtest(config, my_strategy, report_dir="reports")

1.4 Return Value Structure

All three interfaces return a result dict. Commonly used keys:

Key Content
context Backtest context; result['context'].portfolio holds final positions and cash
trade_log List of executed trades (date, security, side, price, amount, commission)
recorded_values Daily records sorted by date (total value, custom record() fields)
benchmark Benchmark code
benchmark_values Benchmark daily close series (used for alpha/beta and charts)

The portfolio backtest adds a config key (the input config, echoed back).

final_value = result['context'].portfolio.total_value
for trade in result['trade_log'][:5]:
    print(trade['date'], trade['security'], trade['type'], trade['price'])

1.5 Benchmark Comparison

Set the benchmark via the benchmark parameter (defaults to 000300.XSHG, the CSI 300 Index). The results will automatically calculate alpha, beta, and information ratio.


For complete parameter documentation, see Backtest Engine API Reference.