paperswithbacktest 0.2.1__tar.gz → 0.2.2__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.
- {paperswithbacktest-0.2.1/paperswithbacktest.egg-info → paperswithbacktest-0.2.2}/PKG-INFO +2 -2
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2/paperswithbacktest.egg-info}/PKG-INFO +2 -2
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/paperswithbacktest.egg-info/SOURCES.txt +7 -1
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/paperswithbacktest.egg-info/requires.txt +1 -1
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/__init__.py +1 -1
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/backtest_engine.py +21 -3
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/feeds.py +46 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/__init__.py +91 -12
- paperswithbacktest-0.2.2/pwb/datasets/nominal.py +234 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/docs/backtesting.md +20 -0
- paperswithbacktest-0.2.2/pwb/world_model/shock_lists.py +218 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/setup.cfg +2 -2
- paperswithbacktest-0.2.2/tests/test_nominal_feed.py +100 -0
- paperswithbacktest-0.2.2/tests/test_nominal_price.py +257 -0
- paperswithbacktest-0.2.2/tests/test_world_model_shock_integration.py +39 -0
- paperswithbacktest-0.2.2/tests/test_world_model_shock_lists.py +138 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/LICENSE +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/NOTICE +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/README.md +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/paperswithbacktest.egg-info/dependency_links.txt +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/paperswithbacktest.egg-info/top_level.txt +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/__init__.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/base_strategy.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/checks.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/commission.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/futures_run.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/indicators.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/lookahead.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/optimization_engine.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/option_costs.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/portfolio.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/strategies.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/backtesting/universe.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/french.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/futures.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/futures_chain.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/index_currencies.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/option_cache.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/options.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/pit_universe.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/datasets/prepared_cache.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/docs/__init__.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/docs/__main__.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/docs/world_model.md +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/engine.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/execution/__init__.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/execution/broker_factory.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/execution/ccxt_connector.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/execution/ib_connector.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/execution/live_utils.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/execution/optimal_limit_order.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/performance/__init__.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/performance/metrics.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/performance/nav_metrics.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/performance/plots.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/performance/reports.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/performance/trade_stats.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/world_model/__init__.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/world_model/_pit.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/world_model/_source.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/world_model/propagate.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pwb/world_model/reader.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/pyproject.toml +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_api_cache.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_array_feed.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_bare_symbol_collisions.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_bond_rates.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_bounded_loader.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_compat_shim.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_currency_costs.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_docs_shipped.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_engine_parity.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_engine_runner.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_engine_selector.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_exposure_cap.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_forex_directions.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_french.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_futures_chain.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_futures_loader.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_futures_rank6.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_futures_run.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_harness_checks.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_holiday_bars.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_hub_snapshot.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_index_currencies.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_lookahead.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_option_cache.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_option_chain.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_option_chain_sources.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_option_costs.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_pit_exit.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_pit_hold.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_pit_hold_accounting.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_pit_hold_same_bar_mark.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_prepared_cache.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_quantile_signal.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_read_memo.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_resolve_reused_property.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_reused_tickers.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_same_bar_orders.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_sells_first.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_short_borrow.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_strategy_commission.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_universe_alias_costs.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_world_model.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/tests/test_world_model_local.py +0 -0
- {paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/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.
|
|
3
|
+
Version: 0.2.2
|
|
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
|
|
@@ -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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: paperswithbacktest
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
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
|
|
@@ -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
|
{paperswithbacktest-0.2.1 → paperswithbacktest-0.2.2}/paperswithbacktest.egg-info/SOURCES.txt
RENAMED
|
@@ -29,6 +29,7 @@ pwb/datasets/french.py
|
|
|
29
29
|
pwb/datasets/futures.py
|
|
30
30
|
pwb/datasets/futures_chain.py
|
|
31
31
|
pwb/datasets/index_currencies.py
|
|
32
|
+
pwb/datasets/nominal.py
|
|
32
33
|
pwb/datasets/option_cache.py
|
|
33
34
|
pwb/datasets/options.py
|
|
34
35
|
pwb/datasets/pit_universe.py
|
|
@@ -54,6 +55,7 @@ pwb/world_model/_pit.py
|
|
|
54
55
|
pwb/world_model/_source.py
|
|
55
56
|
pwb/world_model/propagate.py
|
|
56
57
|
pwb/world_model/reader.py
|
|
58
|
+
pwb/world_model/shock_lists.py
|
|
57
59
|
tests/test_api_cache.py
|
|
58
60
|
tests/test_array_feed.py
|
|
59
61
|
tests/test_bare_symbol_collisions.py
|
|
@@ -77,6 +79,8 @@ tests/test_holiday_bars.py
|
|
|
77
79
|
tests/test_hub_snapshot.py
|
|
78
80
|
tests/test_index_currencies.py
|
|
79
81
|
tests/test_lookahead.py
|
|
82
|
+
tests/test_nominal_feed.py
|
|
83
|
+
tests/test_nominal_price.py
|
|
80
84
|
tests/test_option_cache.py
|
|
81
85
|
tests/test_option_chain.py
|
|
82
86
|
tests/test_option_chain_sources.py
|
|
@@ -97,4 +101,6 @@ tests/test_strategy_commission.py
|
|
|
97
101
|
tests/test_universe_alias_costs.py
|
|
98
102
|
tests/test_world_model.py
|
|
99
103
|
tests/test_world_model_local.py
|
|
100
|
-
tests/test_world_model_shock.py
|
|
104
|
+
tests/test_world_model_shock.py
|
|
105
|
+
tests/test_world_model_shock_integration.py
|
|
106
|
+
tests/test_world_model_shock_lists.py
|
|
@@ -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.
|
|
11
|
+
__version__ = "0.2.2"
|
|
@@ -16,7 +16,7 @@ from ..engine import load as _load_engine
|
|
|
16
16
|
bt = _load_engine() # Tradewind by default, backtrader on request; see pwb.engine
|
|
17
17
|
from . import checks as _checks
|
|
18
18
|
from . import lookahead as _lookahead
|
|
19
|
-
from .feeds import ArrayPandasData
|
|
19
|
+
from .feeds import ArrayPandasData, NominalPandasData, require_feed_lines
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
def _apply_broker_kwargs(broker: bt.BrokerBase, kwargs: dict) -> None:
|
|
@@ -756,7 +756,7 @@ def _blank_out_bars(pivot_df: pd.DataFrame, membership: "_Membership") -> None:
|
|
|
756
756
|
if not names:
|
|
757
757
|
return
|
|
758
758
|
mask = np.column_stack([membership.out[s] for s in names])
|
|
759
|
-
for field in ("open", "high", "low", "close"):
|
|
759
|
+
for field in ("open", "high", "low", "close", "nominal_close"):
|
|
760
760
|
columns = [(s, field) for s in names]
|
|
761
761
|
if any(c not in pivot_df.columns for c in columns):
|
|
762
762
|
continue
|
|
@@ -1618,9 +1618,22 @@ def run_strategy(
|
|
|
1618
1618
|
engine=None,
|
|
1619
1619
|
futures=None,
|
|
1620
1620
|
futures_options=None,
|
|
1621
|
+
nominal=False,
|
|
1621
1622
|
):
|
|
1622
1623
|
"""Run a tactical asset allocation strategy with Backtrader (or Tradewind).
|
|
1623
1624
|
|
|
1625
|
+
``nominal`` -- give every feed a ``nominal`` line: ``data.nominal[0]`` is the
|
|
1626
|
+
price the stock traded at on the bar (``nominal_close`` of
|
|
1627
|
+
``get_pricing(..., nominal=True)``), where ``data.close`` is the close
|
|
1628
|
+
back-adjusted for later splits and dividends. A filter or a sort on a price
|
|
1629
|
+
*level* (``>= 5`` dollars, penny stocks, the share price) must read it: on
|
|
1630
|
+
the adjusted close, AAPL on 2020-08-28 is 121, for a share that traded at
|
|
1631
|
+
499. NaN for a name outside ``Stocks-Daily-Price`` (ETFs, indices...). Orders,
|
|
1632
|
+
fills and the NAV still use the adjusted prices: the option changes nothing
|
|
1633
|
+
a strategy does not read. On Tradewind it needs a release with feed lines
|
|
1634
|
+
(``pwb.backtesting.feeds.FEED_EXTRA_LINES``). ``False`` (default): the run
|
|
1635
|
+
of the releases before it.
|
|
1636
|
+
|
|
1624
1637
|
``futures`` -- futures roots (``["GC", "BZ"]``) the strategy trades as real
|
|
1625
1638
|
contracts of ``Futures-Daily-Price``, on Tradewind only. Each root is one feed
|
|
1626
1639
|
named after it, the ratio-adjusted series of the contract held (signals);
|
|
@@ -1835,6 +1848,9 @@ def run_strategy(
|
|
|
1835
1848
|
broker_kwargs = broker_kwargs or {}
|
|
1836
1849
|
# Load the data from https://paperswithbacktest.com/datasets -- once, and
|
|
1837
1850
|
# reused across attempts, because a re-run must not re-download anything.
|
|
1851
|
+
if nominal:
|
|
1852
|
+
require_feed_lines() # before the download, not at the first feed
|
|
1853
|
+
pricing_kwargs = {"nominal": True} if nominal else {}
|
|
1838
1854
|
pivot_df = pwb_ds.get_pricing(
|
|
1839
1855
|
symbol_list=symbols,
|
|
1840
1856
|
fields=["open", "high", "low", "close"],
|
|
@@ -1843,6 +1859,7 @@ def run_strategy(
|
|
|
1843
1859
|
# "hold" values a position carried through an exit at its real
|
|
1844
1860
|
# prices, so it needs the rows the membership cut would drop.
|
|
1845
1861
|
pit_cut=pit_exit != "hold",
|
|
1862
|
+
**pricing_kwargs,
|
|
1846
1863
|
)
|
|
1847
1864
|
# Which feed each column came from (``get_pricing``), popped so pandas
|
|
1848
1865
|
# does not carry it through every operation below.
|
|
@@ -1951,8 +1968,9 @@ def run_strategy(
|
|
|
1951
1968
|
# Keyed by feed name, because that is what ``addcommissioninfo(name=...)``
|
|
1952
1969
|
# matches on, and what the scheme reads the bar date from.
|
|
1953
1970
|
feeds = {}
|
|
1971
|
+
feed_cls = NominalPandasData if nominal else ArrayPandasData
|
|
1954
1972
|
for symbol in pivot_df.columns.levels[0]:
|
|
1955
|
-
data =
|
|
1973
|
+
data = feed_cls(dataname=pivot_df[symbol].copy())
|
|
1956
1974
|
cerebro.adddata(data, name=symbol)
|
|
1957
1975
|
feeds[symbol] = data
|
|
1958
1976
|
guard = {"liquidating": False}
|
|
@@ -31,6 +31,7 @@ identical to the cent.
|
|
|
31
31
|
from __future__ import annotations
|
|
32
32
|
|
|
33
33
|
import numpy as np
|
|
34
|
+
import pandas as pd
|
|
34
35
|
|
|
35
36
|
from ..engine import load as _load_engine
|
|
36
37
|
|
|
@@ -72,3 +73,48 @@ else:
|
|
|
72
73
|
getattr(lines, datafield)[0] = values[idx]
|
|
73
74
|
lines.datetime[0] = self._pwb_dtnum[idx]
|
|
74
75
|
return True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
#: Whether the running engine's ``PandasData`` reads lines a subclass declares
|
|
79
|
+
#: (``lines = ("nominal",)``). backtrader always has; Tradewind from the release
|
|
80
|
+
#: that adds ``tradewind.feeds.EXTRA_LINES`` (paperswithbacktest/tradewind#67).
|
|
81
|
+
FEED_EXTRA_LINES = bt.__name__ == "backtrader" or bool(getattr(bt.feeds, "EXTRA_LINES", False))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def require_feed_lines() -> None:
|
|
85
|
+
"""Raise unless the running engine's feeds take the lines a subclass declares."""
|
|
86
|
+
if not FEED_EXTRA_LINES:
|
|
87
|
+
raise RuntimeError(
|
|
88
|
+
"data.nominal needs an engine whose feeds take extra lines: this Tradewind "
|
|
89
|
+
"does not (it needs the release of paperswithbacktest/tradewind#67). Run "
|
|
90
|
+
"with PWB_ENGINE=backtrader, or read nominal_close from "
|
|
91
|
+
"pwb.datasets.get_pricing(..., nominal=True) outside the feed."
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class NominalPandasData(ArrayPandasData):
|
|
96
|
+
"""``ArrayPandasData`` with one more line, ``nominal``: the price of the date.
|
|
97
|
+
|
|
98
|
+
It reads the ``nominal_close`` column of the frame (``get_pricing(...,
|
|
99
|
+
nominal=True)``, ``run_strategy(..., nominal=True)``), NaN when the frame
|
|
100
|
+
has none. ``data.close`` stays the adjusted close the strategy trades on;
|
|
101
|
+
``data.nominal[0]`` is what a filter on a price level (``>= 5`` dollars,
|
|
102
|
+
penny stocks, a sort on the share price) must compare -- the adjusted
|
|
103
|
+
close is a level the stock reached only after its later splits (see
|
|
104
|
+
:mod:`pwb.datasets.nominal`).
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
lines = ("nominal",)
|
|
108
|
+
params = (("nominal", "nominal_close"),)
|
|
109
|
+
|
|
110
|
+
def __init__(self):
|
|
111
|
+
require_feed_lines()
|
|
112
|
+
# The engines take the parameters (``dataname`` among them) before
|
|
113
|
+
# ``__init__`` runs, so the frame is completed on ``self.p``.
|
|
114
|
+
frame = self.p.dataname
|
|
115
|
+
column = self.p.nominal
|
|
116
|
+
if isinstance(frame, pd.DataFrame) and isinstance(column, str) and column not in frame.columns:
|
|
117
|
+
# One feed class for every name of a panel: an ETF or an index has
|
|
118
|
+
# no nominal price, and reads NaN rather than failing.
|
|
119
|
+
self.p.dataname = frame.assign(**{column: np.nan})
|
|
120
|
+
super().__init__()
|
|
@@ -21,6 +21,14 @@ import requests
|
|
|
21
21
|
from tqdm import tqdm
|
|
22
22
|
|
|
23
23
|
from . import prepared_cache as _prepared
|
|
24
|
+
from .nominal import ( # noqa: F401 (re-exported)
|
|
25
|
+
DISTRIBUTION_ROWS,
|
|
26
|
+
NOMINAL_COLUMNS,
|
|
27
|
+
SPLITS_DATASET,
|
|
28
|
+
load_splits,
|
|
29
|
+
nominal_factor,
|
|
30
|
+
nominal_price,
|
|
31
|
+
)
|
|
24
32
|
from .index_currencies import ( # noqa: F401 (re-exported)
|
|
25
33
|
INDEX_CURRENCY,
|
|
26
34
|
IndexCurrencyWarning,
|
|
@@ -1115,6 +1123,8 @@ def _load_dataset_from_hf(dataset_name: str, split: str, hf_token: str, symbols=
|
|
|
1115
1123
|
return _read_parquet_files(local_files, desc=f"Load {dataset_name}", symbols=symbols,
|
|
1116
1124
|
columns=columns, window=_row_window(window))
|
|
1117
1125
|
|
|
1126
|
+
STOCKS_DAILY_DATASET = "Stocks-Daily-Price"
|
|
1127
|
+
|
|
1118
1128
|
DAILY_PRICE_DATASETS = [
|
|
1119
1129
|
"Bonds-Daily-Price",
|
|
1120
1130
|
"Commodities-Daily-Price",
|
|
@@ -1954,6 +1964,7 @@ def load_dataset(
|
|
|
1954
1964
|
columns=None,
|
|
1955
1965
|
*,
|
|
1956
1966
|
split="train",
|
|
1967
|
+
nominal=False,
|
|
1957
1968
|
):
|
|
1958
1969
|
"""Load a PWB dataset as a pandas DataFrame.
|
|
1959
1970
|
|
|
@@ -1965,7 +1976,24 @@ def load_dataset(
|
|
|
1965
1976
|
Keep only these symbols. The filter is pushed down to each shard's
|
|
1966
1977
|
read, so memory stays bounded to the matching rows. Universe names
|
|
1967
1978
|
(``"sp500"``...) are resolved as before.
|
|
1968
|
-
adjust
|
|
1979
|
+
adjust : bool
|
|
1980
|
+
Which prices of a daily price table come back under ``open``,
|
|
1981
|
+
``high``, ``low`` and ``close``. On ``Stocks-Daily-Price`` **neither
|
|
1982
|
+
setting gives the price the stock traded at**: the table's two price
|
|
1983
|
+
columns are both back-adjusted for every later split.
|
|
1984
|
+
|
|
1985
|
+
* ``True`` (default): ``adj_close``, adjusted for splits and
|
|
1986
|
+
dividends (a total-return series), under the name ``close``; the
|
|
1987
|
+
open, high and low are scaled by the same factor, and there is no
|
|
1988
|
+
``adj_close`` column.
|
|
1989
|
+
* ``False``: the table's own ``open``/``high``/``low``/``close``,
|
|
1990
|
+
adjusted for splits but not for dividends, **and** ``adj_close``
|
|
1991
|
+
next to them. It is not an unadjusted price: AAPL on 2020-08-28 is
|
|
1992
|
+
124.81, for a share that traded at 499.23. Strategies rely on
|
|
1993
|
+
getting both columns from one read, so ``adj_close`` stays.
|
|
1994
|
+
|
|
1995
|
+
For the price of the date, pass ``nominal=True``.
|
|
1996
|
+
extend, to_usd, rate_to_price : bool
|
|
1969
1997
|
Post-processing of the daily price datasets. ``rate_to_price``
|
|
1970
1998
|
turns the yields of ``Bonds-Daily-Price`` into zero-coupon prices,
|
|
1971
1999
|
the TIPS real yields (``US5YT``...) included; see
|
|
@@ -1987,6 +2015,13 @@ def load_dataset(
|
|
|
1987
2015
|
|
|
1988
2016
|
split : str, optional
|
|
1989
2017
|
Named table to read. Most datasets use ``"train"``.
|
|
2018
|
+
nominal : bool, optional
|
|
2019
|
+
``Stocks-Daily-Price`` only: add ``nominal_open``, ``nominal_high``,
|
|
2020
|
+
``nominal_low`` and ``nominal_close``, the prices the stock traded at
|
|
2021
|
+
on the date (the split-adjusted prices times the
|
|
2022
|
+
``Stocks-Daily-Splits`` ratios dated after it; see
|
|
2023
|
+
:mod:`pwb.datasets.nominal`). What a filter or a sort on a price
|
|
2024
|
+
*level* must read. The other columns are those ``adjust`` gives.
|
|
1990
2025
|
|
|
1991
2026
|
Without ``start``, ``end`` and ``columns`` the behaviour is unchanged. A
|
|
1992
2027
|
minute dataset loaded without ``start``/``end`` still loads, but warns
|
|
@@ -2104,6 +2139,16 @@ def load_dataset(
|
|
|
2104
2139
|
if path == "Universe-Daily-Price":
|
|
2105
2140
|
df = _with_forex_inverse_names(df)
|
|
2106
2141
|
|
|
2142
|
+
if nominal:
|
|
2143
|
+
if path != STOCKS_DAILY_DATASET:
|
|
2144
|
+
raise ValueError(
|
|
2145
|
+
f"nominal=True: nominal prices exist for {STOCKS_DAILY_DATASET} only "
|
|
2146
|
+
f"(the split table is a table of stocks), not for {path!r}"
|
|
2147
|
+
)
|
|
2148
|
+
# From the split-adjusted columns, before ``adjust`` replaces them with
|
|
2149
|
+
# the dividend-adjusted ones.
|
|
2150
|
+
df = nominal_price(df, assume_split_adjusted=True)
|
|
2151
|
+
|
|
2107
2152
|
if path in DAILY_PRICE_DATASETS:
|
|
2108
2153
|
if adjust and "adj_close" in df.columns:
|
|
2109
2154
|
adj_factor = df["adj_close"] / df["close"]
|
|
@@ -2120,9 +2165,12 @@ def load_dataset(
|
|
|
2120
2165
|
},
|
|
2121
2166
|
inplace=True,
|
|
2122
2167
|
)
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2168
|
+
# adjust=False: the table's split-adjusted open/high/low/close, and
|
|
2169
|
+
# adj_close kept next to them. Until 0.2.1 this branch called
|
|
2170
|
+
# ``df.drop(columns=["adj_close"])`` without keeping the result, so
|
|
2171
|
+
# adj_close always stayed; 38 published strategies read both columns
|
|
2172
|
+
# from one ``adjust=False`` load (a dividend yield, a total return next
|
|
2173
|
+
# to a price), so the behaviour is kept and the dead line removed.
|
|
2126
2174
|
|
|
2127
2175
|
if path in DAILY_PRICE_DATASETS and (extend and path == "ETFs-Daily-Price"):
|
|
2128
2176
|
df = __extend_etfs(df)
|
|
@@ -2339,7 +2387,7 @@ def __extend_etfs(df_etfs):
|
|
|
2339
2387
|
)
|
|
2340
2388
|
|
|
2341
2389
|
|
|
2342
|
-
ALLOWED_FIELDS = {"open", "high", "low", "close", "volume"}
|
|
2390
|
+
ALLOWED_FIELDS = {"open", "high", "low", "close", "volume", *NOMINAL_COLUMNS.values()}
|
|
2343
2391
|
|
|
2344
2392
|
|
|
2345
2393
|
# Which repository a bare ticker resolves to when ``Universe-Daily-Price`` lists
|
|
@@ -2803,12 +2851,23 @@ def _pricing_shard_window(repo_id, names, extend, contested, reused_names, start
|
|
|
2803
2851
|
return None
|
|
2804
2852
|
|
|
2805
2853
|
|
|
2806
|
-
def
|
|
2854
|
+
def _pricing_load_kwargs(repo_id, extend, nominal) -> dict:
|
|
2855
|
+
"""The ``load_dataset`` arguments of one repository of a ``get_pricing`` read."""
|
|
2856
|
+
kwargs = {"extend": extend}
|
|
2857
|
+
if nominal and repo_id == STOCKS_DAILY_DATASET:
|
|
2858
|
+
# Passed only when asked for, so a loader replaced in a test keeps
|
|
2859
|
+
# the signature it has always had.
|
|
2860
|
+
kwargs["nominal"] = True
|
|
2861
|
+
return kwargs
|
|
2862
|
+
|
|
2863
|
+
|
|
2864
|
+
def _load_for_pricing(repo_id, names, extend, shard_window, nominal=False):
|
|
2865
|
+
kwargs = _pricing_load_kwargs(repo_id, extend, nominal)
|
|
2807
2866
|
if shard_window is None:
|
|
2808
|
-
return load_dataset(repo_id, names,
|
|
2867
|
+
return load_dataset(repo_id, names, **kwargs)
|
|
2809
2868
|
token = _SHARD_WINDOW.set(shard_window)
|
|
2810
2869
|
try:
|
|
2811
|
-
return load_dataset(repo_id, names,
|
|
2870
|
+
return load_dataset(repo_id, names, **kwargs)
|
|
2812
2871
|
finally:
|
|
2813
2872
|
_SHARD_WINDOW.reset(token)
|
|
2814
2873
|
|
|
@@ -2822,6 +2881,7 @@ def get_pricing(
|
|
|
2822
2881
|
extend=False,
|
|
2823
2882
|
keep_single_level=False, # backward-compat flag
|
|
2824
2883
|
pit_cut=True,
|
|
2884
|
+
nominal=False,
|
|
2825
2885
|
):
|
|
2826
2886
|
"""
|
|
2827
2887
|
Fetch OHLC pricing for the requested symbols.
|
|
@@ -2832,8 +2892,11 @@ def get_pricing(
|
|
|
2832
2892
|
One ticker or a list of tickers. Supports suffixed form "SYM.CAT"
|
|
2833
2893
|
where CAT in {CRYPTO, STOCK, CMDTY, IDX, ETF, FX, BND}.
|
|
2834
2894
|
fields : list[str] | None
|
|
2835
|
-
Any subset of ["open", "high", "low", "close"]
|
|
2836
|
-
|
|
2895
|
+
Any subset of ["open", "high", "low", "close", "volume"], plus
|
|
2896
|
+
``nominal_open``/``nominal_high``/``nominal_low``/``nominal_close``
|
|
2897
|
+
(which imply ``nominal=True``). Defaults to ["close"] for backward
|
|
2898
|
+
compatibility. ``close`` is the dividend- and split-adjusted close
|
|
2899
|
+
(``load_dataset``'s ``adjust=True``), not the price of the date.
|
|
2837
2900
|
start_date, end_date : str (YYYY-MM-DD)
|
|
2838
2901
|
Slice the date index (inclusive).
|
|
2839
2902
|
extend : bool
|
|
@@ -2848,6 +2911,13 @@ def get_pricing(
|
|
|
2848
2911
|
every price row of every name that was ever a member: what
|
|
2849
2912
|
``run_strategy`` needs to value a position held through an exit at its
|
|
2850
2913
|
real prices, membership being enforced on the orders instead.
|
|
2914
|
+
nominal : bool
|
|
2915
|
+
Add ``nominal_close`` to ``fields`` (unless a nominal field is already
|
|
2916
|
+
asked for): the price a stock traded at on the date, for a filter or a
|
|
2917
|
+
sort on a price level (see :mod:`pwb.datasets.nominal`). It exists for
|
|
2918
|
+
the names read from ``Stocks-Daily-Price`` only; for the others
|
|
2919
|
+
(ETFs, indices, crypto...) the column is absent from the panel.
|
|
2920
|
+
``False`` (default): the panel is the one of the releases before it.
|
|
2851
2921
|
|
|
2852
2922
|
Returns
|
|
2853
2923
|
-------
|
|
@@ -2872,6 +2942,10 @@ def get_pricing(
|
|
|
2872
2942
|
bad = [f for f in fields if f not in ALLOWED_FIELDS]
|
|
2873
2943
|
if bad:
|
|
2874
2944
|
raise ValueError(f"Invalid field(s): {bad}. Allowed: {sorted(ALLOWED_FIELDS)}")
|
|
2945
|
+
nominal_fields = set(NOMINAL_COLUMNS.values())
|
|
2946
|
+
if nominal and not nominal_fields.intersection(fields):
|
|
2947
|
+
fields = fields + ["nominal_close"]
|
|
2948
|
+
nominal = bool(nominal_fields.intersection(fields))
|
|
2875
2949
|
|
|
2876
2950
|
# --------------------------------------------------------------- download
|
|
2877
2951
|
# Direct routing for suffixed symbols (skip Universe lookup)
|
|
@@ -2972,7 +3046,7 @@ def get_pricing(
|
|
|
2972
3046
|
shard_window = _pricing_shard_window(
|
|
2973
3047
|
repo_id, names, ext_flag, contested, reused_names, start_date, end_date
|
|
2974
3048
|
)
|
|
2975
|
-
df_part = _load_for_pricing(repo_id, names, ext_flag, shard_window)
|
|
3049
|
+
df_part = _load_for_pricing(repo_id, names, ext_flag, shard_window, nominal)
|
|
2976
3050
|
if shard_window is not None:
|
|
2977
3051
|
pruned.append((repo_id, names, ext_flag))
|
|
2978
3052
|
if not df_part.empty:
|
|
@@ -2981,7 +3055,7 @@ def get_pricing(
|
|
|
2981
3055
|
# Nothing in the window anywhere: read everything, as before, so the
|
|
2982
3056
|
# panel comes out the way it always did for an empty window.
|
|
2983
3057
|
for repo_id, names, ext_flag in pruned:
|
|
2984
|
-
df_part = load_dataset(repo_id, names,
|
|
3058
|
+
df_part = load_dataset(repo_id, names, **_pricing_load_kwargs(repo_id, ext_flag, nominal))
|
|
2985
3059
|
if not df_part.empty:
|
|
2986
3060
|
loaded[repo_id] = df_part
|
|
2987
3061
|
loaded = _arbitrate_collisions(loaded, contested, start_date, end_date)
|
|
@@ -3017,6 +3091,11 @@ def get_pricing(
|
|
|
3017
3091
|
df = df.loc[start_date:end_date]
|
|
3018
3092
|
|
|
3019
3093
|
# ------------------------------------------------------------- reshape
|
|
3094
|
+
if nominal:
|
|
3095
|
+
# No stock in the panel: no nominal column was loaded at all.
|
|
3096
|
+
for field in nominal_fields.intersection(fields):
|
|
3097
|
+
if field not in df.columns:
|
|
3098
|
+
df[field] = np.nan
|
|
3020
3099
|
prices = df.pivot_table(values=fields, index=df.index, columns="symbol")
|
|
3021
3100
|
prices = prices.swaplevel(axis=1).sort_index(axis=1)
|
|
3022
3101
|
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""The price a stock actually traded at on the date: ``nominal_close``.
|
|
2
|
+
|
|
3
|
+
Why
|
|
4
|
+
---
|
|
5
|
+
``Stocks-Daily-Price`` has no raw price. Its two price columns are both
|
|
6
|
+
back-adjusted for every split recorded after the date:
|
|
7
|
+
|
|
8
|
+
* ``close`` (and ``open``/``high``/``low``): adjusted for splits, not for
|
|
9
|
+
dividends -- what ``load_dataset(..., adjust=False)`` returns;
|
|
10
|
+
* ``adj_close``: adjusted for splits **and** dividends -- what
|
|
11
|
+
``load_dataset(...)`` (``adjust=True``, the default), ``get_pricing`` and
|
|
12
|
+
therefore ``run_strategy`` return under the name ``close``.
|
|
13
|
+
|
|
14
|
+
AAPL on 2020-08-28 is 124.81 in ``close`` and 120.96 in ``adj_close``; it traded
|
|
15
|
+
at 499.23 (4-for-1 split on 2020-08-31). A filter written on a price level
|
|
16
|
+
(``close >= 5``, "penny stocks", a sort on the share price) applied to either
|
|
17
|
+
column reads a level the stock reached only after later splits: it keeps
|
|
18
|
+
future reverse splits and drops future winners. Measured on 2026-12-02
|
|
19
|
+
(``reports/price-filter-lookahead-audit-2026-12-02.md``): at 5 dollars, 15 %
|
|
20
|
+
of all stock-months fall on the wrong side of the threshold with
|
|
21
|
+
``adj_close``, 7.1 % with ``close``.
|
|
22
|
+
|
|
23
|
+
What
|
|
24
|
+
----
|
|
25
|
+
``nominal_close = close x product of the Stocks-Daily-Splits ratios
|
|
26
|
+
(split_to / split_from) dated strictly after the row's date``. A ratio dated
|
|
27
|
+
``d`` applies to the rows before ``d``: the price of the ex-date is already the
|
|
28
|
+
post-split price. Checked against the raw price of ShortOverShorted
|
|
29
|
+
(``market_cap x 1e6 / number_of_shares``) on 844 653 stock-months, 1999-2026:
|
|
30
|
+
92.4 % within 10 %, against 43.3 % for ``adj_close`` (85.0 % against 1.3 % on
|
|
31
|
+
the rows followed by a split).
|
|
32
|
+
|
|
33
|
+
Distributions (paperswithbacktest/data-api#227)
|
|
34
|
+
-----------------------------------------------
|
|
35
|
+
31 rows of ``Stocks-Daily-Splits`` are spin-offs and other distributions
|
|
36
|
+
recorded as ``forward_split`` (DD/Qnity 2025, GE/GE HealthCare 2023, EBAY/PayPal
|
|
37
|
+
2015...): the share count did not change. They are **applied by default**,
|
|
38
|
+
because ``close`` is back-adjusted with the very same ratios -- removing them
|
|
39
|
+
would leave the price divided by the ratio. Measured on the 31 rows, the day
|
|
40
|
+
before each one: with the ratio, the nominal price matches the raw price of
|
|
41
|
+
ShortOverShorted on every row where ShortOverShorted is sound (GE 2021-07-30:
|
|
42
|
+
12.95 against 12.95; MMM 2024-03-28: 106.07 against 106.78; A 2014-10-31: 55.28
|
|
43
|
+
against 55.28); without it, it is 1.05 to 2.8 times too low (DD 2025-10-31:
|
|
44
|
+
34.16 for a stock that traded near 80; GE 2021-07-30: 8.07).
|
|
45
|
+
|
|
46
|
+
``distributions=False`` leaves those rows out, for a caller who wants the
|
|
47
|
+
factor of the share count rather than of the price. The rows are read from
|
|
48
|
+
the ``event_type`` column when the dataset has it (data-api#227 adds it, equal
|
|
49
|
+
to ``adjustment_type`` except ``"distribution"`` on those rows), and otherwise
|
|
50
|
+
from ``DISTRIBUTION_ROWS`` below, the same 31 rows frozen here.
|
|
51
|
+
|
|
52
|
+
Limits
|
|
53
|
+
------
|
|
54
|
+
* The splits table is keyed by ticker: a reused ticker
|
|
55
|
+
(``pwb_ds.get_pricing`` resolves them by date) gets the splits of every
|
|
56
|
+
instrument that traded under it.
|
|
57
|
+
* Outside ``Stocks-Daily-Price`` there is no split table: ETFs, indices and the
|
|
58
|
+
other classes have no nominal price here.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
from __future__ import annotations
|
|
62
|
+
|
|
63
|
+
import numpy as np
|
|
64
|
+
import pandas as pd
|
|
65
|
+
|
|
66
|
+
SPLITS_DATASET = "Stocks-Daily-Splits"
|
|
67
|
+
|
|
68
|
+
#: The price columns a nominal copy is made of, and the name of each copy.
|
|
69
|
+
NOMINAL_COLUMNS = {
|
|
70
|
+
"open": "nominal_open",
|
|
71
|
+
"high": "nominal_high",
|
|
72
|
+
"low": "nominal_low",
|
|
73
|
+
"close": "nominal_close",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
#: The 31 rows of Stocks-Daily-Splits that are distributions (spin-offs,
|
|
77
|
+
#: warrants, a share-class exchange) recorded as ``forward_split``; frozen from
|
|
78
|
+
#: ``reports/splits-misclassified-2026-12-02.md``. Used only when the dataset
|
|
79
|
+
#: has no ``event_type`` column yet -- paperswithbacktest/data-api#227 adds it,
|
|
80
|
+
#: and then the column is read instead. The rule that found them:
|
|
81
|
+
#: ``forward_split``, non-integer ratio, and ``split_from`` >= 250, or >= 100
|
|
82
|
+
#: with a ratio >= 2; plus SLM/Navient 2014 ("1 for 2.798"), added by hand.
|
|
83
|
+
DISTRIBUTION_ROWS = frozenset(
|
|
84
|
+
{
|
|
85
|
+
("ASH", "2005-07-01"),
|
|
86
|
+
("VLO", "2013-05-02"),
|
|
87
|
+
("TRC", "2013-08-29"),
|
|
88
|
+
("SLM", "2014-05-01"),
|
|
89
|
+
("A", "2014-11-03"),
|
|
90
|
+
("EBAY", "2015-07-20"),
|
|
91
|
+
("DHR", "2016-07-05"),
|
|
92
|
+
("YUM", "2016-11-01"),
|
|
93
|
+
("AA", "2016-11-01"),
|
|
94
|
+
("XRX", "2017-01-03"),
|
|
95
|
+
("ASH", "2017-05-15"),
|
|
96
|
+
("LEN", "2017-11-09"),
|
|
97
|
+
("EQT", "2018-11-13"),
|
|
98
|
+
("DELL", "2018-12-28"),
|
|
99
|
+
("HSIC", "2019-02-08"),
|
|
100
|
+
("XPO", "2021-08-02"),
|
|
101
|
+
("DELL", "2021-11-02"),
|
|
102
|
+
("IBM", "2021-11-04"),
|
|
103
|
+
("XPO", "2022-11-01"),
|
|
104
|
+
("GE", "2023-01-04"),
|
|
105
|
+
("MDU", "2023-06-01"),
|
|
106
|
+
("GPUS", "2023-06-23"),
|
|
107
|
+
("LH", "2023-07-03"),
|
|
108
|
+
("MMM", "2024-04-01"),
|
|
109
|
+
("GE", "2024-04-02"),
|
|
110
|
+
("GPUS", "2024-04-12"),
|
|
111
|
+
("MDU", "2024-11-01"),
|
|
112
|
+
("LEN", "2025-01-21"),
|
|
113
|
+
("FTV", "2025-06-30"),
|
|
114
|
+
("HON", "2025-10-30"),
|
|
115
|
+
("DD", "2025-11-03"),
|
|
116
|
+
}
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def load_splits() -> pd.DataFrame:
|
|
121
|
+
"""``Stocks-Daily-Splits`` as ``symbol, date, ratio, event_type``.
|
|
122
|
+
|
|
123
|
+
``ratio`` is ``split_to / split_from`` (4.0 for a 4-for-1 split, 0.125 for a
|
|
124
|
+
1-for-8 reverse split); rows without a usable ratio, and ratios of exactly
|
|
125
|
+
1, are dropped. ``event_type`` is the dataset's own column when it has one,
|
|
126
|
+
otherwise ``adjustment_type`` with ``"distribution"`` on ``DISTRIBUTION_ROWS``.
|
|
127
|
+
"""
|
|
128
|
+
from . import load_dataset # the package imports this module
|
|
129
|
+
|
|
130
|
+
return prepare_splits(load_dataset(SPLITS_DATASET))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def prepare_splits(raw: pd.DataFrame) -> pd.DataFrame:
|
|
134
|
+
"""The normalised split table (see ``load_splits``) from the dataset's rows."""
|
|
135
|
+
sp = pd.DataFrame(
|
|
136
|
+
{
|
|
137
|
+
"symbol": raw["symbol"].astype(str).to_numpy(),
|
|
138
|
+
"date": pd.to_datetime(raw["date"].astype(str).str[:10]).to_numpy(),
|
|
139
|
+
}
|
|
140
|
+
)
|
|
141
|
+
split_from = pd.to_numeric(raw["split_from"], errors="coerce").to_numpy(dtype=float)
|
|
142
|
+
split_to = pd.to_numeric(raw["split_to"], errors="coerce").to_numpy(dtype=float)
|
|
143
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
144
|
+
sp["ratio"] = split_to / split_from
|
|
145
|
+
if "event_type" in raw.columns:
|
|
146
|
+
sp["event_type"] = raw["event_type"].astype(str).to_numpy()
|
|
147
|
+
else:
|
|
148
|
+
kind = (
|
|
149
|
+
raw["adjustment_type"].astype(str).to_numpy()
|
|
150
|
+
if "adjustment_type" in raw.columns
|
|
151
|
+
else np.full(len(raw), "split", dtype=object)
|
|
152
|
+
)
|
|
153
|
+
frozen = [
|
|
154
|
+
(s, d) in DISTRIBUTION_ROWS
|
|
155
|
+
for s, d in zip(sp["symbol"], sp["date"].dt.strftime("%Y-%m-%d"))
|
|
156
|
+
]
|
|
157
|
+
sp["event_type"] = np.where(frozen, "distribution", kind)
|
|
158
|
+
usable = (split_from > 0) & (split_to > 0) & np.isfinite(sp["ratio"].to_numpy())
|
|
159
|
+
sp = sp[usable & (sp["ratio"].to_numpy() != 1.0)]
|
|
160
|
+
return sp.sort_values(["symbol", "date"], kind="stable").reset_index(drop=True)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def nominal_factor(symbols, dates, splits: pd.DataFrame | None = None, *, distributions=True) -> np.ndarray:
|
|
164
|
+
"""The factor that turns ``close`` into the price of the date, row by row.
|
|
165
|
+
|
|
166
|
+
``symbols`` and ``dates`` are aligned sequences (one row each). The factor
|
|
167
|
+
is the product of the ratios dated strictly after the row's date, 1.0 for a
|
|
168
|
+
symbol without later splits. ``splits`` is ``load_splits()`` (loaded when
|
|
169
|
+
omitted); ``distributions=False`` leaves the distribution rows out (see the
|
|
170
|
+
module docstring: the default, True, is the one that gives the price).
|
|
171
|
+
"""
|
|
172
|
+
if splits is None:
|
|
173
|
+
splits = load_splits()
|
|
174
|
+
if not distributions:
|
|
175
|
+
splits = splits[splits["event_type"] != "distribution"]
|
|
176
|
+
symbols = np.asarray(symbols, dtype=object)
|
|
177
|
+
dates = pd.to_datetime(pd.Series(np.asarray(dates))).to_numpy(dtype="datetime64[ns]")
|
|
178
|
+
out = np.ones(len(symbols), dtype=float)
|
|
179
|
+
if not len(symbols) or splits.empty:
|
|
180
|
+
return out
|
|
181
|
+
by_symbol = {
|
|
182
|
+
s: (g["date"].to_numpy(dtype="datetime64[ns]"), g["ratio"].to_numpy(dtype=float))
|
|
183
|
+
for s, g in splits.groupby("symbol", sort=False)
|
|
184
|
+
}
|
|
185
|
+
rows = pd.Series(np.arange(len(symbols))).groupby(symbols).indices
|
|
186
|
+
for symbol, idx in rows.items():
|
|
187
|
+
found = by_symbol.get(symbol)
|
|
188
|
+
if found is None:
|
|
189
|
+
continue
|
|
190
|
+
split_dates, ratios = found
|
|
191
|
+
# tail[k]: product of the ratios k..end; the row before split k gets tail[k]
|
|
192
|
+
tail = np.append(np.cumprod(ratios[::-1])[::-1], 1.0)
|
|
193
|
+
k = np.searchsorted(split_dates, dates[idx], side="right")
|
|
194
|
+
out[idx] = tail[k]
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def nominal_price(df: pd.DataFrame, splits: pd.DataFrame | None = None, *, distributions=True,
|
|
199
|
+
assume_split_adjusted=False) -> pd.DataFrame:
|
|
200
|
+
"""``df`` with ``nominal_open``/``nominal_high``/``nominal_low``/``nominal_close``.
|
|
201
|
+
|
|
202
|
+
``df`` is a long frame of ``Stocks-Daily-Price`` (``symbol``, ``date`` and
|
|
203
|
+
the price columns) whose ``open``/``high``/``low``/``close`` are the
|
|
204
|
+
split-adjusted ones, i.e. loaded with ``adjust=False``: those frames carry
|
|
205
|
+
``adj_close`` next to ``close``, and that is how this function recognises
|
|
206
|
+
them. A frame loaded with ``adjust=True`` (the default) holds ``adj_close``
|
|
207
|
+
under the name ``close``, dividends included, and is refused -- use
|
|
208
|
+
``load_dataset(..., nominal=True)``, which computes the columns before the
|
|
209
|
+
adjustment. ``assume_split_adjusted=True`` skips the check for a frame built
|
|
210
|
+
another way.
|
|
211
|
+
|
|
212
|
+
A copy is returned; one nominal column per price column present.
|
|
213
|
+
"""
|
|
214
|
+
if not assume_split_adjusted and "adj_close" not in df.columns:
|
|
215
|
+
raise ValueError(
|
|
216
|
+
"nominal_price needs the split-adjusted prices of Stocks-Daily-Price "
|
|
217
|
+
"(load_dataset(..., adjust=False), which keeps adj_close next to close): "
|
|
218
|
+
"this frame has no adj_close, so its close is probably adj_close renamed, "
|
|
219
|
+
"dividends included. Load with nominal=True instead, or pass "
|
|
220
|
+
"assume_split_adjusted=True if close is the split-adjusted close."
|
|
221
|
+
)
|
|
222
|
+
present = [c for c in NOMINAL_COLUMNS if c in df.columns]
|
|
223
|
+
if not present:
|
|
224
|
+
raise ValueError(f"no price column among {list(NOMINAL_COLUMNS)} in {list(df.columns)}")
|
|
225
|
+
out = df.copy()
|
|
226
|
+
if out.empty:
|
|
227
|
+
for column in present:
|
|
228
|
+
out[NOMINAL_COLUMNS[column]] = pd.Series(dtype=float)
|
|
229
|
+
return out
|
|
230
|
+
factor = nominal_factor(out["symbol"].to_numpy(), out["date"].to_numpy(), splits,
|
|
231
|
+
distributions=distributions)
|
|
232
|
+
for column in present:
|
|
233
|
+
out[NOMINAL_COLUMNS[column]] = pd.to_numeric(out[column], errors="coerce").to_numpy(dtype=float) * factor
|
|
234
|
+
return out
|