Skip to main content

A toolbox library for quant traders

Project description

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. For detailed instructions on how to use this package effectively, please refer to the associated Substack publication by visiting: https://blog.paperswithbacktest.com/.

Installation

To install the pwb-toolbox package:

pip install pwb-toolbox

This package requires Python 3.10 or higher.

To login to Huggingface Hub with 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:

  • Import pwb_toolbox.datasets and sequentially loads datasets for different asset classes, such as bonds, commodities, cryptocurrencies, ETFs, forex, indices, and stocks, using the load_dataset function:
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")
  • Load daily stock price data for specific symbols using the load_dataset function. The first call retrieves data for Apple and Microsoft. The second call retrieves the same stocks but without price adjustments (adjust=False). The third call loads daily price data for the S&P 500 index:
import pwb_toolbox.datasets as pwb_ds

df = pwb_ds.load_dataset(
    "Stocks-Daily-Price",
    ["AAPL", "MSFT"],
)

df = pwb_ds.load_dataset(
    "Stocks-Daily-Price",
    ["AAPL", "MSFT"],
    adjust=False,
)

df = pwb_ds.load_dataset(
    "Stocks-Daily-Price",
    ["sp500"],
)
  • The extend=True argument instructs the function to return an extended historical data using indices, commodities, and bonds data.
import pwb_toolbox.datasets as pwb_ds

df = pwb_ds.load_dataset(
    "ETFs-Daily-Price",
    ["SPY", "IEF"],
    extend=True,
)
  • The argument rate_to_price=False specifies that bond yield rates should not be converted to price values in the returned data:
import pwb_toolbox.datasets as pwb_ds

df = pwb_ds.load_dataset(
    "Bonds-Daily-Price",
    ["US10Y"],
    rate_to_price=False,
)
  • The argument to_usd=False indicates that the data should not be converted to U.S. dollars, implying that it might be available in another currency.
import pwb_toolbox.datasets as pwb_ds

df = pwb_ds.load_dataset(
    "Indices-Daily-Price",
    ["US10Y"],
    to_usd=False,
)

Backtest engine

The pwb_toolbox.backtest module offers simple building blocks for running Backtrader simulations. Alpha models generate Insight objects which are turned into portfolio weights and executed via Backtrader orders.

from pwb_toolbox.backtest.examples import GoldenCrossAlpha, EqualWeightPortfolio
from pwb_toolbox.backtest import run_backtest
from pwb_toolbox.backtest.execution_models import ImmediateExecutionModel
from pwb_toolbox.backtest.risk_models import MaximumTotalPortfolioExposure
from pwb_toolbox.backtest.universe_models import ManualUniverseSelectionModel

run_backtest(
    ManualUniverseSelectionModel(["SPY", "QQQ"]),
    GoldenCrossAlpha(),
    EqualWeightPortfolio(),
    execution=ImmediateExecutionModel(),
    risk=MaximumTotalPortfolioExposure(max_exposure=1.0),
    start="2015-01-01",
)

Performance Analysis

After running a backtest you can analyze the returned equity series using the pwb_toolbox.performance module.

from pwb_toolbox.backtest.examples import GoldenCrossAlpha, EqualWeightPortfolio
from pwb_toolbox.backtest import run_backtest
from pwb_toolbox.backtest.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)

Plotting utilities require matplotlib; some metrics also need pandas.

Live trading with Interactive Brokers

run_ib_strategy streams Interactive Brokers data and orders. Install ibapi and either atreyu-backtrader-api or ib_insync.

from pwb_toolbox.backtest import IBConnector, run_ib_strategy
from pwb_toolbox.backtest.example.engine import SimpleIBStrategy

data_cfg = [{"dataname": "AAPL", "name": "AAPL"}]
run_ib_strategy(
    SimpleIBStrategy,
    data_cfg,
    host="127.0.0.1",
    port=7497,
    client_id=1,
)

Configure host, port, and client_id to match your TWS or Gateway settings. Test with an Interactive Brokers paper account before trading live.

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.

Please note that all contributions are subject to review and approval by the maintainers.

Build the Package

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

The pwb-toolbox package is released under the MIT license. See the LICENSE file for more details.

Contact

For any questions, issues, or suggestions regarding the pwb-toolbox package, please contact the maintainers or create an issue on the repository. We appreciate your feedback and involvement in improving the package. Happy trading!

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

pwb_toolbox-0.1.15.tar.gz (36.1 kB view details)

Uploaded Source

Built Distribution

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

pwb_toolbox-0.1.15-py3-none-any.whl (34.8 kB view details)

Uploaded Python 3

File details

Details for the file pwb_toolbox-0.1.15.tar.gz.

File metadata

  • Download URL: pwb_toolbox-0.1.15.tar.gz
  • Upload date:
  • Size: 36.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for pwb_toolbox-0.1.15.tar.gz
Algorithm Hash digest
SHA256 4874d2f77c0a4aefaf381925537f806cf7e9f2bb5c9efa03f30d3cf3597192b5
MD5 65b5f944b4235f8e40aa44d7dffe173f
BLAKE2b-256 e94f987e7f5e6eabf4003fb6f813cd872d37cab508d4c49885ecd806dc9f4b72

See more details on using hashes here.

File details

Details for the file pwb_toolbox-0.1.15-py3-none-any.whl.

File metadata

  • Download URL: pwb_toolbox-0.1.15-py3-none-any.whl
  • Upload date:
  • Size: 34.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for pwb_toolbox-0.1.15-py3-none-any.whl
Algorithm Hash digest
SHA256 73d05f2ca3e291ef1c8ea40d8b2932e1a6dbebe5f66db43aee44a61916d9bfe1
MD5 e91da553d0f317261abe6ca2c4a308c8
BLAKE2b-256 478eae2d9ccbdd3f591487104fa5546304986982ebc6a1f40c3b761ccfba2011

See more details on using hashes here.

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