paperswithbacktest 0.2.0__tar.gz → 0.2.1__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.0/paperswithbacktest.egg-info → paperswithbacktest-0.2.1}/PKG-INFO +1 -1
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1/paperswithbacktest.egg-info}/PKG-INFO +1 -1
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/__init__.py +1 -1
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/futures_run.py +9 -4
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/__init__.py +8 -2
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/futures.py +90 -14
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/setup.cfg +1 -1
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_futures_loader.py +58 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/LICENSE +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/NOTICE +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/README.md +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/SOURCES.txt +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/dependency_links.txt +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/requires.txt +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/top_level.txt +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/__init__.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/backtest_engine.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/base_strategy.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/checks.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/commission.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/feeds.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/indicators.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/lookahead.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/optimization_engine.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/option_costs.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/portfolio.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/strategies.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/universe.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/french.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/futures_chain.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/index_currencies.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/option_cache.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/options.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/pit_universe.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/datasets/prepared_cache.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/docs/__init__.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/docs/__main__.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/docs/backtesting.md +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/docs/world_model.md +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/engine.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/execution/__init__.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/execution/broker_factory.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/execution/ccxt_connector.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/execution/ib_connector.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/execution/live_utils.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/execution/optimal_limit_order.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/performance/__init__.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/performance/metrics.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/performance/nav_metrics.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/performance/plots.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/performance/reports.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/performance/trade_stats.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/world_model/__init__.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/world_model/_pit.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/world_model/_source.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/world_model/propagate.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/world_model/reader.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pyproject.toml +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_api_cache.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_array_feed.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_bare_symbol_collisions.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_bond_rates.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_bounded_loader.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_compat_shim.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_currency_costs.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_docs_shipped.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_engine_parity.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_engine_runner.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_engine_selector.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_exposure_cap.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_forex_directions.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_french.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_futures_chain.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_futures_rank6.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_futures_run.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_harness_checks.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_holiday_bars.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_hub_snapshot.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_index_currencies.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_lookahead.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_option_cache.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_option_chain.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_option_chain_sources.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_option_costs.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_pit_exit.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_pit_hold.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_pit_hold_accounting.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_pit_hold_same_bar_mark.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_prepared_cache.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_quantile_signal.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_read_memo.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_resolve_reused_property.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_reused_tickers.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_same_bar_orders.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_sells_first.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_short_borrow.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_strategy_commission.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_universe_alias_costs.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_world_model.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/tests/test_world_model_local.py +0 -0
- {paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/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.1
|
|
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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: paperswithbacktest
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -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.1"
|
|
@@ -58,6 +58,7 @@ DEFAULT_OPTIONS = {
|
|
|
58
58
|
"maintenance_margins": None,
|
|
59
59
|
"on_margin_call": "liquidate",
|
|
60
60
|
"end": None,
|
|
61
|
+
"dataset": None, # alternate source for daily and continuous tables
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
|
|
@@ -349,13 +350,16 @@ def _futures_daily(roots, start, options, held=None):
|
|
|
349
350
|
when that passes the deepest rank of the ``continuous`` table)."""
|
|
350
351
|
from ..datasets import futures as fds
|
|
351
352
|
|
|
352
|
-
|
|
353
|
+
window = {"start": start, "end": options["end"]}
|
|
354
|
+
if options["dataset"] is not None:
|
|
355
|
+
window["dataset"] = options["dataset"]
|
|
356
|
+
daily = fds.load_futures(roots, kind="daily", **window)
|
|
353
357
|
held = held or {}
|
|
354
358
|
if options["ranks"] is not None or held:
|
|
355
359
|
keep = set()
|
|
356
360
|
plain = [r for r in roots if r not in held]
|
|
357
361
|
if plain and options["ranks"] is not None:
|
|
358
|
-
keep |= fds.contract_symbols(plain, options["ranks"],
|
|
362
|
+
keep |= fds.contract_symbols(plain, options["ranks"], **window)
|
|
359
363
|
elif plain:
|
|
360
364
|
keep |= set(daily.loc[daily["root"].isin(plain), "symbol"].astype(str))
|
|
361
365
|
for root, ranks in held.items():
|
|
@@ -366,11 +370,12 @@ def _futures_daily(roots, start, options, held=None):
|
|
|
366
370
|
keep |= set(daily.loc[daily["root"] == root, "symbol"].astype(str))
|
|
367
371
|
continue
|
|
368
372
|
load = set(options["ranks"] or ()) | set(range(1, max(ranks) + 2))
|
|
369
|
-
keep |= fds.contract_symbols([root], sorted(load),
|
|
373
|
+
keep |= fds.contract_symbols([root], sorted(load), **window)
|
|
370
374
|
daily = daily[daily["symbol"].isin(keep)]
|
|
371
375
|
missing = sorted(set(roots) - set(daily["root"].unique()))
|
|
372
376
|
if missing:
|
|
373
|
-
|
|
377
|
+
dataset = options["dataset"] or fds.FUTURES_DAILY_DATASET
|
|
378
|
+
raise ValueError(f"{dataset} has no contract for roots {missing} in the window")
|
|
374
379
|
return daily, fds.engine_table(daily)
|
|
375
380
|
|
|
376
381
|
|
|
@@ -1952,13 +1952,15 @@ def load_dataset(
|
|
|
1952
1952
|
start=None,
|
|
1953
1953
|
end=None,
|
|
1954
1954
|
columns=None,
|
|
1955
|
+
*,
|
|
1956
|
+
split="train",
|
|
1955
1957
|
):
|
|
1956
1958
|
"""Load a PWB dataset as a pandas DataFrame.
|
|
1957
1959
|
|
|
1958
1960
|
Parameters
|
|
1959
1961
|
----------
|
|
1960
1962
|
path : str
|
|
1961
|
-
Dataset name,
|
|
1963
|
+
Dataset name, optionally prefixed with ``paperswithbacktest/``.
|
|
1962
1964
|
symbols : str or list of str, optional
|
|
1963
1965
|
Keep only these symbols. The filter is pushed down to each shard's
|
|
1964
1966
|
read, so memory stays bounded to the matching rows. Universe names
|
|
@@ -1983,6 +1985,9 @@ def load_dataset(
|
|
|
1983
1985
|
``date``/``datetime``). For the minute datasets the read never
|
|
1984
1986
|
materialises the other columns. An unknown column is an error.
|
|
1985
1987
|
|
|
1988
|
+
split : str, optional
|
|
1989
|
+
Named table to read. Most datasets use ``"train"``.
|
|
1990
|
+
|
|
1986
1991
|
Without ``start``, ``end`` and ``columns`` the behaviour is unchanged. A
|
|
1987
1992
|
minute dataset loaded without ``start``/``end`` still loads, but warns
|
|
1988
1993
|
(``UnboundedMinuteLoadWarning``): it downloads every month, ~75 GB for
|
|
@@ -2003,7 +2008,8 @@ def load_dataset(
|
|
|
2003
2008
|
"which downloads only the chains and months asked for."
|
|
2004
2009
|
)
|
|
2005
2010
|
|
|
2006
|
-
|
|
2011
|
+
if isinstance(path, str):
|
|
2012
|
+
path = path.removeprefix("paperswithbacktest/")
|
|
2007
2013
|
pwb_api_key = _get_pwb_api_key()
|
|
2008
2014
|
|
|
2009
2015
|
if isinstance(columns, str):
|
|
@@ -40,9 +40,11 @@ import os
|
|
|
40
40
|
import warnings
|
|
41
41
|
from typing import Iterable, Mapping, Optional, Union
|
|
42
42
|
|
|
43
|
+
import numpy as np
|
|
43
44
|
import pandas as pd
|
|
44
45
|
|
|
45
46
|
FUTURES_DAILY_DATASET = "Futures-Daily-Price"
|
|
47
|
+
VX_FUTURES_DATASET = "paperswithbacktest/Futures-Daily-VX"
|
|
46
48
|
TABLES = ("daily", "contracts", "continuous")
|
|
47
49
|
KINDS = TABLES + ("chain",)
|
|
48
50
|
ADJUSTMENTS = {"ratio": "ratio_adj", "difference": "diff_adj"}
|
|
@@ -62,9 +64,23 @@ def _as_roots(roots: Roots) -> Optional[list]:
|
|
|
62
64
|
return names
|
|
63
65
|
|
|
64
66
|
|
|
65
|
-
def _read_table(table: str, use_hf: bool = False, start=None, end=None
|
|
67
|
+
def _read_table(table: str, use_hf: bool = False, start=None, end=None,
|
|
68
|
+
dataset: str = FUTURES_DAILY_DATASET) -> pd.DataFrame:
|
|
66
69
|
"""One table of the dataset, through the same sources as ``load_dataset``."""
|
|
67
|
-
from . import _Window, _load_dataset_from_hf, _load_dataset_from_pwb
|
|
70
|
+
from . import _Window, _load_dataset_from_hf, _load_dataset_from_pwb, load_dataset
|
|
71
|
+
|
|
72
|
+
if dataset.removeprefix("paperswithbacktest/") == "Futures-Daily-VX":
|
|
73
|
+
with warnings.catch_warnings():
|
|
74
|
+
warnings.filterwarnings("ignore", message=r".*carry no period in their names.*")
|
|
75
|
+
rows = load_dataset(VX_FUTURES_DATASET, split=table, start=start, end=end, use_hf=True)
|
|
76
|
+
if table != "continuous":
|
|
77
|
+
# The historical prices were already divided by ten before the
|
|
78
|
+
# 2007 specification change. The modern multiplier also gives
|
|
79
|
+
# the correct dollar value for those renormalised quotations.
|
|
80
|
+
rows = rows.assign(multiplier=1_000.0, tick_size=0.05, currency="USD")
|
|
81
|
+
return rows
|
|
82
|
+
|
|
83
|
+
dataset = dataset.removeprefix("paperswithbacktest/")
|
|
68
84
|
|
|
69
85
|
bounds = {}
|
|
70
86
|
if table != "contracts" and (start is not None or end is not None):
|
|
@@ -77,8 +93,8 @@ def _read_table(table: str, use_hf: bool = False, start=None, end=None) -> pd.Da
|
|
|
77
93
|
# each table is one file: the window filters its rows, there are no shards to skip
|
|
78
94
|
warnings.filterwarnings("ignore", message=r".*carry no period in their names.*")
|
|
79
95
|
if pwb_api_key and not use_hf:
|
|
80
|
-
return _load_dataset_from_pwb(
|
|
81
|
-
return _load_dataset_from_hf(
|
|
96
|
+
return _load_dataset_from_pwb(dataset, split=table, pwb_api_key=pwb_api_key, **bounds)
|
|
97
|
+
return _load_dataset_from_hf(dataset, split=table, hf_token=hf_token, **bounds)
|
|
82
98
|
|
|
83
99
|
|
|
84
100
|
def _clean(df: pd.DataFrame) -> pd.DataFrame:
|
|
@@ -98,8 +114,12 @@ def _continuous_view(df: pd.DataFrame, adjust: Optional[str]) -> pd.DataFrame:
|
|
|
98
114
|
if adjust is None:
|
|
99
115
|
return df
|
|
100
116
|
keys = ["date", "root", "rank", "symbol", "last_trade_date", "rolled"]
|
|
117
|
+
if "known_at" in df:
|
|
118
|
+
keys.append("known_at")
|
|
101
119
|
if adjust == "none":
|
|
102
|
-
good = df["settlement"].notna()
|
|
120
|
+
good = df["settlement"].notna()
|
|
121
|
+
if "settlement_suspect" in df:
|
|
122
|
+
good &= ~df["settlement_suspect"].astype(bool)
|
|
103
123
|
out = df[keys + ["open", "high", "low"]].copy()
|
|
104
124
|
out["close"] = df["settlement"].where(good, df["close"])
|
|
105
125
|
elif adjust in ADJUSTMENTS:
|
|
@@ -114,8 +134,9 @@ def _continuous_view(df: pd.DataFrame, adjust: Optional[str]) -> pd.DataFrame:
|
|
|
114
134
|
|
|
115
135
|
|
|
116
136
|
def load_futures(roots: Roots = None, kind: str = "daily", rank: Union[int, Iterable[int], None] = None,
|
|
117
|
-
adjust: Optional[str] = None, start=None, end=None, use_hf: bool = False
|
|
118
|
-
|
|
137
|
+
adjust: Optional[str] = None, start=None, end=None, use_hf: bool = False,
|
|
138
|
+
*, dataset: str = FUTURES_DAILY_DATASET):
|
|
139
|
+
"""Read the futures chain and continuous tables.
|
|
119
140
|
|
|
120
141
|
Parameters
|
|
121
142
|
----------
|
|
@@ -139,6 +160,8 @@ def load_futures(roots: Roots = None, kind: str = "daily", rank: Union[int, Iter
|
|
|
139
160
|
Date window (``daily`` and ``continuous``; ignored by ``contracts`` and ``chain``).
|
|
140
161
|
use_hf : bool
|
|
141
162
|
Read from the Hub even when ``PWB_API_KEY`` is set.
|
|
163
|
+
dataset : str
|
|
164
|
+
Defaults to ``Futures-Daily-Price``. ``Futures-Daily-VX`` is read from the private Hub dataset.
|
|
142
165
|
"""
|
|
143
166
|
if kind not in KINDS:
|
|
144
167
|
raise ValueError(f"kind is one of {KINDS}")
|
|
@@ -146,11 +169,14 @@ def load_futures(roots: Roots = None, kind: str = "daily", rank: Union[int, Iter
|
|
|
146
169
|
raise ValueError("rank and adjust apply to kind='continuous' only")
|
|
147
170
|
names = _as_roots(roots)
|
|
148
171
|
table = "contracts" if kind == "chain" else kind
|
|
149
|
-
|
|
172
|
+
source = {"dataset": dataset} if dataset != FUTURES_DAILY_DATASET else {}
|
|
173
|
+
if table == "contracts":
|
|
174
|
+
start = end = None
|
|
175
|
+
df = _clean(_read_table(table, use_hf=use_hf, start=start, end=end, **source))
|
|
150
176
|
if names is not None:
|
|
151
177
|
missing = sorted(set(names) - set(df["root"].unique()))
|
|
152
178
|
if missing:
|
|
153
|
-
warnings.warn(f"{
|
|
179
|
+
warnings.warn(f"{dataset}: no {table} rows for roots {missing}", stacklevel=2)
|
|
154
180
|
df = df[df["root"].isin(names)]
|
|
155
181
|
if kind == "continuous":
|
|
156
182
|
if rank is not None:
|
|
@@ -167,6 +193,52 @@ def load_futures(roots: Roots = None, kind: str = "daily", rank: Union[int, Iter
|
|
|
167
193
|
return df
|
|
168
194
|
|
|
169
195
|
|
|
196
|
+
def constant_maturity_weights(daily: pd.DataFrame, maturity: int, min_business_days: int = 5) -> pd.DataFrame:
|
|
197
|
+
"""Daily market-value weights of the actual contracts bracketing a calendar-day tenor.
|
|
198
|
+
|
|
199
|
+
A time interpolation coefficient is multiplied by its contract price before
|
|
200
|
+
normalisation. The resulting weights invest in the two quoted contracts.
|
|
201
|
+
Sessions without a complete bracket are omitted. Use each row only after
|
|
202
|
+
the underlying settlement has become available.
|
|
203
|
+
"""
|
|
204
|
+
day = pd.to_datetime(daily["date"])
|
|
205
|
+
expiry = pd.to_datetime(daily["last_trade_date"])
|
|
206
|
+
price = daily["settlement"].where(daily["settlement"].gt(0), daily["close"])
|
|
207
|
+
valid = expiry.gt(day) & price.gt(0)
|
|
208
|
+
if "known_at" in daily:
|
|
209
|
+
release = pd.to_datetime(daily["known_at"], utc=True, errors="coerce")
|
|
210
|
+
local_day = release.dt.tz_convert("America/Chicago").dt.tz_localize(None).dt.normalize()
|
|
211
|
+
valid &= local_day.eq(day)
|
|
212
|
+
eligible = pd.DataFrame({
|
|
213
|
+
"date": day[valid], "expiry": expiry[valid],
|
|
214
|
+
"symbol": daily.loc[valid, "symbol"], "price": price[valid],
|
|
215
|
+
})
|
|
216
|
+
eligible["days"] = (eligible["expiry"] - eligible["date"]).dt.days
|
|
217
|
+
business_days = np.busday_count(
|
|
218
|
+
eligible["date"].to_numpy(dtype="datetime64[D]"), eligible["expiry"].to_numpy(dtype="datetime64[D]"),
|
|
219
|
+
)
|
|
220
|
+
eligible = eligible.loc[business_days >= min_business_days].sort_values(["date", "days", "symbol"])
|
|
221
|
+
weights = []
|
|
222
|
+
for date, quotes in eligible.groupby("date", sort=False):
|
|
223
|
+
lower = quotes.loc[quotes["days"].le(maturity)]
|
|
224
|
+
upper = quotes.loc[quotes["days"].ge(maturity)]
|
|
225
|
+
if lower.empty or upper.empty:
|
|
226
|
+
continue
|
|
227
|
+
near, far = lower.iloc[-1], upper.iloc[0]
|
|
228
|
+
if near["days"] == far["days"]:
|
|
229
|
+
weights.append((date, near["symbol"], 1.0, near["price"]))
|
|
230
|
+
continue
|
|
231
|
+
near_share = (far["days"] - maturity) / (far["days"] - near["days"])
|
|
232
|
+
near_value = near_share * near["price"]
|
|
233
|
+
far_value = (1 - near_share) * far["price"]
|
|
234
|
+
total = near_value + far_value
|
|
235
|
+
weights.extend((
|
|
236
|
+
(date, near["symbol"], near_value / total, near["price"]),
|
|
237
|
+
(date, far["symbol"], far_value / total, far["price"]),
|
|
238
|
+
))
|
|
239
|
+
return pd.DataFrame(weights, columns=["date", "symbol", "weight", "price"])
|
|
240
|
+
|
|
241
|
+
|
|
170
242
|
# -- Tradewind --------------------------------------------------------------------------------------
|
|
171
243
|
|
|
172
244
|
|
|
@@ -252,19 +324,21 @@ def engine_table(daily: pd.DataFrame) -> pd.DataFrame:
|
|
|
252
324
|
MAX_CONTINUOUS_RANK = 6
|
|
253
325
|
|
|
254
326
|
|
|
255
|
-
def contract_symbols(roots: Roots, ranks: Iterable[int] = (1, 2), start=None, end=None,
|
|
327
|
+
def contract_symbols(roots: Roots, ranks: Iterable[int] = (1, 2), start=None, end=None,
|
|
328
|
+
use_hf: bool = False, *, dataset: str = FUTURES_DAILY_DATASET) -> set:
|
|
256
329
|
"""The contracts the rolled series of ``roots`` hold at ``ranks`` (the ``continuous``
|
|
257
330
|
table, rolled on volume) over the window: the contracts a strategy rolling the first
|
|
258
331
|
nearby can hold, without the far months it never trades."""
|
|
259
332
|
ranks = [int(r) for r in ranks]
|
|
260
|
-
|
|
333
|
+
source = {"dataset": dataset} if dataset != FUTURES_DAILY_DATASET else {}
|
|
334
|
+
cont = load_futures(roots, kind="continuous", rank=ranks, start=start, end=end, use_hf=use_hf, **source)
|
|
261
335
|
return set(cont["symbol"].astype(str))
|
|
262
336
|
|
|
263
337
|
|
|
264
338
|
def add_futures(engine, roots: Roots, start=None, end=None, margins=None, maintenance_margins=None,
|
|
265
339
|
commission=0.0, continuous_adjust: Optional[str] = None, continuous_rule=None,
|
|
266
340
|
at_expiry: str = "raise", on_margin_call: str = "liquidate", use_hf: bool = False,
|
|
267
|
-
ranks: Optional[Iterable[int]] = (1, 2)) -> dict:
|
|
341
|
+
ranks: Optional[Iterable[int]] = (1, 2), *, dataset: str = FUTURES_DAILY_DATASET) -> dict:
|
|
268
342
|
"""Load the contracts of ``roots`` and add them to a Tradewind ``engine``.
|
|
269
343
|
|
|
270
344
|
One ``FutureData`` per contract (its close is the settlement), the per-contract
|
|
@@ -286,9 +360,11 @@ def add_futures(engine, roots: Roots, start=None, end=None, margins=None, mainte
|
|
|
286
360
|
names = _as_roots(roots)
|
|
287
361
|
if names is None:
|
|
288
362
|
raise ValueError("name the roots to trade: every root of the table is ~17,000 feeds")
|
|
289
|
-
|
|
363
|
+
source = {"dataset": dataset} if dataset != FUTURES_DAILY_DATASET else {}
|
|
364
|
+
daily = load_futures(names, kind="daily", start=start, end=end, use_hf=use_hf, **source)
|
|
290
365
|
if ranks is not None:
|
|
291
|
-
|
|
366
|
+
keep = contract_symbols(names, ranks, start=start, end=end, use_hf=use_hf, **source)
|
|
367
|
+
daily = daily[daily["symbol"].isin(keep)]
|
|
292
368
|
found = sorted(daily["root"].unique())
|
|
293
369
|
if not found:
|
|
294
370
|
raise ValueError(f"no sessions for roots {names} in the window")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[metadata]
|
|
2
2
|
name = paperswithbacktest
|
|
3
|
-
version = 0.2.
|
|
3
|
+
version = 0.2.1
|
|
4
4
|
author = Papers With Backtest
|
|
5
5
|
author_email = hello@paperswithbacktest.com
|
|
6
6
|
description = Papers With Backtest: datasets, backtesting harness and execution for quant traders (import pwb; formerly pwb-toolbox)
|
|
@@ -146,3 +146,61 @@ def test_a_root_without_multiplier_has_no_chain_and_no_spec(tables, monkeypatch)
|
|
|
146
146
|
assert set(chains) == {"CL"}
|
|
147
147
|
with pytest.raises(ValueError, match="no multiplier"):
|
|
148
148
|
fut.futures_specs(c[c.root == "GC"])
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_private_vx_reads_named_tables_and_retains_availability(monkeypatch):
|
|
152
|
+
from pwb import datasets
|
|
153
|
+
|
|
154
|
+
snapshot = _tables()
|
|
155
|
+
for table, rows in snapshot.items():
|
|
156
|
+
rows = rows.loc[rows["root"].eq("CL")].copy()
|
|
157
|
+
rows["root"] = "VX"
|
|
158
|
+
rows["symbol"] = rows["symbol"].str.replace("CL", "VX", regex=False)
|
|
159
|
+
if "date" in rows:
|
|
160
|
+
rows["known_at"] = rows["date"].dt.tz_localize("UTC") + pd.Timedelta(hours=23)
|
|
161
|
+
snapshot[table] = rows.drop(columns=["multiplier", "tick_size", "currency", "settlement_suspect"], errors="ignore")
|
|
162
|
+
requests = []
|
|
163
|
+
|
|
164
|
+
def read(name, split, **kwargs):
|
|
165
|
+
requests.append((name, split, kwargs["use_hf"]))
|
|
166
|
+
return snapshot[split].copy()
|
|
167
|
+
|
|
168
|
+
monkeypatch.setattr(datasets, "load_dataset", read)
|
|
169
|
+
repo = "paperswithbacktest/Futures-Daily-VX"
|
|
170
|
+
daily = fut.load_futures("VX", dataset=repo)
|
|
171
|
+
assert daily["multiplier"].eq(1000).all() and daily["tick_size"].eq(0.05).all()
|
|
172
|
+
assert daily["currency"].eq("USD").all()
|
|
173
|
+
raw = fut.load_futures("VX", kind="continuous", rank=1, adjust="none", dataset=repo)
|
|
174
|
+
assert "known_at" in raw and raw["close"].notna().all()
|
|
175
|
+
assert fut.contract_symbols("VX", ranks=[1], dataset=repo) == {"VXG20", "VXH20"}
|
|
176
|
+
assert requests == [(repo, "daily", True), (repo, "continuous", True), (repo, "continuous", True)]
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def test_standard_loader_accepts_the_qualified_name_and_named_split(monkeypatch):
|
|
180
|
+
from pwb import datasets
|
|
181
|
+
|
|
182
|
+
monkeypatch.setenv("HF_ACCESS_TOKEN", "test-token")
|
|
183
|
+
seen = []
|
|
184
|
+
|
|
185
|
+
def read(name, split, **kwargs):
|
|
186
|
+
seen.append((name, split))
|
|
187
|
+
return pd.DataFrame({"symbol": ["VXG20"], "date": ["2020-01-02"]})
|
|
188
|
+
|
|
189
|
+
monkeypatch.setattr(datasets, "_load_dataset_from_hf", read)
|
|
190
|
+
rows = datasets.load_dataset("paperswithbacktest/Futures-Daily-VX", split="daily", use_hf=True)
|
|
191
|
+
assert rows["symbol"].tolist() == ["VXG20"]
|
|
192
|
+
assert seen == [("Futures-Daily-VX", "daily")]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def test_constant_maturity_uses_observed_brackets_and_price_weights():
|
|
196
|
+
snapshot = pd.DataFrame({
|
|
197
|
+
"date": ["2024-01-03"] * 3,
|
|
198
|
+
"last_trade_date": ["2024-01-23", "2024-02-02", "2024-02-12"],
|
|
199
|
+
"symbol": ["VXG24", "VXF24-late", "VXH24"],
|
|
200
|
+
"settlement": [10.0, 100.0, 20.0], "close": [10.0, 100.0, 20.0],
|
|
201
|
+
"known_at": ["2024-01-03 23:00Z", "2024-01-04 23:00Z", "2024-01-03 23:00Z"],
|
|
202
|
+
})
|
|
203
|
+
result = fut.constant_maturity_weights(snapshot, 30)
|
|
204
|
+
assert result["symbol"].tolist() == ["VXG24", "VXH24"]
|
|
205
|
+
np.testing.assert_allclose(result["weight"], [1 / 3, 2 / 3])
|
|
206
|
+
assert fut.constant_maturity_weights(snapshot, 150).empty
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/requires.txt
RENAMED
|
File without changes
|
{paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/paperswithbacktest.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{paperswithbacktest-0.2.0 → paperswithbacktest-0.2.1}/pwb/backtesting/optimization_engine.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|