跳轉到

回測引擎

oneshot 回測器。用法見回測。

cjtrade.pkgs.analytics.backtest.engine

pkgs/analytics/backtest/engine.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Vectorised (one-shot) backtest engine.

Receives a pre-fetched list of Kbar objects, runs a BaseStrategy over them bar-by-bar with a simulated account, and returns a BacktestResult – all in memory, no HTTP, no time progression.

Usage
from cjtrade.pkgs.analytics.backtest.engine import BacktestEngine
from my_strategy import BollingerStrategy

engine = BacktestEngine(
    kbars=kbars,          # List[Kbar] for one symbol
    symbol="2330",
    initial_balance=1_000_000,
    params={"bb_window": 20, "bb_min_width_pct": 0.01},
)
result = engine.run(BollingerStrategy())
BacktestReport(result).full_report()
Multi-symbol
For multi-symbol backtests, pass a merged & time-sorted list of Kbar
objects with different .symbol attributes and set symbol=None.
The engine will split them internally.

BacktestEngine(kbars, symbol=None, initial_balance=1000000.0, params=None, session_id=None, cost_model=None)

One-shot backtest engine.

Parameters:

Name Type Description Default
kbars list[Kbar]

Pre-fetched bars; the engine sorts them ascending by timestamp. May contain multiple symbols – the engine splits them automatically.

required
symbol str

If provided, every bar is tagged with this symbol before running (overriding the bar's own symbol). Leave as None to pass all symbols to the strategy.

None
initial_balance float

Starting cash in TWD.

1000000.0
params dict

Passed verbatim as ctx.params to every strategy call.

None
session_id str

Stored in the returned BacktestResult for traceability.

None
cost_model CostModel

Commission, tax and slippage model; defaults to CostModel().

None

Raises:

Type Description
ValueError

If any bar has no symbol after tagging.

Source code in src/cjtrade/pkgs/analytics/backtest/engine.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def __init__(
    self,
    kbars: List[Kbar],
    symbol: Optional[str] = None,
    initial_balance: float = 1_000_000.0,
    params: Optional[Dict[str, Any]] = None,
    session_id: Optional[str] = None,
    cost_model: Optional[CostModel] = None,
) -> None:
    # `symbol` overrides whatever the bars carry — a single-symbol caller
    # may have fetched them from a source that left it blank.
    if symbol:
        kbars = [k.tagged(symbol) for k in kbars]

    # Every strategy reads bar.symbol, so an untagged bar would silently
    # look up price history under "".
    missing = sum(1 for k in kbars if not k.symbol)
    if missing:
        raise ValueError(
            f"{missing}/{len(kbars)} kbars have no symbol. Pass symbol= for a "
            f"single-symbol run, or tag them before merging."
        )

    self.kbars = sorted(kbars, key=lambda k: k.timestamp)
    # import time
    # time.sleep(50)
    self.symbol = symbol
    self.initial_balance = initial_balance
    self.params = params or {}
    self.session_id = session_id
    self._account = _SimAccount(initial_balance, cost_model or CostModel())

run(strategy)

Run the strategy over all bars and return a BacktestResult.

Raises:

Type Description
ValueError

If there are no bars.

Source code in src/cjtrade/pkgs/analytics/backtest/engine.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def run(self, strategy: BaseStrategy) -> BacktestResult:
    """Run the strategy over all bars and return a BacktestResult.

    Raises
    ------
    ValueError
        If there are no bars.
    """
    if not self.kbars:
        raise ValueError("kbars list is empty – nothing to backtest.")

    log.info("run start: n=%d bars, session_id=%s", len(self.kbars), self.session_id)

    account    = self._account
    price_map: Dict[str, float] = {}   # latest price per symbol
    price_hist: Dict[str, List[float]] = {}
    equity_curve: List[Dict] = []

    # Initial context (before first bar)
    init_ctx = StrategyContext(
        timestamp=self.kbars[0].timestamp,
        balance=account.balance,
        equity=account.initial_balance,
        positions=[],
        price_history={},
        bar_index=0,
        params=self.params,
    )
    strategy.on_start(init_ctx)

    for idx, bar in enumerate(self.kbars):
        sym = bar.symbol

        # Update price map
        price_map[sym] = bar.close
        price_hist.setdefault(sym, []).append(bar.close)

        # Build context
        # Avoid copying entire price_hist every bar (O(n²) complexity)
        # Create a shallow reference to price_hist; each list is still mutable,
        # so strategy sees live prices, but we don't deep-copy every iteration
        ctx = StrategyContext(
            timestamp=bar.timestamp,
            balance=account.balance,
            equity=account.equity(price_map),
            positions=account.positions_list(price_map),
            price_history=price_hist,  # Direct reference, not a deep copy
            bar_index=idx,
            params=self.params,
        )

        # Ask strategy for signals
        signals: List[Signal] = strategy.on_bar(bar, ctx) or []

        # Execute signals
        for sig in signals:
            if sig.action == "BUY":
                fill = account.buy(sig.symbol, sig.quantity, sig.price,
                                   bar.timestamp, reason=sig.reason)
                if fill:
                    strategy.on_fill(fill, ctx)
            elif sig.action == "SELL":
                fill = account.sell(sig.symbol, sig.quantity, sig.price,
                                    bar.timestamp, reason=sig.reason)
                if fill:
                    strategy.on_fill(fill, ctx)

        # Record equity point (once per minute, deduped)
        minute_key = bar.timestamp.replace(second=0, microsecond=0).isoformat()
        if not equity_curve or equity_curve[-1]["time"] != minute_key:
            equity_curve.append({
                "time":  minute_key,
                "value": account.equity(price_map),
            })

    # Final context
    final_ctx = StrategyContext(
        timestamp=self.kbars[-1].timestamp,
        balance=account.balance,
        equity=account.equity(price_map),
        positions=account.positions_list(price_map),
        price_history=price_hist,  # Direct reference, not a deep copy
        bar_index=len(self.kbars) - 1,
        params=self.params,
    )
    strategy.on_end(final_ctx)

    final_equity = account.equity(price_map)
    log.info(
        f"run done: {len(self.kbars)} bars, "
        f"{len(account.fill_history)} fills, "
        f"equity {account.initial_balance:,.0f} -> {final_equity:,.0f}"
    )

    return BacktestResult(
        initial_balance=account.initial_balance,
        final_balance=account.balance,
        equity_curve=equity_curve,
        fill_history=account.fill_history,
        session_id=self.session_id,
        start_time=self.kbars[0].timestamp.isoformat() if self.kbars else None,
        final_equity=final_equity,
    )