Skip to content
Proyectos

Acerca de

The toolbox for developing systematic trading strategies. It includes datasets and strategy ideas to assist in developing and backtesting trading algorithms.

Negocios y finanzas

Cómo se miden estas cifras

Crecimiento de estrellas medido

in 24h
0
in 7 days
-1
in 15 days
-1
in 1 month
0

Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.

README.md

Original

Papers With Backtest Toolbox

License: Apache 2.0

The paperswithbacktest package (import name pwb; formerly pwb-toolbox, import pwb_toolbox) 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 package:

pip install paperswithbacktest

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, four at a time, into a local cache (~/.cache/pwb_toolbox/api, or $PWB_CACHE_DIR/api; capped at PWB_API_CACHE_MAX_GB, 10 GB by default, least recently used files evicted first; PWB_API_CACHE=0 turns it off). A file is kept under its content hash, so a second call, or a new version of a dataset that leaves a month unchanged, downloads nothing for it. 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

What get_pricing, load_dataset and the cost schedules of the backtest harness return is also kept on disk between processes (~/.cache/pwb_toolbox/prepared, or $PWB_CACHE_DIR/prepared; capped at PWB_PREPARED_CACHE_MAX_GB, 10 GB by default; PWB_CACHE=0 turns it off). An entry is keyed on the call, the version of the package and the exact revision of every dataset read, so a new revision of a dataset is simply another entry; nothing expires by age. A run that falls back to a degraded mode (a cost table it cannot read, a dataset whose revision is unknown) neither reads nor writes it.

load_option_chain keeps the bytes it fetches from Options-Daily-Price on disk too ($PWB_CACHE_DIR/options; capped at PWB_OPTIONS_CACHE_MAX_GB, 20 GB by default; PWB_CACHE=0 or PWB_OPTIONS_CACHE=0 turns it off). Blocks are keyed on the exact revision of the dataset and the file, so what is read back is what the Hub would have sent; a month read once by any strategy is read again from disk, without a request. Offline, degraded, or without a known revision (files listed by the subscriber API), it is neither read nor written.

Futures: load_futures("CL") reads Futures-Daily-Price (one row per contract and session; kind="contracts", "continuous" with rank and adjust, or "chain"), and add_futures(engine, ["CL"], margins=...) adds the contracts to a Tradewind engine for a tradewind.futures.Roller. See docs/datasets.md.

Usage

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

Datasets

The pwb.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.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")

The 1-minute datasets (Stocks-1Min-Price, Cryptocurrencies-1Min-Price, Forex-1Min-Price) are one parquet shard per month. Bound the read with start, end and columns so only the months and columns you need are downloaded and read:

bars = pwb_ds.load_dataset(
    "Stocks-1Min-Price",
    symbols=["SPY", "QQQ"],
    start="2024-01-01",
    end="2024-03-31",
    columns=["adj_open", "adj_close", "volume"],
)

Without start/end, a minute dataset still loads but warns (UnboundedMinuteLoadWarning): every month is downloaded, about 75 GB for the stocks.

Kenneth French's Data Library (Fama-French factors, momentum, reversals, industry and sorted portfolios) is loaded on the fly with load_french("ff5"), load_french("ind48", frequency="daily"), etc. These are data from Kenneth R. French's Data Library, downloaded on the user's machine and cached locally; they are not redistributed by Papers With Backtest.

For more, see docs/datasets.md.

Backtesting

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

Since 0.1.56 it runs on Tradewind, the Apache 2.0 engine with the backtrader API, by default; backtrader stays available for one month. Choose once, before pwb.backtesting is imported: PWB_ENGINE=backtrader in the environment, or pwb.engine.select("backtrader") in code. The engine that was not chosen is never imported, and pwb.backtesting.bt is the one that was.

Here is a strategy example:

import numpy as np
import backtrader as bt
import pwb.backtesting as pwb_bt
import pwb.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.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.performance module.

from pwb.backtesting.examples import GoldenCrossAlpha, EqualWeightPortfolio
from pwb.backtesting import run_backtest
from pwb.backtesting.execution_models import ImmediateExecutionModel
from pwb.performance import total_return, cagr
from pwb.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/*

License

pwb-toolbox is licensed under the Apache License 2.0, starting with the first release after 0.1.53. Versions up to and including 0.1.53 were released under the MIT License; see NOTICE.

Explorar proyectos relacionados

Cargando…