paperswithbacktest 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. {paperswithbacktest-0.2.1/paperswithbacktest.egg-info → paperswithbacktest-0.2.3}/PKG-INFO +5 -5
  2. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3/paperswithbacktest.egg-info}/PKG-INFO +5 -5
  3. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/paperswithbacktest.egg-info/SOURCES.txt +11 -1
  4. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/paperswithbacktest.egg-info/requires.txt +4 -4
  5. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/__init__.py +1 -1
  6. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/backtest_engine.py +227 -25
  7. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/base_strategy.py +20 -2
  8. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/feeds.py +46 -0
  9. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/__init__.py +99 -12
  10. paperswithbacktest-0.2.3/pwb/datasets/carry.py +549 -0
  11. paperswithbacktest-0.2.3/pwb/datasets/nominal.py +234 -0
  12. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/docs/backtesting.md +20 -0
  13. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/world_model/_source.py +70 -5
  14. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/world_model/reader.py +31 -13
  15. paperswithbacktest-0.2.3/pwb/world_model/shock_lists.py +218 -0
  16. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/setup.cfg +5 -5
  17. paperswithbacktest-0.2.3/tests/test_carry.py +250 -0
  18. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_holiday_bars.py +8 -2
  19. paperswithbacktest-0.2.3/tests/test_leading_fill.py +434 -0
  20. paperswithbacktest-0.2.3/tests/test_nominal_feed.py +100 -0
  21. paperswithbacktest-0.2.3/tests/test_nominal_price.py +257 -0
  22. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_world_model.py +29 -1
  23. paperswithbacktest-0.2.3/tests/test_world_model_edge_integration.py +138 -0
  24. paperswithbacktest-0.2.3/tests/test_world_model_shock_integration.py +39 -0
  25. paperswithbacktest-0.2.3/tests/test_world_model_shock_lists.py +138 -0
  26. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/LICENSE +0 -0
  27. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/NOTICE +0 -0
  28. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/README.md +0 -0
  29. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/paperswithbacktest.egg-info/dependency_links.txt +0 -0
  30. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/paperswithbacktest.egg-info/top_level.txt +0 -0
  31. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/__init__.py +0 -0
  32. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/checks.py +0 -0
  33. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/commission.py +0 -0
  34. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/futures_run.py +0 -0
  35. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/indicators.py +0 -0
  36. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/lookahead.py +0 -0
  37. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/optimization_engine.py +0 -0
  38. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/option_costs.py +0 -0
  39. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/portfolio.py +0 -0
  40. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/strategies.py +0 -0
  41. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/backtesting/universe.py +0 -0
  42. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/french.py +0 -0
  43. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/futures.py +0 -0
  44. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/futures_chain.py +0 -0
  45. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/index_currencies.py +0 -0
  46. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/option_cache.py +0 -0
  47. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/options.py +0 -0
  48. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/pit_universe.py +0 -0
  49. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/datasets/prepared_cache.py +0 -0
  50. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/docs/__init__.py +0 -0
  51. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/docs/__main__.py +0 -0
  52. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/docs/world_model.md +0 -0
  53. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/engine.py +0 -0
  54. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/execution/__init__.py +0 -0
  55. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/execution/broker_factory.py +0 -0
  56. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/execution/ccxt_connector.py +0 -0
  57. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/execution/ib_connector.py +0 -0
  58. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/execution/live_utils.py +0 -0
  59. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/execution/optimal_limit_order.py +0 -0
  60. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/performance/__init__.py +0 -0
  61. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/performance/metrics.py +0 -0
  62. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/performance/nav_metrics.py +0 -0
  63. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/performance/plots.py +0 -0
  64. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/performance/reports.py +0 -0
  65. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/performance/trade_stats.py +0 -0
  66. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/world_model/__init__.py +0 -0
  67. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/world_model/_pit.py +0 -0
  68. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pwb/world_model/propagate.py +0 -0
  69. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/pyproject.toml +0 -0
  70. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_api_cache.py +0 -0
  71. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_array_feed.py +0 -0
  72. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_bare_symbol_collisions.py +0 -0
  73. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_bond_rates.py +0 -0
  74. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_bounded_loader.py +0 -0
  75. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_compat_shim.py +0 -0
  76. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_currency_costs.py +0 -0
  77. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_docs_shipped.py +0 -0
  78. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_engine_parity.py +0 -0
  79. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_engine_runner.py +0 -0
  80. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_engine_selector.py +0 -0
  81. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_exposure_cap.py +0 -0
  82. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_forex_directions.py +0 -0
  83. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_french.py +0 -0
  84. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_futures_chain.py +0 -0
  85. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_futures_loader.py +0 -0
  86. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_futures_rank6.py +0 -0
  87. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_futures_run.py +0 -0
  88. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_harness_checks.py +0 -0
  89. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_hub_snapshot.py +0 -0
  90. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_index_currencies.py +0 -0
  91. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_lookahead.py +0 -0
  92. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_option_cache.py +0 -0
  93. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_option_chain.py +0 -0
  94. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_option_chain_sources.py +0 -0
  95. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_option_costs.py +0 -0
  96. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_pit_exit.py +0 -0
  97. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_pit_hold.py +0 -0
  98. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_pit_hold_accounting.py +0 -0
  99. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_pit_hold_same_bar_mark.py +0 -0
  100. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_prepared_cache.py +0 -0
  101. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_quantile_signal.py +0 -0
  102. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_read_memo.py +0 -0
  103. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_resolve_reused_property.py +0 -0
  104. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_reused_tickers.py +0 -0
  105. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_same_bar_orders.py +0 -0
  106. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_sells_first.py +0 -0
  107. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_short_borrow.py +0 -0
  108. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_strategy_commission.py +0 -0
  109. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_universe_alias_costs.py +0 -0
  110. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_world_model_local.py +0 -0
  111. {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.3}/tests/test_world_model_shock.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: paperswithbacktest
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Papers With Backtest: datasets, backtesting harness and execution for quant traders (import pwb; formerly pwb-toolbox)
5
5
  Home-page: https://paperswithbacktest.com
