Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

paperswithbacktest/pwb-toolbox

Repository files navigation

Papers With Backtest Toolbox

Thepwb-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 thePWB_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 theHuggingface Hub (where public PWB datasets are hosted) with an access token:

huggingface-cli login

Usage

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

Datasets

Thepwb_toolbox.datasets module offers to load datasets for different asset classes, such as bonds, commodities, cryptocurrencies, ETFs, forex, indices, and stocks, using theget_pricing or theload_dataset functions:

importpwb_toolbox.datasetsaspwb_dsdf=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")

For more, seedocs/datasets.md.

Backtesting

Thepwb_toolbox.backtesting module offers simple building blocks for running Backtrader simulations.

Here is a strategy example:

importnumpyasnpimportbacktraderasbtimportpwb_toolbox.backtestingaspwb_btimportpwb_toolbox.datasetsaspwb_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.# ────────────────────────────────────────────────────────────────classSimpleMomentum(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)classMonthlySwitcher(pwb_bt.BaseStrategy):params=dict(period=252,# ~12 monthsrisky="SPY",safe="BIL",leverage=1.0,    )def__init__(self):super().__init__()# Attach momentum indicators to each data feedself.mom= {d._name:SimpleMomentum(d,period=self.p.period)fordinself.datas}self._last_month=-1defnext(self):super().next()# Rebalance only on month changetoday=self.datas[0].datetime.date(0)iftoday.month==self._last_month:returnself._last_month=today.month# Use prior bar to emulate "signal at month-end, trade next month"idx=-1spy_m=float(self.mom[self.p.risky].roc[idx])bil_m=float(self.mom[self.p.safe].roc[idx])# Decide allocationhold_risky= (notnp.isnan(spy_m))and (notnp.isnan(bil_m))and (spy_m>bil_m)targets= {self.p.risky:self.p.leverageifhold_riskyelse0.0,self.p.safe:0.0ifhold_riskyelseself.p.leverage,        }# Set portfolio targetsfordinself.datas:self.order_target_percent(d,targets.get(d._name,0.0))defrun_strategy():# Minimal universe fetched via pwb_ds inside pwb_btsymbols= ["SPY","BIL"]result=pwb_bt.run_strategy(indicator_cls=SimpleMomentum,# kept for compatibility, but not required externallyindicator_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,    )returnresultif__name__=="__main__":run_strategy()

To explore more, you can find over140 strategy examples athttps://paperswithbacktest.com/strategies).

For more about backtesting, seedocs/backtesting.md.

Execution

The execution helpers inpwb_toolbox.execution can connect to brokers to runstrategies 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, seedocs/execution.md.

Performance Analysis

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

frompwb_toolbox.backtesting.examplesimportGoldenCrossAlpha,EqualWeightPortfoliofrompwb_toolbox.backtestingimportrun_backtestfrompwb_toolbox.backtesting.execution_modelsimportImmediateExecutionModelfrompwb_toolbox.performanceimporttotal_return,cagrfrompwb_toolbox.performance.plotsimportplot_equity_curveresult,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 usepwb-toolbox/tools/ib_server.

On a ubuntu server (for instance fromhttps://www.ovhcloud.com/), installMiniconda,IB TWS, and RDP with:

cd pwb-toolbox/tools/ib_server./install.shconda 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/logfile2>&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 xfce4sudo pkill -u ubuntu

Contributing

Contributions to thepwb-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 buildrm -r distpython -m build

To upload the package to PyPI, run:

twine upload dist/*

About

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp