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[source]

Bases: object

Unified 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)[source]

Initialize the performance calculator.

Parameters:

strategy – backtrader strategy instance (result from run())

get_all_metrics()[source]

Return dictionary of all performance metrics.

Returns:

Dictionary containing all performance metrics

Return type:

dict

get_pnl_metrics()[source]

Get profit and loss related metrics.

Returns:

PnL metrics dictionary

Return type:

dict

get_risk_metrics()[source]

Get risk-related metrics.

Returns:

Risk metrics dictionary

Return type:

dict

get_trade_metrics()[source]

Get trade statistics metrics.

Returns:

Trade statistics dictionary

Return type:

dict

get_kpi_metrics()[source]

Get key performance indicators.

Returns:

KPI metrics dictionary

Return type:

dict

get_equity_curve()[source]

Get equity curve data.

Returns:

(dates, values) Lists of dates and equity values

Return type:

tuple

get_buynhold_curve()[source]

Get buy-and-hold comparison curve.

Returns:

(dates, values) Lists of dates and buy-and-hold values

Return type:

tuple

static sqn_to_rating(sqn_score)[source]

Convert SQN score to human-readable rating.

Reference: http://www.vantharp.com/tharp-concepts/sqn.asp

Parameters:

sqn_score – SQN score

Returns:

Human-readable rating

Return type:

str

get_strategy_info()[source]

Get strategy information.

Returns:

Strategy information dictionary

Return type:

dict

get_data_info()[source]

Get data information.

Returns:

Data information dictionary

Return type:

dict

class backtrader.reports.ReportChart[source]

Bases: object

Report-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)[source]

Initialize the chart generator.

Parameters:
  • figsize – Chart size (width, height)

  • dpi – Chart resolution

plot_equity_curve(dates, values, benchmark_dates=None, benchmark_values=None, title='Equity Curve')[source]

Plot equity curve chart.

Parameters:
  • 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

Returns:

matplotlib.figure.Figure or None

plot_return_bars(dates, values, period='auto', title=None)[source]

Plot return bars chart.

Parameters:
  • dates – List of dates

  • values – List of equity values

  • period – Period (‘auto’, ‘daily’, ‘weekly’, ‘monthly’, ‘yearly’)

  • title – Chart title

Returns:

matplotlib.figure.Figure or None

plot_drawdown(dates, values, title='Drawdown')[source]

Plot drawdown area chart.

Parameters:
  • dates – List of dates

  • values – List of equity values

  • title – Chart title

Returns:

matplotlib.figure.Figure or None

save_to_file(fig, filename, format='png')[source]

Save chart to file.

Parameters:
  • fig – matplotlib figure object

  • filename – Output filename

  • format – Image format (‘png’, ‘jpg’, ‘svg’, ‘pdf’)

to_base64(fig, format='png')[source]

Convert chart to base64 encoding.

Parameters:
  • fig – matplotlib figure object

  • format – Image format

Returns:

base64 encoded image data

Return type:

str

close_all()[source]

Close all charts and release memory.

class backtrader.reports.ReportGenerator[source]

Bases: object

Main 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')[source]

Initialize the report generator.

Parameters:
  • strategy – backtrader strategy instance

  • template – Template name or template string

generate_html(output_path, user=None, memo=None, **kwargs)[source]

Generate HTML report.

Parameters:
  • output_path – Output file path

  • user – Username

  • memo – Notes

  • **kwargs – Additional template variables

Returns:

Output file path

Return type:

str

generate_pdf(output_path, user=None, memo=None, **kwargs)[source]

Generate PDF report.

Parameters:
  • output_path – Output file path

  • user – Username

  • memo – Notes

  • **kwargs – Additional template variables

Returns:

Output file path

Return type:

str

generate_json(output_path, indent=2, **kwargs)[source]

Generate JSON report.

Parameters:
  • output_path – Output file path

  • indent – JSON indentation

  • **kwargs – Additional data

Returns:

Output file path

Return type:

str

get_metrics()[source]

Get all performance metrics.

Returns:

Performance metrics dictionary

Return type:

dict

print_summary()[source]

Print performance summary to console.

Submodules