From 292ec2895851e3e72adcccc9e1ccdc7c325d2cf3 Mon Sep 17 00:00:00 2001 From: Edouard d'Archimbaud Date: Mon, 30 Nov 2026 09:04:56 +0100 Subject: [PATCH] Rename pwb_toolbox to pwb (paperswithbacktest 0.2.0) on top of 0.1.56, with the pwb-toolbox alias The 0.1.56 code (Tradewind by default, PWB_ENGINE=backtrader to go back) moves to the import name `pwb`, distributed as `paperswithbacktest` 0.2.0 (`git mv`, history kept; internal imports, tests and docs rewritten). Nothing about the engine or the NAVs changes. * Deprecation alias: compat/pwb-toolbox is the last `pwb-toolbox` release (0.2.0, requires paperswithbacktest>=0.2.0). Every `pwb_toolbox.` is the same module object as `pwb.` (import hook): one BaseStrategy, one engine choice, one cache; one DeprecationWarning; `python -m pwb_toolbox.engine` works. Ported from #79 (7d1c99f), licence now Apache-2.0 like the package. * `pwb.backtesting.bt` is an import path with feeds/indicators/analyzers (from #79, e242c9f): the engine-neutral form the catalogue codemod writes (paperswithbacktest/tradewind#24); it follows PWB_ENGINE. * Kept: the cache directory ~/.cache/pwb_toolbox, the PWB_* variables. The harness' warning recorder accepts callers from `pwb` and `pwb_toolbox`. Tests: 486 passed, 6 skipped (backtrader and Tradewind installed), compat shim included. Nothing is published. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012zrKmQA3f7zJ5y5EL6MNjT --- CHANGELOG.md | 19 +- README.md | 34 +-- compat/pwb-toolbox/LICENSE | 201 ++++++++++++++++++ compat/pwb-toolbox/NOTICE | 45 ++++ compat/pwb-toolbox/pwb_toolbox/__init__.py | 68 ++++++ compat/pwb-toolbox/pyproject.toml | 3 + compat/pwb-toolbox/setup.cfg | 40 ++++ docs/backtesting.md | 24 +-- docs/datasets.md | 20 +- docs/execution.md | 6 +- docs/index.md | 2 +- docs/world_model.md | 4 +- pwb/__init__.py | 11 + {pwb_toolbox => pwb}/backtesting/__init__.py | 19 +- .../backtesting/backtest_engine.py | 16 +- .../backtesting/base_strategy.py | 2 +- {pwb_toolbox => pwb}/backtesting/checks.py | 8 +- .../backtesting/commission.py | 2 +- {pwb_toolbox => pwb}/backtesting/feeds.py | 2 +- .../backtesting/futures_run.py | 4 +- .../backtesting/indicators.py | 4 +- {pwb_toolbox => pwb}/backtesting/lookahead.py | 8 +- .../backtesting/optimization_engine.py | 0 .../backtesting/option_costs.py | 4 +- {pwb_toolbox => pwb}/backtesting/portfolio.py | 2 +- .../backtesting/strategies.py | 2 +- {pwb_toolbox => pwb}/backtesting/universe.py | 4 +- {pwb_toolbox => pwb}/datasets/__init__.py | 4 +- {pwb_toolbox => pwb}/datasets/french.py | 2 +- {pwb_toolbox => pwb}/datasets/futures.py | 2 +- .../datasets/index_currencies.py | 0 {pwb_toolbox => pwb}/datasets/option_cache.py | 0 {pwb_toolbox => pwb}/datasets/options.py | 2 +- {pwb_toolbox => pwb}/datasets/pit_universe.py | 0 .../datasets/prepared_cache.py | 8 +- {pwb_toolbox => pwb}/docs/__init__.py | 2 +- {pwb_toolbox => pwb}/docs/__main__.py | 2 +- {pwb_toolbox => pwb}/docs/backtesting.md | 24 +-- {pwb_toolbox => pwb}/docs/world_model.md | 4 +- {pwb_toolbox => pwb}/engine.py | 32 +-- {pwb_toolbox => pwb}/execution/__init__.py | 0 .../execution/broker_factory.py | 2 +- .../execution/ccxt_connector.py | 2 +- .../execution/ib_connector.py | 2 +- {pwb_toolbox => pwb}/execution/live_utils.py | 0 .../execution/optimal_limit_order.py | 0 {pwb_toolbox => pwb}/performance/__init__.py | 0 {pwb_toolbox => pwb}/performance/metrics.py | 0 .../performance/nav_metrics.py | 0 {pwb_toolbox => pwb}/performance/plots.py | 0 {pwb_toolbox => pwb}/performance/reports.py | 0 .../performance/trade_stats.py | 0 {pwb_toolbox => pwb}/world_model/__init__.py | 4 +- {pwb_toolbox => pwb}/world_model/_pit.py | 0 {pwb_toolbox => pwb}/world_model/_source.py | 0 {pwb_toolbox => pwb}/world_model/reader.py | 2 +- pwb_toolbox/__init__.py | 4 - setup.cfg | 18 +- tests/_long_short_book.py | 4 +- tests/_synthetic.py | 2 +- tests/conftest.py | 2 +- tests/test_api_cache.py | 2 +- tests/test_array_feed.py | 8 +- tests/test_bare_symbol_collisions.py | 4 +- tests/test_bond_rates.py | 2 +- tests/test_bounded_loader.py | 2 +- tests/test_compat_shim.py | 118 ++++++++++ tests/test_currency_costs.py | 2 +- tests/test_docs_shipped.py | 6 +- tests/test_engine_parity.py | 10 +- tests/test_engine_runner.py | 44 +++- tests/test_engine_selector.py | 16 +- tests/test_exposure_cap.py | 4 +- tests/test_forex_directions.py | 2 +- tests/test_french.py | 2 +- tests/test_futures_loader.py | 2 +- tests/test_futures_run.py | 14 +- tests/test_harness_checks.py | 22 +- tests/test_holiday_bars.py | 4 +- tests/test_hub_snapshot.py | 2 +- tests/test_index_currencies.py | 4 +- tests/test_lookahead.py | 4 +- tests/test_option_cache.py | 8 +- tests/test_option_chain.py | 4 +- tests/test_option_chain_sources.py | 4 +- tests/test_option_costs.py | 6 +- tests/test_pit_exit.py | 8 +- tests/test_pit_hold.py | 12 +- tests/test_pit_hold_accounting.py | 10 +- tests/test_prepared_cache.py | 12 +- tests/test_quantile_signal.py | 6 +- tests/test_read_memo.py | 8 +- tests/test_resolve_reused_property.py | 2 +- tests/test_reused_tickers.py | 4 +- tests/test_same_bar_orders.py | 6 +- tests/test_sells_first.py | 4 +- tests/test_short_borrow.py | 8 +- tests/test_strategy_commission.py | 10 +- tests/test_universe_alias_costs.py | 10 +- tests/test_world_model.py | 8 +- tests/test_world_model_local.py | 2 +- tools/ib_server/execute_meta_strategy.py | 2 +- tools/ib_server/monitor.py | 2 +- 103 files changed, 815 insertions(+), 273 deletions(-) create mode 100644 compat/pwb-toolbox/LICENSE create mode 100644 compat/pwb-toolbox/NOTICE create mode 100644 compat/pwb-toolbox/pwb_toolbox/__init__.py create mode 100644 compat/pwb-toolbox/pyproject.toml create mode 100644 compat/pwb-toolbox/setup.cfg create mode 100644 pwb/__init__.py rename {pwb_toolbox => pwb}/backtesting/__init__.py (68%) rename {pwb_toolbox => pwb}/backtesting/backtest_engine.py (99%) rename {pwb_toolbox => pwb}/backtesting/base_strategy.py (98%) rename {pwb_toolbox => pwb}/backtesting/checks.py (99%) rename {pwb_toolbox => pwb}/backtesting/commission.py (99%) rename {pwb_toolbox => pwb}/backtesting/feeds.py (99%) rename {pwb_toolbox => pwb}/backtesting/futures_run.py (99%) rename {pwb_toolbox => pwb}/backtesting/indicators.py (99%) rename {pwb_toolbox => pwb}/backtesting/lookahead.py (98%) rename {pwb_toolbox => pwb}/backtesting/optimization_engine.py (100%) rename {pwb_toolbox => pwb}/backtesting/option_costs.py (98%) rename {pwb_toolbox => pwb}/backtesting/portfolio.py (99%) rename {pwb_toolbox => pwb}/backtesting/strategies.py (99%) rename {pwb_toolbox => pwb}/backtesting/universe.py (94%) rename {pwb_toolbox => pwb}/datasets/__init__.py (99%) rename {pwb_toolbox => pwb}/datasets/french.py (99%) rename {pwb_toolbox => pwb}/datasets/futures.py (99%) rename {pwb_toolbox => pwb}/datasets/index_currencies.py (100%) rename {pwb_toolbox => pwb}/datasets/option_cache.py (100%) rename {pwb_toolbox => pwb}/datasets/options.py (99%) rename {pwb_toolbox => pwb}/datasets/pit_universe.py (100%) rename {pwb_toolbox => pwb}/datasets/prepared_cache.py (99%) rename {pwb_toolbox => pwb}/docs/__init__.py (98%) rename {pwb_toolbox => pwb}/docs/__main__.py (78%) rename {pwb_toolbox => pwb}/docs/backtesting.md (96%) rename {pwb_toolbox => pwb}/docs/world_model.md (97%) rename {pwb_toolbox => pwb}/engine.py (88%) rename {pwb_toolbox => pwb}/execution/__init__.py (100%) rename {pwb_toolbox => pwb}/execution/broker_factory.py (97%) rename {pwb_toolbox => pwb}/execution/ccxt_connector.py (99%) rename {pwb_toolbox => pwb}/execution/ib_connector.py (99%) rename {pwb_toolbox => pwb}/execution/live_utils.py (100%) rename {pwb_toolbox => pwb}/execution/optimal_limit_order.py (100%) rename {pwb_toolbox => pwb}/performance/__init__.py (100%) rename {pwb_toolbox => pwb}/performance/metrics.py (100%) rename {pwb_toolbox => pwb}/performance/nav_metrics.py (100%) rename {pwb_toolbox => pwb}/performance/plots.py (100%) rename {pwb_toolbox => pwb}/performance/reports.py (100%) rename {pwb_toolbox => pwb}/performance/trade_stats.py (100%) rename {pwb_toolbox => pwb}/world_model/__init__.py (90%) rename {pwb_toolbox => pwb}/world_model/_pit.py (100%) rename {pwb_toolbox => pwb}/world_model/_source.py (100%) rename {pwb_toolbox => pwb}/world_model/reader.py (99%) delete mode 100644 pwb_toolbox/__init__.py create mode 100644 tests/test_compat_shim.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b3a7ab54..d6f097c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,24 @@ Earlier releases are described in their pull requests and on PyPI; this file starts with 0.1.56. -## 0.1.56 (unreleased) +## 0.2.0 (unreleased): `pwb-toolbox` becomes `paperswithbacktest`, import `pwb` + +- The package is `pwb` (`pip install paperswithbacktest`); the code is the 0.1.56 code + under its new name (`git mv`, history kept). Engine, defaults and NAVs are unchanged: + Tradewind by default, `PWB_ENGINE=backtrader` to go back. +- **Deprecation alias**: `pwb-toolbox` 0.2.0 (`compat/pwb-toolbox`, its own release, which + requires `paperswithbacktest>=0.2.0`) keeps `import pwb_toolbox` working. Every + `pwb_toolbox.` is the very same module object as `pwb.` (one + `BaseStrategy`, one engine choice, one cache); importing it warns once + (`DeprecationWarning`); `python -m pwb_toolbox.engine` still answers. +- `pwb.backtesting.bt` is an import path with the engine's `feeds`, `indicators` and + `analyzers`: `from pwb.backtesting import bt`, `from pwb.backtesting.bt import + indicators as btind`. A strategy written that way names no engine and follows + `PWB_ENGINE` (the form the catalogue codemod writes, paperswithbacktest/tradewind#24). +- Kept on purpose: the cache directory `~/.cache/pwb_toolbox/` (no re-download), the + `PWB_*` variables, the repository name. + +## 0.1.56 **Tradewind is the default backtest engine.** diff --git a/README.md b/README.md index bc2f054d..8ee18499 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,15 @@ License: Apache 2.0 -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. +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 pwb-toolbox package: +To install the package: ```bash -pip install pwb-toolbox +pip install paperswithbacktest ``` This package requires Python 3.10 or higher. @@ -45,14 +45,14 @@ contracts to a Tradewind engine for a `tradewind.futures.Roller`. See [docs/data ## Usage -The `pwb-toolbox` package offers a range of functionalities for systematic trading analysis. Here are some examples of how to utilize the package: +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_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: +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: ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds df = pwb_ds.get_pricing(["AAPL", "MSFT", "GOOGL"]) df = pwb_ds.load_dataset("Bonds-Daily-Price") @@ -88,17 +88,17 @@ For more, see [docs/datasets.md](/docs/datasets.md). ### Backtesting -The `pwb_toolbox.backtesting` module offers simple building blocks for running Backtrader simulations. +The `pwb.backtesting` module offers simple building blocks for running Backtrader simulations. -Since 0.1.56 it runs on [Tradewind](https://github.com/paperswithbacktest/tradewind), the Apache 2.0 engine with the backtrader API, by default; backtrader stays available for one month. Choose once, before `pwb_toolbox.backtesting` is imported: `PWB_ENGINE=backtrader` in the environment, or `pwb_toolbox.engine.select("backtrader")` in code. The engine that was not chosen is never imported, and `pwb_toolbox.backtesting.bt` is the one that was. +Since 0.1.56 it runs on [Tradewind](https://github.com/paperswithbacktest/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: ```python import numpy as np import backtrader as bt -import pwb_toolbox.backtesting as pwb_bt -import pwb_toolbox.datasets as pwb_ds +import pwb.backtesting as pwb_bt +import pwb.datasets as pwb_ds # ──────────────────────────────────────────────────────────────── @@ -183,7 +183,7 @@ For more about backtesting, see [docs/backtesting.md](/docs/backtesting.md). ### Execution -The execution helpers in `pwb_toolbox.execution` can connect to brokers to run +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. @@ -198,14 +198,14 @@ For more about execution, see [docs/execution.md](/docs/execution.md). ### Performance Analysis After running a live trading session, you can analyze the returned equity series using the -`pwb_toolbox.performance` module. +`pwb.performance` module. ```python -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 +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"]), diff --git a/compat/pwb-toolbox/LICENSE b/compat/pwb-toolbox/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/compat/pwb-toolbox/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/compat/pwb-toolbox/NOTICE b/compat/pwb-toolbox/NOTICE new file mode 100644 index 00000000..28b15043 --- /dev/null +++ b/compat/pwb-toolbox/NOTICE @@ -0,0 +1,45 @@ +pwb-toolbox +Copyright 2022-2026 Papers With Backtest + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this software except in compliance with the License. You may obtain a copy of +the License at http://www.apache.org/licenses/LICENSE-2.0. + +License change +-------------- + +Starting with the first release published after version 0.1.53, pwb-toolbox is +distributed under the Apache License, Version 2.0. + +Versions up to and including 0.1.53 were released under the MIT License. Those +releases, and copies obtained from them, remain available under the MIT License, +whose original notice is reproduced below: + + Copyright (c) 2022-2023 Papers With Backtest and others + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Contributors +------------ + +The git history of this repository up to version 0.1.53 contains no commit +authored outside Papers With Backtest: all code was written by Papers With +Backtest, partly with AI coding assistants. No third-party contribution +therefore remains under the MIT License only. diff --git a/compat/pwb-toolbox/pwb_toolbox/__init__.py b/compat/pwb-toolbox/pwb_toolbox/__init__.py new file mode 100644 index 00000000..f8d31cf0 --- /dev/null +++ b/compat/pwb-toolbox/pwb_toolbox/__init__.py @@ -0,0 +1,68 @@ +"""pwb_toolbox is now ``pwb`` (``pip install paperswithbacktest``). + +This compatibility package keeps ``import pwb_toolbox`` and every +``pwb_toolbox.`` working: each name resolves to the **same module +object** as its ``pwb`` counterpart (``pwb_toolbox.backtesting is +pwb.backtesting``), so classes, the engine chosen by ``pwb.engine`` and every +cache are shared, and nothing runs twice. Importing it warns once with a +``DeprecationWarning``; replace ``pwb_toolbox`` with ``pwb`` in the imports. +""" + +import importlib +import importlib.abc +import importlib.util +import sys +import warnings + +_OLD = __name__ # "pwb_toolbox" +_NEW = "pwb" + +warnings.warn( + "pwb_toolbox has been renamed pwb (pip install paperswithbacktest): " + "replace `pwb_toolbox` with `pwb` in your imports; this alias will be removed " + "in a future release", + DeprecationWarning, + stacklevel=2, +) + + +class _AliasLoader(importlib.abc.Loader): + def __init__(self, target): + self.target = target + + def create_module(self, spec): + # The pwb module itself: the import system then files it under the old name too. + module = importlib.import_module(self.target) + self.spec = module.__spec__ + return module + + def exec_module(self, module): + # Already executed under its pwb name. The import system has just set + # ``__spec__`` to the alias' spec (it always does): put pwb's back, so the + # module keeps one identity (``__spec__.name == __name__``, reload, pickle). + module.__spec__ = self.spec + + def get_code(self, fullname): + # ``python -m pwb_toolbox.engine ...``: runpy asks for the code to run as __main__. + spec = importlib.util.find_spec(self.target) + return spec.loader.get_code(self.target) + + +class _AliasFinder(importlib.abc.MetaPathFinder): + """``pwb_toolbox.x.y`` -> the module ``pwb.x.y``, imported once under its new name.""" + + def find_spec(self, fullname, path=None, target=None): + if not fullname.startswith(_OLD + "."): + return None + new = _NEW + fullname[len(_OLD):] + if importlib.util.find_spec(new) is None: + return None + return importlib.util.spec_from_loader(fullname, _AliasLoader(new)) + + +if not any(isinstance(f, _AliasFinder) for f in sys.meta_path): + sys.meta_path.insert(0, _AliasFinder()) + +# ``import pwb_toolbox`` gives the pwb package itself, so ``pwb_toolbox.__version__``, +# ``pwb_toolbox.backtesting`` (once imported) and the rest are pwb's. +sys.modules[_OLD] = importlib.import_module(_NEW) diff --git a/compat/pwb-toolbox/pyproject.toml b/compat/pwb-toolbox/pyproject.toml new file mode 100644 index 00000000..8fe2f47a --- /dev/null +++ b/compat/pwb-toolbox/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools>=42", "wheel"] +build-backend = "setuptools.build_meta" diff --git a/compat/pwb-toolbox/setup.cfg b/compat/pwb-toolbox/setup.cfg new file mode 100644 index 00000000..c2e14753 --- /dev/null +++ b/compat/pwb-toolbox/setup.cfg @@ -0,0 +1,40 @@ +[metadata] +# The last pwb-toolbox: the import name pwb_toolbox, kept as an alias of pwb. +# Each distribution owns one import name (paperswithbacktest: pwb; pwb-toolbox: +# pwb_toolbox), so upgrading from pwb-toolbox 0.1.x never deletes a file another +# distribution installed. +name = pwb-toolbox +version = 0.2.0 +author = Papers With Backtest +author_email = hello@paperswithbacktest.com +description = Renamed: pip install paperswithbacktest (import pwb). This release keeps import pwb_toolbox working. +long_description = + pwb-toolbox is now **paperswithbacktest** (`pip install paperswithbacktest`, `import pwb`). + + This release installs paperswithbacktest and keeps `import pwb_toolbox` working: + every `pwb_toolbox.` is the same module as `pwb.`, with a + DeprecationWarning. Replace `pwb_toolbox` with `pwb` in your imports. +long_description_content_type = text/markdown +url = https://paperswithbacktest.com +project_urls = + Homepage = https://paperswithbacktest.com + Source = https://github.com/paperswithbacktest/pwb-toolbox +license = Apache-2.0 +license_files = + LICENSE + NOTICE +classifiers = + Development Status :: 7 - Inactive + Programming Language :: Python :: 3 + License :: OSI Approved :: Apache Software License + Operating System :: OS Independent + +[options] +packages = pwb_toolbox +python_requires = >=3.10 +install_requires = + paperswithbacktest>=0.2.0 + +[options.extras_require] +tradewind = + paperswithbacktest[tradewind]>=0.2.0 diff --git a/docs/backtesting.md b/docs/backtesting.md index e6704ab7..fc965a07 100644 --- a/docs/backtesting.md +++ b/docs/backtesting.md @@ -1,16 +1,16 @@ # Backtesting -This page ships with the package: `python -m pwb_toolbox.docs backtesting` prints it. +This page ships with the package: `python -m pwb.docs backtesting` prints it. ## Choosing the engine -Every class in `pwb_toolbox.backtesting` is built on one engine, bound when the package is imported: [Tradewind](https://github.com/paperswithbacktest/tradewind), the Apache 2.0 engine compatible with the backtrader API, by default since 0.1.56, or backtrader. Choose before the import, by precedence: +Every class in `pwb.backtesting` is built on one engine, bound when the package is imported: [Tradewind](https://github.com/paperswithbacktest/tradewind), the Apache 2.0 engine compatible with the backtrader API, by default since 0.1.56, or backtrader. Choose before the import, by precedence: -1. `pwb_toolbox.engine.select("backtrader")` in code; +1. `pwb.engine.select("backtrader")` in code; 2. `PWB_ENGINE=backtrader` (or `tradewind`) in the environment, which switches a whole run without touching a strategy (`PWB_BACKTEST_ENGINE`, the name before 0.1.56, is read when `PWB_ENGINE` is not set); 3. the default, `tradewind`. -`PWB_ENGINE=backtrader` is the way back for one month after 0.1.56; backtrader stays installed with the package until then. The engine that was not chosen is never imported. On Tradewind, importing `pwb_toolbox.backtesting` also makes the name `backtrader` resolve to Tradewind, so a strategy that does `import backtrader as bt` afterwards runs on the same engine; if backtrader was imported first, a warning says so (call `pwb_toolbox.engine.use()` first, or set `PWB_ENGINE=backtrader`). A strategy that needs the engine module takes it from the package, `from pwb_toolbox.backtesting import bt`, and runs on whichever was chosen; `pwb_toolbox.backtesting.engine_name()` says which. Selecting after the import raises, rather than leaving half the classes on each engine. +`PWB_ENGINE=backtrader` is the way back for one month after 0.1.56; backtrader stays installed with the package until then. The engine that was not chosen is never imported. On Tradewind, importing `pwb.backtesting` also makes the name `backtrader` resolve to Tradewind, so a strategy that does `import backtrader as bt` afterwards runs on the same engine; if backtrader was imported first, a warning says so (call `pwb.engine.use()` first, or set `PWB_ENGINE=backtrader`). A strategy that needs the engine module takes it from the package, `from pwb.backtesting import bt`, and runs on whichever was chosen; `pwb.backtesting.engine_name()` says which. Selecting after the import raises, rather than leaving half the classes on each engine. ## Example of trading strategy @@ -21,8 +21,8 @@ Every class in `pwb_toolbox.backtesting` is built on one engine, bound when the ```python import numpy as np import backtrader as bt -import pwb_toolbox.backtesting as pwb_bt -import pwb_toolbox.datasets as pwb_ds +import pwb.backtesting as pwb_bt +import pwb.datasets as pwb_ds # ──────────────────────────────────────────────────────────────── @@ -259,7 +259,7 @@ equal weight, gross exposure `leverage`. Momentum 12-1 by deciles on the S&P 500 point in time, with a 50 bp/yr borrow on the short leg: ```python -from pwb_toolbox.backtesting import ( +from pwb.backtesting import ( CrossSectionalQuantileSignal, MonthlyLongShortQuantilePortfolio, run_strategy, @@ -333,9 +333,9 @@ one `Checks: lookahead pass, universe pass, execution pass, costs pass (3 ms)` l | `execution` | an order filled on the bar whose data produced it (cheat-on-close, cheat-on-open) | nothing was filled; or an `order_target_*` sent on a name that already had an open order on the same bar (see below) | | `costs` | more than 20 % of the traded value of stocks and ETFs charged the default floor instead of a measured spread | more than 5 % of it; or a flat commission set by the strategy; or a book that held short positions with `short_borrow_bps=0` ("short leg carries no borrow cost") | -The rules and thresholds are in `pwb_toolbox/backtesting/checks.py`; the look-ahead -analysis is `pwb_toolbox/backtesting/lookahead.py` (also `python -m -pwb_toolbox.backtesting.lookahead strategy.py`). A check never stops a backtest: one +The rules and thresholds are in `pwb/backtesting/checks.py`; the look-ahead +analysis is `pwb/backtesting/lookahead.py` (also `python -m +pwb.backtesting.lookahead strategy.py`). A check never stops a backtest: one that cannot run is reported as `warn` with the reason. `PWB_HARNESS_CHECKS=0` in the environment switches them off. When the book held short positions, the `costs` detail carries `shortBorrowBps`, `shortBorrowCost`, `shortBorrowStartNavShare` and @@ -362,7 +362,7 @@ close. The cost of a fill is half the quoted spread, in dollars, from `Options-Yearly-TransactionCostParams`: ```python -from pwb_toolbox.backtesting import options_half_spread, options_cost_breakdown, option_volume_tier +from pwb.backtesting import options_half_spread, options_cost_breakdown, option_volume_tier tier = option_volume_tier(mean_daily_option_volume) # 0 (<1k contracts) to 4 (>1M) otm = strike / spot if call else spot / strike @@ -581,7 +581,7 @@ The backtesting package is composed of a few focused modules: - `universe` – helpers for building trading universes (e.g. most liquid symbols). -`pwb_toolbox.backtesting.strategies` ships a collection of portfolio templates +`pwb.backtesting.strategies` ships a collection of portfolio templates with different rebalancing rules and signal expectations: - **DailyEqualWeightPortfolio** – holds all assets with a long signal and diff --git a/docs/datasets.md b/docs/datasets.md index d14b58ed..4ae47855 100644 --- a/docs/datasets.md +++ b/docs/datasets.md @@ -24,7 +24,7 @@ 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: ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds df = pwb_ds.load_dataset( "Stocks-Daily-Price", @@ -46,7 +46,7 @@ df = pwb_ds.load_dataset( The `extend=True` argument instructs the function to return an extended historical data using indices, commodities, and bonds data. ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds df = pwb_ds.load_dataset( "ETFs-Daily-Price", @@ -58,7 +58,7 @@ df = pwb_ds.load_dataset( The argument `rate_to_price=False` specifies that bond yield rates should not be converted to price values in the returned data: ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds df = pwb_ds.load_dataset( "Bonds-Daily-Price", @@ -70,7 +70,7 @@ df = pwb_ds.load_dataset( 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. ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds df = pwb_ds.load_dataset( "Indices-Daily-Price", @@ -87,7 +87,7 @@ inverts it when the other spelling was asked for (`open`, `close` → `1/x`, `high` → `1/low`, `low` → `1/high`, volume unchanged). ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds # Default to_usd=True: every pair comes back as dollars per unit of the other # currency, named XXXUSD, whichever spelling was asked for. @@ -108,7 +108,7 @@ bounded to the matching rows, but every month is still downloaded. Pass a window and the columns you use: ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds bars = pwb_ds.load_dataset( "Stocks-1Min-Price", @@ -146,7 +146,7 @@ about to download every month. `Options-Daily-Price` holds every US-listed option contract that traded since June 2014, one row per contract and session (about 560 million rows, ~20 GB). It is not loaded with `load_dataset`, which downloads every shard before filtering and refuses this dataset. Use `load_option_chain`, which downloads only what it is asked for: ```python -from pwb_toolbox.datasets import load_option_chain +from pwb.datasets import load_option_chain chain = load_option_chain( ["SPY"], "2024-01-01", "2024-03-31", @@ -171,7 +171,7 @@ The loader does not answer an empty frame for a reason it could name: `Futures-Daily-Price` holds every outright contract of CME, CBOT, NYMEX and COMEX since April 2017: one row per contract and session with its terms (`daily`), one row per contract (`contracts`), and continuous series of rank 1 to 6 per root rolled on volume (`continuous`). The layout is Tradewind's `tradewind.futures.future_table`, so a backtest holds real contracts and rolls them with real orders. ```python -from pwb_toolbox.datasets import add_futures, load_futures +from pwb.datasets import add_futures, load_futures daily = load_futures("CL", start="2020-01-01") # one row per CL contract and session terms = load_futures(["CL", "GC"], kind="contracts") # last trade date, multiplier, tick, currency @@ -190,7 +190,7 @@ curve = load_futures("CL", kind="continuous", rank=[1, 2]) # raw and ```python import tradewind as tw from tradewind.futures import Roller, RollOnVolume -from pwb_toolbox.datasets import add_futures +from pwb.datasets import add_futures class Long(tw.Strategy): params = (("chain", None),) @@ -215,7 +215,7 @@ engine.run() The Fama-French factors, the momentum and reversal factors, the industry portfolios and the sorted portfolios of [Kenneth R. French's Data Library](https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html) are loaded on the fly from the author's site. **They are not on the Hub and not behind the PWB API**: the library grants no redistribution right, so the zip is downloaded on your machine and kept in a local cache. Cite the library in anything you build on it. ```python -from pwb_toolbox.datasets import load_french, load_french_blocks, french_datasets +from pwb.datasets import load_french, load_french_blocks, french_datasets ff5 = load_french("ff5") # monthly, decimal returns mom = load_french("mom", frequency="daily") diff --git a/docs/execution.md b/docs/execution.md index f9b5c46c..cece83b0 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -6,7 +6,7 @@ ```python from pathlib import Path import pandas as pd -from pwb_toolbox import execution as pwb_exec +from pwb import execution as pwb_exec STRATEGIES = {"my_strategy": {"path": "my_package.my_strategy", "weight": 1.0}} logs_dir = Path("logs") @@ -58,7 +58,7 @@ ibc.disconnect() ```python from pathlib import Path import pandas as pd -from pwb_toolbox import execution as pwb_exec +from pwb import execution as pwb_exec STRATEGIES = {"my_strategy": {"path": "my_package.my_strategy", "weight": 1.0}} logs_dir = Path("logs") @@ -110,7 +110,7 @@ cc.disconnect() ## Optimal Limit Order -The module `pwb_toolbox.execution.optimal_limit_order` implements the optimal +The module `pwb.execution.optimal_limit_order` implements the optimal limit‑order placement framework described in [Optimal Portfolio Liquidation with Limit Orders](https://arxiv.org/abs/1106.3279) by Guéant, Lehalle, and Tapia. diff --git a/docs/index.md b/docs/index.md index aae4263b..bde7ac3b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -24,7 +24,7 @@ huggingface-cli login ## Quick start ```python -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds df = pwb_ds.get_pricing(["AAPL", "MSFT", "GOOGL"]) df = pwb_ds.load_dataset("Stocks-Daily-Price") diff --git a/docs/world_model.md b/docs/world_model.md index 9cd2d73b..e82daedc 100644 --- a/docs/world_model.md +++ b/docs/world_model.md @@ -1,6 +1,6 @@ # World Model -`pwb_toolbox.world_model` reads the PWB World Model — companies, their +`pwb.world_model` reads the PWB World Model — companies, their identifiers over time, and the relations between them — **as it was knowable at a date**. The tables are private datasets on the Hugging Face Hub: @@ -41,7 +41,7 @@ closed or corrected. ## Resolving a ticker ```python -from pwb_toolbox import world_model as wm +from pwb import world_model as wm wm.resolve("GOOGL", "2024-01-02") # -> "E..." or None wm.resolve("GOOGL", "2024-01-02", details=True) # entity_id, cik, name, source, confidence, interval diff --git a/pwb/__init__.py b/pwb/__init__.py new file mode 100644 index 00000000..d72ca26a --- /dev/null +++ b/pwb/__init__.py @@ -0,0 +1,11 @@ +"""pwb: the Papers With Backtest library (``pip install paperswithbacktest``). + +Formerly ``pwb_toolbox`` (``pip install pwb-toolbox``). The old name stays +importable through the ``pwb-toolbox`` compatibility release, which depends on +this package, gives the very same modules and warns once (``DeprecationWarning``). +""" + +# The release this code is: what the harness checks report as ``toolboxVersion``. +# Kept equal to ``version`` in setup.cfg (tests/test_harness_checks.py checks it): +# the installed metadata can belong to another copy than the one imported. +__version__ = "0.2.0" diff --git a/pwb_toolbox/backtesting/__init__.py b/pwb/backtesting/__init__.py similarity index 68% rename from pwb_toolbox/backtesting/__init__.py rename to pwb/backtesting/__init__.py index b08fad80..67db8eda 100644 --- a/pwb_toolbox/backtesting/__init__.py +++ b/pwb/backtesting/__init__.py @@ -2,12 +2,25 @@ from ..engine import name as engine_name # The engine every class below is built on: Tradewind by default, backtrader when -# ``pwb_toolbox.engine.select("backtrader")`` or ``PWB_ENGINE=backtrader`` said so +# ``pwb.engine.select("backtrader")`` or ``PWB_ENGINE=backtrader`` said so # before this import. A strategy that needs ``bt`` takes it from here -# (``from pwb_toolbox.backtesting import bt``) and runs on whichever was chosen. -# On Tradewind the name ``backtrader`` is aliased to it (pwb_toolbox.engine.bind). +# (``from pwb.backtesting import bt``) and runs on whichever was chosen. +# On Tradewind the name ``backtrader`` is aliased to it (pwb.engine.bind). bt = _bind_engine() +# ``pwb.backtesting.bt`` is also an import path, with the engine's sub-modules, so a +# strategy never names an engine: ``from pwb.backtesting.bt import indicators as btind``, +# ``from pwb.backtesting.bt.feeds import PandasData`` (the corpus codemod's "toolbox" +# form, paperswithbacktest/tradewind#24). It follows the engine chosen above, so +# ``PWB_ENGINE=backtrader`` still takes such a strategy back to backtrader. +import sys as _sys + +_sys.modules[__name__ + ".bt"] = bt +for _sub in ("feeds", "indicators", "analyzers"): + if hasattr(bt, _sub): + _sys.modules[f"{__name__}.bt.{_sub}"] = getattr(bt, _sub) +del _sys, _sub + from .base_strategy import BaseStrategy from .commission import ( get_commissions, diff --git a/pwb_toolbox/backtesting/backtest_engine.py b/pwb/backtesting/backtest_engine.py similarity index 99% rename from pwb_toolbox/backtesting/backtest_engine.py rename to pwb/backtesting/backtest_engine.py index ac8a7ccb..2c8e4a27 100644 --- a/pwb_toolbox/backtesting/backtest_engine.py +++ b/pwb/backtesting/backtest_engine.py @@ -7,13 +7,13 @@ import time import pandas as pd import numpy as np -import pwb_toolbox.backtesting as pwb_bt -import pwb_toolbox.datasets as pwb_ds +import pwb.backtesting as pwb_bt +import pwb.datasets as pwb_ds from ..engine import check as _check_engine from ..engine import load as _load_engine -bt = _load_engine() # Tradewind by default, backtrader on request; see pwb_toolbox.engine +bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine from . import checks as _checks from . import lookahead as _lookahead from .feeds import ArrayPandasData @@ -655,7 +655,7 @@ def _pit_membership(symbols, present: pd.DataFrame, trading_days, cut: bool = Tr names = [s for s in present.columns if s in added and s not in explicit] if not names: return None - from pwb_toolbox.datasets.pit_universe import _ASOF_TOLERANCE, membership_mask + from pwb.datasets.pit_universe import _ASOF_TOLERANCE, membership_mask member = membership_mask(trading_days, names, *spec).to_numpy() rows = present[names].reindex(trading_days, fill_value=False).to_numpy(dtype=bool) @@ -1632,12 +1632,12 @@ def run_strategy( ``futures_options`` tunes it (``roll``, ``days_before``, ``cycle``, ``ranks``, ``adjust``, ``at_expiry``, ``margins``, ``end``). That path skips the funding re-runs and the point-in-time guards below; see - ``pwb_toolbox.backtesting.futures_run``. + ``pwb.backtesting.futures_run``. ``engine`` -- ``"backtrader"`` or ``"tradewind"``: the engine this run must be on. The package binds to one engine when it is imported - (``pwb_toolbox.engine``: ``PWB_ENGINE``, ``engine.use()``, or - ``python -m pwb_toolbox.engine --engine NAME script.py``), so a run cannot + (``pwb.engine``: ``PWB_ENGINE``, ``engine.use()``, or + ``python -m pwb.engine --engine NAME script.py``), so a run cannot switch; naming the other one raises ``RuntimeError`` instead of returning a NAV from the wrong engine. ``None`` (default) runs on the engine in force. @@ -1764,7 +1764,7 @@ def run_strategy( ``costs`` check warns when it was short and charged nothing. At 0 the run is the one of the releases before the parameter, bit for bit. A long-short template: ``docs/backtesting.md``, "Long-short by quantiles" - (``python -m pwb_toolbox.docs backtesting``). + (``python -m pwb.docs backtesting``). **Several orders on one name in one bar.** backtrader sizes ``order_target_*`` on the position as it stands, blind to the orders not diff --git a/pwb_toolbox/backtesting/base_strategy.py b/pwb/backtesting/base_strategy.py similarity index 98% rename from pwb_toolbox/backtesting/base_strategy.py rename to pwb/backtesting/base_strategy.py index 4ea9ca65..948aceab 100644 --- a/pwb_toolbox/backtesting/base_strategy.py +++ b/pwb/backtesting/base_strategy.py @@ -2,7 +2,7 @@ from ..engine import load as _load_engine -bt = _load_engine() # Tradewind by default, backtrader on request; see pwb_toolbox.engine +bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine class BaseStrategy(bt.Strategy): diff --git a/pwb_toolbox/backtesting/checks.py b/pwb/backtesting/checks.py similarity index 99% rename from pwb_toolbox/backtesting/checks.py rename to pwb/backtesting/checks.py index 974a362f..f3930ef4 100644 --- a/pwb_toolbox/backtesting/checks.py +++ b/pwb/backtesting/checks.py @@ -124,7 +124,7 @@ def _index_routes() -> dict: global _INDEX_ROUTES if _INDEX_ROUTES is None: try: - import pwb_toolbox.datasets as pwb_ds + import pwb.datasets as pwb_ds universe = pwb_ds.load_dataset("Universe-Daily-Price") _INDEX_ROUTES = { @@ -279,7 +279,7 @@ def universe_facts(symbols, present, routes: dict | None = None) -> dict: ``present`` is ``run_strategy``'s row mask (``True`` where a symbol has a real bar). Computed at load time so the check does not keep the panel. """ - import pwb_toolbox.datasets as pwb_ds + import pwb.datasets as pwb_ds if isinstance(symbols, str): symbols = [symbols] @@ -639,9 +639,9 @@ def enabled() -> bool: def toolbox_version() -> str | None: """The version of the code running, not of whatever the metadata says is installed.""" try: - import pwb_toolbox + import pwb - return getattr(pwb_toolbox, "__version__", None) + return getattr(pwb, "__version__", None) except Exception: # noqa: BLE001 return None diff --git a/pwb_toolbox/backtesting/commission.py b/pwb/backtesting/commission.py similarity index 99% rename from pwb_toolbox/backtesting/commission.py rename to pwb/backtesting/commission.py index 6b0f6097..5baa01e7 100644 --- a/pwb_toolbox/backtesting/commission.py +++ b/pwb/backtesting/commission.py @@ -63,7 +63,7 @@ from ..datasets import prepared_cache as _prepared from ..engine import load as _load_engine -bt = _load_engine() # Tradewind by default, backtrader on request; see pwb_toolbox.engine +bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine _MIN_OBS = 5 # need at least this many returns to attempt Roll _EPS = 1e-12 diff --git a/pwb_toolbox/backtesting/feeds.py b/pwb/backtesting/feeds.py similarity index 99% rename from pwb_toolbox/backtesting/feeds.py rename to pwb/backtesting/feeds.py index 372815cc..8ca7ea3d 100644 --- a/pwb_toolbox/backtesting/feeds.py +++ b/pwb/backtesting/feeds.py @@ -34,7 +34,7 @@ from ..engine import load as _load_engine -bt = _load_engine() # Tradewind by default, backtrader on request; see pwb_toolbox.engine +bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine if bt.__name__ != "backtrader": ArrayPandasData = bt.feeds.PandasData diff --git a/pwb_toolbox/backtesting/futures_run.py b/pwb/backtesting/futures_run.py similarity index 99% rename from pwb_toolbox/backtesting/futures_run.py rename to pwb/backtesting/futures_run.py index 5788d4c1..7a1cebdc 100644 --- a/pwb_toolbox/backtesting/futures_run.py +++ b/pwb/backtesting/futures_run.py @@ -451,7 +451,7 @@ def _add_futures_legs(engine, roots, daily, table, sessions, options, held=None) def _other_pivot(symbols, start, end): - import pwb_toolbox.datasets as pwb_ds + import pwb.datasets as pwb_ds pivot = pwb_ds.get_pricing(symbol_list=symbols, fields=["open", "high", "low", "close"], start_date=start.strftime("%Y-%m-%d"), extend=True) @@ -491,7 +491,7 @@ def run_futures_strategy(indicator_cls, indicator_kwargs, strategy_cls, strategy if not is_tradewind(): raise RuntimeError( "futures= needs Tradewind (tradewind.futures, the default engine): unset PWB_ENGINE=backtrader " - "or pwb_toolbox.engine.select('tradewind') before importing pwb_toolbox.backtesting") + "or pwb.engine.select('tradewind') before importing pwb.backtesting") options = _options(futures_options) parsed = _parse_futures(futures) roots = [r for r, _ in parsed] diff --git a/pwb_toolbox/backtesting/indicators.py b/pwb/backtesting/indicators.py similarity index 99% rename from pwb_toolbox/backtesting/indicators.py rename to pwb/backtesting/indicators.py index 1806613e..6ba159f4 100644 --- a/pwb_toolbox/backtesting/indicators.py +++ b/pwb/backtesting/indicators.py @@ -2,7 +2,7 @@ from ..engine import load as _load_engine -bt = _load_engine() # Tradewind by default, backtrader on request; see pwb_toolbox.engine +bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine class SigmoidLongCompositeIndicator(bt.Indicator): @@ -102,7 +102,7 @@ class CrossSectionalQuantileSignal(bt.Indicator): symbols=["sp500"], ..., short_borrow_bps=50, ) - (the full example: ``python -m pwb_toolbox.docs backtesting``, section + (the full example: ``python -m pwb.docs backtesting``, section "Long-short by quantiles"). Contract diff --git a/pwb_toolbox/backtesting/lookahead.py b/pwb/backtesting/lookahead.py similarity index 98% rename from pwb_toolbox/backtesting/lookahead.py rename to pwb/backtesting/lookahead.py index 124e03ef..113031d0 100644 --- a/pwb_toolbox/backtesting/lookahead.py +++ b/pwb/backtesting/lookahead.py @@ -355,7 +355,7 @@ def analyse(code: str, allowed_datasets: list[str] | None = None) -> dict: def _is_ours(filename: str) -> bool: - """A frame or class of pwb_toolbox itself: the harness, not the strategy.""" + """A frame or class of pwb itself: the harness, not the strategy.""" try: return os.path.abspath(filename).startswith(_PACKAGE_DIR + os.sep) except (TypeError, ValueError): @@ -439,7 +439,7 @@ def strategy_source(strategy_cls=None, indicator_cls=None, caller=None) -> list[ its file, from ``linecache`` (notebook cells register there), or recovered from the caller of ``exec`` (:func:`_exec_source`); 2. the files the strategy and indicator classes were defined in, when - they are not that script and not pwb_toolbox itself. + they are not that script and not pwb itself. An empty list means nothing could be read: the check then says so rather than passing. @@ -480,11 +480,11 @@ def strategy_source(strategy_cls=None, indicator_cls=None, caller=None) -> list[ def main() -> int: - """``python -m pwb_toolbox.backtesting.lookahead [datasets_csv]``.""" + """``python -m pwb.backtesting.lookahead [datasets_csv]``.""" import json if len(sys.argv) < 2: - print("Usage: python -m pwb_toolbox.backtesting.lookahead [allowed_datasets_csv]", + print("Usage: python -m pwb.backtesting.lookahead [allowed_datasets_csv]", file=sys.stderr) return 1 path = sys.argv[1] diff --git a/pwb_toolbox/backtesting/optimization_engine.py b/pwb/backtesting/optimization_engine.py similarity index 100% rename from pwb_toolbox/backtesting/optimization_engine.py rename to pwb/backtesting/optimization_engine.py diff --git a/pwb_toolbox/backtesting/option_costs.py b/pwb/backtesting/option_costs.py similarity index 98% rename from pwb_toolbox/backtesting/option_costs.py rename to pwb/backtesting/option_costs.py index 4ba4349f..7696cc66 100644 --- a/pwb_toolbox/backtesting/option_costs.py +++ b/pwb/backtesting/option_costs.py @@ -5,7 +5,7 @@ model behind that half spread was a literal pasted into every option strategy (``HALF_SPREAD_BY_TIER`` and ``HALF_SPREAD_BY_UNDERLYING``). It now lives in ``paperswithbacktest/Options-Yearly-TransactionCostParams``, like the stock, -forex and crypto spreads in :mod:`pwb_toolbox.backtesting.commission`, and this +forex and crypto spreads in :mod:`pwb.backtesting.commission`, and this module reads it. The model @@ -36,7 +36,7 @@ Usage:: - from pwb_toolbox.backtesting import options_half_spread, option_volume_tier + from pwb.backtesting import options_half_spread, option_volume_tier tier = option_volume_tier(mean_daily_option_volume) cost = 100 * options_half_spread(price, otm, tier=tier, underlying="SPY", year=2018) diff --git a/pwb_toolbox/backtesting/portfolio.py b/pwb/backtesting/portfolio.py similarity index 99% rename from pwb_toolbox/backtesting/portfolio.py rename to pwb/backtesting/portfolio.py index b60ac13f..06dce64d 100644 --- a/pwb_toolbox/backtesting/portfolio.py +++ b/pwb/backtesting/portfolio.py @@ -5,7 +5,7 @@ from typing import Dict, Any import pandas as pd -import pwb_toolbox.performance as pwb_perf +import pwb.performance as pwb_perf def run_portfolio( diff --git a/pwb_toolbox/backtesting/strategies.py b/pwb/backtesting/strategies.py similarity index 99% rename from pwb_toolbox/backtesting/strategies.py rename to pwb/backtesting/strategies.py index 411f666e..67595523 100644 --- a/pwb_toolbox/backtesting/strategies.py +++ b/pwb/backtesting/strategies.py @@ -2,7 +2,7 @@ from ..engine import load as _load_engine -bt = _load_engine() # Tradewind by default, backtrader on request; see pwb_toolbox.engine +bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine from .base_strategy import BaseStrategy diff --git a/pwb_toolbox/backtesting/universe.py b/pwb/backtesting/universe.py similarity index 94% rename from pwb_toolbox/backtesting/universe.py rename to pwb/backtesting/universe.py index 0b49dbf5..cb5575b0 100644 --- a/pwb_toolbox/backtesting/universe.py +++ b/pwb/backtesting/universe.py @@ -1,6 +1,6 @@ from typing import List import pandas as pd -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds def get_most_liquid_symbols(n: int = 1_200, as_of=None) -> List[str]: @@ -20,7 +20,7 @@ def get_most_liquid_symbols(n: int = 1_200, as_of=None) -> List[str]: strategy that wants the membership enforced per date should load through ``symbols=["sp500"]``, which applies it, or call this per rebalance date. """ - from pwb_toolbox.datasets.pit_universe import load_pit_universe, pit_symbols + from pwb.datasets.pit_universe import load_pit_universe, pit_symbols if as_of is None: return pit_symbols(n) diff --git a/pwb_toolbox/datasets/__init__.py b/pwb/datasets/__init__.py similarity index 99% rename from pwb_toolbox/datasets/__init__.py rename to pwb/datasets/__init__.py index 509b228f..d6d7454d 100644 --- a/pwb_toolbox/datasets/__init__.py +++ b/pwb/datasets/__init__.py @@ -1999,7 +1999,7 @@ def load_dataset( # same repository, and an exact match let that spelling through. raise ValueError( "Options-Daily-Price is not loaded whole: use " - "pwb_toolbox.datasets.load_option_chain(underlyings, start, end, columns=...), " + "pwb.datasets.load_option_chain(underlyings, start, end, columns=...), " "which downloads only the chains and months asked for." ) @@ -2141,7 +2141,7 @@ def load_dataset( def _indices_to_usd(df: pd.DataFrame, requested=None) -> pd.DataFrame: - """Every index level in dollars; see :mod:`pwb_toolbox.datasets.index_currencies`.""" + """Every index level in dollars; see :mod:`pwb.datasets.index_currencies`.""" if df.empty or "symbol" not in df.columns: return df currencies = needed_currencies(df["symbol"].unique()) diff --git a/pwb_toolbox/datasets/french.py b/pwb/datasets/french.py similarity index 99% rename from pwb_toolbox/datasets/french.py rename to pwb/datasets/french.py index 95921e99..b29b0b57 100644 --- a/pwb_toolbox/datasets/french.py +++ b/pwb/datasets/french.py @@ -22,7 +22,7 @@ Example:: - from pwb_toolbox.datasets import load_french + from pwb.datasets import load_french ff5 = load_french("ff5") # monthly, decimal mom = load_french("mom", frequency="daily") diff --git a/pwb_toolbox/datasets/futures.py b/pwb/datasets/futures.py similarity index 99% rename from pwb_toolbox/datasets/futures.py rename to pwb/datasets/futures.py index a83d861a..77fbea0b 100644 --- a/pwb_toolbox/datasets/futures.py +++ b/pwb/datasets/futures.py @@ -16,7 +16,7 @@ of some roots into a Tradewind engine (one feed per contract, expiries, margins, the chain each ``tradewind.futures.Roller`` rolls on):: - from pwb_toolbox.datasets import add_futures, load_futures + from pwb.datasets import add_futures, load_futures daily = load_futures("CL", start="2020-01-01") # every CL contract chain = load_futures("CL", kind="chain") # FutureChain, no feeds diff --git a/pwb_toolbox/datasets/index_currencies.py b/pwb/datasets/index_currencies.py similarity index 100% rename from pwb_toolbox/datasets/index_currencies.py rename to pwb/datasets/index_currencies.py diff --git a/pwb_toolbox/datasets/option_cache.py b/pwb/datasets/option_cache.py similarity index 100% rename from pwb_toolbox/datasets/option_cache.py rename to pwb/datasets/option_cache.py diff --git a/pwb_toolbox/datasets/options.py b/pwb/datasets/options.py similarity index 99% rename from pwb_toolbox/datasets/options.py rename to pwb/datasets/options.py index d61f17f3..82c9a6c6 100644 --- a/pwb_toolbox/datasets/options.py +++ b/pwb/datasets/options.py @@ -22,7 +22,7 @@ Example:: - from pwb_toolbox.datasets import load_option_chain + from pwb.datasets import load_option_chain chain = load_option_chain(["SPY"], "2024-01-01", "2024-03-31", columns=["expiration", "strike", "option_type", "close", diff --git a/pwb_toolbox/datasets/pit_universe.py b/pwb/datasets/pit_universe.py similarity index 100% rename from pwb_toolbox/datasets/pit_universe.py rename to pwb/datasets/pit_universe.py diff --git a/pwb_toolbox/datasets/prepared_cache.py b/pwb/datasets/prepared_cache.py similarity index 99% rename from pwb_toolbox/datasets/prepared_cache.py rename to pwb/datasets/prepared_cache.py index 8b97a9ae..ec085361 100644 --- a/pwb_toolbox/datasets/prepared_cache.py +++ b/pwb/datasets/prepared_cache.py @@ -16,7 +16,7 @@ * the call -- function, every argument (defaults included), the ``PWB_*`` settings of the environment and whether the subscriber API is in use; -* the code -- a hash of every ``.py`` file of the installed ``pwb_toolbox``, +* the code -- a hash of every ``.py`` file of the installed ``pwb``, and the versions of Python, pandas, numpy and pyarrow; * the data -- the **exact revision** (commit hash) of every dataset the process had resolved when the result was computed. @@ -53,7 +53,7 @@ * an argument the key cannot describe exactly. Side effects are replayed: what the computation printed to stdout (the -``[costs]`` and ``Warning:`` lines the harness reads) and the ``pwb_toolbox`` +``[costs]`` and ``Warning:`` lines the harness reads) and the ``pwb`` warnings it raised are written and raised again on a hit. Storage @@ -450,7 +450,7 @@ def __getattr__(self, name): class _Recorded: - """Prints of a computation, and the warnings ``pwb_toolbox`` code raised in it. + """Prints of a computation, and the warnings ``pwb`` code raised in it. The stack levels of those warnings already count the cache's wrapper, so they point at the caller of ``load_dataset``; a replayed one does too.""" @@ -467,7 +467,7 @@ def warn(message, category=None, stacklevel=1, *args, **kwargs): cat = category if category is not None else ( type(message) if isinstance(message, Warning) else UserWarning) caller = sys._getframe(1).f_globals.get("__name__", "") - if str(caller).startswith("pwb_toolbox"): + if caller == "pwb" or str(caller).startswith(("pwb.", "pwb_toolbox")): recorder.warnings.append((cat.__module__, cat.__qualname__, str(message))) return recorder._warn(message, category, stacklevel + 1, *args, **kwargs) diff --git a/pwb_toolbox/docs/__init__.py b/pwb/docs/__init__.py similarity index 98% rename from pwb_toolbox/docs/__init__.py rename to pwb/docs/__init__.py index db69dc2e..cf288c3e 100644 --- a/pwb_toolbox/docs/__init__.py +++ b/pwb/docs/__init__.py @@ -1,7 +1,7 @@ """The package's documentation pages, shipped in the wheel. A sandbox that installed ``pwb-toolbox`` from PyPI (the site's research chat, -a server task) has no checkout of the repository: ``python -m pwb_toolbox.docs +a server task) has no checkout of the repository: ``python -m pwb.docs backtesting`` prints ``docs/backtesting.md`` from the installed package. The copies here are kept identical to ``docs/`` by ``tests/test_docs_shipped.py``. """ diff --git a/pwb_toolbox/docs/__main__.py b/pwb/docs/__main__.py similarity index 78% rename from pwb_toolbox/docs/__main__.py rename to pwb/docs/__main__.py index c7e84812..4a001192 100644 --- a/pwb_toolbox/docs/__main__.py +++ b/pwb/docs/__main__.py @@ -1,4 +1,4 @@ -"""``python -m pwb_toolbox.docs [page]``: print a documentation page (default ``backtesting``).""" +"""``python -m pwb.docs [page]``: print a documentation page (default ``backtesting``).""" import sys diff --git a/pwb_toolbox/docs/backtesting.md b/pwb/docs/backtesting.md similarity index 96% rename from pwb_toolbox/docs/backtesting.md rename to pwb/docs/backtesting.md index e6704ab7..fc965a07 100644 --- a/pwb_toolbox/docs/backtesting.md +++ b/pwb/docs/backtesting.md @@ -1,16 +1,16 @@ # Backtesting -This page ships with the package: `python -m pwb_toolbox.docs backtesting` prints it. +This page ships with the package: `python -m pwb.docs backtesting` prints it. ## Choosing the engine -Every class in `pwb_toolbox.backtesting` is built on one engine, bound when the package is imported: [Tradewind](https://github.com/paperswithbacktest/tradewind), the Apache 2.0 engine compatible with the backtrader API, by default since 0.1.56, or backtrader. Choose before the import, by precedence: +Every class in `pwb.backtesting` is built on one engine, bound when the package is imported: [Tradewind](https://github.com/paperswithbacktest/tradewind), the Apache 2.0 engine compatible with the backtrader API, by default since 0.1.56, or backtrader. Choose before the import, by precedence: -1. `pwb_toolbox.engine.select("backtrader")` in code; +1. `pwb.engine.select("backtrader")` in code; 2. `PWB_ENGINE=backtrader` (or `tradewind`) in the environment, which switches a whole run without touching a strategy (`PWB_BACKTEST_ENGINE`, the name before 0.1.56, is read when `PWB_ENGINE` is not set); 3. the default, `tradewind`. -`PWB_ENGINE=backtrader` is the way back for one month after 0.1.56; backtrader stays installed with the package until then. The engine that was not chosen is never imported. On Tradewind, importing `pwb_toolbox.backtesting` also makes the name `backtrader` resolve to Tradewind, so a strategy that does `import backtrader as bt` afterwards runs on the same engine; if backtrader was imported first, a warning says so (call `pwb_toolbox.engine.use()` first, or set `PWB_ENGINE=backtrader`). A strategy that needs the engine module takes it from the package, `from pwb_toolbox.backtesting import bt`, and runs on whichever was chosen; `pwb_toolbox.backtesting.engine_name()` says which. Selecting after the import raises, rather than leaving half the classes on each engine. +`PWB_ENGINE=backtrader` is the way back for one month after 0.1.56; backtrader stays installed with the package until then. The engine that was not chosen is never imported. On Tradewind, importing `pwb.backtesting` also makes the name `backtrader` resolve to Tradewind, so a strategy that does `import backtrader as bt` afterwards runs on the same engine; if backtrader was imported first, a warning says so (call `pwb.engine.use()` first, or set `PWB_ENGINE=backtrader`). A strategy that needs the engine module takes it from the package, `from pwb.backtesting import bt`, and runs on whichever was chosen; `pwb.backtesting.engine_name()` says which. Selecting after the import raises, rather than leaving half the classes on each engine. ## Example of trading strategy @@ -21,8 +21,8 @@ Every class in `pwb_toolbox.backtesting` is built on one engine, bound when the ```python import numpy as np import backtrader as bt -import pwb_toolbox.backtesting as pwb_bt -import pwb_toolbox.datasets as pwb_ds +import pwb.backtesting as pwb_bt +import pwb.datasets as pwb_ds # ──────────────────────────────────────────────────────────────── @@ -259,7 +259,7 @@ equal weight, gross exposure `leverage`. Momentum 12-1 by deciles on the S&P 500 point in time, with a 50 bp/yr borrow on the short leg: ```python -from pwb_toolbox.backtesting import ( +from pwb.backtesting import ( CrossSectionalQuantileSignal, MonthlyLongShortQuantilePortfolio, run_strategy, @@ -333,9 +333,9 @@ one `Checks: lookahead pass, universe pass, execution pass, costs pass (3 ms)` l | `execution` | an order filled on the bar whose data produced it (cheat-on-close, cheat-on-open) | nothing was filled; or an `order_target_*` sent on a name that already had an open order on the same bar (see below) | | `costs` | more than 20 % of the traded value of stocks and ETFs charged the default floor instead of a measured spread | more than 5 % of it; or a flat commission set by the strategy; or a book that held short positions with `short_borrow_bps=0` ("short leg carries no borrow cost") | -The rules and thresholds are in `pwb_toolbox/backtesting/checks.py`; the look-ahead -analysis is `pwb_toolbox/backtesting/lookahead.py` (also `python -m -pwb_toolbox.backtesting.lookahead strategy.py`). A check never stops a backtest: one +The rules and thresholds are in `pwb/backtesting/checks.py`; the look-ahead +analysis is `pwb/backtesting/lookahead.py` (also `python -m +pwb.backtesting.lookahead strategy.py`). A check never stops a backtest: one that cannot run is reported as `warn` with the reason. `PWB_HARNESS_CHECKS=0` in the environment switches them off. When the book held short positions, the `costs` detail carries `shortBorrowBps`, `shortBorrowCost`, `shortBorrowStartNavShare` and @@ -362,7 +362,7 @@ close. The cost of a fill is half the quoted spread, in dollars, from `Options-Yearly-TransactionCostParams`: ```python -from pwb_toolbox.backtesting import options_half_spread, options_cost_breakdown, option_volume_tier +from pwb.backtesting import options_half_spread, options_cost_breakdown, option_volume_tier tier = option_volume_tier(mean_daily_option_volume) # 0 (<1k contracts) to 4 (>1M) otm = strike / spot if call else spot / strike @@ -581,7 +581,7 @@ The backtesting package is composed of a few focused modules: - `universe` – helpers for building trading universes (e.g. most liquid symbols). -`pwb_toolbox.backtesting.strategies` ships a collection of portfolio templates +`pwb.backtesting.strategies` ships a collection of portfolio templates with different rebalancing rules and signal expectations: - **DailyEqualWeightPortfolio** – holds all assets with a long signal and diff --git a/pwb_toolbox/docs/world_model.md b/pwb/docs/world_model.md similarity index 97% rename from pwb_toolbox/docs/world_model.md rename to pwb/docs/world_model.md index 9cd2d73b..e82daedc 100644 --- a/pwb_toolbox/docs/world_model.md +++ b/pwb/docs/world_model.md @@ -1,6 +1,6 @@ # World Model -`pwb_toolbox.world_model` reads the PWB World Model — companies, their +`pwb.world_model` reads the PWB World Model — companies, their identifiers over time, and the relations between them — **as it was knowable at a date**. The tables are private datasets on the Hugging Face Hub: @@ -41,7 +41,7 @@ closed or corrected. ## Resolving a ticker ```python -from pwb_toolbox import world_model as wm +from pwb import world_model as wm wm.resolve("GOOGL", "2024-01-02") # -> "E..." or None wm.resolve("GOOGL", "2024-01-02", details=True) # entity_id, cik, name, source, confidence, interval diff --git a/pwb_toolbox/engine.py b/pwb/engine.py similarity index 88% rename from pwb_toolbox/engine.py rename to pwb/engine.py index fa3e2e9d..34249ae8 100644 --- a/pwb_toolbox/engine.py +++ b/pwb/engine.py @@ -1,6 +1,6 @@ """Which engine runs the backtests: Tradewind, or backtrader. -``pwb_toolbox.backtesting`` is written against the backtrader API, and Tradewind +``pwb.backtesting`` is written against the backtrader API, and Tradewind (``pip install tradewind``) implements that same API under the Apache 2.0 licence. Every module of the backtesting package takes its ``bt`` from here instead of importing an engine itself, so the choice is made once, in one place, and the @@ -8,7 +8,7 @@ How to choose, in order of precedence: -1. ``pwb_toolbox.engine.select("backtrader")`` **before** ``pwb_toolbox.backtesting`` +1. ``pwb.engine.select("backtrader")`` **before** ``pwb.backtesting`` is imported. The base classes (``BaseStrategy`` is a ``bt.Strategy``) are bound at import time, so a choice made after that is refused rather than half applied. 2. The environment variable ``PWB_ENGINE`` (``tradewind`` or ``backtrader``), which is @@ -26,10 +26,10 @@ backtrader ``Cerebro`` around a Tradewind ``BaseStrategy``. :func:`use` (or the runner below) makes the name ``backtrader`` resolve to Tradewind for this process, so such code runs unchanged on the chosen engine; with backtrader chosen it does -nothing. Importing ``pwb_toolbox.backtesting`` on Tradewind installs that alias too +nothing. Importing ``pwb.backtesting`` on Tradewind installs that alias too when nothing has imported backtrader yet. The runner switches a campaign with one flag:: - python -m pwb_toolbox.engine --engine tradewind [--report] script.py [args ...] + python -m pwb.engine --engine tradewind [--report] script.py [args ...] runs ``script.py`` as ``__main__`` on that engine; ``--report`` adds one ``ENGINE ...`` line on exit saying which engine ran and whether any module was @@ -66,7 +66,7 @@ def _normalise(name) -> str: def select(name: str) -> str: """Choose the engine for this process. Returns the normalised name. - Must run before ``pwb_toolbox.backtesting`` is imported: once the package is + Must run before ``pwb.backtesting`` is imported: once the package is bound to an engine, asking for the other one raises ``RuntimeError`` instead of leaving half the classes on each engine. """ @@ -74,7 +74,7 @@ def select(name: str) -> str: key = _normalise(name) if _loaded is not None and _loaded[0] != key: raise RuntimeError( - f"pwb_toolbox.backtesting is already running on {_loaded[0]!r}; " + f"pwb.backtesting is already running on {_loaded[0]!r}; " f"select({key!r}) must be called before it is imported" ) _selected = key @@ -173,7 +173,7 @@ def use(engine: str | None = None, alias: bool = True): With ``alias`` (the default) code that imports ``backtrader`` by name runs on the chosen engine too (:func:`alias_backtrader`). Like :func:`select`, it must - run before ``pwb_toolbox.backtesting`` is imported. + run before ``pwb.backtesting`` is imported. """ if engine is not None: select(engine) @@ -183,11 +183,11 @@ def use(engine: str | None = None, alias: bool = True): def bind(): - """Load the engine for ``pwb_toolbox.backtesting`` and return ``bt``. + """Load the engine for ``pwb.backtesting`` and return ``bt``. On Tradewind (the default) it also installs the ``backtrader`` alias, as the parity runs did, so a strategy that does ``import backtrader as bt`` *after* - importing pwb_toolbox runs on the same engine as ``BaseStrategy``. When the + importing pwb runs on the same engine as ``BaseStrategy``. When the real backtrader was imported first, the alias is refused; the run would mix the two engines' classes, so this warns with the two ways out instead of failing later inside ``Cerebro``. @@ -202,8 +202,8 @@ def bind(): if current is None or current is bt: return alias_backtrader() warnings.warn( - "backtrader was imported before pwb_toolbox.backtesting, which runs on Tradewind " - f"(the default since 0.1.56): call pwb_toolbox.engine.use() before importing " + "backtrader was imported before pwb.backtesting, which runs on Tradewind " + f"(the default since 0.1.56): call pwb.engine.use() before importing " f"backtrader, or set {ENV_VAR}=backtrader to stay on backtrader", RuntimeWarning, stacklevel=3, @@ -222,9 +222,9 @@ def check(engine: str | None) -> str: if engine is not None and _normalise(engine) != current: raise RuntimeError( f"this process runs on {current!r}, not {_normalise(engine)!r}: the engine is " - f"chosen before pwb_toolbox.backtesting is imported -- set {ENV_VAR}=" - f"{_normalise(engine)}, call pwb_toolbox.engine.use({_normalise(engine)!r}) first, " - f"or run the script with python -m pwb_toolbox.engine --engine {_normalise(engine)}" + f"chosen before pwb.backtesting is imported -- set {ENV_VAR}=" + f"{_normalise(engine)}, call pwb.engine.use({_normalise(engine)!r}) first, " + f"or run the script with python -m pwb.engine --engine {_normalise(engine)}" ) return current @@ -250,13 +250,13 @@ def report_line() -> str: def main(argv=None) -> int: - """``python -m pwb_toolbox.engine [--engine NAME] [--report] script.py [args ...]``.""" + """``python -m pwb.engine [--engine NAME] [--report] script.py [args ...]``.""" import argparse import runpy import sys parser = argparse.ArgumentParser( - prog="python -m pwb_toolbox.engine", + prog="python -m pwb.engine", description="Run a script as __main__ on the chosen backtest engine.", ) parser.add_argument("--engine", choices=ENGINES, default=None, diff --git a/pwb_toolbox/execution/__init__.py b/pwb/execution/__init__.py similarity index 100% rename from pwb_toolbox/execution/__init__.py rename to pwb/execution/__init__.py diff --git a/pwb_toolbox/execution/broker_factory.py b/pwb/execution/broker_factory.py similarity index 97% rename from pwb_toolbox/execution/broker_factory.py rename to pwb/execution/broker_factory.py index 1052db7a..3665b63c 100644 --- a/pwb_toolbox/execution/broker_factory.py +++ b/pwb/execution/broker_factory.py @@ -23,7 +23,7 @@ Example ------- - >>> from pwb_toolbox.execution import create_connector + >>> from pwb.execution import create_connector >>> conn = create_connector({"broker": "ccxt", "exchange": "binance"}) >>> conn.connect() """ diff --git a/pwb_toolbox/execution/ccxt_connector.py b/pwb/execution/ccxt_connector.py similarity index 99% rename from pwb_toolbox/execution/ccxt_connector.py rename to pwb/execution/ccxt_connector.py index 50a3265b..877e8ed2 100644 --- a/pwb_toolbox/execution/ccxt_connector.py +++ b/pwb/execution/ccxt_connector.py @@ -7,7 +7,7 @@ Example ------- - >>> from pwb_toolbox.execution import create_connector + >>> from pwb.execution import create_connector >>> cc = create_connector({"broker": "ccxt", "exchange": "binance", "api_key": "...", "api_secret": "..."}) >>> cc.connect() >>> nav = cc.get_account_nav() diff --git a/pwb_toolbox/execution/ib_connector.py b/pwb/execution/ib_connector.py similarity index 99% rename from pwb_toolbox/execution/ib_connector.py rename to pwb/execution/ib_connector.py index 88c441db..0d097bae 100644 --- a/pwb_toolbox/execution/ib_connector.py +++ b/pwb/execution/ib_connector.py @@ -7,7 +7,7 @@ Example ------- - >>> from pwb_toolbox.execution import create_connector + >>> from pwb.execution import create_connector >>> ibc = create_connector({"broker": "ib"}) >>> ibc.connect() >>> nav = ibc.get_account_nav() diff --git a/pwb_toolbox/execution/live_utils.py b/pwb/execution/live_utils.py similarity index 100% rename from pwb_toolbox/execution/live_utils.py rename to pwb/execution/live_utils.py diff --git a/pwb_toolbox/execution/optimal_limit_order.py b/pwb/execution/optimal_limit_order.py similarity index 100% rename from pwb_toolbox/execution/optimal_limit_order.py rename to pwb/execution/optimal_limit_order.py diff --git a/pwb_toolbox/performance/__init__.py b/pwb/performance/__init__.py similarity index 100% rename from pwb_toolbox/performance/__init__.py rename to pwb/performance/__init__.py diff --git a/pwb_toolbox/performance/metrics.py b/pwb/performance/metrics.py similarity index 100% rename from pwb_toolbox/performance/metrics.py rename to pwb/performance/metrics.py diff --git a/pwb_toolbox/performance/nav_metrics.py b/pwb/performance/nav_metrics.py similarity index 100% rename from pwb_toolbox/performance/nav_metrics.py rename to pwb/performance/nav_metrics.py diff --git a/pwb_toolbox/performance/plots.py b/pwb/performance/plots.py similarity index 100% rename from pwb_toolbox/performance/plots.py rename to pwb/performance/plots.py diff --git a/pwb_toolbox/performance/reports.py b/pwb/performance/reports.py similarity index 100% rename from pwb_toolbox/performance/reports.py rename to pwb/performance/reports.py diff --git a/pwb_toolbox/performance/trade_stats.py b/pwb/performance/trade_stats.py similarity index 100% rename from pwb_toolbox/performance/trade_stats.py rename to pwb/performance/trade_stats.py diff --git a/pwb_toolbox/world_model/__init__.py b/pwb/world_model/__init__.py similarity index 90% rename from pwb_toolbox/world_model/__init__.py rename to pwb/world_model/__init__.py index 37e80e24..30e969ee 100644 --- a/pwb_toolbox/world_model/__init__.py +++ b/pwb/world_model/__init__.py @@ -9,12 +9,12 @@ * among those, each key keeps its latest publication, and the row whose half-open interval ``[valid_from, valid_to)`` holds the date is the answer. ->>> from pwb_toolbox import world_model as wm +>>> from pwb import world_model as wm >>> wm.resolve("TGX", "2012-06-01") # doctest: +SKIP >>> wm.resolve_panel(["TGX", "GOOGL"], dates) # doctest: +SKIP >>> wm.get_graph("2020-12-31", relations=["customer_of"]) # doctest: +SKIP -See ``docs/world_model.md`` (``python -m pwb_toolbox.docs world_model``). +See ``docs/world_model.md`` (``python -m pwb.docs world_model``). """ from ._source import LOCAL_DIR_ENV, WorldModelNotAvailable diff --git a/pwb_toolbox/world_model/_pit.py b/pwb/world_model/_pit.py similarity index 100% rename from pwb_toolbox/world_model/_pit.py rename to pwb/world_model/_pit.py diff --git a/pwb_toolbox/world_model/_source.py b/pwb/world_model/_source.py similarity index 100% rename from pwb_toolbox/world_model/_source.py rename to pwb/world_model/_source.py diff --git a/pwb_toolbox/world_model/reader.py b/pwb/world_model/reader.py similarity index 99% rename from pwb_toolbox/world_model/reader.py rename to pwb/world_model/reader.py index 250d35de..a8d28f58 100644 --- a/pwb_toolbox/world_model/reader.py +++ b/pwb/world_model/reader.py @@ -86,7 +86,7 @@ class WorldModel: Every method takes an ``as_of``: nothing published after it is read (``known_at <= as_of``), and the intervals are tested at its date. See - :func:`pwb_toolbox.world_model.resolve` for how a date is turned into a + :func:`pwb.world_model.resolve` for how a date is turned into a knowledge cutoff. """ diff --git a/pwb_toolbox/__init__.py b/pwb_toolbox/__init__.py deleted file mode 100644 index f55b266c..00000000 --- a/pwb_toolbox/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# The release this code is: what the harness checks report as ``toolboxVersion``. -# Kept equal to ``version`` in setup.cfg (tests/test_harness_checks.py checks it): -# the installed metadata can belong to another copy than the one imported. -__version__ = "0.1.56" diff --git a/setup.cfg b/setup.cfg index edb3ca2c..b0b5b7f0 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,9 +1,9 @@ [metadata] -name = pwb-toolbox -version = 0.1.56 +name = paperswithbacktest +version = 0.2.0 author = Papers With Backtest author_email = hello@paperswithbacktest.com -description = A toolbox library for quant traders +description = Papers With Backtest: datasets, backtesting harness and execution for quant traders (import pwb; formerly pwb-toolbox) long_description = file: README.md long_description_content_type = text/markdown url = https://paperswithbacktest.com @@ -52,11 +52,17 @@ install_requires = transformers webdriver_manager +[options.packages.find] +# pwb only: the pwb_toolbox compatibility package is its own release (compat/pwb-toolbox). +include = + pwb + pwb.* + [options.package_data] -# python -m pwb_toolbox.docs backtesting -pwb_toolbox.docs = *.md +# python -m pwb.docs backtesting +pwb.docs = *.md [options.extras_require] -# Kept so `pip install pwb-toolbox[tradewind]` still resolves; Tradewind is now required. +# Kept so `pip install paperswithbacktest[tradewind]` resolves like pwb-toolbox[tradewind]; Tradewind is required. tradewind = tradewind>=0.0.3 diff --git a/tests/_long_short_book.py b/tests/_long_short_book.py index e2dec2f7..18742cb7 100644 --- a/tests/_long_short_book.py +++ b/tests/_long_short_book.py @@ -10,8 +10,8 @@ import numpy as np -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be from _synthetic import offline, panel, walk diff --git a/tests/_synthetic.py b/tests/_synthetic.py index b53a24cb..fda4a03d 100644 --- a/tests/_synthetic.py +++ b/tests/_synthetic.py @@ -11,7 +11,7 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds def walk(rng, start, mu, sigma, n): diff --git a/tests/conftest.py b/tests/conftest.py index 767deae1..2fab03e1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,7 +7,7 @@ ``checks._INDEX_ROUTES`` itself. """ -import pwb_toolbox.backtesting.checks as _checks +import pwb.backtesting.checks as _checks _checks._INDEX_ROUTES = {} diff --git a/tests/test_api_cache.py b/tests/test_api_cache.py index 52cdd64f..d5eac241 100644 --- a/tests/test_api_cache.py +++ b/tests/test_api_cache.py @@ -23,7 +23,7 @@ import pyarrow as pa import pyarrow.parquet as pq -import pwb_toolbox.datasets as ds +import pwb.datasets as ds NAME = "Test-Daily-Price" MONTHS = ["2019-01", "2019-02", "2019-03", "2019-04"] diff --git a/tests/test_array_feed.py b/tests/test_array_feed.py index 12158b52..07b89621 100644 --- a/tests/test_array_feed.py +++ b/tests/test_array_feed.py @@ -12,10 +12,10 @@ import numpy as np import pandas as pd -from pwb_toolbox import engine -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.backtesting.feeds import ArrayPandasData +from pwb import engine +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be +from pwb.backtesting.feeds import ArrayPandasData from _synthetic import offline, panel diff --git a/tests/test_bare_symbol_collisions.py b/tests/test_bare_symbol_collisions.py index eeaf2ac6..68e19c15 100644 --- a/tests/test_bare_symbol_collisions.py +++ b/tests/test_bare_symbol_collisions.py @@ -29,8 +29,8 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import pit_universe +import pwb.datasets as ds +from pwb.datasets import pit_universe ETF = "paperswithbacktest/ETFs-Daily-Price" STK = "paperswithbacktest/Stocks-Daily-Price" diff --git a/tests/test_bond_rates.py b/tests/test_bond_rates.py index 7d520bfd..49cbb686 100644 --- a/tests/test_bond_rates.py +++ b/tests/test_bond_rates.py @@ -13,7 +13,7 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as pwb_ds +import pwb.datasets as pwb_ds def _frame(rows): diff --git a/tests/test_bounded_loader.py b/tests/test_bounded_loader.py index 5ea4258a..2ff73740 100644 --- a/tests/test_bounded_loader.py +++ b/tests/test_bounded_loader.py @@ -17,7 +17,7 @@ import pyarrow as pa import pyarrow.parquet as pq -import pwb_toolbox.datasets as ds +import pwb.datasets as ds SYMBOLS = ["AAA", "BBB", "CCC"] MONTHS = ["2024-01", "2024-02", "2024-03"] diff --git a/tests/test_compat_shim.py b/tests/test_compat_shim.py new file mode 100644 index 00000000..933b8b6b --- /dev/null +++ b/tests/test_compat_shim.py @@ -0,0 +1,118 @@ +"""``pwb_toolbox`` after the rename: the same modules as ``pwb``, with one warning. + +The compatibility package lives in ``compat/pwb-toolbox`` (its own release, +``pwb-toolbox`` 0.2.0, which depends on ``paperswithbacktest``). Each case runs +in a subprocess with that directory on the path, because the alias installs an +import hook and files modules under two names for the life of the process. +""" + +import configparser +import os +import subprocess +import sys +import textwrap +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +COMPAT = os.path.join(ROOT, "compat", "pwb-toolbox") + + +def _run(code, *args): + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join( + p for p in (COMPAT, ROOT, env.get("PYTHONPATH", "")) if p + ) + env.pop("PWB_BACKTEST_ENGINE", None) + env.pop("PWB_ENGINE", None) + env["TQDM_DISABLE"] = "1" + proc = subprocess.run( + [sys.executable, *args] if code is None else [sys.executable, "-c", textwrap.dedent(code)], + env=env, capture_output=True, text=True, check=False, cwd=ROOT, + ) + if proc.returncode: + raise AssertionError(proc.stderr.strip().splitlines()[-1] if proc.stderr.strip() else proc.stdout) + return proc.stdout.strip() + + +class CompatShimTest(unittest.TestCase): + def test_one_deprecation_warning_naming_the_new_package(self): + out = _run( + """ + import warnings + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + import pwb_toolbox + import pwb_toolbox.datasets + import pwb_toolbox.backtesting + import pwb_toolbox + ours = [w for w in caught if issubclass(w.category, DeprecationWarning) + and "pwb_toolbox has been renamed pwb" in str(w.message)] + print(len(ours), "paperswithbacktest" in str(ours[0].message)) + """ + ) + self.assertEqual(out, "1 True") + + def test_old_names_are_the_same_module_objects(self): + out = _run( + """ + import sys, warnings + warnings.simplefilter("ignore") + import pwb_toolbox + import pwb_toolbox.backtesting as old_bt + import pwb_toolbox.datasets as old_ds + from pwb_toolbox.datasets.pit_universe import load_pit_universe + from pwb_toolbox.backtesting import BaseStrategy, run_strategy + import pwb, pwb.backtesting, pwb.datasets, pwb.datasets.pit_universe + checks = [ + pwb_toolbox is pwb, + old_bt is pwb.backtesting, + old_ds is pwb.datasets, + load_pit_universe is pwb.datasets.pit_universe.load_pit_universe, + BaseStrategy is pwb.backtesting.BaseStrategy, + run_strategy is pwb.backtesting.run_strategy, + pwb.backtesting.__spec__.name == "pwb.backtesting", + ] + # nothing loaded twice: every pwb_toolbox.* entry is the pwb.* module + for name, mod in list(sys.modules.items()): + if name == "pwb_toolbox" or name.startswith("pwb_toolbox."): + checks.append(sys.modules["pwb" + name[len("pwb_toolbox"):]] is mod) + names = {m.__name__ for n, m in sys.modules.items() if n.startswith("pwb")} + checks.append(not any(n.startswith("pwb_toolbox") for n in names)) + print(all(checks), checks.count(False)) + """ + ) + self.assertEqual(out, "True 0") + + def test_engine_choice_is_shared(self): + out = _run( + """ + import warnings + warnings.simplefilter("ignore") + import pwb_toolbox.engine as old + import pwb.engine as new + old.select("tradewind") + print(old is new, new.name()) + """ + ) + self.assertEqual(out, "True tradewind") + + def test_the_engine_runner_answers_under_the_old_name(self): + out = _run(None, "-W", "ignore", "-m", "pwb_toolbox.engine", "--help") + self.assertIn("--engine", out) + + def test_each_release_owns_one_import_name(self): + main, compat = configparser.ConfigParser(), configparser.ConfigParser() + main.read(os.path.join(ROOT, "setup.cfg")) + compat.read(os.path.join(COMPAT, "setup.cfg")) + self.assertEqual(main.get("metadata", "name"), "paperswithbacktest") + self.assertEqual(main.get("options.packages.find", "include").split(), ["pwb", "pwb.*"]) + self.assertEqual(compat.get("metadata", "name"), "pwb-toolbox") + self.assertEqual(compat.get("options", "packages").strip(), "pwb_toolbox") + # the alias release requires at least the version it aliases + version = main.get("metadata", "version") + self.assertIn(f"paperswithbacktest>={version}", compat.get("options", "install_requires")) + self.assertEqual(compat.get("metadata", "version"), version) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_currency_costs.py b/tests/test_currency_costs.py index abd99d61..ebcedaf0 100644 --- a/tests/test_currency_costs.py +++ b/tests/test_currency_costs.py @@ -5,7 +5,7 @@ import pandas as pd -import pwb_toolbox.backtesting.commission as cm +import pwb.backtesting.commission as cm def _table(repo_id): diff --git a/tests/test_docs_shipped.py b/tests/test_docs_shipped.py index 53f20257..3834c8a1 100644 --- a/tests/test_docs_shipped.py +++ b/tests/test_docs_shipped.py @@ -5,8 +5,8 @@ import unittest from pathlib import Path -import pwb_toolbox.docs as docs -from pwb_toolbox.docs.__main__ import main +import pwb.docs as docs +from pwb.docs.__main__ import main ROOT = Path(__file__).resolve().parent.parent @@ -17,7 +17,7 @@ def test_copies_match_the_repository(self): for name in docs.pages(): self.assertEqual( docs.read(name), (ROOT / "docs" / f"{name}.md").read_text(encoding="utf-8"), - f"pwb_toolbox/docs/{name}.md differs from docs/{name}.md: copy it over", + f"pwb/docs/{name}.md differs from docs/{name}.md: copy it over", ) def test_command_prints_the_page(self): diff --git a/tests/test_engine_parity.py b/tests/test_engine_parity.py index 9b1d243e..7e967e4a 100644 --- a/tests/test_engine_parity.py +++ b/tests/test_engine_parity.py @@ -4,7 +4,7 @@ that everything *this package* wires around a strategy -- ``BaseStrategy``'s log, ``ArrayPandasData``, the per-symbol ``SpreadImpactCommission`` with a yearly schedule, ``FundingAudit`` / ``FillAudit``, the listing guard and the -exposure cap -- behaves the same whichever engine ``pwb_toolbox.engine`` +exposure cap -- behaves the same whichever engine ``pwb.engine`` picked. Synthetic bars, no download, a few seconds. Skipped unless both engines are importable by this interpreter. @@ -17,17 +17,17 @@ import sys import unittest -from pwb_toolbox import engine +from pwb import engine SCRIPT = r""" import json import numpy as np import pandas as pd -import pwb_toolbox.backtesting as pwb_bt -from pwb_toolbox.backtesting.backtest_engine import ( +import pwb.backtesting as pwb_bt +from pwb.backtesting.backtest_engine import ( FillAudit, FundingAudit, _refuse_before_listing, _with_exposure_cap, ) -from pwb_toolbox.backtesting.feeds import ArrayPandasData +from pwb.backtesting.feeds import ArrayPandasData bt = pwb_bt.bt rng = np.random.default_rng(3) diff --git a/tests/test_engine_runner.py b/tests/test_engine_runner.py index bda93ad8..eee4d12c 100644 --- a/tests/test_engine_runner.py +++ b/tests/test_engine_runner.py @@ -2,7 +2,7 @@ The strategy below is written the way ~150 corpus strategies are: it names ``backtrader`` itself (``import backtrader as bt``) next to ``BaseStrategy``. It -runs through ``python -m pwb_toolbox.engine --engine NAME --report``, which is +runs through ``python -m pwb.engine --engine NAME --report``, which is how a campaign switches engine without touching a strategy: on Tradewind the name ``backtrader`` resolves to Tradewind and no module of a backtrader package may be loaded. @@ -31,7 +31,7 @@ import textwrap import unittest -from pwb_toolbox import engine +from pwb import engine BOTH = bool(importlib.util.find_spec("backtrader") and importlib.util.find_spec("tradewind")) @@ -45,8 +45,8 @@ import numpy as np import pandas as pd - import pwb_toolbox.backtesting as pwb_bt - from pwb_toolbox.backtesting.feeds import ArrayPandasData + import pwb.backtesting as pwb_bt + from pwb.backtesting.feeds import ArrayPandasData GRID = os.environ.get("GRID") == "1" rng = np.random.default_rng(11) @@ -113,7 +113,7 @@ def _run(engine_name, script, extra_env=None): env = {k: v for k, v in os.environ.items() if k not in engine.ENV_VARS} env.update(TQDM_DISABLE="1", **(extra_env or {})) proc = subprocess.run( - [sys.executable, "-m", "pwb_toolbox.engine", "--engine", engine_name, "--report", script], + [sys.executable, "-m", "pwb.engine", "--engine", engine_name, "--report", script], env=env, capture_output=True, text=True, check=False, ) if proc.returncode: @@ -137,6 +137,11 @@ def setUpClass(cls): fh.write(STRATEGY) cls.bt_result, cls.bt_report = _run("backtrader", cls.script, {"GRID": cls.GRID}) cls.tw_result, cls.tw_report = _run("tradewind", cls.script, {"GRID": cls.GRID}) + # the same file after the corpus codemod's "toolbox" form: it names no engine + cls.neutral = os.path.join(cls.tmp.name, "strategy_neutral.py") + with open(cls.neutral, "w", encoding="utf-8") as fh: + fh.write(STRATEGY.replace("import backtrader as bt\n", "from pwb.backtesting import bt\n")) + cls.neutral_tw, _ = _run("tradewind", cls.neutral, {"GRID": cls.GRID}) @classmethod def tearDownClass(cls): @@ -163,6 +168,12 @@ def test_nav_paths_are_bit_identical(self): self.assertEqual(ref["cash"], cand["cash"]) self.assertEqual(ref["positions"], cand["positions"]) + def test_engine_neutral_file_gives_the_same_path(self): + with open(self.neutral, encoding="utf-8") as fh: + self.assertNotIn("backtrader", fh.read()) + self.assertEqual(self.neutral_tw["bt"], "tradewind") + self.assertEqual(self.neutral_tw["hex"], self.tw_result["hex"]) + @unittest.skipUnless(BOTH, "both engines are needed") class SameNavOnFloatPricesTest(SameNavToTheBitTest): @@ -193,7 +204,7 @@ class AliasAndCheckTest(unittest.TestCase): @unittest.skipUnless(BOTH, "both engines are needed") def test_alias_is_refused_once_the_real_backtrader_is_loaded(self): proc = _subprocess( - "import backtrader, pwb_toolbox.engine as e\n" + "import backtrader, pwb.engine as e\n" "try:\n e.use('tradewind')\nexcept RuntimeError as exc:\n print('refused', exc)\n", "tradewind", ) @@ -202,12 +213,12 @@ def test_alias_is_refused_once_the_real_backtrader_is_loaded(self): @unittest.skipUnless(importlib.util.find_spec("tradewind"), "tradewind not installed") def test_alias_gives_the_submodules_the_corpus_imports(self): proc = _subprocess( - "import pwb_toolbox.engine as e\n" + "import pwb.engine as e\n" "bt = e.use('tradewind')\n" "import backtrader, backtrader.feeds, backtrader.indicators as btind\n" "from backtrader.utils.date import num2date\n" "from backtrader.feeds import PandasData\n" - "import pwb_toolbox.backtesting as b\n" + "import pwb.backtesting as b\n" "assert backtrader is bt and btind is bt.indicators and PandasData is bt.PandasData\n" "assert num2date is bt.num2date and b.bt is bt\n" "assert b.BaseStrategy.__mro__[1].__module__.split('.')[0] == 'tradewind'\n" @@ -219,7 +230,7 @@ def test_alias_gives_the_submodules_the_corpus_imports(self): @unittest.skipUnless(importlib.util.find_spec("backtrader"), "backtrader not installed") def test_alias_is_a_no_op_on_backtrader(self): proc = _subprocess( - "import sys, pwb_toolbox.engine as e\n" + "import sys, pwb.engine as e\n" "bt = e.use()\n" "import backtrader\n" "print(bt is backtrader, 'tradewind' in sys.modules)\n", @@ -230,7 +241,7 @@ def test_alias_is_a_no_op_on_backtrader(self): @unittest.skipUnless(importlib.util.find_spec("backtrader"), "backtrader not installed") def test_run_strategy_refuses_the_engine_it_is_not_on(self): proc = _subprocess( - "import pwb_toolbox.backtesting as b\n" + "import pwb.backtesting as b\n" "try:\n" " b.run_strategy(None, {}, None, {}, [], '2020-01-01', 1, engine='tradewind')\n" "except RuntimeError as exc:\n" @@ -240,6 +251,19 @@ def test_run_strategy_refuses_the_engine_it_is_not_on(self): self.assertIn("refused: this process runs on 'backtrader', not 'tradewind'", proc.stdout, proc.stderr) + def test_engine_is_an_import_path_under_the_toolbox(self): + for name in [n for n in ("backtrader", "tradewind") if importlib.util.find_spec(n)]: + proc = _subprocess( + "import pwb.backtesting as b\n" + "from pwb.backtesting.bt import indicators as btind, num2date\n" + "from pwb.backtesting.bt.feeds import PandasData\n" + "import pwb.backtesting.bt as bt2\n" + "assert bt2 is b.bt and btind is b.bt.indicators and PandasData is b.bt.feeds.PandasData\n" + "print(b.bt.__name__)\n", + name, + ) + self.assertEqual(proc.stdout.strip(), name, proc.stderr) + def test_check_accepts_the_engine_in_force(self): self.assertEqual(engine.check(None), engine.name()) self.assertEqual(engine.check(engine.name().upper()), engine.name()) diff --git a/tests/test_engine_selector.py b/tests/test_engine_selector.py index 9dd79918..16c3fa15 100644 --- a/tests/test_engine_selector.py +++ b/tests/test_engine_selector.py @@ -2,7 +2,7 @@ Every case that binds the package runs in a subprocess, because a bound package cannot be unbound: ``BaseStrategy`` is a subclass of the chosen engine's -``Strategy`` from the moment ``pwb_toolbox.backtesting`` is imported. +``Strategy`` from the moment ``pwb.backtesting`` is imported. """ import importlib.util @@ -11,7 +11,7 @@ import sys import unittest -from pwb_toolbox import engine +from pwb import engine ENV = engine.ENV_VAR LEGACY = engine.LEGACY_ENV_VAR @@ -36,7 +36,7 @@ def _run(code, engine_name=None, var=ENV): # The last two fields: what the name ``backtrader`` resolves to (the real package, # Tradewind through the alias, or nothing), and whether tradewind is imported. REPORT = ( - "import sys, pwb_toolbox.backtesting as b; " + "import sys, pwb.backtesting as b; " "print(b.engine_name(), b.bt.__name__, b.BaseStrategy.__mro__[1].__module__.split('.')[0], " "getattr(sys.modules.get('backtrader'), '__name__', None), 'tradewind' in sys.modules)" ) @@ -83,7 +83,7 @@ def test_backtrader_imported_first_warns_instead_of_mixing_silently(self): code = ( "import warnings; warnings.simplefilter('error', RuntimeWarning)\n" "import backtrader\n" - "try:\n import pwb_toolbox.backtesting\n" + "try:\n import pwb.backtesting\n" "except RuntimeWarning as exc:\n print('warned', 'PWB_ENGINE=backtrader' in str(exc))\n" ) self.assertEqual(_run(code), "warned True") @@ -96,13 +96,13 @@ def test_environment_picks_tradewind_without_importing_backtrader(self): @unittest.skipUnless(_installed("backtrader"), "backtrader not installed") def test_select_before_import_wins_over_the_default(self): - code = "import pwb_toolbox.engine as e; e.select('backtrader'); " + REPORT + code = "import pwb.engine as e; e.select('backtrader'); " + REPORT self.assertEqual(_run(code), "backtrader backtrader backtrader backtrader False") @unittest.skipUnless(_installed("tradewind"), "tradewind not installed") def test_select_after_import_is_refused(self): code = ( - "import pwb_toolbox.engine as e, pwb_toolbox.backtesting\n" + "import pwb.engine as e, pwb.backtesting\n" "try:\n e.select('backtrader')\n" "except RuntimeError as exc:\n print('refused')\n" ) @@ -111,14 +111,14 @@ def test_select_after_import_is_refused(self): @unittest.skipUnless(_installed("tradewind"), "tradewind not installed") def test_array_feed_is_the_engines_pandas_feed_on_tradewind(self): code = ( - "import pwb_toolbox.backtesting as b; from pwb_toolbox.backtesting.feeds import ArrayPandasData; " + "import pwb.backtesting as b; from pwb.backtesting.feeds import ArrayPandasData; " "print(ArrayPandasData is b.bt.feeds.PandasData)" ) self.assertEqual(_run(code, "tradewind"), "True") def test_unknown_engine_in_the_environment_is_an_error(self): proc = subprocess.run( - [sys.executable, "-c", "import pwb_toolbox.backtesting"], + [sys.executable, "-c", "import pwb.backtesting"], env={**{k: v for k, v in os.environ.items() if k not in engine.ENV_VARS}, ENV: "zipline"}, capture_output=True, text=True, check=False, ) diff --git a/tests/test_exposure_cap.py b/tests/test_exposure_cap.py index 40fa0396..9b35a00d 100644 --- a/tests/test_exposure_cap.py +++ b/tests/test_exposure_cap.py @@ -21,8 +21,8 @@ import numpy as np import pandas as pd -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be from _synthetic import offline, panel diff --git a/tests/test_forex_directions.py b/tests/test_forex_directions.py index e960317c..01053ddc 100644 --- a/tests/test_forex_directions.py +++ b/tests/test_forex_directions.py @@ -15,7 +15,7 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as ds +import pwb.datasets as ds DATES = ["2020-01-02", "2020-01-03", "2020-01-06", "2020-01-07"] diff --git a/tests/test_french.py b/tests/test_french.py index 1d4fc4e5..c4a9603d 100644 --- a/tests/test_french.py +++ b/tests/test_french.py @@ -24,7 +24,7 @@ import pandas as pd import requests -from pwb_toolbox.datasets import french +from pwb.datasets import french FIXTURES = Path(__file__).resolve().parent / "data" / "french" diff --git a/tests/test_futures_loader.py b/tests/test_futures_loader.py index b2f9effe..79da3a25 100644 --- a/tests/test_futures_loader.py +++ b/tests/test_futures_loader.py @@ -5,7 +5,7 @@ import pandas as pd import pytest -from pwb_toolbox.datasets import futures as fut +from pwb.datasets import futures as fut def _tables(): diff --git a/tests/test_futures_run.py b/tests/test_futures_run.py index 762d8133..4b9e65c1 100644 --- a/tests/test_futures_run.py +++ b/tests/test_futures_run.py @@ -1,7 +1,7 @@ """``run_strategy(..., futures=[...])``: a card in the standard shape trading gold contracts. Synthetic Futures-Daily-Price tables and cost table, no download. Run in a subprocess on -Tradewind (the engine is bound when ``pwb_toolbox.backtesting`` is imported). Skipped +Tradewind (the engine is bound when ``pwb.backtesting`` is imported). Skipped unless ``tradewind.futures`` with liquid cycles is importable. """ @@ -17,9 +17,9 @@ import json import numpy as np import pandas as pd -import pwb_toolbox.backtesting as pwb_bt -from pwb_toolbox.backtesting import commission as cm -from pwb_toolbox.datasets import futures as fds +import pwb.backtesting as pwb_bt +from pwb.backtesting import commission as cm +from pwb.datasets import futures as fds # Gold: February and April are in the cycle (G J M Q V Z), March is a serial month that # trades more than February from the start -- a roll on every listed month would hold it. @@ -132,9 +132,9 @@ def test_a_standard_card_trades_contracts_through_run_strategy(): RANKS_SCRIPT = r""" import json import pandas as pd -import pwb_toolbox.backtesting as pwb_bt -from pwb_toolbox.backtesting import commission as cm -from pwb_toolbox.datasets import futures as fds +import pwb.backtesting as pwb_bt +from pwb.backtesting import commission as cm +from pwb.datasets import futures as fds # Crude: a contract every month (CL rolls through every month); the front trades most, so # the rule rolls a rank five days before its last trading date diff --git a/tests/test_harness_checks.py b/tests/test_harness_checks.py index bb936623..17e4bf31 100644 --- a/tests/test_harness_checks.py +++ b/tests/test_harness_checks.py @@ -16,11 +16,11 @@ import numpy as np import pandas as pd -import pwb_toolbox.backtesting as pwb_bt -import pwb_toolbox.backtesting.checks as checks -import pwb_toolbox.backtesting.commission as cm -from pwb_toolbox.datasets import PIT_UNIVERSES -from pwb_toolbox.datasets import pit_universe +import pwb.backtesting as pwb_bt +import pwb.backtesting.checks as checks +import pwb.backtesting.commission as cm +from pwb.datasets import PIT_UNIVERSES +from pwb.datasets import pit_universe from _synthetic import offline, panel @@ -33,8 +33,8 @@ VINTAGES = {s: {y: 0.0005 for y in range(2010, 2027)} for s in NAMES + ("SPY", "TLT")} RUN = Template(''' -import pwb_toolbox.backtesting as pwb_bt -from pwb_toolbox.backtesting import BaseStrategy +import pwb.backtesting as pwb_bt +from pwb.backtesting import BaseStrategy class Monthly(BaseStrategy): @@ -174,7 +174,7 @@ def _known_gap_on_tradewind(test): signal bar, so the execution check stays ``pass``. Known since 0.1.56 made Tradewind the default; expectedFailure so the test flips when it is fixed. """ - from pwb_toolbox import engine + from pwb import engine return unittest.expectedFailure(test) if engine.is_tradewind() else test @@ -347,12 +347,12 @@ def test_nothing_filled_is_a_warning(self): class Version(unittest.TestCase): def test_the_reported_version_is_the_release(self): import configparser - import pwb_toolbox + import pwb setup = configparser.ConfigParser() setup.read(os.path.join(os.path.dirname(__file__), "..", "setup.cfg")) - self.assertEqual(pwb_toolbox.__version__, setup["metadata"]["version"]) - self.assertEqual(checks.toolbox_version(), pwb_toolbox.__version__) + self.assertEqual(pwb.__version__, setup["metadata"]["version"]) + self.assertEqual(checks.toolbox_version(), pwb.__version__) if __name__ == "__main__": diff --git a/tests/test_holiday_bars.py b/tests/test_holiday_bars.py index 23e1857f..667d4846 100644 --- a/tests/test_holiday_bars.py +++ b/tests/test_holiday_bars.py @@ -13,8 +13,8 @@ import numpy as np import pandas as pd -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be from _synthetic import offline, panel diff --git a/tests/test_hub_snapshot.py b/tests/test_hub_snapshot.py index cf648a3a..12861189 100644 --- a/tests/test_hub_snapshot.py +++ b/tests/test_hub_snapshot.py @@ -5,7 +5,7 @@ import unittest from unittest import mock -import pwb_toolbox.datasets as ds +import pwb.datasets as ds def _fake_cache(root, repo_id, sha, files): diff --git a/tests/test_index_currencies.py b/tests/test_index_currencies.py index dc35f51a..c07f4484 100644 --- a/tests/test_index_currencies.py +++ b/tests/test_index_currencies.py @@ -14,8 +14,8 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import index_currencies as ic +import pwb.datasets as ds +from pwb.datasets import index_currencies as ic DAY = "2024-12-30" diff --git a/tests/test_lookahead.py b/tests/test_lookahead.py index 8abbf576..35585de1 100644 --- a/tests/test_lookahead.py +++ b/tests/test_lookahead.py @@ -22,8 +22,8 @@ import pandas as pd -from pwb_toolbox.backtesting import lookahead -from pwb_toolbox.backtesting.lookahead import check_anchored_calendar_offsets +from pwb.backtesting import lookahead +from pwb.backtesting.lookahead import check_anchored_calendar_offsets # A first session on the 1st, two first sessions after a weekend, and a 2 January. MONDAY_THE_1ST = pd.Timestamp("2019-07-01") diff --git a/tests/test_option_cache.py b/tests/test_option_cache.py index 33c39034..23f79cc1 100644 --- a/tests/test_option_cache.py +++ b/tests/test_option_cache.py @@ -16,10 +16,10 @@ import pandas as pd import pyarrow.parquet as pq -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import option_cache as oc -from pwb_toolbox.datasets import options as opt -from pwb_toolbox.datasets import prepared_cache +import pwb.datasets as ds +from pwb.datasets import option_cache as oc +from pwb.datasets import options as opt +from pwb.datasets import prepared_cache from test_option_chain import _month_table from test_option_chain_sources import _Server diff --git a/tests/test_option_chain.py b/tests/test_option_chain.py index b98be516..add5f7a4 100644 --- a/tests/test_option_chain.py +++ b/tests/test_option_chain.py @@ -17,8 +17,8 @@ import pyarrow as pa import pyarrow.parquet as pq -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import options as opt +import pwb.datasets as ds +from pwb.datasets import options as opt UNDERLYINGS = [f"U{i:03d}" for i in range(400)] + ["AAPL", "SPY"] diff --git a/tests/test_option_chain_sources.py b/tests/test_option_chain_sources.py index 805bdad5..6b103716 100644 --- a/tests/test_option_chain_sources.py +++ b/tests/test_option_chain_sources.py @@ -21,8 +21,8 @@ import pandas as pd import pyarrow.parquet as pq -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import options as opt +import pwb.datasets as ds +from pwb.datasets import options as opt from test_option_chain import _month_table MONTHS = ("2024-01", "2024-02", "2024-03", "2024-04") diff --git a/tests/test_option_costs.py b/tests/test_option_costs.py index 97053e0f..6c362c49 100644 --- a/tests/test_option_costs.py +++ b/tests/test_option_costs.py @@ -8,8 +8,8 @@ import numpy as np import pandas as pd -import pwb_toolbox.backtesting.option_costs as oc -from pwb_toolbox.backtesting.commission import SOURCE_EXTRAPOLATED, SOURCE_MEASURED +import pwb.backtesting.option_costs as oc +from pwb.backtesting.commission import SOURCE_EXTRAPOLATED, SOURCE_MEASURED PRICE_LOWS = (0.0, 0.10, 0.50, 1.0, 2.0, 5.0, 10.0, 25.0) VOLUME_LOWS = (0.0, 1e3, 1e4, 1e5, 1e6) @@ -177,7 +177,7 @@ def test_loaded_once_and_an_unreachable_table_raises(self): oc.options_half_spread(0.3, 1.0, tier=1) def test_exported_from_the_backtesting_package(self): - from pwb_toolbox import backtesting + from pwb import backtesting for name in ("options_half_spread", "options_cost_breakdown", "option_volume_tier", "load_options_cost_model", "OptionsCostModel", "OPTIONS_PARAMS_REPO"): diff --git a/tests/test_pit_exit.py b/tests/test_pit_exit.py index d39187de..90b4e023 100644 --- a/tests/test_pit_exit.py +++ b/tests/test_pit_exit.py @@ -13,10 +13,10 @@ import numpy as np import pandas as pd -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.datasets import PIT_UNIVERSES -from pwb_toolbox.datasets import pit_universe +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be +from pwb.datasets import PIT_UNIVERSES +from pwb.datasets import pit_universe from _synthetic import offline, panel diff --git a/tests/test_pit_hold.py b/tests/test_pit_hold.py index 7cad6ed8..cbcf0bbc 100644 --- a/tests/test_pit_hold.py +++ b/tests/test_pit_hold.py @@ -16,10 +16,10 @@ import numpy as np import pandas as pd -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.datasets import PIT_UNIVERSES -from pwb_toolbox.datasets import pit_universe +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be +from pwb.datasets import PIT_UNIVERSES +from pwb.datasets import pit_universe from _synthetic import offline, panel @@ -166,7 +166,7 @@ def loader(*args, **kwargs): return (cut if kwargs.get("pit_cut", True) else prices).copy() from unittest import mock - import pwb_toolbox.datasets as pwb_ds + import pwb.datasets as pwb_ds with mock.patch.object(pwb_ds, "get_pricing", loader): return be.run_strategy( @@ -393,7 +393,7 @@ def _run(self, pit_exit): cut = full.copy() cut.loc[cut.index[self.OUT[0]:self.OUT[1]], "X"] = np.nan from unittest import mock - import pwb_toolbox.datasets as pwb_ds + import pwb.datasets as pwb_ds loader = lambda *a, **k: (cut if k.get("pit_cut", True) else full).copy() with mock.patch.object(pwb_ds, "get_pricing", loader): diff --git a/tests/test_pit_hold_accounting.py b/tests/test_pit_hold_accounting.py index ad1884b9..5e72a128 100644 --- a/tests/test_pit_hold_accounting.py +++ b/tests/test_pit_hold_accounting.py @@ -16,11 +16,11 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as pwb_ds -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.datasets import PIT_UNIVERSES -from pwb_toolbox.datasets import pit_universe +import pwb.datasets as pwb_ds +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be +from pwb.datasets import PIT_UNIVERSES +from pwb.datasets import pit_universe from _synthetic import panel, walk diff --git a/tests/test_prepared_cache.py b/tests/test_prepared_cache.py index 7a6aca48..c8709095 100644 --- a/tests/test_prepared_cache.py +++ b/tests/test_prepared_cache.py @@ -1,4 +1,4 @@ -"""The disk cache of prepared data (``pwb_toolbox.datasets.prepared_cache``). +"""The disk cache of prepared data (``pwb.datasets.prepared_cache``). What it must guarantee: a hit returns, bit for bit, what the computation returns; a new revision of a dataset, a new version of the code or a degraded @@ -19,9 +19,9 @@ import numpy as np import pandas as pd -import pwb_toolbox.backtesting.commission as commission -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import prepared_cache as pc +import pwb.backtesting.commission as commission +import pwb.datasets as ds +from pwb.datasets import prepared_cache as pc def _fresh_process(): @@ -238,7 +238,7 @@ def test_pwb_warnings_are_raised_again_on_a_hit(self): @pc.cached("warns") def compute(): pc.note_revision("hub", "paperswithbacktest/Fake", self.sha[0]) - ds._warn_unbounded_minute("Test-1Min-Price", ["AAA"]) # raised by pwb_toolbox code + ds._warn_unbounded_minute("Test-1Min-Price", ["AAA"]) # raised by pwb code warnings.warn("the test's own warning is not the cache's business") return 1 @@ -410,7 +410,7 @@ def test_a_table_that_fails_only_at_the_check_is_a_miss(self): _WRITER = textwrap.dedent(""" import sys, numpy as np, pandas as pd - from pwb_toolbox.datasets import prepared_cache as pc + from pwb.datasets import prepared_cache as pc path, seed = sys.argv[1], int(sys.argv[2]) df = pd.DataFrame(np.random.default_rng(0).normal(size=(200_000, 8))) for _ in range(15): diff --git a/tests/test_quantile_signal.py b/tests/test_quantile_signal.py index d57c528f..1dc5ff8e 100644 --- a/tests/test_quantile_signal.py +++ b/tests/test_quantile_signal.py @@ -14,13 +14,13 @@ import numpy as np import pandas as pd -from pwb_toolbox.backtesting import ( +from pwb.backtesting import ( BaseStrategy, CrossSectionalQuantileSignal, MonthlyLongShortQuantilePortfolio, ) -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.backtesting import engine_name +from pwb.backtesting import backtest_engine as be +from pwb.backtesting import engine_name from _synthetic import offline, panel diff --git a/tests/test_read_memo.py b/tests/test_read_memo.py index 8d1b4289..fd5ac1d3 100644 --- a/tests/test_read_memo.py +++ b/tests/test_read_memo.py @@ -26,10 +26,10 @@ import pyarrow as pa import pyarrow.parquet as pq -import pwb_toolbox.datasets as ds -from pwb_toolbox import engine -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.backtesting import commission +import pwb.datasets as ds +from pwb import engine +from pwb.backtesting import backtest_engine as be +from pwb.backtesting import commission bt = engine.load() diff --git a/tests/test_resolve_reused_property.py b/tests/test_resolve_reused_property.py index 1ed63cb0..8fa8fb87 100644 --- a/tests/test_resolve_reused_property.py +++ b/tests/test_resolve_reused_property.py @@ -17,7 +17,7 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as ds +import pwb.datasets as ds def _old_resolve(frames: dict, reused: dict, start_date, end_date) -> dict: diff --git a/tests/test_reused_tickers.py b/tests/test_reused_tickers.py index 0ff35ea2..198854bf 100644 --- a/tests/test_reused_tickers.py +++ b/tests/test_reused_tickers.py @@ -19,8 +19,8 @@ import numpy as np import pandas as pd -import pwb_toolbox.datasets as ds -from pwb_toolbox.datasets import pit_universe +import pwb.datasets as ds +from pwb.datasets import pit_universe ETF = "paperswithbacktest/ETFs-Daily-Price" STK = "paperswithbacktest/Stocks-Daily-Price" diff --git a/tests/test_same_bar_orders.py b/tests/test_same_bar_orders.py index b353e693..8e148ce5 100644 --- a/tests/test_same_bar_orders.py +++ b/tests/test_same_bar_orders.py @@ -16,9 +16,9 @@ import numpy as np -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.backtesting import checks +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be +from pwb.backtesting import checks from _synthetic import offline, panel diff --git a/tests/test_sells_first.py b/tests/test_sells_first.py index 3bccc180..42d1dcc7 100644 --- a/tests/test_sells_first.py +++ b/tests/test_sells_first.py @@ -22,8 +22,8 @@ import numpy as np -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be from _synthetic import offline, panel diff --git a/tests/test_short_borrow.py b/tests/test_short_borrow.py index bc345872..d7264d32 100644 --- a/tests/test_short_borrow.py +++ b/tests/test_short_borrow.py @@ -25,10 +25,10 @@ import numpy as np -from pwb_toolbox.backtesting import BaseStrategy -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.backtesting import checks -from pwb_toolbox.backtesting import engine_name +from pwb.backtesting import BaseStrategy +from pwb.backtesting import backtest_engine as be +from pwb.backtesting import checks +from pwb.backtesting import engine_name import _long_short_book as book import test_pit_hold_accounting as acc diff --git a/tests/test_strategy_commission.py b/tests/test_strategy_commission.py index 7f2cffe4..c1562c81 100644 --- a/tests/test_strategy_commission.py +++ b/tests/test_strategy_commission.py @@ -7,16 +7,16 @@ strategy charged **0.10** on a 1 000 fill instead of **10.00**. Rule since 0.1.43: each fill pays the higher of the two. Runs on whichever -engine ``pwb_toolbox.engine`` selected (backtrader or Tradewind). +engine ``pwb.engine`` selected (backtrader or Tradewind). """ import unittest from unittest import mock -import pwb_toolbox.backtesting as pwb_bt -from pwb_toolbox.backtesting import BaseStrategy, bt -from pwb_toolbox.backtesting import backtest_engine as be -from pwb_toolbox.backtesting.commission import Cost +import pwb.backtesting as pwb_bt +from pwb.backtesting import BaseStrategy, bt +from pwb.backtesting import backtest_engine as be +from pwb.backtesting.commission import Cost from _synthetic import offline, panel diff --git a/tests/test_universe_alias_costs.py b/tests/test_universe_alias_costs.py index 12eb8cd8..6c4b3610 100644 --- a/tests/test_universe_alias_costs.py +++ b/tests/test_universe_alias_costs.py @@ -15,11 +15,11 @@ from contextlib import redirect_stdout from unittest import mock -import pwb_toolbox.backtesting as pwb_bt -import pwb_toolbox.backtesting.commission as cm -import pwb_toolbox.datasets as pwb_ds -import pwb_toolbox.datasets.pit_universe as pit -from pwb_toolbox.backtesting import backtest_engine as be +import pwb.backtesting as pwb_bt +import pwb.backtesting.commission as cm +import pwb.datasets as pwb_ds +import pwb.datasets.pit_universe as pit +from pwb.backtesting import backtest_engine as be MEMBERS = ["AAPL", "AET", "ETH", "MSFT", "YHOO"] diff --git a/tests/test_world_model.py b/tests/test_world_model.py index 8e5b6e34..a098bd07 100644 --- a/tests/test_world_model.py +++ b/tests/test_world_model.py @@ -15,8 +15,8 @@ import pyarrow as pa import pyarrow.parquet as pq -from pwb_toolbox.world_model import WorldModel, WorldModelNotAvailable -from pwb_toolbox.world_model import _pit +from pwb.world_model import WorldModel, WorldModelNotAvailable +from pwb.world_model import _pit IDENTIFIERS_SCHEMA = pa.schema([ ("entity_id", pa.string()), ("scheme", pa.string()), ("value", pa.string()), @@ -556,7 +556,7 @@ def _download(self, repo_id, repo_type, filename, revision, token): def test_current_revision_and_shard_window(self): snapshot = ("abc123", ["data/train-2000.parquet", "data/train-2030.parquet", "README.md"]) - with self.mock.patch("pwb_toolbox.datasets._hub_snapshot", return_value=snapshot), \ + with self.mock.patch("pwb.datasets._hub_snapshot", return_value=snapshot), \ self.mock.patch("huggingface_hub.hf_hub_download", side_effect=self._download): model = WorldModel() self.assertEqual(model.resolve("AAA", "2020-01-02"), "E_A") @@ -578,7 +578,7 @@ def test_pinned_revision(self): self.assertEqual(self.downloads[0][2], "def456") def test_unreadable_dataset_is_said(self): - with self.mock.patch("pwb_toolbox.datasets._hub_snapshot", side_effect=RuntimeError("404")): + with self.mock.patch("pwb.datasets._hub_snapshot", side_effect=RuntimeError("404")): with self.assertRaisesRegex(WorldModelNotAvailable, "WorldModel-Identifiers"): WorldModel().resolve("AAA", "2020-01-02") diff --git a/tests/test_world_model_local.py b/tests/test_world_model_local.py index b46ea3f1..019f31b6 100644 --- a/tests/test_world_model_local.py +++ b/tests/test_world_model_local.py @@ -11,7 +11,7 @@ import pandas as pd -from pwb_toolbox.world_model import WorldModel +from pwb.world_model import WorldModel ROOT = os.path.expanduser( os.getenv("PWB_WORLD_MODEL_TEST_DIR", "~/dev/pwb/worldmodel-cache/out") diff --git a/tools/ib_server/execute_meta_strategy.py b/tools/ib_server/execute_meta_strategy.py index b9f1ae3b..7b49cc30 100644 --- a/tools/ib_server/execute_meta_strategy.py +++ b/tools/ib_server/execute_meta_strategy.py @@ -6,7 +6,7 @@ import pandas as pd -import pwb_toolbox.execution as pwb_exec +import pwb.execution as pwb_exec logs_dir = Path.home() / "pwb-data" / "ib" / "execution_logs" diff --git a/tools/ib_server/monitor.py b/tools/ib_server/monitor.py index 40d284df..1007cd6b 100644 --- a/tools/ib_server/monitor.py +++ b/tools/ib_server/monitor.py @@ -1,6 +1,6 @@ from pathlib import Path -import pwb_toolbox.performance as pwb_perf +import pwb.performance as pwb_perf logs_dir = Path.home() / "pwb-fund-data" / "strategies" / "all" / "execution_logs"