6
6
  Author: Papers With Backtest
@@ -20,8 +20,8 @@ Requires-Python: >=3.10
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  License-File: NOTICE
23
- Requires-Dist: tradewind>=0.0.4
24
- Requires-Dist: backtrader
23
+ Requires-Dist: tradewind>=0.0.5
24
+ Requires-Dist: pwb-backtrader>=1.9.78.126
25
25
  Requires-Dist: beautifulsoup4
26
26
  Requires-Dist: ccxt
27
27
  Requires-Dist: click
@@ -32,7 +32,7 @@ Requires-Dist: huggingface_hub
32
32
  Requires-Dist: ib_insync
33
33
  Requires-Dist: matplotlib
34
34
  Requires-Dist: numpy
35
- Requires-Dist: pandas
35
+ Requires-Dist: pandas<3,>=2.2
36
36
  Requires-Dist: pyarrow
37
37
  Requires-Dist: python-dateutil
38
38
  Requires-Dist: requests
@@ -42,7 +42,7 @@ Requires-Dist: tqdm
42
42
  Requires-Dist: transformers
43
43
  Requires-Dist: webdriver_manager
44
44
  Provides-Extra: tradewind
45
- Requires-Dist: tradewind>=0.0.4; extra == "tradewind"
45
+ Requires-Dist: tradewind>=0.0.5; extra == "tradewind"
46
46
  Dynamic: license-file
47
47
 
48
48
  <div align="center">
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: paperswithbacktest
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Papers With Backtest: datasets, backtesting harness and execution for quant traders (import pwb; formerly pwb-toolbox)
5
5
  Home-page: https://paperswithbacktest.com
6
6
  Author: Papers With Backtest
@@ -20,8 +20,8 @@ Requires-Python: >=3.10
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  License-File: NOTICE
23
- Requires-Dist: tradewind>=0.0.4
24
- Requires-Dist: backtrader
23
+ Requires-Dist: tradewind>=0.0.5
24
+ Requires-Dist: pwb-backtrader>=1.9.78.126
25
25
  Requires-Dist: beautifulsoup4
26
26
  Requires-Dist: ccxt
27
27
  Requires-Dist: click
@@ -32,7 +32,7 @@ Requires-Dist: huggingface_hub
32
32
  Requires-Dist: ib_insync
33
33
  Requires-Dist: matplotlib
34
34
  Requires-Dist: numpy
35
- Requires-Dist: pandas
35
+ Requires-Dist: pandas<3,>=2.2
36
36
  Requires-Dist: pyarrow
37
37
  Requires-Dist: python-dateutil
38
38
  Requires-Dist: requests
@@ -42,7 +42,7 @@ Requires-Dist: tqdm
42
42
  Requires-Dist: transformers
43
43
  Requires-Dist: webdriver_manager
44
44
  Provides-Extra: tradewind
45
- Requires-Dist: tradewind>=0.0.4; extra == "tradewind"
45
+ Requires-Dist: tradewind>=0.0.5; extra == "tradewind"
46
46
  Dynamic: license-file
47
47
 
48
48
  <div align="center">
@@ -25,10 +25,12 @@ pwb/backtesting/portfolio.py
25
25
  pwb/backtesting/strategies.py
26
26
  pwb/backtesting/universe.py
27
27
  pwb/datasets/__init__.py
28
+ pwb/datasets/carry.py
28
29
  pwb/datasets/french.py
29
30
  pwb/datasets/futures.py
30
31
  pwb/datasets/futures_chain.py
31
32
  pwb/datasets/index_currencies.py
33
+ pwb/datasets/nominal.py
32
34
  pwb/datasets/option_cache.py
33
35
  pwb/datasets/options.py
34
36
  pwb/datasets/pit_universe.py
@@ -54,11 +56,13 @@ pwb/world_model/_pit.py
54
56
  pwb/world_model/_source.py
55
57
  pwb/world_model/propagate.py
56
58
  pwb/world_model/reader.py
59
+ pwb/world_model/shock_lists.py
57
60
  tests/test_api_cache.py
58
61
  tests/test_array_feed.py
