tradesigns 1.0.0__py3-none-any.whl
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.
- tradesigns/__init__.py +3 -0
- tradesigns/bars.py +159 -0
- tradesigns/rules.py +98 -0
- tradesigns/score.py +45 -0
- tradesigns-1.0.0.dist-info/METADATA +195 -0
- tradesigns-1.0.0.dist-info/RECORD +8 -0
- tradesigns-1.0.0.dist-info/WHEEL +4 -0
- tradesigns-1.0.0.dist-info/licenses/LICENSE +21 -0
tradesigns/__init__.py
ADDED
tradesigns/bars.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Dollar-imbalance bar boundaries driven by external signs.
|
|
2
|
+
|
|
3
|
+
A faithful twin of the imbalance-bar segmentation in clockbars 1.1.0
|
|
4
|
+
(``clockbars.adaptive.imbalance_bounds``): same signed-metric accumulation,
|
|
5
|
+
same prepend-carry cumsum so batch and streaming orders agree on identical
|
|
6
|
+
floats, same closure rule (``|running| >= E[T] * |e|``), same EWMA state
|
|
7
|
+
(``alpha = 2 / (window + 1)``, updated only by completed bars).
|
|
8
|
+
|
|
9
|
+
The one difference is the point of this library: the signs are an argument.
|
|
10
|
+
clockbars signs trades with its internal tick rule; this function accepts
|
|
11
|
+
any sign source, so the same bar engine can be driven by the tick rule or
|
|
12
|
+
by the exchange's own aggressor flags. Parity with clockbars is pinned by
|
|
13
|
+
``tests/test_bars.py``: with identical tick-rule signs the two produce
|
|
14
|
+
bit-identical boundaries.
|
|
15
|
+
|
|
16
|
+
Conventions carried over from clockbars:
|
|
17
|
+
|
|
18
|
+
- a bar closes at the first trade where the running signed metric reaches
|
|
19
|
+
the target in absolute value, and the closing trade belongs to the bar
|
|
20
|
+
- only completed bars update the E[T] and e estimates
|
|
21
|
+
- the final bar of a segment stays open and is flagged partial
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import math
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
from numpy.typing import NDArray
|
|
30
|
+
|
|
31
|
+
_CHUNK = 2048
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check_positive(value: float, name: str) -> float:
|
|
35
|
+
if not math.isfinite(value) or value <= 0:
|
|
36
|
+
raise ValueError(f"{name} must be a positive finite number, got {value}")
|
|
37
|
+
return float(value)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def imbalance_bounds(
|
|
41
|
+
metric: NDArray[np.float64],
|
|
42
|
+
signs: NDArray[np.float64],
|
|
43
|
+
*,
|
|
44
|
+
expected_trades: float,
|
|
45
|
+
expected_imbalance: float,
|
|
46
|
+
window: int,
|
|
47
|
+
) -> tuple[list[int], list[bool], dict[str, float]]:
|
|
48
|
+
"""Start index and partial flag of every dollar-imbalance bar.
|
|
49
|
+
|
|
50
|
+
``metric`` is the per-trade quantity (dollar notional) and ``signs`` the
|
|
51
|
+
per-trade signs (+1 buy, -1 sell), both as float64 arrays of equal
|
|
52
|
+
length. Returns ``(bar_starts, partials)``; the last bar is partial when
|
|
53
|
+
the stream ends before its target is reached.
|
|
54
|
+
"""
|
|
55
|
+
if metric.ndim != 1 or signs.ndim != 1 or metric.size != signs.size:
|
|
56
|
+
raise ValueError("metric and signs must be 1-D arrays of equal length")
|
|
57
|
+
if window < 1:
|
|
58
|
+
raise ValueError("window must be at least 1")
|
|
59
|
+
est_trades = _check_positive(expected_trades, "expected_trades")
|
|
60
|
+
est_imb = expected_imbalance
|
|
61
|
+
if not math.isfinite(est_imb) or est_imb == 0:
|
|
62
|
+
raise ValueError("expected_imbalance must be finite and nonzero")
|
|
63
|
+
|
|
64
|
+
alpha = 2.0 / (window + 1.0)
|
|
65
|
+
signed = signs * metric
|
|
66
|
+
|
|
67
|
+
bar_starts: list[int] = []
|
|
68
|
+
partials: list[bool] = []
|
|
69
|
+
n = metric.size
|
|
70
|
+
start = 0
|
|
71
|
+
while start < n:
|
|
72
|
+
bar_starts.append(start)
|
|
73
|
+
target = est_trades * abs(est_imb)
|
|
74
|
+
closing = -1
|
|
75
|
+
partial = 0.0
|
|
76
|
+
position = start
|
|
77
|
+
while position < n:
|
|
78
|
+
stop = min(position + _CHUNK, n)
|
|
79
|
+
carried = np.concatenate(([partial], signed[position:stop]))
|
|
80
|
+
running = np.cumsum(carried)
|
|
81
|
+
absolute = np.abs(running[1:])
|
|
82
|
+
hits = np.flatnonzero(absolute >= target)
|
|
83
|
+
if hits.size:
|
|
84
|
+
closing = position + int(hits[0])
|
|
85
|
+
bar_total = float(running[hits[0] + 1])
|
|
86
|
+
break
|
|
87
|
+
partial = float(running[-1])
|
|
88
|
+
position = stop
|
|
89
|
+
if closing < 0:
|
|
90
|
+
partials.append(True)
|
|
91
|
+
carry = {
|
|
92
|
+
"est_trades": est_trades,
|
|
93
|
+
"est_imb": est_imb,
|
|
94
|
+
"partial": partial,
|
|
95
|
+
"seen": float(n - start),
|
|
96
|
+
"open": 1.0,
|
|
97
|
+
}
|
|
98
|
+
return bar_starts, partials, carry
|
|
99
|
+
partials.append(False)
|
|
100
|
+
length = closing - start + 1
|
|
101
|
+
est_trades += alpha * (length - est_trades)
|
|
102
|
+
est_imb += alpha * (bar_total / length - est_imb)
|
|
103
|
+
start = closing + 1
|
|
104
|
+
carry = {
|
|
105
|
+
"est_trades": est_trades,
|
|
106
|
+
"est_imb": est_imb,
|
|
107
|
+
"partial": 0.0,
|
|
108
|
+
"seen": 0.0,
|
|
109
|
+
"open": 0.0,
|
|
110
|
+
}
|
|
111
|
+
return bar_starts, partials, carry
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def fixed_imbalance_bounds(
|
|
115
|
+
metric: NDArray[np.float64],
|
|
116
|
+
signs: NDArray[np.float64],
|
|
117
|
+
*,
|
|
118
|
+
threshold: float,
|
|
119
|
+
) -> tuple[list[int], list[bool]]:
|
|
120
|
+
"""Start index and partial flag of every fixed-threshold imbalance bar.
|
|
121
|
+
|
|
122
|
+
The adaptive-free variant of the imbalance clock: a bar closes when the
|
|
123
|
+
running signed metric reaches ``+threshold`` or ``-threshold`` in
|
|
124
|
+
absolute value, and the accumulator restarts from zero with the next
|
|
125
|
+
trade, the same restart convention clockbars uses for its threshold
|
|
126
|
+
kinds. Nothing adapts, so two sign sources on the same stream with the
|
|
127
|
+
same threshold differ by their signs alone.
|
|
128
|
+
"""
|
|
129
|
+
if metric.ndim != 1 or signs.ndim != 1 or metric.size != signs.size:
|
|
130
|
+
raise ValueError("metric and signs must be 1-D arrays of equal length")
|
|
131
|
+
if not math.isfinite(threshold) or threshold <= 0:
|
|
132
|
+
raise ValueError(f"threshold must be a positive finite number, got {threshold}")
|
|
133
|
+
|
|
134
|
+
signed = signs * metric
|
|
135
|
+
bar_starts: list[int] = []
|
|
136
|
+
partials: list[bool] = []
|
|
137
|
+
n = metric.size
|
|
138
|
+
start = 0
|
|
139
|
+
while start < n:
|
|
140
|
+
bar_starts.append(start)
|
|
141
|
+
closing = -1
|
|
142
|
+
partial = 0.0
|
|
143
|
+
position = start
|
|
144
|
+
while position < n:
|
|
145
|
+
stop = min(position + _CHUNK, n)
|
|
146
|
+
carried = np.concatenate(([partial], signed[position:stop]))
|
|
147
|
+
running = np.cumsum(carried)
|
|
148
|
+
hits = np.flatnonzero(np.abs(running[1:]) >= threshold)
|
|
149
|
+
if hits.size:
|
|
150
|
+
closing = position + int(hits[0])
|
|
151
|
+
break
|
|
152
|
+
partial = float(running[-1])
|
|
153
|
+
position = stop
|
|
154
|
+
if closing < 0:
|
|
155
|
+
partials.append(True)
|
|
156
|
+
break
|
|
157
|
+
partials.append(False)
|
|
158
|
+
start = closing + 1
|
|
159
|
+
return bar_starts, partials
|
tradesigns/rules.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Trade classification rules, with the conventions this library documents.
|
|
2
|
+
|
|
3
|
+
Every rule maps a trade stream to signs: +1 when the rule calls the trade an
|
|
4
|
+
aggressor buy, -1 an aggressor sell, None where the rule cannot classify.
|
|
5
|
+
|
|
6
|
+
Conventions, enforced by tests in ``tests/test_rules.py``:
|
|
7
|
+
|
|
8
|
+
- Signs are a property of the stream. The tick rule carries its state across
|
|
9
|
+
flat prices and across session boundaries, exactly as clockbars does when
|
|
10
|
+
it builds imbalance and runs bars from signs.
|
|
11
|
+
- The first trade of a stream has no tick history: the tick rule leaves it
|
|
12
|
+
unclassified rather than guessing.
|
|
13
|
+
- The quote rule classifies against the quote midpoint attached to the
|
|
14
|
+
trade. Trades at the midpoint are ambiguous and stay unclassified; the
|
|
15
|
+
Lee-Ready rule resolves them with the tick test.
|
|
16
|
+
- Ground truth is the exchange aggressor flag. Databento's ``side`` field is
|
|
17
|
+
``B`` when the aggressor bought, ``A`` when it sold, and anything else
|
|
18
|
+
(implied and system records arrive as ``N``) is treated as untagged.
|
|
19
|
+
|
|
20
|
+
All rules are strictly causal: mutating or appending future trades never
|
|
21
|
+
changes a sign at or before the mutation point.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import polars as pl
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def require(trades: pl.DataFrame, cols: tuple[str, ...]) -> None:
|
|
30
|
+
"""Raise a clear error when the frame lacks required columns."""
|
|
31
|
+
missing = [c for c in cols if c not in trades.columns]
|
|
32
|
+
if missing:
|
|
33
|
+
raise ValueError(f"trades frame is missing columns: {missing}")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _tick_expr() -> pl.Expr:
|
|
37
|
+
"""Tick-rule sign expression: uptick +1, downtick -1, carry across flats."""
|
|
38
|
+
diff = pl.col("price").diff()
|
|
39
|
+
return (
|
|
40
|
+
pl.when(diff > 0)
|
|
41
|
+
.then(1)
|
|
42
|
+
.when(diff < 0)
|
|
43
|
+
.then(-1)
|
|
44
|
+
.otherwise(None)
|
|
45
|
+
.forward_fill()
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def tick_rule(trades: pl.DataFrame) -> pl.Series:
|
|
50
|
+
"""Classify each trade by price direction alone."""
|
|
51
|
+
require(trades, ("price",))
|
|
52
|
+
return trades.select(_tick_expr().alias("sign")).to_series()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _quote_expr() -> tuple[pl.Expr, tuple[str, ...]]:
|
|
56
|
+
"""Quote-rule sign expression and the columns it requires."""
|
|
57
|
+
cols = ("price", "bid_px_00", "ask_px_00")
|
|
58
|
+
mid = (pl.col("bid_px_00") + pl.col("ask_px_00")) / 2
|
|
59
|
+
expr = (
|
|
60
|
+
pl.when(pl.col("price") > mid)
|
|
61
|
+
.then(1)
|
|
62
|
+
.when(pl.col("price") < mid)
|
|
63
|
+
.then(-1)
|
|
64
|
+
.otherwise(None)
|
|
65
|
+
)
|
|
66
|
+
return expr, cols
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def quote_rule(trades: pl.DataFrame) -> pl.Series:
|
|
70
|
+
"""Classify each trade against the quote midpoint attached to it."""
|
|
71
|
+
expr, cols = _quote_expr()
|
|
72
|
+
require(trades, cols)
|
|
73
|
+
return trades.select(expr.alias("sign")).to_series()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def lee_ready(trades: pl.DataFrame) -> pl.Series:
|
|
77
|
+
"""Lee-Ready: quote rule first, tick test where the quote is ambiguous."""
|
|
78
|
+
quote, cols = _quote_expr()
|
|
79
|
+
require(trades, cols)
|
|
80
|
+
return trades.select(
|
|
81
|
+
pl.when(quote.is_null())
|
|
82
|
+
.then(_tick_expr())
|
|
83
|
+
.otherwise(quote)
|
|
84
|
+
.alias("sign")
|
|
85
|
+
).to_series()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def ground_truth(trades: pl.DataFrame) -> pl.Series:
|
|
89
|
+
"""Map the exchange aggressor flag to signs: B -> +1, A -> -1, else None."""
|
|
90
|
+
require(trades, ("side",))
|
|
91
|
+
return trades.select(
|
|
92
|
+
pl.when(pl.col("side") == "B")
|
|
93
|
+
.then(1)
|
|
94
|
+
.when(pl.col("side") == "A")
|
|
95
|
+
.then(-1)
|
|
96
|
+
.otherwise(None)
|
|
97
|
+
.alias("truth")
|
|
98
|
+
).to_series()
|
tradesigns/score.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Score classification rules against exchange ground truth."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import polars as pl
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _check_alignment(sign: pl.Series, truth: pl.Series) -> None:
|
|
9
|
+
if sign.len() != truth.len():
|
|
10
|
+
raise ValueError(
|
|
11
|
+
f"sign and truth must be aligned: {sign.len()} vs {truth.len()} rows"
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def accuracy(
|
|
16
|
+
sign: pl.Series,
|
|
17
|
+
truth: pl.Series,
|
|
18
|
+
weights: pl.Series | None = None,
|
|
19
|
+
) -> float | None:
|
|
20
|
+
"""Share of correctly signed trades, over rows both series classify.
|
|
21
|
+
|
|
22
|
+
Unclassified rows (sign is None) and untagged trades (truth is None)
|
|
23
|
+
are excluded from the denominator. With ``weights``, each trade counts
|
|
24
|
+
by its size instead of once.
|
|
25
|
+
"""
|
|
26
|
+
_check_alignment(sign, truth)
|
|
27
|
+
ok = sign.is_not_null() & truth.is_not_null()
|
|
28
|
+
n = int(ok.sum())
|
|
29
|
+
if n == 0:
|
|
30
|
+
return None
|
|
31
|
+
correct = (sign == truth) & ok
|
|
32
|
+
if weights is None:
|
|
33
|
+
return float(correct.sum()) / n
|
|
34
|
+
w = weights.cast(pl.Int64)
|
|
35
|
+
return float((correct.cast(pl.Int64) * w).sum()) / float((ok.cast(pl.Int64) * w).sum())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def coverage(sign: pl.Series, truth: pl.Series) -> float | None:
|
|
39
|
+
"""Share of tagged trades the rule classified at all."""
|
|
40
|
+
_check_alignment(sign, truth)
|
|
41
|
+
tagged = truth.is_not_null()
|
|
42
|
+
n = int(tagged.sum())
|
|
43
|
+
if n == 0:
|
|
44
|
+
return None
|
|
45
|
+
return float((sign.is_not_null() & tagged).sum()) / n
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: tradesigns
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Trade classification rules, benchmarked against exchange aggressor-side ground truth.
|
|
5
|
+
Project-URL: Homepage, https://github.com/zzionz/tradesigns
|
|
6
|
+
Project-URL: Issues, https://github.com/zzionz/tradesigns/issues
|
|
7
|
+
Author: zzionz
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: financial-data,market-microstructure,order-flow,polars,quantitative-finance
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Requires-Dist: numpy>=1.26
|
|
24
|
+
Requires-Dist: polars>=1.0
|
|
25
|
+
Provides-Extra: bench
|
|
26
|
+
Requires-Dist: clockbars>=1.1.0; extra == 'bench'
|
|
27
|
+
Requires-Dist: databento>=0.44.0; extra == 'bench'
|
|
28
|
+
Requires-Dist: matplotlib>=3.8; extra == 'bench'
|
|
29
|
+
Requires-Dist: pyarrow>=16.0; extra == 'bench'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# tradesigns
|
|
33
|
+
|
|
34
|
+
[](https://github.com/zzionz/tradesigns/actions/workflows/ci.yml)
|
|
35
|
+
[](https://github.com/zzionz/tradesigns/actions/workflows/ci.yml)
|
|
36
|
+
[](https://github.com/zzionz/tradesigns/actions/workflows/ci.yml)
|
|
37
|
+
[](https://github.com/zzionz/tradesigns/actions/workflows/ci.yml)
|
|
38
|
+
[](https://pypi.org/project/tradesigns/)
|
|
39
|
+
[](LICENSE)
|
|
40
|
+
[](https://pypi.org/project/tradesigns/)
|
|
41
|
+
|
|
42
|
+
Your order-flow measures run on signed trades. VPIN needs buys and sells per
|
|
43
|
+
volume bucket. Order-flow imbalance needs the aggressor of every print.
|
|
44
|
+
Imbalance bars need signs to know when to close. Your data almost certainly
|
|
45
|
+
does not say who initiated anything, so you sign it with the tick rule or
|
|
46
|
+
Lee-Ready and inherit accuracy numbers measured on 1990s NASDAQ.
|
|
47
|
+
|
|
48
|
+
CME futures never needed the inference. The matching engine knows which side
|
|
49
|
+
crossed the spread, because it is the matching engine, and it tags every
|
|
50
|
+
print with the aggressor's side before the tape leaves the building. We
|
|
51
|
+
scored the classical rules against that tag on 34.4 million prints across
|
|
52
|
+
gold, Nasdaq-100, and WTI crude, September to November 2026. The full study,
|
|
53
|
+
with the literature and the arithmetic behind every number below, is
|
|
54
|
+
[docs/paper.md](docs/paper.md).
|
|
55
|
+
|
|
56
|
+
Three findings, ranked by how much they should change your pipeline.
|
|
57
|
+
|
|
58
|
+
1. Against the quote that prevailed at the trade, the quote rule classifies
|
|
59
|
+
99.59 to 100.00 percent of prints correctly. On 23.2 million Nasdaq-100
|
|
60
|
+
prints it made zero errors. With at-trade quotes, the problem is solved.
|
|
61
|
+
2. One second of quote staleness drops the rule to 67.32 percent, below the
|
|
62
|
+
tick rule's 83.65. The 1990s canon was built on consolidated quotes that
|
|
63
|
+
were stale by construction. On a fresh book, the advice inverts.
|
|
64
|
+
3. With no quotes at all, the tick rule carries 16 to 28 percent error, and
|
|
65
|
+
the error runs in clusters. It flips the dominant side of a volume bucket
|
|
66
|
+
roughly one time in six on gold and one in five on crude, and it moves
|
|
67
|
+
about nine out of ten imbalance-bar boundaries.
|
|
68
|
+
|
|
69
|
+
## The scorecard
|
|
70
|
+
|
|
71
|
+
| product | prints | tick | quote at-trade | Lee-Ready |
|
|
72
|
+
| :--- | ---: | ---: | ---: | ---: |
|
|
73
|
+
| GCZ6 gold | 6.40M | 83.55% | 99.59% | 99.56% |
|
|
74
|
+
| NQZ6 Nasdaq-100 | 23.22M | 83.65% | 100.00% | 100.00% |
|
|
75
|
+
| CLX6 WTI (Sep) | 1.81M | 73.86% | 98.92% | 98.11% |
|
|
76
|
+
| CLZ6 WTI (Oct) | 1.81M | 73.76% | 98.68% | 97.87% |
|
|
77
|
+
| CLF7 WTI (Nov) | 1.12M | 72.07% | 98.54% | 97.68% |
|
|
78
|
+
|
|
79
|
+
Read the last two columns together. The Lee-Ready hybrid is dominated by the
|
|
80
|
+
pure quote rule on all five contracts; its tick-test fallback at the midpoint
|
|
81
|
+
adds error, because at-trade quotes are so good that any fallback is a
|
|
82
|
+
downgrade. Volume weighting helps the tick rule a little (crude improves from
|
|
83
|
+
26-28 percent error by count to 20-23 by volume), and the error it cannot
|
|
84
|
+
shed concentrates at the touch, where consecutive prints on an unmoved price
|
|
85
|
+
defeat the carry logic. Crude's implied and system records arrive untagged
|
|
86
|
+
(about 14 percent of prints); every number here excludes them, and both sign
|
|
87
|
+
sources face the same exclusion.
|
|
88
|
+
|
|
89
|
+
## One second old is worse than none
|
|
90
|
+
|
|
91
|
+

|
|
92
|
+
|
|
93
|
+
The at-trade quote is a gift of hindsight. Live, and in most datasets,
|
|
94
|
+
quotes arrive old, so we joined each Nasdaq-100 print to the prevailing quote
|
|
95
|
+
on a 1-second grid and added lag on top. Accuracy: 100.00 percent at trade,
|
|
96
|
+
67.32 on the grid (median effective staleness 0.65s), 61.35 at one second,
|
|
97
|
+
56.67 at five, 52.49 at a minute. The tick rule sits flat at 83.65 with no
|
|
98
|
+
quotes at all, which means every row of the ladder is below it.
|
|
99
|
+
|
|
100
|
+
The five-second figure lands exactly on the 56.7 percent a 2026 study of a
|
|
101
|
+
one-tick futures market measured for Lee-Ready under a five-second lag. Two
|
|
102
|
+
markets, two datasets, one answer, and a neat closing of the loop on 35
|
|
103
|
+
years of literature: the rules were never wrong to prefer quotes, they were
|
|
104
|
+
calibrated to quotes worth less than none. The mechanism is fast. Only 9.9
|
|
105
|
+
percent of prints see the same midpoint one grid step later. The Nasdaq-100
|
|
106
|
+
touch churns in under a second.
|
|
107
|
+
|
|
108
|
+
## What the error costs downstream
|
|
109
|
+
|
|
110
|
+
Per equal-volume bucket, the volume-clock quantity VPIN consumes, the tick
|
|
111
|
+
rule calls the wrong dominant side 14.83 percent of the time on Nasdaq-100,
|
|
112
|
+
16.41 percent on gold, and 17.96 to 21.71 percent on crude, with buy-fraction
|
|
113
|
+
correlation 0.80 to 0.88. A threshold detector built on those fractions reads
|
|
114
|
+
toxicity where there is none and misses it where there is, at exactly that
|
|
115
|
+
rate.
|
|
116
|
+
|
|
117
|
+

|
|
118
|
+
|
|
119
|
+
Bars fare no better. We drove the same fixed-threshold imbalance engine with
|
|
120
|
+
tick signs and with exchange signs, on identical streams, after asserting the
|
|
121
|
+
engine bit-identical to
|
|
122
|
+
[clockbars](https://github.com/zzionz/clockbars) itself. Signed magnitude is
|
|
123
|
+
barely inflated (1.03x on all three products tested) and bar counts nearly
|
|
124
|
+
agree (1.00 to 1.15x), so the clock keeps roughly the right speed. But 92 to
|
|
125
|
+
94 percent of boundaries land in different places: median displacement 6 to
|
|
126
|
+
32 trades, 90th percentile up to 217. Boundaries agree where flow is fast
|
|
127
|
+
and scatter where it is quiet, which is exactly where tick signs call window
|
|
128
|
+
direction wrong. The clock runs at nearly the right rate over the wrong
|
|
129
|
+
places. Anything you compute per bar is computed over a partition of the
|
|
130
|
+
stream that true signs would not have produced.
|
|
131
|
+
|
|
132
|
+
## BVC is one line of arithmetic
|
|
133
|
+
|
|
134
|
+

|
|
135
|
+
|
|
136
|
+
Bulk volume classification splits a bar's volume with Phi(dP / sigma), and
|
|
137
|
+
the literature has spent a decade disputing which sigma. The dispute never
|
|
138
|
+
touched the thing that matters: sigma is a positive scalar, so the sign of
|
|
139
|
+
Phi(dP / sigma) is always the sign of dP. BVC's directional content is
|
|
140
|
+
exactly the sign of the bar's price change. We scored both sigma
|
|
141
|
+
conventions; the wrong-direction rates are identical in every single row,
|
|
142
|
+
as the arithmetic says they must be.
|
|
143
|
+
|
|
144
|
+
That direction errs 14.90 to 30.76 percent on gold and up to 37.78 percent on
|
|
145
|
+
crude as bars grow from 1s to 5m, the opposite of the bar-size profile the
|
|
146
|
+
equities literature reports. BVC beats the tick rule only at 1-second bars
|
|
147
|
+
on crude, where the tick rule is weakest, and loses everywhere at 1m and
|
|
148
|
+
above, to a rule that is itself wrong a quarter of the time.
|
|
149
|
+
|
|
150
|
+
## The library
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
pip install tradesigns
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from tradesigns.rules import tick_rule, quote_rule, lee_ready, ground_truth
|
|
158
|
+
from tradesigns.score import accuracy, coverage
|
|
159
|
+
|
|
160
|
+
signs = tick_rule(trades) # Polars Series of +1 / -1, None where unclassified
|
|
161
|
+
truth = ground_truth(trades) # exchange flags: B -> +1, A -> -1, untagged -> None
|
|
162
|
+
print(accuracy(signs, truth)) # 0.8355 on the gold window, for example
|
|
163
|
+
print(coverage(signs, truth)) # both metrics exclude unclassified and untagged rows
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Also in the box: the imbalance engines (an adaptive twin of clockbars' rule
|
|
167
|
+
with the sign column exposed, plus an adaptation-free fixed-threshold
|
|
168
|
+
variant), and the scripts under `scripts/` that recompute every number and
|
|
169
|
+
figure in this README from the data. Nothing here is hand-copied;
|
|
170
|
+
`examples/make_figures.py` regenerates all three images. The bar engine is
|
|
171
|
+
asserted bit-identical to clockbars on every run, and the test suite pins
|
|
172
|
+
that parity on synthetic streams.
|
|
173
|
+
|
|
174
|
+
## The contract
|
|
175
|
+
|
|
176
|
+
- Strictly causal, and provably so: every rule and engine ships with a test
|
|
177
|
+
that mutates or appends future trades and asserts that no earlier sign or
|
|
178
|
+
boundary moved.
|
|
179
|
+
- 24 tests at 100 percent statement coverage, strict mypy, ruff clean, CI on
|
|
180
|
+
ubuntu and windows across Python 3.11 to 3.14.
|
|
181
|
+
- Licensed market data never enters the repository; the data ledger records
|
|
182
|
+
what was purchased and what it cost to the cent.
|
|
183
|
+
|
|
184
|
+
## Bottom line
|
|
185
|
+
|
|
186
|
+
If your feed carries the aggressor flag, use it and end the discussion. If
|
|
187
|
+
you can join quotes at the trade, the quote rule alone is near-perfect and
|
|
188
|
+
the Lee-Ready fallback only subtracts. If your quotes lag more than about a
|
|
189
|
+
second, or you have none, sign with the tick rule and be honest about it: 16
|
|
190
|
+
percent error on the index and gold products, 26 to 28 on crude, clustered
|
|
191
|
+
enough that independent-error statistics overstate your precision by an
|
|
192
|
+
order of magnitude. Do not use BVC where direction matters. And when you
|
|
193
|
+
build bars or buckets from classified signs, remember that the boundaries
|
|
194
|
+
themselves, not just the values inside them, are artifacts of the classifier
|
|
195
|
+
that signed them. The full story is in [docs/paper.md](docs/paper.md).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
tradesigns/__init__.py,sha256=o38r_vLlnrf7cqjmjXSSnKgOxhFOTJrHB-avEOtofxQ,99
|
|
2
|
+
tradesigns/bars.py,sha256=fbxuHbz-SGb8maQ5aopFaI1U1m9J_EvDxi7onJnMaco,5821
|
|
3
|
+
tradesigns/rules.py,sha256=NLaA1FKwbRi-fxbnWj7_3pjt4jUg37DvtH8jSV6mLyw,3347
|
|
4
|
+
tradesigns/score.py,sha256=hM1T9Ho61ksS0y9gZtnhGpjymuj1vphzU6zdIi04cZQ,1396
|
|
5
|
+
tradesigns-1.0.0.dist-info/METADATA,sha256=EFO0x9tteTPUIUoFDWUsiAj3vUf6MVDcZK2MS6L4Zhg,10178
|
|
6
|
+
tradesigns-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
tradesigns-1.0.0.dist-info/licenses/LICENSE,sha256=YFbNRVk36qT22u0PWVAYOooIuwUh9LXZgwoJHUWDNF8,1063
|
|
8
|
+
tradesigns-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zzionz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|