- Notifications
You must be signed in to change notification settings - Fork13
The toolbox for developing systematic trading strategies. It includes datasets and strategy ideas to assist in developing and backtesting trading algorithms.
License
paperswithbacktest/pwb-toolbox
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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.
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
Thepwb-toolbox package offers a range of functionalities for systematic trading analysis. Here are some examples of how to utilize the package:
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.
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.
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.
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)
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 pwbIf TWS is already started:
PWB_API_KEY="" python -m execute_meta_strategyIf 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_logsNB: Fix to restart the desktop environment:
ps aux| grep xfce4sudo pkill -u ubuntuContributions to thepwb-toolbox package are welcome! If you have any improvements, new datasets, or strategy ideas to share, please follow these guidelines:
- Fork the repository and create a new branch for your feature.
- Make your changes and ensure they adhere to the package's coding style.
- Write tests to validate the functionality or provide sample usage examples.
- 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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
