Skip to main content

Papers With Backtest Toolbox

The pwb-toolbox package is designed to provide tools and resources for systematic trading strategies. It includes datasets and strategy ideas to assist in developing and backtesting trading algorithms.

Installation

To install the pwb-toolbox package:

pip install pwb-toolbox

This package requires Python 3.10 or higher.

To use PWB datasets, you can supply a Papers With Backtest API key via the PWB_API_KEY environment variable. When that is set, load_dataset will download parquet shards directly from the PWB API. If no API key is available, you can instead login to the Huggingface Hub (where public PWB datasets are hosted) with an access token:

huggingface-cli login

Usage

The pwb-toolbox package offers a range of functionalities for systematic trading analysis. Here are some examples of how to utilize the package:

Datasets

The pwb_toolbox.datasets module offers to load datasets for different asset classes, such as bonds, commodities, cryptocurrencies, ETFs, forex, indices, and stocks, using the get_pricing or the load_dataset functions:

import pwb_toolbox.datasets as pwb_ds

df = pwb_ds.get_pricing(["AAPL", "MSFT", "GOOGL"])
df = pwb_ds.load_dataset("Bonds-Daily-Price")
df = pwb_ds.load_dataset("Commodities-Daily-Price")
df = pwb_ds.load_dataset("Cryptocurrencies-Daily-Price")
df = pwb_ds.load_dataset("ETFs-Daily-Price")
df = pwb_ds.load_dataset("Forex-Daily-Price")
df = pwb_ds.load_dataset("Indices-Daily-Price")
df = pwb_ds.load_dataset("Stocks-Daily-Price")
df = pwb_ds.load_dataset("Preferreds-Daily-Price")
df = pwb_ds.load_dataset("Warrants-Daily-Price")
df = pwb_ds.load_dataset("StructuredProducts-Daily-Price")

For more, see docs/datasets.md.

Backtesting

The pwb_toolbox.backtesting module offers simple building blocks for running Backtrader simulations.

It runs on backtrader by default, or on Tradewind, the Apache 2.0 engine with the same API (pip install pwb-toolbox[tradewind]). Choose once, before pwb_toolbox.backtesting is imported: PWB_BACKTEST_ENGINE=tradewind in the environment, or pwb_toolbox.engine.select("tradewind") in code. The engine that was not chosen is never imported, and pwb_toolbox.backtesting.bt is the one that was.

Here is a strategy example:

import numpy as np
import backtrader as bt
import pwb_toolbox.backtesting as pwb_bt
import pwb_toolbox.datasets as pwb_ds


# ────────────────────────────────────────────────────────────────
# Toy dual-momentum: each month hold SPY if its lookback return > T-bill,
# otherwise sit in BIL. Kept minimal while using pwb_bt & pwb_ds.
# ────────────────────────────────────────────────────────────────

class SimpleMomentum(bt.Indicator):
    """12-month rate of change on close."""
    lines = ("roc",)
    params = (("period", 252),)

    def __init__(self):
        self.lines.roc = bt.indicators.RateOfChange(self.data.close, period=self.p.period)


class MonthlySwitcher(pwb_bt.BaseStrategy):
    params = dict(
        period=252,            # ~12 months
        risky="SPY",
        safe="BIL",
        leverage=1.0,
    )

    def __init__(self):
        super().__init__()
        # Attach momentum indicators to each data feed
        self.mom = {d._name: SimpleMomentum(d, period=self.p.period) for d in self.datas}
        self._last_month = -1

    def next(self):
        super().next()

        # Rebalance only on month change
        today = self.datas[0].datetime.date(0)
        if today.month == self._last_month:
            return
        self._last_month = today.month

        # Use prior bar to emulate "signal at month-end, trade next month"
        idx = -1
        spy_m = float(self.mom[self.p.risky].roc[idx])
        bil_m = float(self.mom[self.p.safe].roc[idx])

        # Decide allocation
        hold_risky = (not np.isnan(spy_m)) and (not np.isnan(bil_m)) and (spy_m > bil_m)

        targets = {
            self.p.risky: self.p.leverage if hold_risky else 0.0,
            self.p.safe:  0.0 if hold_risky else self.p.leverage,
        }

        # Set portfolio targets
        for d in self.datas:
            self.order_target_percent(d, targets.get(d._name, 0.0))


def run_strategy():
    # Minimal universe fetched via pwb_ds inside pwb_bt
    symbols = ["SPY", "BIL"]

    result = pwb_bt.run_strategy(
        indicator_cls=SimpleMomentum,             # kept for compatibility, but not required externally
        indicator_kwargs={"period": 252},
        strategy_cls=MonthlySwitcher,
        strategy_kwargs={"period": 252, "risky": "SPY", "safe": "BIL", "leverage": 1.0},
        symbols=symbols,
        start_date="2005-01-01",
        cash=100_000.0,
    )
    return result