59
62
  tests/test_bare_symbol_collisions.py
60
63
  tests/test_bond_rates.py
61
64
  tests/test_bounded_loader.py
65
+ tests/test_carry.py
62
66
  tests/test_compat_shim.py
63
67
  tests/test_currency_costs.py
64
68
  tests/test_docs_shipped.py
@@ -76,7 +80,10 @@ tests/test_harness_checks.py
76
80
  tests/test_holiday_bars.py
77
81
  tests/test_hub_snapshot.py
78
82
  tests/test_index_currencies.py
83
+ tests/test_leading_fill.py
79
84
  tests/test_lookahead.py
85
+ tests/test_nominal_feed.py
86
+ tests/test_nominal_price.py
80
87
  tests/test_option_cache.py
81
88
  tests/test_option_chain.py
82
89
  tests/test_option_chain_sources.py
@@ -96,5 +103,8 @@ tests/test_short_borrow.py
96
103
  tests/test_strategy_commission.py
97
104
  tests/test_universe_alias_costs.py
98
105
  tests/test_world_model.py
106
+ tests/test_world_model_edge_integration.py
99
107
  tests/test_world_model_local.py
100
- tests/test_world_model_shock.py
108
+ tests/test_world_model_shock.py
109
+ tests/test_world_model_shock_integration.py
110
+ tests/test_world_model_shock_lists.py
@@ -1,5 +1,5 @@
1
- tradewind>=0.0.4
2
- backtrader
1
+ tradewind>=0.0.5
2
+ pwb-backtrader>=1.9.78.126
3
3
  beautifulsoup4
4
4
  ccxt
5
5
  click
@@ -10,7 +10,7 @@ huggingface_hub
10
10
  ib_insync
11
11
  matplotlib
12
12
  numpy
13
- pandas
13
+ pandas<3,>=2.2
14
14
  pyarrow
15
15
  python-dateutil
16
16
  requests
@@ -21,4 +21,4 @@ transformers
21
21
  webdriver_manager
22
22
 
23
23
  [tradewind]
