Backtest engine¶
The oneshot backtester. See Backtesting for usage.
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 |
None
|
session_id
|
str
|
Stored in the returned BacktestResult for traceability. |
None
|
cost_model
|
CostModel
|
Commission, tax and slippage model; defaults to |
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 | |
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 | |