if __name__ == "__main__":
    run_strategy()

To explore more, you can find over 140 strategy examples at https://paperswithbacktest.com/strategies).

For more about backtesting, see docs/backtesting.md.

Execution

The execution helpers in pwb_toolbox.execution can connect to brokers to run strategies in real time. A typical session collects account information, computes target positions and submits the necessary orders.

Two brokers are supporter today:

  • Interactive Brokers
  • CCXT (crypto)

For more about execution, see docs/execution.md.

Performance Analysis

After running a live trading session, you can analyze the returned equity series using the pwb_toolbox.performance module.

from pwb_toolbox.backtesting.examples import GoldenCrossAlpha, EqualWeightPortfolio
from pwb_toolbox.backtesting import run_backtest
from pwb_toolbox.backtesting.execution_models import ImmediateExecutionModel
from pwb_toolbox.performance import total_return, cagr
from pwb_toolbox.performance.plots import plot_equity_curve

result, equity = run_backtest(
    ManualUniverseSelectionModel(["SPY", "QQQ"]),
    GoldenCrossAlpha(),
    EqualWeightPortfolio(),
    execution=ImmediateExecutionModel(),
    start="2015-01-01",
)

print("Total return:", total_return(equity))
print("CAGR:", cagr(equity))

plot_equity_curve(equity)

Tools

Interactive Brokers server

To trade PWB strategies live with Interactive Brokers, you can use pwb-toolbox/tools/ib_server.

On a ubuntu server (for instance from https://www.ovhcloud.com/), install Miniconda, IB TWS, and RDP with:

cd pwb-toolbox/tools/ib_server
./install.sh
conda activate pwb

If TWS is already started:

PWB_API_KEY="" python -m execute_meta_strategy

If TWS isn'y already started:

TWS_USERNAME="" TWS_PASSWORD="" python -m launch_ib && PWB_API_KEY="" python -m execute_meta_strategy

And to run the strategy daily, define the environment variables in .bashrc and then set up the following cron:

30 9 * * Mon-Fri /bin/bash /path/to/run_daily.sh >> /path/to/logfile 2>&1

To get logs:

python -m monitor --logs-dir $HOME/pwb-data/ib/execution_logs

NB: Fix to restart the desktop environment:

ps aux | grep xfce4
sudo pkill -u ubuntu

Contributing

Contributions to the pwb-toolbox package are welcome! If you have any improvements, new datasets, or strategy ideas to share, please follow these guidelines:

  1. Fork the repository and create a new branch for your feature.
  2. Make your changes and ensure they adhere to the package's coding style.
  3. Write tests to validate the functionality or provide sample usage examples.
  4. Submit a pull request, clearly explaining the purpose and benefits of your contribution.

To build the package, run:

python -m pip install --upgrade build
rm -r dist
python -m build

To upload the package to PyPI, run:

twine upload dist/*

Metadata

Release files for pwb-toolbox 0.1.43

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

Source distribution (sdist)

Source distribution for pwb-toolbox 0.1.43
File Size Uploaded Provenance Actions
pwb_toolbox-0.1.43.tar.gz 108.9 kB Without provenance Details for pwb_toolbox-0.1.43.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pwb-toolbox 0.1.43
File Interpreter ABI Platform Actions
pwb_toolbox-0.1.43-py3-none-any.whl Python 3 none any Details for pwb_toolbox-0.1.43-py3-none-any.whl

Total release size: 209.7 kB

Release files / pwb_toolbox-0.1.43.tar.gz

Download URL pwb_toolbox-0.1.43.tar.gz
Size 108.9 kB
Tags Source
SHA-256 checksum
How to use checksums
b028b196fb6eca802b7caf9d92c4d94704cc8d4b8638cccde919576da1c45f9b
BLAKE2b-256 checksum
How to use checksums
373accf5a702d217cd2133cf98a17d85e1516a336c7df901cee2076ba8842f29
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / pwb_toolbox-0.1.43-py3-none-any.whl

Download URL pwb_toolbox-0.1.43-py3-none-any.whl
Size 100.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
48db3fa0ccefcb983b35097c63b51ef789412409dfdefb2b79871aafd42c6a7d
BLAKE2b-256 checksum
How to use checksums
a6b1e567a401bb1bdc90d219d00bd547c8e0fccf88663783e9085a2bf59e49c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Security for pwb-toolbox 0.1.43

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.43 This release

2 release files No provenance

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