vectorbt 1.2.1__tar.gz → 1.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.
- {vectorbt-1.2.1/vectorbt.egg-info → vectorbt-1.2.2}/PKG-INFO +2 -2
- {vectorbt-1.2.1 → vectorbt-1.2.2}/pyproject.toml +1 -1
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_base.py +118 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_data.py +262 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_engine.py +53 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_indicators.py +70 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_returns.py +128 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_utils.py +39 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/_version.py +1 -1
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/index_fns.py +8 -4
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/data/base.py +9 -3
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/data/custom.py +16 -2
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/indicators/nb.py +28 -4
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/returns/accessors.py +87 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/returns/dispatch.py +49 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/returns/nb.py +75 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/array_.py +1 -1
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/datetime_.py +10 -3
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/params.py +12 -3
- {vectorbt-1.2.1 → vectorbt-1.2.2/vectorbt.egg-info}/PKG-INFO +2 -2
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt.egg-info/requires.txt +1 -1
- {vectorbt-1.2.1 → vectorbt-1.2.2}/LICENSE.md +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/MANIFEST.in +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/README.md +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/setup.cfg +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/setup.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/conftest.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_generic.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_labels.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_plotting.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_portfolio.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_records.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_settings.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/test_signals.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/tests/utils.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/_engine.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/_settings.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/_typing.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/accessors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/array_wrapper.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/column_grouper.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/combine_fns.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/indexing.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/base/reshape_fns.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/data/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/data/updater.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/accessors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/decorators.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/dispatch.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/drawdowns.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/enums.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/nb.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/plots_builder.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/plotting.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/ranges.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/splitters.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/generic/stats_builder.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/indicators/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/indicators/basic.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/indicators/configs.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/indicators/dispatch.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/indicators/factory.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/labels/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/labels/dispatch.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/labels/enums.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/labels/generators.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/labels/nb.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/messaging/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/messaging/telegram.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/ohlcv_accessors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/base.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/decorators.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/dispatch.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/enums.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/logs.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/nb.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/orders.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/portfolio/trades.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/px_accessors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/py.typed +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/base.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/col_mapper.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/decorators.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/dispatch.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/mapped_array.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/records/nb.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/returns/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/returns/metrics.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/returns/qs_adapter.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/root_accessors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/accessors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/dispatch.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/enums.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/factory.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/generators.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/signals/nb.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/templates/dark.json +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/templates/light.json +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/templates/seaborn.json +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/__init__.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/attr_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/checks.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/colors.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/config.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/decorators.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/docs.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/enum_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/figure.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/image_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/mapping.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/math_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/module_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/random_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/requests_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/schedule_.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/tags.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt/utils/template.py +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt.egg-info/SOURCES.txt +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt.egg-info/dependency_links.txt +0 -0
- {vectorbt-1.2.1 → vectorbt-1.2.2}/vectorbt.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: vectorbt
|
|
3
|
-
Version: 1.2.
|
|
3
|
+
Version: 1.2.2
|
|
4
4
|
Summary: Python library for backtesting and analyzing trading strategies at scale
|
|
5
5
|
Author-email: Oleg Polakow <olegpolakow@vectorbt.pro>
|
|
6
6
|
Project-URL: Homepage, https://github.com/polakowo/vectorbt
|
|
@@ -38,7 +38,7 @@ Requires-Dist: requests
|
|
|
38
38
|
Requires-Dist: pytz
|
|
39
39
|
Requires-Dist: mypy_extensions
|
|
40
40
|
Provides-Extra: rust
|
|
41
|
-
Requires-Dist: vectorbt-rust==1.2.
|
|
41
|
+
Requires-Dist: vectorbt-rust==1.2.2; extra == "rust"
|
|
42
42
|
Provides-Extra: full
|
|
43
43
|
Requires-Dist: TA-Lib; extra == "full"
|
|
44
44
|
Requires-Dist: yfinance>=0.2.22; extra == "full"
|
|
@@ -1124,6 +1124,7 @@ class TestIndexFns:
|
|
|
1124
1124
|
pd.testing.assert_index_equal(
|
|
1125
1125
|
index_fns.rename_levels(i, {"i": "f"}), pd.Index([1, 2, 3], dtype="int64", name="f")
|
|
1126
1126
|
)
|
|
1127
|
+
assert i.name == "i"
|
|
1127
1128
|
pd.testing.assert_index_equal(index_fns.rename_levels(i, {"a": "b"}, strict=False), i)
|
|
1128
1129
|
with pytest.raises(Exception):
|
|
1129
1130
|
_ = index_fns.rename_levels(i, {"a": "b"}, strict=True)
|
|
@@ -1214,6 +1215,61 @@ class TestIndexFns:
|
|
|
1214
1215
|
with pytest.raises(ValueError, match="Values in second index"):
|
|
1215
1216
|
index_fns.align_index_to(source, target)
|
|
1216
1217
|
|
|
1218
|
+
@pytest.mark.parametrize("categorical", [False, True])
|
|
1219
|
+
@pytest.mark.parametrize("missing", [False, True])
|
|
1220
|
+
@pytest.mark.parametrize("permuted", [False, True])
|
|
1221
|
+
def test_align_index_to_unused_levels(self, categorical, missing, permuted):
|
|
1222
|
+
assets = ["A", "B", None] if missing else ["A", "B"]
|
|
1223
|
+
source = pd.Index(assets, name="asset")
|
|
1224
|
+
labels = assets + ["C"]
|
|
1225
|
+
if categorical:
|
|
1226
|
+
labels = pd.CategoricalIndex(labels, categories=["C", "B", "A"], ordered=True)
|
|
1227
|
+
full = pd.MultiIndex.from_product([[1, 2], labels], names=["parameter", "asset"])
|
|
1228
|
+
target = full[full.get_level_values("asset") != "C"]
|
|
1229
|
+
expected = [0, 1, 2, 0, 1, 2] if missing else [0, 1, 0, 1]
|
|
1230
|
+
if permuted:
|
|
1231
|
+
target = target[::-1]
|
|
1232
|
+
expected = expected[::-1]
|
|
1233
|
+
|
|
1234
|
+
# Filtering keeps C in the level pool, but only observed A/B/missing keys need alignment.
|
|
1235
|
+
levels_before = [level.copy(deep=True) for level in target.levels]
|
|
1236
|
+
codes_before = [code.copy() for code in target.codes]
|
|
1237
|
+
np.testing.assert_array_equal(index_fns.align_index_to(source, target), expected)
|
|
1238
|
+
for level, before in zip(target.levels, levels_before):
|
|
1239
|
+
pd.testing.assert_index_equal(level, before)
|
|
1240
|
+
for code, before in zip(target.codes, codes_before):
|
|
1241
|
+
np.testing.assert_array_equal(code, before)
|
|
1242
|
+
|
|
1243
|
+
def test_align_index_to_observed_source_keys(self):
|
|
1244
|
+
# Unused source labels cannot provide a position for an observed target key.
|
|
1245
|
+
source = pd.MultiIndex(levels=[["A", "B", "C"], [1, 2, 3]], codes=[[0, 1], [0, 1]], names=["asset", "window"])
|
|
1246
|
+
valid = pd.MultiIndex.from_tuples([("B", 2), ("A", 1), ("B", 2)], names=source.names)
|
|
1247
|
+
np.testing.assert_array_equal(index_fns.align_index_to(source, valid), [1, 0, 1])
|
|
1248
|
+
for target in [
|
|
1249
|
+
pd.MultiIndex.from_tuples([("C", 3)], names=source.names),
|
|
1250
|
+
pd.MultiIndex.from_tuples([("A", 2), ("B", 2)], names=source.names),
|
|
1251
|
+
]:
|
|
1252
|
+
with pytest.raises(ValueError):
|
|
1253
|
+
index_fns.align_index_to(source, target)
|
|
1254
|
+
|
|
1255
|
+
@pytest.mark.parametrize("compact", [False, True])
|
|
1256
|
+
@pytest.mark.parametrize("missing", [False, True])
|
|
1257
|
+
def test_align_index_to_empty_source(self, compact, missing):
|
|
1258
|
+
source = pd.MultiIndex(levels=[["A"]], codes=[[]], names=["asset"])
|
|
1259
|
+
target = pd.MultiIndex(levels=[["B"]], codes=[[-1] if missing else [0]], names=["asset"])
|
|
1260
|
+
if compact:
|
|
1261
|
+
source, target = source.remove_unused_levels(), target.remove_unused_levels()
|
|
1262
|
+
# Neither an ordinary nor a missing target key has a position in an empty source.
|
|
1263
|
+
with pytest.raises(ValueError):
|
|
1264
|
+
index_fns.align_index_to(source, target)
|
|
1265
|
+
|
|
1266
|
+
def test_align_index_to_empty_target(self):
|
|
1267
|
+
source = pd.Index(["A", "B"], name="asset")
|
|
1268
|
+
target = pd.MultiIndex.from_product([[1, 2], ["A", "B", "C"]], names=["parameter", "asset"])[:0]
|
|
1269
|
+
# An empty filtered target requests no keys, even though its level pools remain populated.
|
|
1270
|
+
indexer = index_fns.align_index_to(source, target)
|
|
1271
|
+
np.testing.assert_array_equal(np.arange(len(source))[indexer], [])
|
|
1272
|
+
|
|
1217
1273
|
def test_align_index_to(self):
|
|
1218
1274
|
index1 = pd.Index(["c", "b", "a"], name="name1")
|
|
1219
1275
|
assert index_fns.align_index_to(index1, index1) == pd.IndexSlice[:]
|
|
@@ -2899,6 +2955,12 @@ class TestAccessors:
|
|
|
2899
2955
|
columns=pd.MultiIndex.from_tuples([("a7", "a8"), ("b7", "b8"), ("c7", "c8")], names=["c7", "c9"]),
|
|
2900
2956
|
),
|
|
2901
2957
|
)
|
|
2958
|
+
df = pd.DataFrame([[1, 2], [3, 4]], columns=pd.Index(["x", "y"], name="c"))
|
|
2959
|
+
pd.testing.assert_frame_equal(
|
|
2960
|
+
df.vbt.rename_levels({"c": "d"}),
|
|
2961
|
+
pd.DataFrame([[1, 2], [3, 4]], columns=pd.Index(["x", "y"], name="d")),
|
|
2962
|
+
)
|
|
2963
|
+
assert df.columns.name == "c"
|
|
2902
2964
|
|
|
2903
2965
|
def test_select_levels(self):
|
|
2904
2966
|
pd.testing.assert_frame_equal(
|
|
@@ -2966,6 +3028,62 @@ class TestAccessors:
|
|
|
2966
3028
|
),
|
|
2967
3029
|
)
|
|
2968
3030
|
|
|
3031
|
+
@pytest.mark.parametrize("axis", [0, 1])
|
|
3032
|
+
@pytest.mark.parametrize("broadcast", [False, True])
|
|
3033
|
+
@pytest.mark.parametrize("categorical_missing", [False, True])
|
|
3034
|
+
def test_align_to_filtered_grid(self, axis, broadcast, categorical_missing):
|
|
3035
|
+
source = pd.Index(["A", "B"], name="asset")
|
|
3036
|
+
labels = ["A", "B", "C"]
|
|
3037
|
+
if categorical_missing:
|
|
3038
|
+
source = pd.Index(["A", "B", None], name="asset")
|
|
3039
|
+
labels = pd.CategoricalIndex(["A", "B", None, "C"], categories=["C", "B", "A"], ordered=True)
|
|
3040
|
+
full = pd.MultiIndex.from_product([[1, 2], labels], names=["parameter", "asset"])
|
|
3041
|
+
target = full[[5, 2, 4, 1]] if categorical_missing else full[[4, 0, 3, 1]]
|
|
3042
|
+
# Requests are B,missing,A,B or B,A,A,B, with unused C left behind by filtering.
|
|
3043
|
+
values = [[10, 20, 30], [11, 22, 33]] if categorical_missing else [[10, 20], [11, 22]]
|
|
3044
|
+
prices = pd.DataFrame(values, columns=source)
|
|
3045
|
+
other = pd.DataFrame(np.zeros((2, 4), dtype=int), columns=target)
|
|
3046
|
+
expected_values = (
|
|
3047
|
+
[[20, 30, 10, 20], [22, 33, 11, 22]] if categorical_missing else [[20, 10, 10, 20], [22, 11, 11, 22]]
|
|
3048
|
+
)
|
|
3049
|
+
expected = pd.DataFrame(expected_values, columns=target)
|
|
3050
|
+
if axis == 0:
|
|
3051
|
+
prices, other, expected = prices.T, other.T, expected.T
|
|
3052
|
+
prices_before, other_before = prices.copy(deep=True), other.copy(deep=True)
|
|
3053
|
+
|
|
3054
|
+
# Both public preparation paths must preserve the values and the complete target axes.
|
|
3055
|
+
if broadcast:
|
|
3056
|
+
kwargs = dict(align_index=axis == 0, align_columns=axis == 1)
|
|
3057
|
+
kwargs["index_from" if axis == 0 else "columns_from"] = 1
|
|
3058
|
+
result, aligned_other = reshape_fns.broadcast(prices, other, **kwargs)
|
|
3059
|
+
pd.testing.assert_frame_equal(aligned_other, other_before)
|
|
3060
|
+
else:
|
|
3061
|
+
result = prices.vbt.align_to(other)
|
|
3062
|
+
pd.testing.assert_frame_equal(result, expected)
|
|
3063
|
+
pd.testing.assert_frame_equal(prices, prices_before)
|
|
3064
|
+
pd.testing.assert_frame_equal(other, other_before)
|
|
3065
|
+
|
|
3066
|
+
@pytest.mark.parametrize("axis", [0, 1])
|
|
3067
|
+
@pytest.mark.parametrize("empty", [False, True])
|
|
3068
|
+
def test_align_to_missing_keys_from_empty_source(self, axis, empty):
|
|
3069
|
+
source_axis = pd.MultiIndex(levels=[["A"]], codes=[[] if empty else [-1]], names=["asset"])
|
|
3070
|
+
target_axis = pd.MultiIndex(levels=[["B"]], codes=[[-1, -1]], names=["asset"])
|
|
3071
|
+
source = pd.DataFrame(np.empty((2, 0)) if empty else [[10], [20]], columns=source_axis)
|
|
3072
|
+
target = pd.DataFrame([[7, 8], [9, 10]], columns=target_axis)
|
|
3073
|
+
expected = pd.DataFrame([[10, 10], [20, 20]], columns=target_axis)
|
|
3074
|
+
if axis == 0:
|
|
3075
|
+
source, target, expected = source.T, target.T, expected.T
|
|
3076
|
+
source_before, target_before = source.copy(deep=True), target.copy(deep=True)
|
|
3077
|
+
|
|
3078
|
+
# Missing keys can repeat a real source position; an empty source must reject them.
|
|
3079
|
+
if empty:
|
|
3080
|
+
with pytest.raises(ValueError):
|
|
3081
|
+
source.vbt.align_to(target)
|
|
3082
|
+
else:
|
|
3083
|
+
pd.testing.assert_frame_equal(source.vbt.align_to(target), expected)
|
|
3084
|
+
pd.testing.assert_frame_equal(source, source_before)
|
|
3085
|
+
pd.testing.assert_frame_equal(target, target_before)
|
|
3086
|
+
|
|
2969
3087
|
def test_align_to(self):
|
|
2970
3088
|
multi_c1 = pd.MultiIndex.from_arrays([["a8", "b8"]], names=["c8"])
|
|
2971
3089
|
multi_c2 = pd.MultiIndex.from_arrays([["a7", "a7", "c7", "c7"], ["a8", "b8", "a8", "b8"]], names=["c7", "c8"])
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
from datetime import datetime, timedelta, timezone
|
|
2
|
+
from enum import Enum
|
|
2
3
|
|
|
3
4
|
import numpy as np
|
|
4
5
|
import pandas as pd
|
|
@@ -871,6 +872,93 @@ class TestData:
|
|
|
871
872
|
),
|
|
872
873
|
)
|
|
873
874
|
|
|
875
|
+
@pytest.mark.parametrize("as_frame", [False, True])
|
|
876
|
+
@pytest.mark.parametrize(
|
|
877
|
+
"values,dtype,expected_dtype",
|
|
878
|
+
[
|
|
879
|
+
([1704067200000000001, 1704067200000000003], "int64", "int64"),
|
|
880
|
+
([2**64 - 3, 2**64 - 1], "uint64", "uint64"),
|
|
881
|
+
([1, 2], "int16", "int16"),
|
|
882
|
+
([1.5, np.nan], "float32", "float32"),
|
|
883
|
+
([1.5, np.nan], "float64", "float64"),
|
|
884
|
+
([np.nan, np.nan], "float64", "float64"),
|
|
885
|
+
([True, False], "bool", "bool"),
|
|
886
|
+
([2**53 + 1, 2**53 + 3], object, "int64"),
|
|
887
|
+
(["a", pd.NA], "string", "string"),
|
|
888
|
+
([2**53 + 1, pd.NA], "Int64", "Int64"),
|
|
889
|
+
([True, pd.NA], "boolean", "boolean"),
|
|
890
|
+
([pd.Timestamp("2024-01-01"), pd.NaT], "datetime64[ns]", "datetime64[ns]"),
|
|
891
|
+
([pd.Timestamp("2024-01-01", tz="UTC"), pd.NaT], "datetime64[ns, UTC]", "datetime64[ns, UTC]"),
|
|
892
|
+
([pd.Timedelta(1, "ns"), pd.NaT], "timedelta64[ns]", "timedelta64[ns]"),
|
|
893
|
+
(["a", "b"], "category", "category"),
|
|
894
|
+
([], "int64", "int64"),
|
|
895
|
+
],
|
|
896
|
+
)
|
|
897
|
+
def test_concat_single_symbol_values(self, values, dtype, expected_dtype, as_frame):
|
|
898
|
+
# Derive the expected values independently, including the retained object inference.
|
|
899
|
+
index = pd.Index(["tick1", "tick2"][: len(values)], name="tick")
|
|
900
|
+
source = pd.Series(values, index=index, name="feature", dtype=dtype)
|
|
901
|
+
data = vbt.Data.from_data({"A": source.to_frame() if as_frame else source})
|
|
902
|
+
result = data.concat()["feature"]
|
|
903
|
+
expected = pd.Series(values, index=index, name="A", dtype=expected_dtype)
|
|
904
|
+
assert result.dtype == expected.dtype
|
|
905
|
+
pd.testing.assert_series_equal(result, expected, check_exact=True)
|
|
906
|
+
pd.testing.assert_series_equal(source, pd.Series(values, index=index, name="feature", dtype=dtype))
|
|
907
|
+
|
|
908
|
+
@pytest.mark.parametrize("as_frame", [False, True])
|
|
909
|
+
@pytest.mark.parametrize("infer_string", [False, True])
|
|
910
|
+
def test_concat_single_symbol_inference(self, as_frame, infer_string):
|
|
911
|
+
# Preserve pandas' final object inference under either supported string-inference setting.
|
|
912
|
+
with pd.option_context("future.infer_string", infer_string):
|
|
913
|
+
source = pd.Series(["a", None], name="feature", dtype=object)
|
|
914
|
+
data = vbt.Data.from_data({"A": source.to_frame() if as_frame else source})
|
|
915
|
+
result = data.concat()["feature"]
|
|
916
|
+
expected = pd.Series(["a", None], name="A", dtype="str" if infer_string else object)
|
|
917
|
+
assert result.dtype == expected.dtype
|
|
918
|
+
pd.testing.assert_series_equal(result, expected)
|
|
919
|
+
|
|
920
|
+
@pytest.mark.parametrize("as_frame", [False, True])
|
|
921
|
+
@pytest.mark.parametrize("symbol,feature", [(None, "id"), (("venue", "A"), ("feed", "id")), ("A", None)])
|
|
922
|
+
def test_concat_single_symbol_labels(self, symbol, feature, as_frame):
|
|
923
|
+
# An explicit None symbol must replace the feature name, rather than inherit it.
|
|
924
|
+
index = pd.MultiIndex.from_tuples([("day1", 1), ("day1", 2)], names=["day", "tick"])
|
|
925
|
+
source = pd.Series([3, 4], index=index, name=feature)
|
|
926
|
+
data = vbt.Data.from_data({symbol: source.to_frame(name=feature) if as_frame else source})
|
|
927
|
+
result = data.concat(level_name="instrument")
|
|
928
|
+
assert list(result) == [feature]
|
|
929
|
+
pd.testing.assert_series_equal(result[feature], pd.Series([3, 4], index=index, name=symbol))
|
|
930
|
+
|
|
931
|
+
@pytest.mark.parametrize("as_frame", [False, True])
|
|
932
|
+
@pytest.mark.parametrize("dtype", ["int64", "Int64"])
|
|
933
|
+
def test_concat_single_symbol_ownership(self, as_frame, dtype):
|
|
934
|
+
source = pd.Series([2**53 + 1, 2**53 + 3], name="id", dtype=dtype)
|
|
935
|
+
data = vbt.Data.from_data({"A": source.to_frame() if as_frame else source})
|
|
936
|
+
result = data.concat()["id"]
|
|
937
|
+
stored = data.data["A"]["id"] if as_frame else data.data["A"]
|
|
938
|
+
|
|
939
|
+
# Array-level writes also detect shared buffers that pandas copy-on-write could hide.
|
|
940
|
+
result.array[0] = 7
|
|
941
|
+
pd.testing.assert_series_equal(stored, pd.Series([2**53 + 1, 2**53 + 3], name="id", dtype=dtype))
|
|
942
|
+
stored.array[1] = 9
|
|
943
|
+
pd.testing.assert_series_equal(result, pd.Series([7, 2**53 + 3], name="A", dtype=dtype))
|
|
944
|
+
|
|
945
|
+
@pytest.mark.parametrize("as_frame", [False, True])
|
|
946
|
+
def test_concat_single_symbol_export(self, as_frame):
|
|
947
|
+
# Neighboring nanosecond timestamps must remain distinct in an actual CSV export.
|
|
948
|
+
index = pd.Index(["tick1", "tick2"], name="tick")
|
|
949
|
+
source = pd.Series([1704067200000000001, 1704067200000000003], index=index, name="EventTime")
|
|
950
|
+
payload = source.to_frame() if as_frame else source
|
|
951
|
+
data = vbt.Data.from_data({"A": payload})
|
|
952
|
+
result = data.concat()["EventTime"]
|
|
953
|
+
assert [int(value) for value in result] == [1704067200000000001, 1704067200000000003]
|
|
954
|
+
assert result.nunique() == 2
|
|
955
|
+
# Keep the exact CSV oracle independent of the platform's default line ending.
|
|
956
|
+
assert result.to_csv(lineterminator="\n") == "tick,A\ntick1,1704067200000000001\ntick2,1704067200000000003\n"
|
|
957
|
+
if as_frame:
|
|
958
|
+
pd.testing.assert_frame_equal(data.get(), payload)
|
|
959
|
+
else:
|
|
960
|
+
pd.testing.assert_series_equal(data.get(), payload)
|
|
961
|
+
|
|
874
962
|
def test_concat(self):
|
|
875
963
|
index = pd.DatetimeIndex(
|
|
876
964
|
[
|
|
@@ -1187,6 +1275,180 @@ class TestData:
|
|
|
1187
1275
|
pd.testing.assert_index_equal(stats_df.columns, stats_index)
|
|
1188
1276
|
|
|
1189
1277
|
|
|
1278
|
+
# ############# custom.py ############# #
|
|
1279
|
+
|
|
1280
|
+
binance_end = pd.Timestamp("2021-01-02", tz="UTC")
|
|
1281
|
+
binance_start_ms = 1609459200000 # 2021-01-01 00:00 UTC
|
|
1282
|
+
|
|
1283
|
+
|
|
1284
|
+
def binance_klines(n, start_ms=binance_start_ms, price=100.0):
|
|
1285
|
+
"""Build 1-minute kline rows shaped like python-binance responses."""
|
|
1286
|
+
rows = []
|
|
1287
|
+
for i in range(n):
|
|
1288
|
+
open_time = start_ms + i * 60_000
|
|
1289
|
+
p = price + i
|
|
1290
|
+
rows.append(
|
|
1291
|
+
[
|
|
1292
|
+
open_time,
|
|
1293
|
+
str(p),
|
|
1294
|
+
str(p + 2),
|
|
1295
|
+
str(p - 1),
|
|
1296
|
+
str(p + 1),
|
|
1297
|
+
"1.5",
|
|
1298
|
+
open_time + 59_999,
|
|
1299
|
+
str(p * 1.5),
|
|
1300
|
+
10 + i,
|
|
1301
|
+
"0.75",
|
|
1302
|
+
str(p * 0.75),
|
|
1303
|
+
"0",
|
|
1304
|
+
]
|
|
1305
|
+
)
|
|
1306
|
+
return rows
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
class FakeBinanceClient:
|
|
1310
|
+
"""Serve in-memory klines per client method and record each request."""
|
|
1311
|
+
|
|
1312
|
+
def __init__(self, **rows_by_method):
|
|
1313
|
+
self.rows_by_method = rows_by_method
|
|
1314
|
+
self.calls = []
|
|
1315
|
+
|
|
1316
|
+
def _serve(self, method, symbol, interval, limit, startTime, endTime=None):
|
|
1317
|
+
self.calls.append((method, dict(interval=interval, limit=limit, startTime=startTime, endTime=endTime)))
|
|
1318
|
+
rows = [
|
|
1319
|
+
row for row in self.rows_by_method[method] if row[0] >= startTime and (endTime is None or row[0] <= endTime)
|
|
1320
|
+
]
|
|
1321
|
+
return [list(row) for row in rows[:limit]]
|
|
1322
|
+
|
|
1323
|
+
def get_klines(self, **params):
|
|
1324
|
+
return self._serve("get_klines", **params)
|
|
1325
|
+
|
|
1326
|
+
def futures_klines(self, **params):
|
|
1327
|
+
return self._serve("futures_klines", **params)
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
class KlinesTypeStandIn(Enum):
|
|
1331
|
+
"""Same member names as `binance.enums.HistoricalKlinesType`, which is not a test dependency."""
|
|
1332
|
+
|
|
1333
|
+
SPOT = 1
|
|
1334
|
+
FUTURES = 2
|
|
1335
|
+
FUTURES_COIN = 3
|
|
1336
|
+
|
|
1337
|
+
|
|
1338
|
+
def download_binance_symbol(client, **kwargs):
|
|
1339
|
+
kwargs = merge_dicts(dict(interval="1m", end=binance_end, limit=2, delay=None, show_progress=False), kwargs)
|
|
1340
|
+
return vbt.BinanceData.download_symbol("BTCUSDT", client=client, **kwargs)
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
class TestBinanceData:
|
|
1344
|
+
def test_download_symbol_spot_default(self):
|
|
1345
|
+
client = FakeBinanceClient(get_klines=binance_klines(3))
|
|
1346
|
+
df = download_binance_symbol(client)
|
|
1347
|
+
end_ms = int(binance_end.timestamp() * 1000)
|
|
1348
|
+
# Without klines_type, requests stay on the spot endpoint with the same probe and pagination as before.
|
|
1349
|
+
assert client.calls == [
|
|
1350
|
+
("get_klines", dict(interval="1m", limit=1, startTime=0, endTime=None)),
|
|
1351
|
+
("get_klines", dict(interval="1m", limit=2, startTime=binance_start_ms, endTime=end_ms)),
|
|
1352
|
+
("get_klines", dict(interval="1m", limit=2, startTime=binance_start_ms + 60_000, endTime=end_ms)),
|
|
1353
|
+
("get_klines", dict(interval="1m", limit=2, startTime=binance_start_ms + 120_000, endTime=end_ms)),
|
|
1354
|
+
]
|
|
1355
|
+
assert list(df.columns) == [
|
|
1356
|
+
"Open",
|
|
1357
|
+
"High",
|
|
1358
|
+
"Low",
|
|
1359
|
+
"Close",
|
|
1360
|
+
"Volume",
|
|
1361
|
+
"Close time",
|
|
1362
|
+
"Quote volume",
|
|
1363
|
+
"Number of trades",
|
|
1364
|
+
"Taker base volume",
|
|
1365
|
+
"Taker quote volume",
|
|
1366
|
+
]
|
|
1367
|
+
pd.testing.assert_index_equal(
|
|
1368
|
+
df.index,
|
|
1369
|
+
pd.to_datetime([binance_start_ms + i * 60_000 for i in range(3)], unit="ms", utc=True).rename("Open time"),
|
|
1370
|
+
)
|
|
1371
|
+
np.testing.assert_array_equal(df["Open"].values, np.array([100.0, 101.0, 102.0]))
|
|
1372
|
+
np.testing.assert_array_equal(df["Number of trades"].values, np.array([10, 11, 12]))
|
|
1373
|
+
|
|
1374
|
+
@pytest.mark.parametrize(
|
|
1375
|
+
"klines_type,method",
|
|
1376
|
+
[
|
|
1377
|
+
("spot", "get_klines"),
|
|
1378
|
+
("futures", "futures_klines"),
|
|
1379
|
+
("FUTURES", "futures_klines"),
|
|
1380
|
+
(KlinesTypeStandIn.SPOT, "get_klines"),
|
|
1381
|
+
(KlinesTypeStandIn.FUTURES, "futures_klines"),
|
|
1382
|
+
],
|
|
1383
|
+
)
|
|
1384
|
+
def test_download_symbol_klines_type(self, klines_type, method):
|
|
1385
|
+
rows = binance_klines(3)
|
|
1386
|
+
spot_client = FakeBinanceClient(get_klines=rows)
|
|
1387
|
+
spot_df = download_binance_symbol(spot_client)
|
|
1388
|
+
client = FakeBinanceClient(get_klines=rows, futures_klines=rows)
|
|
1389
|
+
df = download_binance_symbol(client, klines_type=klines_type)
|
|
1390
|
+
# Every request, including the first-timestamp probe, goes to the selected market's endpoint.
|
|
1391
|
+
assert [m for m, _ in client.calls] == [method] * len(spot_client.calls)
|
|
1392
|
+
# Pagination and parsing are shared with the spot path.
|
|
1393
|
+
assert [params for _, params in client.calls] == [params for _, params in spot_client.calls]
|
|
1394
|
+
pd.testing.assert_frame_equal(df, spot_df)
|
|
1395
|
+
|
|
1396
|
+
def test_download_symbol_klines_type_probe(self):
|
|
1397
|
+
# Futures history starting before the spot listing must not be cut at the spot listing date.
|
|
1398
|
+
futures_rows = binance_klines(4, start_ms=binance_start_ms - 2 * 60_000, price=50.0)
|
|
1399
|
+
client = FakeBinanceClient(get_klines=binance_klines(2), futures_klines=futures_rows)
|
|
1400
|
+
df = download_binance_symbol(client, klines_type="futures")
|
|
1401
|
+
assert df.index[0] == pd.Timestamp(futures_rows[0][0], unit="ms", tz="UTC")
|
|
1402
|
+
np.testing.assert_array_equal(df["Open"].values, np.array([50.0, 51.0, 52.0, 53.0]))
|
|
1403
|
+
assert {m for m, _ in client.calls} == {"futures_klines"}
|
|
1404
|
+
|
|
1405
|
+
@pytest.mark.parametrize("klines_type", ["margin", "futures_coin", KlinesTypeStandIn.FUTURES_COIN, 2])
|
|
1406
|
+
def test_download_symbol_invalid_klines_type(self, klines_type):
|
|
1407
|
+
client = FakeBinanceClient(get_klines=binance_klines(3))
|
|
1408
|
+
with pytest.raises(ValueError, match="klines_type"):
|
|
1409
|
+
download_binance_symbol(client, klines_type=klines_type)
|
|
1410
|
+
assert client.calls == []
|
|
1411
|
+
|
|
1412
|
+
def test_update_keeps_klines_type(self):
|
|
1413
|
+
rows = binance_klines(4)
|
|
1414
|
+
client = FakeBinanceClient(futures_klines=rows[:3])
|
|
1415
|
+
download_kwargs = dict(
|
|
1416
|
+
client=client,
|
|
1417
|
+
klines_type="futures",
|
|
1418
|
+
interval="1m",
|
|
1419
|
+
end=binance_end,
|
|
1420
|
+
limit=2,
|
|
1421
|
+
delay=None,
|
|
1422
|
+
show_progress=False,
|
|
1423
|
+
)
|
|
1424
|
+
df = vbt.BinanceData.download_symbol("BTCUSDT", **download_kwargs)
|
|
1425
|
+
data = vbt.BinanceData.from_data({"BTCUSDT": df}, download_kwargs=download_kwargs)
|
|
1426
|
+
client.rows_by_method["futures_klines"] = rows
|
|
1427
|
+
new_data = data.update()
|
|
1428
|
+
# Updates reuse the stored klines_type instead of falling back to spot.
|
|
1429
|
+
assert {m for m, _ in client.calls} == {"futures_klines"}
|
|
1430
|
+
np.testing.assert_array_equal(new_data.get("Open").values, np.array([100.0, 101.0, 102.0, 103.0]))
|
|
1431
|
+
|
|
1432
|
+
def test_download_historical_klines_type(self):
|
|
1433
|
+
enums = pytest.importorskip("binance.enums")
|
|
1434
|
+
rows = binance_klines(4)
|
|
1435
|
+
client = FakeBinanceClient(futures_klines=rows[:3])
|
|
1436
|
+
data = vbt.BinanceData.download(
|
|
1437
|
+
"BTCUSDT",
|
|
1438
|
+
client=client,
|
|
1439
|
+
klines_type=enums.HistoricalKlinesType.FUTURES,
|
|
1440
|
+
interval="1m",
|
|
1441
|
+
end=binance_end,
|
|
1442
|
+
limit=2,
|
|
1443
|
+
delay=None,
|
|
1444
|
+
show_progress=False,
|
|
1445
|
+
)
|
|
1446
|
+
client.rows_by_method["futures_klines"] = rows
|
|
1447
|
+
new_data = data.update()
|
|
1448
|
+
assert {m for m, _ in client.calls} == {"futures_klines"}
|
|
1449
|
+
np.testing.assert_array_equal(new_data.get("Open").values, np.array([100.0, 101.0, 102.0, 103.0]))
|
|
1450
|
+
|
|
1451
|
+
|
|
1190
1452
|
# ############# updater.py ############# #
|
|
1191
1453
|
|
|
1192
1454
|
|
|
@@ -29,6 +29,34 @@ def teardown_module():
|
|
|
29
29
|
|
|
30
30
|
|
|
31
31
|
class TestEngineResolution:
|
|
32
|
+
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
|
|
33
|
+
@pytest.mark.parametrize("close_dtype", [np.float64, np.uint64])
|
|
34
|
+
def test_obv_integer_fallback(self, dtype, close_dtype):
|
|
35
|
+
# The integer-price variant also challenges direction after float64 would erase unit gaps.
|
|
36
|
+
close = np.array([[2, 1], [1, 3], [3, 2]], dtype=close_dtype)
|
|
37
|
+
if close_dtype == np.uint64:
|
|
38
|
+
close += np.uint64(2**63)
|
|
39
|
+
volume = np.array([[10, 10], [20, 20], [30, 30]], dtype=dtype)
|
|
40
|
+
close_before, volume_before = close.copy(), volume.copy()
|
|
41
|
+
expected_dtype = np.promote_types(np.dtype(dtype), np.dtype(int))
|
|
42
|
+
expected = np.array([[10, 10], [-10, 30], [20, 0]], dtype=expected_dtype)
|
|
43
|
+
index = pd.date_range("2024-01-01", periods=3, tz="UTC", name="bar")
|
|
44
|
+
columns = pd.Index(["a", "b"], name="asset")
|
|
45
|
+
assert not _engine.array_compatible_with_rust(volume).supported
|
|
46
|
+
# Automatic selection must keep the exact integer path, including when Rust is installed.
|
|
47
|
+
for engine in ("numba", "auto"):
|
|
48
|
+
actual = indicator_dispatch.obv_custom(close, volume, engine=engine)
|
|
49
|
+
np.testing.assert_array_equal(actual, expected)
|
|
50
|
+
assert actual.dtype == expected_dtype
|
|
51
|
+
obj = vbt.OBV.run(
|
|
52
|
+
pd.DataFrame(close, index=index, columns=columns),
|
|
53
|
+
pd.DataFrame(volume, index=index, columns=columns),
|
|
54
|
+
engine=engine,
|
|
55
|
+
)
|
|
56
|
+
pd.testing.assert_frame_equal(obj.obv, pd.DataFrame(expected, index=index, columns=columns))
|
|
57
|
+
np.testing.assert_array_equal(close, close_before)
|
|
58
|
+
np.testing.assert_array_equal(volume, volume_before)
|
|
59
|
+
|
|
32
60
|
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
|
|
33
61
|
def test_true_range_unsigned_fallback(self, dtype):
|
|
34
62
|
high = np.array([105, 95, 109], dtype=dtype)[:, None]
|
|
@@ -285,6 +313,23 @@ class TestEngineResolution:
|
|
|
285
313
|
returns_dispatch.rolling_martin_ratio(arr, 2, None, 365.0, 0.0, engine="rust")
|
|
286
314
|
assert returns_dispatch.martin_ratio(arr, 365.0, 0.0, engine="auto").shape == (1,)
|
|
287
315
|
|
|
316
|
+
@pytest.mark.parametrize(
|
|
317
|
+
"name,args,expected_shape",
|
|
318
|
+
[
|
|
319
|
+
("pain_index", (), (1,)),
|
|
320
|
+
("rolling_pain_index", (2, None), (3, 1)),
|
|
321
|
+
("pain_ratio", (365.0, 0.0), (1,)),
|
|
322
|
+
("rolling_pain_ratio", (2, None, 365.0, 0.0), (3, 1)),
|
|
323
|
+
],
|
|
324
|
+
)
|
|
325
|
+
def test_pain_reject_explicit_rust(self, monkeypatch, name, args, expected_shape):
|
|
326
|
+
monkeypatch.setattr(_engine, "is_rust_available", lambda: True)
|
|
327
|
+
arr = np.array([[0.01], [-0.02], [0.03]])
|
|
328
|
+
func = getattr(returns_dispatch, name)
|
|
329
|
+
with pytest.raises(ValueError, match=f"not implemented for `{name}`"):
|
|
330
|
+
func(arr, *args, engine="rust")
|
|
331
|
+
assert func(arr, *args, engine="auto").shape == expected_shape
|
|
332
|
+
|
|
288
333
|
@pytest.mark.skipif(not _engine.is_rust_available(), reason="vectorbt-rust is not installed or version-compatible")
|
|
289
334
|
def test_rust_accepts_safe_cast_arrays(self):
|
|
290
335
|
f32_arr = np.array([[1.0, np.nan], [3.0, 4.0]], dtype=np.float32)
|
|
@@ -1410,6 +1455,14 @@ class TestSignalsRustParity:
|
|
|
1410
1455
|
|
|
1411
1456
|
@pytest.mark.skipif(not _engine.is_rust_available(), reason="vectorbt-rust is not installed or version-compatible")
|
|
1412
1457
|
class TestIndicatorRustParity:
|
|
1458
|
+
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
|
|
1459
|
+
def test_obv_integer_rejected(self, dtype):
|
|
1460
|
+
# Keep explicit Rust calls separate so conftest cannot skip the core fallback regressions.
|
|
1461
|
+
close = np.array([2.0, 1.0, 3.0])[:, None]
|
|
1462
|
+
volume = np.array([10, 20, 30], dtype=dtype)[:, None]
|
|
1463
|
+
with pytest.raises(ValueError, match="cannot be safely cast"):
|
|
1464
|
+
indicator_dispatch.obv_custom(close, volume, engine="rust")
|
|
1465
|
+
|
|
1413
1466
|
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
|
|
1414
1467
|
@pytest.mark.parametrize("layout", ["C", "F", "strided"])
|
|
1415
1468
|
def test_obv_flat_close(self, dtype, layout):
|
|
@@ -3396,3 +3396,73 @@ raise SystemExit(pytest.main(sys.argv[1:]))
|
|
|
3396
3396
|
np.testing.assert_array_equal(vbt.indicators.nb.obv_custom_nb(close, volume), expected)
|
|
3397
3397
|
# Integers remain on Numba's precision-preserving path under automatic engine selection.
|
|
3398
3398
|
np.testing.assert_array_equal(vbt.indicators.dispatch.obv_custom(close, volume, engine="auto"), expected)
|
|
3399
|
+
|
|
3400
|
+
@pytest.mark.parametrize(
|
|
3401
|
+
"dtype", [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64]
|
|
3402
|
+
)
|
|
3403
|
+
def test_OBV_integer_volume(self, dtype):
|
|
3404
|
+
# A decline must subtract unsigned counts, and a flat bar must contribute zero.
|
|
3405
|
+
close = pd.Series([100, 90, 90, 110, 90], name="price")
|
|
3406
|
+
volume = pd.Series([10, 20, 25, 30, 40], dtype=dtype, name="price")
|
|
3407
|
+
expected_dtype = np.promote_types(np.dtype(dtype), np.dtype(int))
|
|
3408
|
+
expected = pd.Series([10, -10, -10, 20, -20], dtype=expected_dtype, name="price")
|
|
3409
|
+
close_before, volume_before = close.copy(), volume.copy()
|
|
3410
|
+
actual = vbt.indicators.nb.obv_custom_nb(close.to_numpy()[:, None], volume.to_numpy()[:, None])
|
|
3411
|
+
np.testing.assert_array_equal(actual[:, 0], expected.to_numpy())
|
|
3412
|
+
assert actual.dtype == expected_dtype
|
|
3413
|
+
obj = vbt.OBV.run(close, volume, engine="numba")
|
|
3414
|
+
pd.testing.assert_series_equal(obj.obv, expected)
|
|
3415
|
+
# Wrong signed contributions previously hid the first negative crossing.
|
|
3416
|
+
pd.testing.assert_series_equal(
|
|
3417
|
+
obj.obv_crossed_below(0.0), pd.Series([False, True, False, False, True], name="price")
|
|
3418
|
+
)
|
|
3419
|
+
pd.testing.assert_series_equal(close, close_before)
|
|
3420
|
+
pd.testing.assert_series_equal(volume, volume_before)
|
|
3421
|
+
|
|
3422
|
+
@pytest.mark.parametrize(
|
|
3423
|
+
"dtype,offset",
|
|
3424
|
+
[
|
|
3425
|
+
(np.int64, 2**53 - 1),
|
|
3426
|
+
(np.int64, -(2**63)),
|
|
3427
|
+
(np.int64, 2**63 - 4),
|
|
3428
|
+
(np.uint64, 2**63),
|
|
3429
|
+
(np.uint64, 2**64 - 4),
|
|
3430
|
+
],
|
|
3431
|
+
)
|
|
3432
|
+
def test_OBV_integer_price_direction(self, dtype, offset):
|
|
3433
|
+
# Keep adjacent integer prices distinct before the down/flat comparison.
|
|
3434
|
+
close = pd.Series([offset + 2, offset + 1, offset + 1, offset + 3], dtype=dtype, name="price")
|
|
3435
|
+
volume = pd.Series([10, 20, 30, 40], name="price")
|
|
3436
|
+
expected = pd.Series([10, -10, -10, 30], name="price")
|
|
3437
|
+
np.testing.assert_array_equal(
|
|
3438
|
+
vbt.indicators.nb.obv_custom_nb(close.to_numpy()[:, None], volume.to_numpy()[:, None])[:, 0], expected
|
|
3439
|
+
)
|
|
3440
|
+
pd.testing.assert_series_equal(vbt.OBV.run(close, volume, engine="numba").obv, expected)
|
|
3441
|
+
|
|
3442
|
+
@pytest.mark.parametrize(
|
|
3443
|
+
"dtype", [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64]
|
|
3444
|
+
)
|
|
3445
|
+
def test_OBV_integer_volume_boundaries(self, dtype):
|
|
3446
|
+
# Equal large contributions cancel before adding one; flat volume must still be ignored.
|
|
3447
|
+
limit = int(np.iinfo(dtype).max)
|
|
3448
|
+
close = np.array([2, 1, 2, 2])[:, None]
|
|
3449
|
+
volume = np.array([limit, limit, 1, limit], dtype=dtype)[:, None]
|
|
3450
|
+
expected_dtype = np.promote_types(np.dtype(dtype), np.dtype(int))
|
|
3451
|
+
actual = vbt.indicators.nb.obv_custom_nb(close, volume)
|
|
3452
|
+
assert actual.dtype == expected_dtype
|
|
3453
|
+
np.testing.assert_array_equal(actual[:, 0], np.array([limit, 0, 1, 1], dtype=expected_dtype))
|
|
3454
|
+
|
|
3455
|
+
def test_OBV_float32_accumulation(self):
|
|
3456
|
+
# Promoting integer contributions must not change native float32 accumulation.
|
|
3457
|
+
close = np.array([1, 2, 3], dtype=np.float32)[:, None]
|
|
3458
|
+
volume = np.array([2**24, 1, 1], dtype=np.float32)[:, None]
|
|
3459
|
+
expected = vbt.generic.nb.nancumsum_nb(volume)
|
|
3460
|
+
np.testing.assert_array_equal(vbt.indicators.nb.obv_custom_nb(close, volume), expected)
|
|
3461
|
+
|
|
3462
|
+
def test_OBV_boolean_volume(self):
|
|
3463
|
+
# Boolean volumes already represent zero/one counts on the native path.
|
|
3464
|
+
close = np.array([2, 1, 3])[:, None]
|
|
3465
|
+
volume = np.ones(close.shape, dtype=bool)
|
|
3466
|
+
actual = vbt.indicators.nb.obv_custom_nb(close, volume)
|
|
3467
|
+
np.testing.assert_array_equal(actual[:, 0], [1, 0, 1])
|
|
3468
|
+
assert actual.dtype == np.dtype(np.int64)
|