Skip to main content

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

For standalone chronological position exposure, use from wbt import calculate_position_risk and pass a DataFrame containing dt, symbol, weight. It returns seven exposure metrics on the sorted time axis with forward-filled positions. See contract, examples and reproducible Rust/Python benchmark.

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",  # exact lowercase "ts" (mean) or "cs" (sum); other strings raise ValueError
    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 normalization is performed once by the Rust engine using digits and half-away-from-zero rounding. The first BAR of each symbol is excluded from return rows and fees; later price returns and same-BAR position-change costs belong to that BAR's date.

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 alpha['策略'] equals daily_return.total (TS mean / CS sum); the benchmark remains an equal-weight mean. Review yearly/recent absolute returns sum the same portfolio daily returns.
  • 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_rolling_metrics,  # rolling sharpe/return/vol over time (252d window)
    plot_segment_comparison,  # recent-1y vs full-sample metric table
    plot_stats_comparison,  # 多空/多头/空头/基准/超额 metric comparison table
    plot_symbol_returns,  # per-symbol cumulative returns
    plot_verdict,  # history (yearly) + recent-window verdict
    plot_yearly_returns,  # yearly absolute vs excess returns (grouped bars)
)

Typical usage:

result = wb.to_result()

fig1 = plot_cumulative_returns(result, keys=["多空", "多头", "空头", "基准"])
fig2 = plot_cumulative_returns(result, keys=["多空", "多头", "空头", "基准", "多头超额", "空头超额"], voladj=True)
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                       # pure Rust crate entry; Python bindings are off by default
|   |-- python.rs                    # PyO3 bindings (enabled by the python feature)
|   `-- 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

Metadata

Release files for wbt 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wbt 0.9.0
File Size Uploaded
wbt-0.9.0.tar.gz 2.5 MB Details

Built distributions (wheels)

Table of built distributions (wheels) for wbt 0.9.0
File
wbt-0.9.0-cp310-abi3-win_amd64.whl CPython 3.10 abi3 Windows x86-64 Details
wbt-0.9.0-cp310-abi3-manylinux_2_28_x86_64.whl CPython 3.10 abi3 Linux glibc 2.28+ x86-64 Details
wbt-0.9.0-cp310-abi3-manylinux_2_28_aarch64.whl CPython 3.10 abi3 Linux glibc 2.28+ ARM64 Details
wbt-0.9.0-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details
wbt-0.9.0-cp310-abi3-macosx_10_12_x86_64.whl CPython 3.10 abi3 macOS 10.12+ x86-64 Details

Total release size: 95.3 MB

Release files / wbt-0.9.0.tar.gz

Download URL wbt-0.9.0.tar.gz
Size 2.5 MB
Tags Source
SHA-256 checksum
How to use checksums
d0da48c4a26f8d05d38098df4b3df1b20a248b63d3701403de28599666f22760
BLAKE2b-256 checksum
How to use checksums
e967e230e0bb3962d2339334895b594f7fecb39b3bfbc6e7395f643db953d991
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / wbt-0.9.0-cp310-abi3-win_amd64.whl

Download URL wbt-0.9.0-cp310-abi3-win_amd64.whl
Size 20.9 MB
Tags CPython 3.10 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
3c73ddc446bc2e24348bf35b70ab80e2446522ca0f9faea2d2eb2c777da8a667
BLAKE2b-256 checksum
How to use checksums
3a42ecf9b6b1581e2fb72918a72d4655aad48b5e1aef4a78a49821d32e4a5837
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / wbt-0.9.0-cp310-abi3-manylinux_2_28_x86_64.whl

Download URL wbt-0.9.0-cp310-abi3-manylinux_2_28_x86_64.whl
Size 19.1 MB
Tags CPython 3.10 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
a046d4cc2ab68eb5be59b904fd3afefa1f6053ee8246056198cfc79f68e208be
BLAKE2b-256 checksum
How to use checksums
09e3e99d8d6ef6e8e5f8a054c02327761bc12d5e3cba5e38eeb199197c8ab13f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / wbt-0.9.0-cp310-abi3-manylinux_2_28_aarch64.whl

Download URL wbt-0.9.0-cp310-abi3-manylinux_2_28_aarch64.whl
Size 17.5 MB
Tags CPython 3.10 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
1bda25faa53f3ef2b87f3af9ef75cf99bd66f389a7c55eff35e3ad2abf12666d
BLAKE2b-256 checksum
How to use checksums
3893c4dc9b229424c9cbc8fc1a629a515dc58093b4c651d20f2cea3c5440a777
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / wbt-0.9.0-cp310-abi3-macosx_11_0_arm64.whl

Download URL wbt-0.9.0-cp310-abi3-macosx_11_0_arm64.whl
Size 16.8 MB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
4caea3205177af65b993a64996181f3969510d6461bb7b6a563ca348c152ff21
BLAKE2b-256 checksum
How to use checksums
e9404c112f4871bcebdc2650b4c1a4a3c8fdd70044ab3562aa90553cb35f743d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / wbt-0.9.0-cp310-abi3-macosx_10_12_x86_64.whl

Download URL wbt-0.9.0-cp310-abi3-macosx_10_12_x86_64.whl
Size 18.6 MB
Tags CPython 3.10 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
719e4a0bcce21401b66e53e13522b2d627f3d36577cb8e25d237f5cdbbdc2ec0
BLAKE2b-256 checksum
How to use checksums
10f434113268539f9cd98a2a9ec98366b2f89ecb7320a2f9e77535e94d9c6877
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release history Release notifications | RSS feed

0.9.1

6 release files

This release

0.9.0 This release

6 release files

0.8.2

6 release files

0.8.1

6 release files

0.8.0

6 release files

0.7.1

6 release files

0.7.0

6 release files

0.6.0

6 release files

0.5.0

6 release files

0.4.3

6 release files

0.4.2

6 release files

0.4.1

6 release files

0.4.0

6 release files

0.3.2

6 release files

0.3.1

6 release files

0.3.0

6 release files

0.2.3

6 release files

0.2.2

6 release files

0.2.1

6 release files

0.2.0

6 release files

0.1.8

6 release files

0.1.7

6 release files

0.1.6

6 release files

0.1.5

4 release files

0.1.4

4 release files

0.1.3

4 release files

0.1.2

4 release files

0.1.1

4 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page