Skip to main content

Weight-based backtesting engine for quantitative trading

Project description

wbt Python Package

Python API for the wbt Rust backtesting engine.

中文文档

Development Objectives

This Python subproject aims to provide a practical research-facing interface for weight-based backtesting while keeping the heavy computation in Rust.

Design priorities:

  1. Keep data input flexible for common research formats.
  2. Return analysis-friendly outputs as pandas objects.
  3. Preserve one consistent metric schema across stats outputs.
  4. Provide plotting utilities that work directly on backtest outputs.

Project Layout

This directory is an independent Python subproject.

python/
|-- pyproject.toml
|-- README.md
|-- scripts/
|-- tests/
`-- wbt/

The Rust crate remains one level up at ../Cargo.toml. maturin builds the extension module from there.

Installation And Local Setup

Requirements:

  • Rust toolchain
  • Python 3.10+
  • uv

Setup:

cd python
uv sync --extra dev
uv run maturin develop --release

Quick Start

import pandas as pd
from wbt import WeightBacktest

df = pd.DataFrame(
    {
        "dt": [
            "2024-01-02 09:01:00",
            "2024-01-02 09:02:00",
            "2024-01-02 09:03:00",
            "2024-01-02 09:04:00",
        ],
        "symbol": ["AAPL", "AAPL", "AAPL", "AAPL"],
        "weight": [0.5, 0.2, 0.0, -0.3],
        "price": [185.0, 186.0, 186.5, 184.5],
    }
)

wb = WeightBacktest(
    df,
    digits=2,
    fee_rate=0.0002,
    n_jobs=4,
    weight_type="ts",   # "ts" or "cs"
    yearly_days=252,
)

print("all:", wb.stats)
print("long:", wb.long_stats)
print("short:", wb.short_stats)

print(wb.daily_return.head())
print(wb.dailys.head())
print(wb.pairs.head())

print(wb.segment_stats("2024-01-01", "2024-12-31", kind="多空"))
print(wb.long_alpha_stats)

Accepted Inputs

The data argument accepts:

  • pandas.DataFrame
  • polars.DataFrame
  • polars.LazyFrame
  • file path as str or Path

Supported file formats from path input:

  • csv
  • parquet
  • feather
  • arrow

Required columns:

Column Type Meaning
dt datetime-like Bar end time
symbol str Instrument code
weight float Target position weight
price float Price used for return calculation

Notes:

  • Null values are not allowed.
  • weight is rounded by digits before backtest.

Main API Surface

Top-level imports (all reachable from import wbt):

from wbt import (
    # Backtest engine
    WeightBacktest, backtest,
    # Performance metrics (Rust-backed)
    daily_performance,
    top_drawdowns,
    rolling_daily_performance,
    cal_yearly_days,
    # Strategy utilities (pure Python)
    weights_simple_ensemble,
    cal_trade_price,
    log_strategy_info,
    # Reporting
    generate_backtest_report,
    # Test data
    mock_symbol_kline, mock_weights,
)

Primary class and helpers:

  • WeightBacktest(...): main backtest engine entry.
  • backtest(...): convenience wrapper returning a WeightBacktest.
  • daily_performance(returns, yearly_days=252): standalone metric utility on a daily-return array.
  • top_drawdowns(returns, top=10): top-N drawdown windows.
  • rolling_daily_performance(df, ret_col, window=252, min_periods=100, yearly_days=None): rolling-window daily performance.
  • cal_yearly_days(dts): infer yearly trading-day count from a date series.
  • weights_simple_ensemble(df, weight_cols, method="mean", only_long=False, **kwargs): ensemble multiple strategy weights (mean / vote / sum_clip).
  • cal_trade_price(df, digits=None, windows=(5, 10, 15, 20, 30, 60)): TWAP / VWAP and next-bar trade-price table grouped by symbol.
  • log_strategy_info(strategy, df): pretty-print per-symbol weight summaries via loguru.
  • generate_backtest_report(wb, output_path): render a self-contained HTML report.
  • mock_symbol_kline(...) / mock_weights(...): generators for quick experiments.

Core WeightBacktest properties and methods:

  • stats, long_stats, short_stats
  • daily_return, long_daily_return, short_daily_return
  • dailys, pairs
  • alpha, alpha_stats, bench_stats
  • segment_stats(sdt, edt, kind)
  • long_alpha_stats
  • get_symbol_daily(symbol), get_symbol_pairs(symbol)

Logging Note

cal_yearly_days and rolling_daily_performance emit warnings from Rust (e.g. short-span fallback) via the log crate. The package initializes pyo3-log at module load, so those warnings show up through Python's standard logging. If you use loguru, install an InterceptHandler once to route them into your loguru sinks.

Plotting Utilities

All plotting functions are single-purpose figures that consume a BacktestResult (from wb.to_result()) with zero data transformation — each field maps straight to a plotly trace. There are no composite (subplot) charts; the HTML report composes single figures into a CSS grid instead.

from wbt.plotting import (
    plot_colored_table,        # stats as a colored table
    plot_cumulative_returns,   # cumulative curves (voladj=True for vol-normalized)
    plot_daily_return_dist,    # daily-return histogram
    plot_drawdown,             # drawdown + cumulative (dual-axis single figure)
    plot_drawdowns_table,      # top-drawdowns detail table
    plot_key_trades,           # yearly best/worst key trades
    plot_monthly_heatmap,      # monthly-return heatmap
    plot_pairs_hold_dist,      # holding-bars distribution by direction
    plot_pairs_pnl_dist,       # pnl-ratio distribution by direction
    plot_stats_comparison,     # 多空/多头/空头/基准/超额 metric comparison table
    plot_symbol_returns,       # per-symbol cumulative returns
    plot_verdict,              # is_good_strategy verdict + yearly metrics
)

Typical usage:

result = wb.to_result()

fig1 = plot_cumulative_returns(result, keys=["多空", "多头", "空头", "基准"])
fig2 = plot_cumulative_returns(result, voladj=True)   # vol-normalized
fig3 = plot_drawdown(result)
fig4 = plot_pairs_pnl_dist(result)

# Optional HTML export
html = plot_cumulative_returns(result, to_html=True)

# Full HTML report file (composes single figures into a tabbed CSS grid)
generate_backtest_report(df, "report.html")

Quality And Testing

Run checks from python/:

uv run pytest -v
uv run ruff format --check .
uv run ruff check . --no-fix
uv run basedpyright

Architecture Snapshot

repo-root/
|-- Cargo.toml
|-- src/
|   |-- lib.rs                       # PyO3 bindings (pyfunctions, _wbt pymodule)
|   `-- core/
|       |-- cal_yearly_days.rs       # Rust core for cal_yearly_days
|       |-- daily_performance.rs
|       |-- rolling_daily_performance.rs
|       |-- top_drawdowns.rs
|       `-- ...                      # backtest engine internals
`-- python/
    `-- wbt/
        |-- __init__.py              # top-level exports
        |-- _df_convert.py           # pandas <-> Arrow IPC helpers
        |-- _wbt.pyi                 # Rust extension stubs
        |-- backtest.py              # WeightBacktest class
        |-- mock.py                  # mock_symbol_kline / mock_weights
        |-- top_drawdowns.py         # adapter for _wbt.top_drawdowns
        |-- utils/                   # adapters + pure-Python utilities
        |   |-- __init__.py
        |   |-- cal_yearly_days.py
        |   |-- rolling_daily_performance.py
        |   |-- weights_simple_ensemble.py
        |   |-- cal_trade_price.py
        |   `-- log_strategy_info.py
        |-- plotting/                # single-purpose plotly charts
        |   |-- __init__.py
        |   |-- _common.py
        |   |-- returns.py
        |   |-- risk.py
        |   |-- trades.py
        |   `-- overview.py
        `-- report/                  # HTML report + composite charts
            |-- __init__.py
            |-- _generator.py
            |-- _plot_backtest.py
            `-- html_builder.py

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

wbt-0.3.1.tar.gz (368.7 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

wbt-0.3.1-cp310-abi3-win_amd64.whl (21.4 MB view details)

Uploaded CPython 3.10+Windows x86-64

wbt-0.3.1-cp310-abi3-manylinux_2_28_x86_64.whl (19.6 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.28+ x86-64

wbt-0.3.1-cp310-abi3-manylinux_2_28_aarch64.whl (18.0 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.28+ ARM64

wbt-0.3.1-cp310-abi3-macosx_11_0_arm64.whl (17.3 MB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

wbt-0.3.1-cp310-abi3-macosx_10_12_x86_64.whl (19.0 MB view details)

Uploaded CPython 3.10+macOS 10.12+ x86-64

File details

Details for the file wbt-0.3.1.tar.gz.

File metadata

  • Download URL: wbt-0.3.1.tar.gz
  • Upload date:
  • Size: 368.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for wbt-0.3.1.tar.gz
Algorithm Hash digest
SHA256 4b61393d2ada6f756dec1b4387a8285ab005d7da9a6681bd0d7f98266244fceb
MD5 7f35dc6267c9c6ade5cb98350199f4f6
BLAKE2b-256 94c91a4c74d214d66306d85d401ffacc3930ecbeb948c323f36edf2436fc23d4

See more details on using hashes here.

Provenance

The following attestation bundles were made for wbt-0.3.1.tar.gz:

Publisher: release.yml on zengbin93/wbt

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wbt-0.3.1-cp310-abi3-win_amd64.whl.

File metadata

  • Download URL: wbt-0.3.1-cp310-abi3-win_amd64.whl
  • Upload date:
  • Size: 21.4 MB
  • Tags: CPython 3.10+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for wbt-0.3.1-cp310-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 a6419f61e4a6650dd782fc9e09e8460680733b874fd669d1baebc6711a9db315
MD5 fc929efaeac09bebf45fbd90dfc0896d
BLAKE2b-256 d2fb1ece6059e415a8525a5baa35b90a1c49502574b590e70cbc8c7e3b121a5d

See more details on using hashes here.

Provenance

The following attestation bundles were made for wbt-0.3.1-cp310-abi3-win_amd64.whl:

Publisher: release.yml on zengbin93/wbt

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wbt-0.3.1-cp310-abi3-manylinux_2_28_x86_64.whl.

File metadata

  • Download URL: wbt-0.3.1-cp310-abi3-manylinux_2_28_x86_64.whl
  • Upload date:
  • Size: 19.6 MB
  • Tags: CPython 3.10+, manylinux: glibc 2.28+ x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for wbt-0.3.1-cp310-abi3-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 f1f3e461d56760e1b99eff4ff096ed2e46bac1353e299ecee8a37bd526224c18
MD5 ac4a487c07e398b7bd2709f5d3480cc5
BLAKE2b-256 3b1018b9eca954755b5dc20624959cf3594b7428beb61badc2e70687d34f52c0

See more details on using hashes here.

Provenance

The following attestation bundles were made for wbt-0.3.1-cp310-abi3-manylinux_2_28_x86_64.whl:

Publisher: release.yml on zengbin93/wbt

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wbt-0.3.1-cp310-abi3-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for wbt-0.3.1-cp310-abi3-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 240b84c82be28569938c317d01bfed2cf0a830f8ebc073ed3195cdd53b63dbd4
MD5 ce9185e7fad84d8078eb781ca068c038
BLAKE2b-256 91f9a2203162b24a052414e1904f7605bfe475e48c36ff1f11c7b44008bd6846

See more details on using hashes here.

Provenance

The following attestation bundles were made for wbt-0.3.1-cp310-abi3-manylinux_2_28_aarch64.whl:

Publisher: release.yml on zengbin93/wbt

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wbt-0.3.1-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

  • Download URL: wbt-0.3.1-cp310-abi3-macosx_11_0_arm64.whl
  • Upload date:
  • Size: 17.3 MB
  • Tags: CPython 3.10+, macOS 11.0+ ARM64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for wbt-0.3.1-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 ac6d0c1d72346b68bcd6f1f0634697f2ce44dd4e5ab14878d878ea80336b45d6
MD5 1b7edaced414a18d5bfb35f6be4dde05
BLAKE2b-256 ea80cb13d434302fd0d0cdebff8b2c1f2c4587deb643b905a2d7a9bbaa8d0107

See more details on using hashes here.

Provenance

The following attestation bundles were made for wbt-0.3.1-cp310-abi3-macosx_11_0_arm64.whl:

Publisher: release.yml on zengbin93/wbt

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wbt-0.3.1-cp310-abi3-macosx_10_12_x86_64.whl.

File metadata

  • Download URL: wbt-0.3.1-cp310-abi3-macosx_10_12_x86_64.whl
  • Upload date:
  • Size: 19.0 MB
  • Tags: CPython 3.10+, macOS 10.12+ x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for wbt-0.3.1-cp310-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 a27b2f86d3824c5a9018f5808f314f4a2377052ec2337d1da181190f389d0aff
MD5 aad4dba139370b61ce09759b7c5b1954
BLAKE2b-256 f769f5b7f17c78e3247b352ea60d09a85ecebcb642a453706fb78b80f9f1bcc3

See more details on using hashes here.

Provenance

The following attestation bundles were made for wbt-0.3.1-cp310-abi3-macosx_10_12_x86_64.whl:

Publisher: release.yml on zengbin93/wbt

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page