24
- tradewind>=0.0.4
24
+ tradewind>=0.0.5
@@ -8,4 +8,4 @@ this package, gives the very same modules and warns once (``DeprecationWarning``
8
8
  # The release this code is: what the harness checks report as ``toolboxVersion``.
9
9
  # Kept equal to ``version`` in setup.cfg (tests/test_harness_checks.py checks it):
10
10
  # the installed metadata can belong to another copy than the one imported.
11
- __version__ = "0.2.1"
11
+ __version__ = "0.2.3"
@@ -5,6 +5,7 @@ import os
5
5
  import itertools
6
6
  import sys
7
7
  import time
8
+ import traceback
8
9
  import pandas as pd
9
10
  import numpy as np
10
11
  import pwb.backtesting as pwb_bt
@@ -16,7 +17,7 @@ from ..engine import load as _load_engine
16
17
  bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine
17
18
  from . import checks as _checks
18
19
  from . import lookahead as _lookahead
19
- from .feeds import ArrayPandasData
20
+ from .feeds import ArrayPandasData, NominalPandasData, require_feed_lines
20
21
 
21
22
 
22
23
  def _apply_broker_kwargs(broker: bt.BrokerBase, kwargs: dict) -> None:
@@ -275,9 +276,18 @@ SCALINGS = ("bar", "uniform")
275
276
  ERA_GAP_YEARS = 3
276
277
 
277
278
  # Refuse orders on a symbol before its first real bar, instead of letting the
278
- # back-fill below sell a flat line. ``PWB_REFUSE_BEFORE_LISTING=0`` switches it off.
279
+ # back-fill (``leading_fill="bfill"``) sell a flat line.
280
+ # ``PWB_REFUSE_BEFORE_LISTING=0`` switches it off, under the back-fill only.
279
281
  REFUSE_BEFORE_LISTING = True
280
282
 
283
+ # What a feed reads before its symbol's first real bar; see ``run_strategy``.
284
+ # "nan": nothing -- the bars exist (every feed shares the calendar) but carry no
285
+ # price. "bfill" (every release up to 0.2.2): the first real bar copied
286
+ # backwards, a price from the future. ``PWB_LEADING_FILL`` in the environment
287
+ # overrides the default for a whole campaign.
288
+ LEADING_FILLS = ("nan", "bfill")
289
+ LEADING_FILL = "nan"
290
+
281
291
  # What happens to a name that leaves a point-in-time universe ("sp500",
282
292
  # "liquid1000"); see ``run_strategy``. ``PWB_PIT_EXIT`` in the environment
283
293
  # overrides the default for a whole campaign.
@@ -551,13 +561,14 @@ def _underfunded(audit: dict, tolerance: float, debit_tolerance: float = DEBIT_T
551
561
  return audit["min_value"] is not None and audit["min_value"] <= 0
552
562
 
553
563
 
554
- def _refuse_before_listing(broker, first_bar: dict) -> dict:
564
+ def _refuse_before_listing(broker, first_bar: dict, audit: "dict | None" = None) -> dict:
555
565
  """Make ``broker`` reject any order dated before its symbol's first real bar.
556
566
 
557
- ``run_strategy`` back-fills the panel so every feed starts on the same day,
558
- which is what keeps backtrader's feeds aligned and is harmless for a
559
- holiday. For a symbol listed years after ``start_date`` it paints a flat
560
- line the strategy can buy: ``FillAudit`` found the crypto books holding
567
+ Every feed of ``run_strategy`` starts on the same day. Before 0.2.3 the
568
+ bars in front of a symbol's first real bar were back-filled with that bar
569
+ (``leading_fill="bfill"``); they are now empty (``"nan"``), and an order
570
+ there has no price to fill at. Under the back-fill, for a symbol listed
571
+ years after ``start_date``, they were a flat line the strategy could buy: ``FillAudit`` found the crypto books holding
561
572
  XRP for 2 711 bars of 2014-2024 -- an ETF listed in 2024, read from
562
573
  ``Stocks-Daily-Price`` and extended backwards at a constant price. The
563
574
  position earns nothing, pays the floor spread at every rebalance, and
@@ -576,9 +587,11 @@ def _refuse_before_listing(broker, first_bar: dict) -> dict:
576
587
  guarded by ``_refuse_outside_universe``.
577
588
 
578
589
  Returns the audit, filled as the run goes: ``{symbol: {"orders": n,
579
- "first": date, "last": date}}`` of the refusals.
590
+ "first": date, "last": date}}`` of the refusals. ``audit`` -- a dict to
591
+ fill instead of a new one (``run_strategy`` shares it with the targets the
592
+ strategy wrapper drops for want of a price, see ``_with_exposure_cap``).
580
593
  """
581
- audit = {}
594
+ audit = {} if audit is None else audit
582
595
  original = broker.submit
583
596
 
584
597
  def submit(order, check=True):
@@ -601,6 +614,37 @@ def _refuse_before_listing(broker, first_bar: dict) -> dict:
601
614
  return audit
602
615
 
603
616
 
617
+ def _value_held_positions_only(broker) -> None:
618
+ """Make backtrader's NAV skip the flat positions, whose feed may have no price.
619
+
620
+ backtrader's ``BackBroker._get_value`` values every position it has ever
621
+ created -- ``getposition`` creates one, flat -- at ``data.close[0]``, and
622
+ ``0 x NaN`` is NaN: one look at a feed before its first real bar
623
+ (``leading_fill="nan"``) turned the NAV into NaN for good. A flat position
624
+ is worth nothing whatever the price, so the sum is taken over the held ones
625
+ only, which is what Tradewind does. A call naming its feeds is unchanged.
626
+ """
627
+ original = getattr(broker, "_get_value", None)
628
+ every = getattr(broker, "positions", None)
629
+ if original is None or not hasattr(every, "items"):
630
+ return
631
+
632
+ def _get_value(datas=None, lever=False):
633
+ if datas is not None:
634
+ return original(datas=datas, lever=lever)
635
+ full = broker.positions
636
+ held = full.copy()
637
+ for data in [d for d, position in full.items() if not position.size]:
638
+ del held[data]
639
+ broker.positions = held
640
+ try:
641
+ return original(datas=None, lever=lever)
642
+ finally:
643
+ broker.positions = full
644
+
645
+ broker._get_value = _get_value
646
+
647
+
604
648
  class _Membership:
605
649
  """The bars on which a point-in-time name is outside its universe.
606
650
 
@@ -716,8 +760,8 @@ def _flatten_filled_bars(pivot_df: pd.DataFrame, filled: pd.DataFrame) -> None:
716
760
  day only London traded). The fill copies the whole last bar, so an order
717
761
  filled there traded at the open of the day before -- a price older than
718
762
  the close the order was computed on. A flat bar at the last close is the
719
- only price that existed. The leading gap before a first bar is the
720
- back-fill's and is left to it.
763
+ only price that existed. The leading gap before a first bar is not a
764
+ hole: it stays empty (``leading_fill="nan"``) or is the back-fill's.
721
765
  """
722
766
  names = list(filled.columns[filled.to_numpy(dtype=bool).any(axis=0)])
723
767
  if not names:
@@ -756,7 +800,7 @@ def _blank_out_bars(pivot_df: pd.DataFrame, membership: "_Membership") -> None:
756
800
  if not names:
757
801
  return
758
802
  mask = np.column_stack([membership.out[s] for s in names])
759
- for field in ("open", "high", "low", "close"):
803
+ for field in ("open", "high", "low", "close", "nominal_close"):
760
804
  columns = [(s, field) for s in names]
761
805
  if any(c not in pivot_df.columns for c in columns):
762
806
  continue
@@ -988,6 +1032,7 @@ def _same_bar_report(record: dict) -> dict:
988
1032
  def _with_exposure_cap(
989
1033
  strategy_cls, cap: float = 1.0, schedule=None, membership=None, guard=None,
990
1034
  pit_exit="liquidate", real_prices=None, short_borrow_bps=0.0,
1035
+ first_bar=None, unlisted=None,
991
1036
  ):
992
1037
  """Subclass ``strategy_cls`` to scale, and record, every target it asks for.
993
1038
 
@@ -1054,8 +1099,18 @@ def _with_exposure_cap(
1054
1099
  At 0 nothing is called and the run is the one of the releases without it,
1055
1100
  bit for bit; which names were ever short is recorded either way
1056
1101
  (``_pwb_short_seen``), for the ``costs`` check.
1102
+
1103
+ ``first_bar`` -- ``{symbol: Timestamp}`` of each symbol's first real bar.
1104
+ ``is_listed(data)`` answers whether the bar is at or after it, and a
1105
+ non-zero ``order_target_percent``/``order_target_value`` on a feed without
1106
+ a price on the bar (before that first bar, under ``leading_fill="nan"``)
1107
+ is dropped instead of sized on NaN: the order could not fill, and the
1108
+ listing guard would refuse it anyway. It returns ``None`` and is counted in
1109
+ ``unlisted`` (the listing audit, same format).
1057
1110
  """
1058
1111
  days, scales = schedule if schedule else ((), ())
1112
+ first_bar = first_bar or {}
1113
+ unlisted = unlisted if unlisted is not None else {}
1059
1114
  borrow_rate = float(short_borrow_bps or 0.0) / 1e4
1060
1115
  guard = guard if guard is not None else {}
1061
1116
  hold = membership is not None and pit_exit == "hold"
@@ -1158,6 +1213,8 @@ def _with_exposure_cap(
1158
1213
  self._pwb_targeting -= 1
1159
1214
 
1160
1215
  def order_target_percent(self, data=None, target=0.0, **kwargs):
1216
+ if target and self._pwb_unpriced(data):
1217
+ return None
1161
1218
  self._pwb_targeting += 1
1162
1219
  try:
1163
1220
  return self._pwb_target_percent(data, target, **kwargs)
@@ -1165,12 +1222,53 @@ def _with_exposure_cap(
1165
1222
  self._pwb_targeting -= 1
1166
1223
 
1167
1224
  def order_target_value(self, data=None, target=0.0, **kwargs):
1225
+ if target and kwargs.get("price") is None and self._pwb_unpriced(data):
1226
+ return None
1168
1227
  self._pwb_targeting += 1
1169
1228
  try:
1170
1229
  return self._pwb_target_value(data, target, **kwargs)
1171
1230
  finally:
1172
1231
  self._pwb_targeting -= 1
1173
1232
 
1233
+ # -- listing ---------------------------------------------------------------
1234
+ def is_listed(self, data) -> bool:
1235
+ """Whether ``data`` has had its first real bar by this bar.
1236
+
1237
+ Before it the feed carries no price (``leading_fill="nan"``) or
1238
+ the first real price copied backwards (``"bfill"``); either way
1239
+ nothing can be read or traded there.
1240
+ """
1241
+ data = self._pwb_feed(data)
1242
+ listed = first_bar.get(getattr(data, "_name", None))
1243
+ if listed is None:
1244
+ parent = getattr(super(), "is_listed", None)
1245
+ if parent is not None:
1246
+ return parent(data)
1247
+ return bool(np.isfinite(float(data.close[0])))
1248
+ return data.datetime.date(0) >= listed.date()
1249
+
1250
+ def _pwb_unpriced(self, data) -> bool:
1251
+ """No price on this bar: count the target as refused before listing."""
1252
+ if self._pwb_cap_scaling:
1253
+ return False
1254
+ feed = self._pwb_feed(data)
1255
+ try:
1256
+ price = float(feed.close[0])
1257
+ except (IndexError, TypeError, ValueError):
1258
+ return False
1259
+ if np.isfinite(price):
1260
+ return False
1261
+ if self.getposition(feed).size:
1262
+ return False # a holding without a price: let the engine answer
1263
+ self._pwb_act(feed) # still a rebalancing bar, as under the back-fill
1264
+ today = feed.datetime.date(0)
1265
+ entry = unlisted.setdefault(
1266
+ getattr(feed, "_name", None), {"orders": 0, "first": today, "last": today}
1267
+ )
1268
+ entry["orders"] += 1
1269
+ entry["last"] = today
1270
+ return True
1271
+
1174
1272
  def _pwb_target_percent(self, data, target, **kwargs):
1175
1273
  self._pwb_act(data)
1176
1274
  # backtrader's own order_target_percent multiplies by the NAV and
@@ -1618,9 +1716,23 @@ def run_strategy(
1618
1716
  engine=None,
1619
1717
  futures=None,
1620
1718
  futures_options=None,
1719
+ nominal=False,
1720
+ leading_fill=None,
1621
1721
  ):
1622
1722
  """Run a tactical asset allocation strategy with Backtrader (or Tradewind).
1623
1723
 
1724
+ ``nominal`` -- give every feed a ``nominal`` line: ``data.nominal[0]`` is the
1725
+ price the stock traded at on the bar (``nominal_close`` of
1726
+ ``get_pricing(..., nominal=True)``), where ``data.close`` is the close
1727
+ back-adjusted for later splits and dividends. A filter or a sort on a price
1728
+ *level* (``>= 5`` dollars, penny stocks, the share price) must read it: on
1729
+ the adjusted close, AAPL on 2020-08-28 is 121, for a share that traded at
1730
+ 499. NaN for a name outside ``Stocks-Daily-Price`` (ETFs, indices...). Orders,
1731
+ fills and the NAV still use the adjusted prices: the option changes nothing
1732
+ a strategy does not read. On Tradewind it needs a release with feed lines
1733
+ (``pwb.backtesting.feeds.FEED_EXTRA_LINES``). ``False`` (default): the run
1734
+ of the releases before it.
1735
+
1624
1736
  ``futures`` -- futures roots (``["GC", "BZ"]``) the strategy trades as real
1625
1737
  contracts of ``Futures-Daily-Price``, on Tradewind only. Each root is one feed
1626
1738
  named after it, the ratio-adjusted series of the contract held (signals);
@@ -1649,8 +1761,9 @@ def run_strategy(
1649
1761
  since July 2024, and the forward-fill below stitches them
1650
1762
  into one series with a +1 000 % day and a −90 % day at the seams. The
1651
1763
  instrument the strategy names is the one trading today, so the earlier
1652
- eras are dropped (the leading back-fill then makes them a flat line, which
1653
- the cost schedule charges at the floor and ``FillAudit`` reports). It is
1764
+ eras are dropped (they become the leading gap: empty, or under
1765
+ ``leading_fill="bfill"`` a flat line, which the cost schedule charges at
1766
+ the floor and ``FillAudit`` reports). It is
1654
1767
  the default since 0.1.36: measured on/off on the 80 published strategies
1655
1768
  most exposed to ticker reuse, 10 received a cut, 7 of them moved by less
1656
1769
  than the sampling noise of a Sharpe, 2 gained and the 1 that lost had
@@ -1666,7 +1779,46 @@ def run_strategy(
1666
1779
  that buys it holds a position earning nothing, pays the floor spread at
1667
1780
  each rebalance and reports a 1/N book as fully invested when part of it
1668
1781
  did not exist. See ``_refuse_before_listing``; the refusals are on the
1669
- returned strategy as ``listing_audit``.
1782
+ returned strategy as ``listing_audit``. Under ``leading_fill="nan"`` the
1783
+ guard is always on: there is no price to fill at.
1784
+
1785
+ ``leading_fill`` -- what a feed carries before its symbol's first real
1786
+ bar (default ``LEADING_FILL``, ``PWB_LEADING_FILL`` in the environment).
1787
+ Every feed shares the calendar, so those bars exist.
1788
+
1789
+ * ``"nan"`` (since 0.2.3) -- open, high, low, close and volume are NaN.
1790
+ Holes *after* the first bar are still forward-filled (a flat bar at the
1791
+ last close), which only ever copies the past.
1792
+ * ``"bfill"`` (every release up to 0.2.2) -- the first real bar is copied
1793
+ backwards. That is a price from the future: a strategy reading a level
1794
+ (a yield, a rate, a spread, a price relative) before the series exists
1795
+ reads its first value, which it could not have known. Kept for the
1796
+ transition, to reproduce a past measure.
1797
+
1798
+ ``is_listed(data)`` on the strategy answers whether the bar is at or after
1799
+ the first real bar, in both modes; ``is_tradable`` answers ``False`` on a
1800
+ bar without a price. A non-zero ``order_target_percent`` or
1801
+ ``order_target_value`` on such a bar is dropped (``None``) and counted in
1802
+ ``listing_audit`` rather than sized on NaN.
1803
+
1804
+ A strategy written around the back-fill can raise on the empty bars (it
1805
+ sizes on the price itself, ``int(value / close[0])``). Under ``"nan"`` an
1806
+ exception from the run is therefore printed and the run is started again,
1807
+ once, from scratch, on the back-filled panel: ``run_report["leading_fill"]``
1808
+ stays ``"nan"`` (what was asked), ``run_report["leading_fill_used"]`` is
1809
+ ``"bfill"`` and ``run_report["leading_fill_error"]`` holds the exception.
1810
+ If the back-filled run raises too, that exception propagates. Fix such a
1811
+ strategy with ``is_listed(d)`` rather than relying on the fallback.
1812
+
1813
+ Indicators on a late feed start on its first real bar. A window indicator
1814
+ (``SMA``, a rolling max) is valid once it has seen ``period`` real bars. A
1815
+ recursive one (``EMA``, ``MACD``, ``RSI``, ``ATR``) is too on tradewind >=
1816
+ 0.0.5 and pwb-backtrader >= 1.9.78.126, whose exponential smoothing waits
1817
+ for the series' first value: NaN before it, then the indicator of the
1818
+ series that starts on that bar. On earlier engines (and the original
1819
+ ``backtrader`` 1.9.78.123) it is seeded on the leading NaN and stays NaN
1820
+ for the whole run: build it on a feed that starts with the panel, or
1821
+ compute it in ``next`` from the bars where ``is_listed``.
1670
1822
 
1671
1823
  **Point-in-time universes** (``"sp500"``, ``"liquid1000"``). ``pit_exit``
1672
1824
  (default ``PIT_EXIT``, ``PWB_PIT_EXIT`` in the environment) says what
@@ -1835,6 +1987,9 @@ def run_strategy(
1835
1987
  broker_kwargs = broker_kwargs or {}
1836
1988
  # Load the data from https://paperswithbacktest.com/datasets -- once, and
1837
1989
  # reused across attempts, because a re-run must not re-download anything.
1990
+ if nominal:
1991
+ require_feed_lines() # before the download, not at the first feed
1992
+ pricing_kwargs = {"nominal": True} if nominal else {}
1838
1993
  pivot_df = pwb_ds.get_pricing(
1839
1994
  symbol_list=symbols,
1840
1995
  fields=["open", "high", "low", "close"],
@@ -1843,6 +1998,7 @@ def run_strategy(
1843
1998
  # "hold" values a position carried through an exit at its real
1844
1999
  # prices, so it needs the rows the membership cut would drop.
1845
2000
  pit_cut=pit_exit != "hold",
2001
+ **pricing_kwargs,
1846
2002
  )
1847
2003
  # Which feed each column came from (``get_pricing``), popped so pandas
1848
2004
  # does not carry it through every operation below.
@@ -1890,8 +2046,8 @@ def run_strategy(
1890
2046
  active_years = {
1891
2047
  symbol: set(present.index[present[symbol]].year) for symbol in present.columns
1892
2048
  }
1893
- # The first real bar of each symbol, read before the back-fill below
1894
- # paints a flat line in front of it; what ``_refuse_before_listing`` guards.
2049
+ # The first real bar of each symbol, read before the fills below; what
2050
+ # ``_refuse_before_listing`` guards and ``is_listed`` answers.
1895
2051
  first_bar = {
1896
2052
  symbol: present.index[present[symbol]].min()
1897
2053
  for symbol in present.columns
@@ -1901,6 +2057,13 @@ def run_strategy(
1901
2057
  refuse_before_listing = os.getenv(
1902
2058
  "PWB_REFUSE_BEFORE_LISTING", "1" if REFUSE_BEFORE_LISTING else "0"
1903
2059
  ) != "0"
2060
+ if leading_fill is None:
2061
+ leading_fill = os.getenv("PWB_LEADING_FILL", LEADING_FILL)
2062
+ leading_fill = str(leading_fill).strip().lower()
2063
+ if leading_fill not in LEADING_FILLS:
2064
+ raise ValueError(f"leading_fill must be one of {LEADING_FILLS}, not {leading_fill!r}")
2065
+ if leading_fill == "nan":
2066
+ refuse_before_listing = True # nothing to fill an order at
1904
2067
  # Create trading-day index (optional but keeps Cerebro happy)
1905
2068
  trading_days = _session_days(pivot_df.index, sessions)
1906
2069
  membership = _pit_membership(symbols, present, trading_days, cut=pit_exit != "hold")
@@ -1933,7 +2096,12 @@ def run_strategy(
1933
2096
  pivot_df.ffill(inplace=True) # forward-fill holes
1934
2097
  if filled is not None:
1935
2098
  _flatten_filled_bars(pivot_df, filled)
1936
- pivot_df.bfill(inplace=True) # back-fill leading IPO gaps
2099
+ if leading_fill == "bfill":
2100
+ # 0.2.2 and before: the first real bar copied backwards -- a price
2101
+ # from the future for every bar before it. Kept for the transition.
2102
+ pivot_df.bfill(inplace=True)
2103
+ # "nan": the bars before a symbol's first real bar stay empty. The forward
2104
+ # fill above cannot reach them, and only ever copies the past.
1937
2105
  all_years = set(trading_days.year)
1938
2106
  inactive = {
1939
2107
  symbol: all_years - years for symbol, years in active_years.items()
@@ -1951,17 +2119,22 @@ def run_strategy(
1951
2119
  # Keyed by feed name, because that is what ``addcommissioninfo(name=...)``
1952
2120
  # matches on, and what the scheme reads the bar date from.
1953
2121
  feeds = {}
2122
+ feed_cls = NominalPandasData if nominal else ArrayPandasData
1954
2123
  for symbol in pivot_df.columns.levels[0]:
1955
- data = ArrayPandasData(dataname=pivot_df[symbol].copy())
2124
+ data = feed_cls(dataname=pivot_df[symbol].copy())
1956
2125
  cerebro.adddata(data, name=symbol)
1957
2126
  feeds[symbol] = data
1958
2127
  guard = {"liquidating": False}
2128
+ # Refusals before the first bar: the broker's, and the targets the
2129
+ # wrapper drops for want of a price.
2130
+ listing_audit = {}
1959
2131
  # Strategy
1960
2132
  cerebro.addstrategy(
1961
2133
  _with_exposure_cap(
1962
2134
  strategy_cls, cap, schedule=schedule, membership=acting, guard=guard,
1963
2135
  pit_exit=pit_exit, real_prices=real_prices,
1964
2136
  short_borrow_bps=short_borrow_bps,
2137
+ first_bar=first_bar, unlisted=listing_audit,
1965
2138
  ),
1966
2139
  total_days=len(trading_days),
1967
2140
  indicator_cls=indicator_cls,
@@ -2011,11 +2184,10 @@ def run_strategy(
2011
2184
  if acting is not None
2012
2185
  else {}
2013
2186
  )
2014
- listing_audit = (
2015
- _refuse_before_listing(cerebro.broker, first_bar)
2016
- if refuse_before_listing
2017
- else {}
2018
- )
2187
+ if refuse_before_listing:
2188
+ _refuse_before_listing(cerebro.broker, first_bar, audit=listing_audit)
2189
+ if fill_used == "nan" and bt.__name__ == "backtrader":
2190
+ _value_held_positions_only(cerebro.broker)
2019
2191
  # Run the strategy
2020
2192
  strategy = cerebro.run()[0]
2021
2193
  strategy.commission_policy = commission_policy
@@ -2038,6 +2210,8 @@ def run_strategy(
2038
2210
  f"(first bar {first_bar[worst[0]].date()})"
2039
2211
  )
2040
2212
  strategy.pit_exit = pit_exit
2213
+ strategy.leading_fill = leading_fill
2214
+ strategy.leading_fill_used = fill_used
2041
2215
  strategy.pit_membership = membership
2042
2216
  strategy.membership_audit = {
2043
2217
  "refused": refused_outside,
@@ -2074,6 +2248,9 @@ def run_strategy(
2074
2248
  report = {
2075
2249
  "attempts": attempts,
2076
2250
  "scaling": scaling,
2251
+ "leading_fill": leading_fill,
2252
+ "leading_fill_used": fill_used,
2253
+ "leading_fill_error": fill_error,
2077
2254
  "scaling_used": "uniform" if fallback else scaling,
2078
2255
  "max_leverage": max_leverage,
2079
2256
  "exposure_cap": min([cap] + applied),
@@ -2207,11 +2384,36 @@ def run_strategy(
2207
2384
  }))
2208
2385
  return strategy
2209
2386
 
2387
+ # The panel the attempts read: ``leading_fill`` unless the strategy raised
2388
+ # on the empty bars, see below.
2389
+ fill_used, fill_error = leading_fill, None
2210
2390
  cap, schedule, steps, attempts, as_published = 1.0, None, 0, 0, None
2211
2391
  fallback = False
2212
2392
  cushion = 1.0
2213
2393
  while True:
2214
- strategy = attempt(cap, schedule)
2394
+ try:
2395
+ strategy = attempt(cap, schedule)
2396
+ except Exception as exc: # noqa: BLE001 -- re-raised unless "nan"
2397
+ if fill_used != "nan":
2398
+ raise
2399
+ # Written around the back-fill: it raised on a bar without a price
2400
+ # (``int(value / close[0])``). Once, from scratch, on the 0.2.2
2401
+ # panel -- the exception is printed and kept in the report.
2402
+ where = traceback.extract_tb(exc.__traceback__)[-1:]
2403
+ fill_error = f"{type(exc).__name__}: {exc}" + (
2404
+ f" ({os.path.basename(where[0].filename)}:{where[0].lineno})" if where else ""
2405
+ )
2406
+ print(
2407
+ f"Leading fill: the strategy raised under leading_fill='nan' ({fill_error}) "
2408
+ f"-- re-running it once with the first real bar back-filled "
2409
+ f"(leading_fill_used='bfill'); use is_listed(data) to read the empty bars"
2410
+ )
2411
+ pivot_df.bfill(inplace=True)
2412
+ fill_used = "bfill"
2413
+ cap, schedule, steps, attempts, as_published = 1.0, None, 0, 0, None
2414
+ fallback = False
2415
+ cushion = 1.0
2416
+ continue
2215
2417
  attempts += 1
2216
2418
  if as_published is None:
2217
2419
  as_published = strategy
@@ -16,10 +16,28 @@ class BaseStrategy(bt.Strategy):
16
16
  self.log_data = []
17
17
 
18
18
  def is_tradable(self, data):
19
- """Return True if the instrument's price is not constant."""
19
+ """Return True if the instrument has a price and it is not constant.
20
+
21
+ Before a symbol's first real bar ``run_strategy`` gives its feed no
22
+ price (NaN, see ``leading_fill``); ``NaN != NaN`` is true, so the
23
+ test of a flat line alone would call it tradable.
24
+ """
20
25
  if len(data.close) < 3:
21
26
  return False
22
- return data.close[0] != data.close[-2]
27
+ now, before = data.close[0], data.close[-2]
28
+ if now != now or before != before: # NaN: no price yet
29
+ return False
30
+ return now != before
31
+
32
+ def is_listed(self, data):
33
+ """Whether the instrument has a price on this bar.
34
+
35
+ ``run_strategy`` answers from each symbol's first real bar, under
36
+ either ``leading_fill``; outside it, this reads the feed: a NaN close
37
+ is a bar before the first one.
38
+ """
39
+ price = data.close[0]
40
+ return price == price
23
41
 
24
42
  def is_member(self, data):
25
43
  """Whether the instrument belongs to the strategy's universe on this bar.