backtrader.reports package¶
Report generation module.
Provides backtest report generation functionality, including: - PerformanceCalculator: Performance metrics calculation - ReportChart: Report-specific chart generation - ReportGenerator: Main report generator
- Usage example:
import backtrader as bt from backtrader.reports import ReportGenerator, PerformanceCalculator
# Run strategy cerebro = bt.Cerebro() cerebro.addstrategy(MyStrategy) cerebro.adddata(data) results = cerebro.run()
# Method 1: Generate report report = ReportGenerator(results[0]) report.generate_html('report.html') report.generate_pdf('report.pdf')
# Method 2: Get metrics only calc = PerformanceCalculator(results[0]) metrics = calc.get_all_metrics() print(metrics['sharpe_ratio'])
- class backtrader.reports.PerformanceCalculator[源代码]¶
基类:
objectUnified performance metrics calculator.
Extracts and calculates all performance metrics from strategies and analyzers, including: - PnL metrics: total return, annual return, cumulative return - Risk metrics: max drawdown, Sharpe ratio, SQN, Calmar ratio - Trade statistics: win rate, profit/loss ratio, average profit/loss
- strategy¶
Strategy instance
- Usage example:
calc = PerformanceCalculator(strategy) metrics = calc.get_all_metrics() print(f"Sharpe ratio: {metrics['sharpe_ratio']}") print(f"SQN rating: {metrics['sqn_human']}")
- __init__(strategy)[源代码]¶
Initialize the performance calculator.
- 参数:
strategy -- backtrader strategy instance (result from run())
- get_all_metrics()[源代码]¶
Return dictionary of all performance metrics.
- 返回:
Dictionary containing all performance metrics
- 返回类型:
- get_equity_curve()[源代码]¶
Get equity curve data.
- 返回:
(dates, values) Lists of dates and equity values
- 返回类型:
- get_buynhold_curve()[源代码]¶
Get buy-and-hold comparison curve.
- 返回:
(dates, values) Lists of dates and buy-and-hold values
- 返回类型:
- static sqn_to_rating(sqn_score)[源代码]¶
Convert SQN score to human-readable rating.
Reference: http://www.vantharp.com/tharp-concepts/sqn.asp
- 参数:
sqn_score -- SQN score
- 返回:
Human-readable rating
- 返回类型:
- class backtrader.reports.ReportChart[源代码]¶
基类:
objectReport-specific chart generator.
Generates static charts for reports, including: - Equity curve chart (with buy-and-hold comparison line) - Return bars chart (automatic period detection) - Drawdown area chart
- figsize¶
Default chart size
- dpi¶
Chart resolution
- __init__(figsize=(10, 3), dpi=100)[源代码]¶
Initialize the chart generator.
- 参数:
figsize -- Chart size (width, height)
dpi -- Chart resolution
- plot_equity_curve(dates, values, benchmark_dates=None, benchmark_values=None, title='Equity Curve')[源代码]¶
Plot equity curve chart.
- 参数:
dates -- List of dates
values -- List of equity values
benchmark_dates -- List of benchmark dates (optional)
benchmark_values -- List of benchmark values (optional, e.g., buy-and-hold)
title -- Chart title
- 返回:
matplotlib.figure.Figure or None
- plot_return_bars(dates, values, period='auto', title=None)[源代码]¶
Plot return bars chart.
- 参数:
dates -- List of dates
values -- List of equity values
period -- Period ('auto', 'daily', 'weekly', 'monthly', 'yearly')
title -- Chart title
- 返回:
matplotlib.figure.Figure or None
- plot_drawdown(dates, values, title='Drawdown')[源代码]¶
Plot drawdown area chart.
- 参数:
dates -- List of dates
values -- List of equity values
title -- Chart title
- 返回:
matplotlib.figure.Figure or None
- save_to_file(fig, filename, format='png')[源代码]¶
Save chart to file.
- 参数:
fig -- matplotlib figure object
filename -- Output filename
format -- Image format ('png', 'jpg', 'svg', 'pdf')
- class backtrader.reports.ReportGenerator[源代码]¶
基类:
objectMain report generator.
Generates backtest reports in HTML, PDF, and JSON formats.
- strategy¶
Strategy instance
- calculator¶
Performance calculator
- charts¶
Chart generator
- Usage example:
report = ReportGenerator(strategy) report.generate_html('report.html') report.generate_pdf('report.pdf') report.generate_json('report.json')
- __init__(strategy, template='default')[源代码]¶
Initialize the report generator.
- 参数:
strategy -- backtrader strategy instance
template -- Template name or template string
- generate_html(output_path, user=None, memo=None, **kwargs)[源代码]¶
Generate HTML report.
- 参数:
output_path -- Output file path
user -- Username
memo -- Notes
**kwargs -- Additional template variables
- 返回:
Output file path
- 返回类型:
- generate_pdf(output_path, user=None, memo=None, **kwargs)[源代码]¶
Generate PDF report.
- 参数:
output_path -- Output file path
user -- Username
memo -- Notes
**kwargs -- Additional template variables
- 返回:
Output file path
- 返回类型:
Submodules¶
- backtrader.reports.charts module
- backtrader.reports.performance module
PerformanceCalculatorPerformanceCalculator.strategyPerformanceCalculator.__init__()PerformanceCalculator.get_all_metrics()PerformanceCalculator.get_pnl_metrics()PerformanceCalculator.get_risk_metrics()PerformanceCalculator.get_trade_metrics()PerformanceCalculator.get_kpi_metrics()PerformanceCalculator.get_equity_curve()PerformanceCalculator.get_buynhold_curve()PerformanceCalculator.sqn_to_rating()PerformanceCalculator.get_strategy_info()PerformanceCalculator.get_data_info()
- backtrader.reports.reporter module