backtrader.observer module

Observer Module - Strategy monitoring and data collection.

This module provides the Observer base class for monitoring strategy execution and collecting data during backtesting. Observers track metrics like cash, value, drawdown, and trade statistics.

Observers are similar to indicators but are used primarily for monitoring and recording strategy state rather than generating trading signals.

Key Classes:

Observer: Base class for all observers.

Observers receive the same notifications as strategies:
  • prenext/nextstart/next: Called during each bar

  • start/stop: Called at the beginning and end of backtesting

示例

Creating a custom observer: >>> class MyObserver(Observer): ... lines = ('custom_metric',) ... ... def next(self): ... self.lines.custom_metric[0] = self.data.close[0] * 2

class backtrader.observer.Observer[源代码]

基类:ObserverBase

Base class for monitoring strategy execution.

Observers track and record strategy state during backtesting. They can track metrics like cash, value, drawdown, positions, etc.

csv

Whether to save observer data to CSV (default: True).

plotinfo

Plotting configuration dictionary.

示例

>>> observer = MyObserver()
>>> cerebro.addobserver(observer)
csv = True
plotinfo = <backtrader.metabase.plotinfo_obj object>
__init__(*args, **kwargs)

Wrapped __init__ that properly handles observer initialization

prenext()[源代码]

Process bars before minimum period is reached.

By default, observers always process every bar by calling next() even during the prenext phase. Subclasses can override this behavior.

备注

This default implementation calls next() to ensure observers track all bars from the beginning.

start()[源代码]

Called at the start of the backtesting run.

This method can be overridden by subclasses to perform initialization at the start of strategy execution.

frompackages = ()
packages = ()