Analyzer Plugins¶
An analyzer plugin listens to bars and fills during a backtest and produces a custom analysis at the end, stored in result.analyzer_outputs. Use it for statistics the built-in metrics don't cover — fills by time of day, how often a condition occurred — without touching strategy code.
Minimal example¶
import akquant as aq
class TradeCounter:
name = "trade_counter"
def __init__(self):
self.bars = 0
self.trades = 0
def on_start(self, context):
pass
def on_bar(self, context):
self.bars += 1
def on_trade(self, context):
self.trades += 1
def on_finish(self, context):
return {"bars": self.bars, "trades": self.trades}
result = aq.run_backtest(
data=df,
strategy=MyStrategy,
symbols="600000",
analyzer_plugins=[TradeCounter()],
)
print(result.analyzer_outputs) # {"trade_counter": {"bars": ..., "trades": ...}}
analyzer_plugins must be a list or tuple. Pass fresh plugin instances to each backtest, since plugins accumulate state.
Plugin protocol¶
class AnalyzerPlugin(Protocol):
name: str
def on_start(self, context: dict[str, Any]) -> None: ...
def on_bar(self, context: dict[str, Any]) -> None: ...
def on_trade(self, context: dict[str, Any]) -> None: ...
def on_finish(self, context: dict[str, Any]) -> dict[str, Any]: ...
- All four methods and
nameare required; otherwiserun_backtestraisesTypeErrorbefore starting. - The return value of
on_finishis stored inresult.analyzer_outputsundername; a later plugin with the same name overwrites an earlier one. akquant.analyzer_plugin.AnalyzerTemplateis a ready-to-copy template (it counts fills asseen_trades).
Callback timing and context¶
| Callback | When | context keys |
|---|---|---|
on_start |
Once, before the data loop | engine, strategy, strategies, slot_strategy_map, symbols |
on_bar |
After the strategy callback for each bar (not during warmup, see below) | strategy, bar, engine, ctx, owner_strategy_id |
on_trade |
For each fill | strategy, trade, engine, ctx, owner_strategy_id |
on_finish |
Once, after the backtest result is built | engine, strategy, strategies, slot_strategy_map, result |
strategyis the main strategy instance; with multiple strategies,strategiesholds all instances,slot_strategy_mapmaps strategy id to instance, andowner_strategy_idis the id the callback belongs to.- The
resultpassed toon_finishis theBacktestResultabout to be returned; you can read its trades, equity curve and so on. - With multiple strategies, all strategies share the same plugins: each bar and each fill triggers a callback once per owning strategy; use
owner_strategy_idto tell them apart. - Only bars trigger
on_bar; ticks do not.
When a plugin fails¶
Plugins are isolated from each other: if one plugin's callback raises, only that call is skipped; other plugins still receive the same callback and the backtest continues.
- The first error per plugin and callback is logged at error level with a traceback; later errors of the same kind are only counted, and one summary line ("N more exceptions suppressed") is logged when the backtest ends.
- A plugin whose
on_finishfails is left out ofresult.analyzer_outputs; other plugins' outputs are kept.
Known limitations¶
- Backtest only:
run_livedoes not acceptanalyzer_plugins. - No automatic discovery: plugins must be passed in
analyzer_pluginsexplicitly; registration through package entry points is not supported. - During warmup
on_bardoes not reach analyzers, buton_tradedoes.Strategy.warmup_periodis counted per symbol; while a symbol has fewer bars thanwarmup_period, the engine returns before callingon_bar, whereason_tradegoes through the separate order-event path and is not gated. Plugins that use the number ofon_barcalls as a denominator or index will therefore under-count or misalign with multiple symbols and warmup. Count per symbol instead (accumulate bycontext["bar"].symbolinon_barandcontext["trade"].symbolinon_trade), and don't rely on the two callbacks staying in step.