clockbars 0.1.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.
clockbars/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """clockbars — bars sampled on the market's own clock.
2
+
3
+ Converts a stream of trades into tick, volume, dollar, or time bars, using a
4
+ deterministic restart-from-zero rule with vectorised aggregation in Polars.
5
+
6
+ >>> import clockbars
7
+ >>> bars = clockbars.resample(trades, kind="dollar", threshold=1_000_000)
8
+
9
+ Two execution paths share that one rule: `resample` builds bars in batch
10
+ from a Polars frame, and `BarBuilder` builds the same bars one trade at a
11
+ time for live streams. A parity test asserts the two agree byte for byte,
12
+ session cuts included.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from clockbars.builder import Bar, BarBuilder, bars_to_frame
18
+ from clockbars.core import resample, validate_trades
19
+ from clockbars.synthetic import synthetic_ticks
20
+
21
+ __all__ = [
22
+ "Bar",
23
+ "BarBuilder",
24
+ "__version__",
25
+ "bars_to_frame",
26
+ "resample",
27
+ "synthetic_ticks",
28
+ "validate_trades",
29
+ ]
30
+
31
+ __version__ = "0.1.0"
clockbars/builder.py ADDED
@@ -0,0 +1,333 @@
1
+ """Incremental construction: the streaming twin of `resample()`.
2
+
3
+ Bar construction runs in two places — research, over a historical file, and
4
+ production, one trade at a time. This module is the production path, and the
5
+ parity test holds it to agreement with the batch path:
6
+
7
+ - **Exact** on everything that decides what a bar *is*: bar boundaries, bar_id,
8
+ timestamps, OHLC, n_trades, and the partial flag. Both paths cumulate the
9
+ metric left to right within a segment and close on the same comparison, so
10
+ they make identical closure decisions on identical floats.
11
+ - **Within float-summation order** (<= 1e-12 relative in practice) on per-bar
12
+ volume, notional, and vwap. A vectorised group sum and a sequential
13
+ accumulator sum the same numbers in different orders; pretending otherwise
14
+ would be a stronger claim than floating point can support.
15
+
16
+ Two limits inherited from Python datetimes, stated rather than hidden:
17
+ timestamps pushed into a builder carry microsecond resolution, and trades
18
+ finer than that belong in the batch path.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from collections.abc import Sequence
25
+ from dataclasses import dataclass
26
+ from datetime import UTC, datetime, timedelta
27
+
28
+ import numpy as np
29
+ import polars as pl
30
+
31
+ from clockbars.core import (
32
+ _ATOL,
33
+ _BAR_COLUMNS,
34
+ _check_threshold,
35
+ _interval_ns,
36
+ _utc_ns,
37
+ validate_trades,
38
+ )
39
+
40
+ _KINDS = ("tick", "volume", "dollar", "time")
41
+
42
+ _BARS_SCHEMA: dict[str, pl.DataType] = {
43
+ "bar_id": pl.Int64(),
44
+ "start_ts": pl.Datetime("ns", "UTC"),
45
+ "end_ts": pl.Datetime("ns", "UTC"),
46
+ "duration": pl.Duration("ns"),
47
+ "open": pl.Float64(),
48
+ "high": pl.Float64(),
49
+ "low": pl.Float64(),
50
+ "close": pl.Float64(),
51
+ "volume": pl.Float64(),
52
+ "notional": pl.Float64(),
53
+ "vwap": pl.Float64(),
54
+ # pl.len() in the batch path counts groups as UInt32; match it exactly.
55
+ "n_trades": pl.UInt32(),
56
+ "is_partial": pl.Boolean(),
57
+ }
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Bar:
62
+ """One completed bar, shaped like a row of `resample()`'s output."""
63
+
64
+ bar_id: int
65
+ start_ts: datetime
66
+ end_ts: datetime
67
+ duration: timedelta
68
+ open: float
69
+ high: float
70
+ low: float
71
+ close: float
72
+ volume: float
73
+ notional: float
74
+ vwap: float
75
+ n_trades: int
76
+ is_partial: bool
77
+
78
+
79
+ class BarBuilder:
80
+ """Build bars one trade at a time, under the same rule as `resample()`.
81
+
82
+ Parameters mirror `resample`: threshold kinds take `threshold`, time bars
83
+ take `every`. Pushes must arrive in non-decreasing timestamp order; a live
84
+ feed already guarantees that, and silently reordering would be a policy
85
+ decision this library does not make.
86
+
87
+ Call `close_session()` at a rollover to end the current accumulation —
88
+ the streaming counterpart of `session_starts` in the batch path. Call
89
+ `flush()` at the end of a stream (or any time you want the trailing bar)
90
+ to emit what is still open.
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ kind: str,
96
+ *,
97
+ threshold: float | None = None,
98
+ every: str | None = None,
99
+ ) -> None:
100
+ if kind not in _KINDS:
101
+ raise ValueError(f"unknown kind {kind!r}; expected one of {_KINDS}")
102
+ self._kind = kind
103
+
104
+ if kind == "time":
105
+ if every is None:
106
+ raise ValueError("kind='time' requires every=..., e.g. every='1m'")
107
+ if threshold is not None:
108
+ raise ValueError("kind='time' takes every=..., not threshold=")
109
+ self._interval = _interval_ns(every)
110
+ self._threshold = 0.0
111
+ else:
112
+ if threshold is None:
113
+ raise ValueError(f"kind={kind!r} requires threshold=")
114
+ if every is not None:
115
+ raise ValueError(f"kind={kind!r} takes threshold=..., not every=")
116
+ _check_threshold(threshold)
117
+ self._threshold = float(threshold)
118
+ self._interval = 0
119
+
120
+ # Segment state: the cumulative metric since the last session boundary.
121
+ self._seg_cum = 0.0
122
+ self._seg_fresh = True
123
+ self._bar_open_cum = 0.0
124
+
125
+ # Bar state.
126
+ self._bar_id = 0
127
+ self._n = 0
128
+ self._start_ts: datetime | None = None
129
+ self._end_ts: datetime | None = None
130
+ self._open = 0.0
131
+ self._high = 0.0
132
+ self._low = 0.0
133
+ self._close = 0.0
134
+ self._volume = 0.0
135
+ self._notional = 0.0
136
+ self._total = 0.0
137
+ self._window = 0
138
+ self._last_ts_ns: int | None = None
139
+
140
+ def push(self, ts: datetime, price: float, size: float) -> Bar | None:
141
+ """Add one trade; returns the bar it closed, if it closed one."""
142
+ moment = self._check_push(ts, price, size)
143
+ ts_ns = _utc_ns(moment)
144
+ if self._kind == "time":
145
+ return self._push_time(moment, ts_ns, price, size)
146
+ return self._push_threshold(moment, price, size)
147
+
148
+ def push_frame(self, trades: pl.DataFrame) -> list[Bar]:
149
+ """Push a whole frame in order. Convenience, not a fast path.
150
+
151
+ The frame goes through the same validation as `resample`, so a bad
152
+ column fails here too. Sub-microsecond timestamps are refused rather
153
+ than truncated, because a Python datetime cannot carry them.
154
+ """
155
+ frame = validate_trades(trades)
156
+ stamps = frame["ts"].dt.cast_time_unit("ns").cast(pl.Int64).to_numpy()
157
+ if stamps.size and np.any(stamps % 1_000 != 0):
158
+ raise ValueError(
159
+ "push_frame refuses sub-microsecond timestamps: a Python datetime "
160
+ "cannot carry them. Use the batch path (resample) for such data."
161
+ )
162
+ prices = frame["price"].to_numpy().astype(np.float64, copy=False)
163
+ sizes = frame["size"].to_numpy().astype(np.float64, copy=False)
164
+
165
+ bars: list[Bar] = []
166
+ epoch = datetime(1970, 1, 1, tzinfo=UTC)
167
+ for ts_ns, price, size in zip(
168
+ stamps.tolist(), prices.tolist(), sizes.tolist(), strict=True
169
+ ):
170
+ moment = epoch + timedelta(microseconds=ts_ns // 1_000)
171
+ if self._kind == "time":
172
+ bar = self._push_time(moment, int(ts_ns), price, size)
173
+ else:
174
+ self._check_push(moment, price, size)
175
+ bar = self._push_threshold(moment, price, size)
176
+ if bar is not None:
177
+ bars.append(bar)
178
+ return bars
179
+
180
+ def close_session(self) -> Bar | None:
181
+ """End the current accumulation, as a session rollover does.
182
+
183
+ The trailing bar is emitted, flagged partial if it fell short of the
184
+ threshold, and the next trade starts a fresh segment at zero.
185
+ """
186
+ if self._kind == "time":
187
+ raise ValueError(
188
+ "time bars are cut by the clock; close_session applies to threshold bars"
189
+ )
190
+ bar = None
191
+ if self._n > 0:
192
+ bar = self._emit(partial=self._total < self._threshold * (1.0 - _ATOL))
193
+ self._seg_cum = 0.0
194
+ self._seg_fresh = True
195
+ return bar
196
+
197
+ def flush(self) -> Bar | None:
198
+ """Emit the bar still open at the end of a stream, if there is one."""
199
+ if self._n == 0:
200
+ return None
201
+ if self._kind == "time":
202
+ return self._emit(partial=False)
203
+ return self._emit(partial=self._total < self._threshold * (1.0 - _ATOL))
204
+
205
+ # -- internals ----------------------------------------------------------
206
+
207
+ def _check_push(self, ts: datetime, price: float, size: float) -> datetime:
208
+ if not isinstance(ts, datetime):
209
+ raise TypeError(f"ts must be a datetime, got {type(ts).__name__}")
210
+ if ts.tzinfo is None:
211
+ raise ValueError("ts is timezone-naive; declare the zone before pushing")
212
+ if not math.isfinite(price) or not math.isfinite(size):
213
+ raise ValueError("price and size must be finite (no NaN or inf)")
214
+ if price <= 0 or size <= 0:
215
+ raise ValueError("price and size must be strictly positive")
216
+
217
+ moment = ts.astimezone(UTC)
218
+ ts_ns = _utc_ns(moment)
219
+ if self._last_ts_ns is not None and ts_ns < self._last_ts_ns:
220
+ raise ValueError("pushes must be non-decreasing in ts")
221
+ self._last_ts_ns = ts_ns
222
+ return moment
223
+
224
+ def _open_bar(self, moment: datetime, price: float, base_cum: float) -> None:
225
+ """Initialise an empty bar; the caller's update block adds the trade.
226
+
227
+ `high`/`low` start at infinities so the first max/min land correctly
228
+ for any positive price, and `_n` starts at zero so the increment in
229
+ the update block counts the opening trade exactly once.
230
+ """
231
+ self._n = 0
232
+ self._start_ts = moment
233
+ self._open = price
234
+ self._high = -math.inf
235
+ self._low = math.inf
236
+ self._volume = 0.0
237
+ self._notional = 0.0
238
+ self._bar_open_cum = base_cum
239
+
240
+ def _push_threshold(self, moment: datetime, price: float, size: float) -> Bar | None:
241
+ if self._kind == "tick":
242
+ metric = 1.0
243
+ elif self._kind == "volume":
244
+ metric = size
245
+ else:
246
+ metric = size * price
247
+
248
+ if self._seg_fresh:
249
+ self._seg_cum = metric
250
+ self._seg_fresh = False
251
+ else:
252
+ self._seg_cum += metric
253
+
254
+ if self._n == 0:
255
+ self._open_bar(moment, price, self._seg_cum - metric)
256
+
257
+ self._high = max(self._high, price)
258
+ self._low = min(self._low, price)
259
+ self._close = price
260
+ self._end_ts = moment
261
+ self._volume += size
262
+ self._notional += size * price
263
+ self._n += 1
264
+ self._total += metric
265
+
266
+ if self._seg_cum >= self._bar_open_cum + self._threshold:
267
+ return self._emit(partial=self._total < self._threshold * (1.0 - _ATOL))
268
+ return None
269
+
270
+ def _push_time(self, moment: datetime, ts_ns: int, price: float, size: float) -> Bar | None:
271
+ window = (ts_ns // self._interval) * self._interval
272
+ emitted: Bar | None = None
273
+ if self._n > 0 and window != self._window:
274
+ emitted = self._emit(partial=False)
275
+ if self._n == 0:
276
+ self._open_bar(moment, price, 0.0)
277
+ self._window = window
278
+ self._high = max(self._high, price)
279
+ self._low = min(self._low, price)
280
+ self._close = price
281
+ self._end_ts = moment
282
+ self._volume += size
283
+ self._notional += size * price
284
+ self._n += 1
285
+ return emitted
286
+
287
+ def _emit(self, *, partial: bool) -> Bar:
288
+ assert self._start_ts is not None and self._end_ts is not None
289
+ bar = Bar(
290
+ bar_id=self._bar_id,
291
+ start_ts=self._start_ts,
292
+ end_ts=self._end_ts,
293
+ duration=self._end_ts - self._start_ts,
294
+ open=self._open,
295
+ high=self._high,
296
+ low=self._low,
297
+ close=self._close,
298
+ volume=self._volume,
299
+ notional=self._notional,
300
+ vwap=self._notional / self._volume,
301
+ n_trades=self._n,
302
+ is_partial=partial,
303
+ )
304
+ self._bar_id += 1
305
+ self._n = 0
306
+ self._total = 0.0
307
+ self._start_ts = None
308
+ self._end_ts = None
309
+ return bar
310
+
311
+
312
+ def bars_to_frame(bars: Sequence[Bar]) -> pl.DataFrame:
313
+ """Collect bars into a frame with exactly `resample()`'s schema and dtypes."""
314
+ if not bars:
315
+ return pl.DataFrame(schema=_BARS_SCHEMA)
316
+ frame = pl.DataFrame(
317
+ {
318
+ "bar_id": pl.Series([b.bar_id for b in bars], dtype=pl.Int64),
319
+ "start_ts": pl.Series([b.start_ts for b in bars]).cast(pl.Datetime("ns", "UTC")),
320
+ "end_ts": pl.Series([b.end_ts for b in bars]).cast(pl.Datetime("ns", "UTC")),
321
+ "duration": pl.Series([b.duration for b in bars]).cast(pl.Duration("ns")),
322
+ "open": pl.Series([b.open for b in bars], dtype=pl.Float64),
323
+ "high": pl.Series([b.high for b in bars], dtype=pl.Float64),
324
+ "low": pl.Series([b.low for b in bars], dtype=pl.Float64),
325
+ "close": pl.Series([b.close for b in bars], dtype=pl.Float64),
326
+ "volume": pl.Series([b.volume for b in bars], dtype=pl.Float64),
327
+ "notional": pl.Series([b.notional for b in bars], dtype=pl.Float64),
328
+ "vwap": pl.Series([b.vwap for b in bars], dtype=pl.Float64),
329
+ "n_trades": pl.Series([b.n_trades for b in bars], dtype=pl.UInt32),
330
+ "is_partial": pl.Series([b.is_partial for b in bars], dtype=pl.Boolean),
331
+ }
332
+ )
333
+ return frame.select(_BAR_COLUMNS)
clockbars/core.py ADDED
@@ -0,0 +1,456 @@
1
+ """Core bar-construction engine.
2
+
3
+ The rule for every threshold bar type:
4
+
5
+ A bar closes on the trade that makes its running total reach or exceed the
6
+ threshold, and that trade is included in the closing bar. The next bar then
7
+ restarts from zero.
8
+
9
+ Consequences of that choice, both deliberate:
10
+
11
+ * A closed bar's total is always **at least** the threshold; it can exceed it
12
+ only by the size of its own final trade.
13
+ * Carry is *not* propagated between bars. If a bar overshoots, the next bar is
14
+ not short-changed to "make up" the difference — it starts fresh. (A global
15
+ cumulative-sum implementation would silently do exactly that, producing bars
16
+ below threshold in the middle of the series.)
17
+
18
+ Session cuts generalise the same idea one level up: pass `session_starts` and
19
+ accumulation restarts at each boundary, so a bar never straddles a rollover.
20
+ Time bars are cut by the clock instead, with windows aligned to the epoch via
21
+ integer floor division — the same arithmetic the streaming BarBuilder uses,
22
+ so the two paths cannot drift.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import math
28
+ import re
29
+ from collections.abc import Sequence
30
+ from datetime import UTC, datetime
31
+ from typing import Literal
32
+
33
+ import numpy as np
34
+ import polars as pl
35
+
36
+ BarKind = Literal["tick", "volume", "dollar", "time"]
37
+
38
+ _REQUIRED = ("ts", "price", "size")
39
+
40
+ _EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
41
+
42
+ _BAR_COLUMNS = [
43
+ "bar_id",
44
+ "start_ts",
45
+ "end_ts",
46
+ "duration",
47
+ "open",
48
+ "high",
49
+ "low",
50
+ "close",
51
+ "volume",
52
+ "notional",
53
+ "vwap",
54
+ "n_trades",
55
+ "is_partial",
56
+ ]
57
+
58
+ # Relative tolerance for float accumulation when deciding whether a bar hit its
59
+ # target. Sums of thousands of floats are not exact, and pretending otherwise
60
+ # produces phantom partial bars.
61
+ _ATOL = 1e-9
62
+
63
+ _INTERVAL_UNITS: dict[str, int] = {
64
+ "ns": 1,
65
+ "us": 1_000,
66
+ "ms": 1_000_000,
67
+ "s": 1_000_000_000,
68
+ "m": 60 * 1_000_000_000,
69
+ "h": 3_600 * 1_000_000_000,
70
+ "d": 86_400 * 1_000_000_000,
71
+ "w": 604_800 * 1_000_000_000,
72
+ }
73
+
74
+ _INTERVAL_RE = re.compile(r"(\d+)(ns|us|ms|s|m|h|d|w)")
75
+
76
+
77
+ def _coerce(trades: object) -> pl.DataFrame:
78
+ """Accept a Polars frame, or a pandas frame if pandas happens to be installed."""
79
+ if isinstance(trades, pl.DataFrame):
80
+ return trades
81
+ try: # pragma: no cover - only exercised when pandas is present
82
+ import pandas as pd
83
+ except ImportError:
84
+ raise TypeError(
85
+ f"expected a polars.DataFrame, got {type(trades).__name__}"
86
+ ) from None
87
+ if isinstance(trades, pd.DataFrame):
88
+ return pl.from_pandas(trades)
89
+ raise TypeError(f"expected a polars.DataFrame, got {type(trades).__name__}")
90
+
91
+
92
+ def validate_trades(trades: pl.DataFrame) -> pl.DataFrame:
93
+ """Validate and normalise a trades frame.
94
+
95
+ Requires columns ``ts``, ``price``, ``size``. ``ts`` must be a timezone-aware
96
+ datetime and is normalised to ``Datetime("ns", "UTC")``. Rows must be sorted
97
+ ascending by ``ts``; duplicate timestamps are allowed and keep input order.
98
+ """
99
+ trades = _coerce(trades)
100
+
101
+ missing = [name for name in _REQUIRED if name not in trades.columns]
102
+ if missing:
103
+ raise ValueError(f"trades is missing required column(s): {', '.join(missing)}")
104
+ if trades.height == 0:
105
+ raise ValueError("trades is empty")
106
+
107
+ dtype = trades.schema["ts"]
108
+ if not isinstance(dtype, pl.Datetime):
109
+ raise TypeError(f"'ts' must be a Datetime column, got {dtype}")
110
+ if dtype.time_zone is None:
111
+ raise ValueError(
112
+ "'ts' is timezone-naive; trading timestamps must be explicit. "
113
+ 'Use .dt.replace_time_zone("UTC") on a known-UTC column.'
114
+ )
115
+
116
+ if dtype.time_unit != "ns":
117
+ trades = trades.with_columns(pl.col("ts").dt.cast_time_unit("ns"))
118
+ if dtype.time_zone != "UTC":
119
+ trades = trades.with_columns(pl.col("ts").dt.convert_time_zone("UTC"))
120
+
121
+ if trades.select(list(_REQUIRED)).null_count().to_numpy().sum() > 0:
122
+ raise ValueError("trades contains null values in ts/price/size")
123
+ if not trades["ts"].is_sorted():
124
+ raise ValueError("'ts' must be sorted ascending")
125
+
126
+ # NaN and inf compare False against everything, so `column <= 0` alone
127
+ # would let them through. Check finiteness first, then sign.
128
+ for name in ("price", "size"):
129
+ column = trades[name]
130
+ if trades.schema[name].is_float() and not column.is_finite().all():
131
+ raise ValueError(f"'{name}' must be finite (no NaN or inf)")
132
+ if (column <= 0).any():
133
+ raise ValueError(f"'{name}' must be strictly positive")
134
+
135
+ return trades
136
+
137
+
138
+ def _check_threshold(threshold: float) -> None:
139
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)):
140
+ raise TypeError(f"threshold must be a number, got {type(threshold).__name__}")
141
+ if not math.isfinite(threshold):
142
+ raise ValueError(f"threshold must be finite, got {threshold}")
143
+ if threshold <= 0:
144
+ raise ValueError(f"threshold must be positive, got {threshold}")
145
+
146
+
147
+ def _interval_ns(every: str) -> int:
148
+ """Parse a duration string into nanoseconds.
149
+
150
+ Accepts single units (``"5m"``, ``"1h"``) and compounds (``"1h30m"``), summed
151
+ left to right. Index windows (``"1i"``) are meaningless for a datetime
152
+ column and are rejected here rather than by a downstream library whose
153
+ grammar may differ.
154
+ """
155
+ if not isinstance(every, str):
156
+ raise TypeError(
157
+ f"'every' must be a duration string like '5m', got {type(every).__name__}"
158
+ )
159
+ position, total = 0, 0
160
+ while position < len(every):
161
+ match = _INTERVAL_RE.match(every, position)
162
+ if match is None:
163
+ raise ValueError(
164
+ f"could not parse interval {every!r}; expected a form like '5m' or '1h30m'"
165
+ )
166
+ total += int(match.group(1)) * _INTERVAL_UNITS[match.group(2)]
167
+ position = match.end()
168
+ if total <= 0:
169
+ raise ValueError(f"interval must be positive, got {every!r}")
170
+ return total
171
+
172
+
173
+ def _utc_ns(moment: datetime) -> int:
174
+ """Whole nanoseconds since the epoch, in exact integer arithmetic."""
175
+ delta = moment - _EPOCH
176
+ return ((delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds) * 1_000
177
+
178
+
179
+ def _session_starts_ns(session_starts: pl.Series | Sequence[datetime]) -> np.ndarray:
180
+ """Normalise user-supplied session boundaries to sorted, deduped UTC nanoseconds."""
181
+ if isinstance(session_starts, pl.Series):
182
+ dtype = session_starts.dtype
183
+ if not isinstance(dtype, pl.Datetime):
184
+ raise TypeError(f"session_starts must be a Datetime series, got {dtype}")
185
+ if dtype.time_zone is None:
186
+ raise ValueError(
187
+ "session_starts is timezone-naive; boundaries must carry an explicit zone"
188
+ )
189
+ values = (
190
+ session_starts.dt.convert_time_zone("UTC")
191
+ .dt.cast_time_unit("ns")
192
+ .cast(pl.Int64)
193
+ .to_numpy()
194
+ )
195
+ elif isinstance(session_starts, str):
196
+ raise TypeError("session_starts must be a Series or a sequence of datetimes")
197
+ else:
198
+ moments = list(session_starts)
199
+ values = np.empty(len(moments), dtype=np.int64)
200
+ for i, moment in enumerate(moments):
201
+ if not isinstance(moment, datetime):
202
+ raise TypeError(
203
+ f"session_starts entries must be datetime, got {type(moment).__name__}"
204
+ )
205
+ if moment.tzinfo is None:
206
+ raise ValueError(
207
+ "session_starts entries must be timezone-aware, got a naive datetime"
208
+ )
209
+ values[i] = _utc_ns(moment.astimezone(UTC))
210
+
211
+ if values.size == 0:
212
+ raise ValueError("session_starts is empty; pass None when no cuts are wanted")
213
+ if values.size > 1 and not np.all(np.diff(values) >= 0):
214
+ raise ValueError("session_starts must be sorted ascending")
215
+ return np.unique(values)
216
+
217
+
218
+ def _segment_start_indices(ts_ns: np.ndarray, starts_ns: np.ndarray) -> np.ndarray:
219
+ """Indices where a new session begins; index 0 always starts a segment.
220
+
221
+ A trade exactly on a boundary belongs to the new session.
222
+ """
223
+ segment_ids = np.searchsorted(starts_ns, ts_ns, side="right")
224
+ flags = np.empty(ts_ns.size, dtype=bool)
225
+ flags[0] = True
226
+ flags[1:] = segment_ids[1:] != segment_ids[:-1]
227
+ return np.flatnonzero(flags)
228
+
229
+
230
+ def _metric_expr(kind: str) -> pl.Expr:
231
+ """The quantity accumulated toward the threshold, as a Polars expression."""
232
+ if kind == "tick":
233
+ return pl.lit(1.0).alias("_metric")
234
+ if kind == "volume":
235
+ return pl.col("size").cast(pl.Float64).alias("_metric")
236
+ if kind == "dollar":
237
+ return (pl.col("size").cast(pl.Float64) * pl.col("price")).alias("_metric")
238
+ raise ValueError(f"unknown bar kind: {kind!r}")
239
+
240
+
241
+ def _metric_values(df: pl.DataFrame, kind: str) -> np.ndarray:
242
+ """The same quantity, as a numpy array, for the segmentation pass."""
243
+ if kind == "tick":
244
+ return np.ones(df.height, dtype=np.float64)
245
+ size = df["size"].to_numpy().astype(np.float64, copy=False)
246
+ if kind == "volume":
247
+ return size
248
+ price = df["price"].to_numpy().astype(np.float64, copy=False)
249
+ return size * price
250
+
251
+
252
+ def _bar_bounds(metric: np.ndarray, threshold: float) -> list[int]:
253
+ """Start index of each bar under the restart-from-zero rule.
254
+
255
+ Each bar runs from its start index up to and including the first trade whose
256
+ running total (measured from that start) reaches ``threshold``.
257
+
258
+ This is a linear scan over *bars*, not trades: ``O(n_bars * log n_trades)``.
259
+ With a realistic threshold there are far fewer bars than trades, and a tick
260
+ threshold of 1 degrades to one trade per bar, which is the expected answer.
261
+ """
262
+ cumulative = np.cumsum(metric)
263
+ total = float(cumulative[-1])
264
+ bounds = [0]
265
+ start = 0
266
+
267
+ while start < metric.size:
268
+ base = float(cumulative[start - 1]) if start else 0.0
269
+ target = base + threshold
270
+ if target > total:
271
+ break
272
+ # First index at or after `start` whose cumulative total reaches target.
273
+ end = int(np.searchsorted(cumulative, target, side="left"))
274
+ start = end + 1
275
+ if start < metric.size:
276
+ bounds.append(start)
277
+
278
+ return bounds
279
+
280
+
281
+ def _aggregate(df: pl.DataFrame, threshold: float | None) -> pl.DataFrame:
282
+ bars = (
283
+ df.group_by("bar_id", maintain_order=True)
284
+ .agg(
285
+ pl.col("ts").first().alias("start_ts"),
286
+ pl.col("ts").last().alias("end_ts"),
287
+ pl.col("price").first().alias("open"),
288
+ pl.col("price").max().alias("high"),
289
+ pl.col("price").min().alias("low"),
290
+ pl.col("price").last().alias("close"),
291
+ pl.col("size").sum().alias("volume"),
292
+ (pl.col("size").cast(pl.Float64) * pl.col("price"))
293
+ .sum()
294
+ .alias("notional"),
295
+ pl.col("_metric").sum().alias("_target"),
296
+ pl.len().alias("n_trades"),
297
+ )
298
+ .sort("bar_id")
299
+ )
300
+
301
+ partial = (
302
+ pl.lit(False)
303
+ if threshold is None
304
+ else pl.col("_target") < threshold * (1.0 - _ATOL)
305
+ )
306
+
307
+ bars = bars.with_columns(
308
+ (pl.col("end_ts") - pl.col("start_ts")).alias("duration"),
309
+ (pl.col("notional") / pl.col("volume")).alias("vwap"),
310
+ partial.alias("is_partial"),
311
+ )
312
+
313
+ return bars.select(_BAR_COLUMNS)
314
+
315
+
316
+ def _threshold_bars(
317
+ trades: pl.DataFrame,
318
+ kind: str,
319
+ threshold: float,
320
+ session_starts: pl.Series | Sequence[datetime] | None,
321
+ ) -> pl.DataFrame:
322
+ _check_threshold(threshold)
323
+ trades = validate_trades(trades)
324
+
325
+ metric = _metric_values(trades, kind)
326
+ if session_starts is None:
327
+ segment_indices = np.array([0], dtype=np.int64)
328
+ else:
329
+ starts_ns = _session_starts_ns(session_starts)
330
+ ts_ns = trades["ts"].dt.cast_time_unit("ns").cast(pl.Int64).to_numpy()
331
+ segment_indices = _segment_start_indices(ts_ns, starts_ns)
332
+
333
+ n = metric.size
334
+ bar_starts: list[int] = []
335
+ for i in range(segment_indices.size):
336
+ begin = int(segment_indices[i])
337
+ end = int(segment_indices[i + 1]) if i + 1 < segment_indices.size else n
338
+ bar_starts.extend(begin + b for b in _bar_bounds(metric[begin:end], float(threshold)))
339
+
340
+ lengths = np.diff(np.append(np.asarray(bar_starts, dtype=np.int64), n))
341
+ bar_ids = np.repeat(np.arange(len(bar_starts), dtype=np.int64), lengths)
342
+
343
+ labelled = trades.with_columns(
344
+ _metric_expr(kind),
345
+ pl.Series("bar_id", bar_ids, dtype=pl.Int64),
346
+ )
347
+ return _aggregate(labelled, float(threshold))
348
+
349
+
350
+ def _time_bars(trades: pl.DataFrame, every: str) -> pl.DataFrame:
351
+ trades = validate_trades(trades)
352
+ interval = _interval_ns(every)
353
+
354
+ # Epoch-aligned windows via integer floor division: the same arithmetic
355
+ # BarBuilder uses one trade at a time, so the two paths cannot disagree
356
+ # about where a window starts. A window with no trades never exists.
357
+ window = (pl.col("ts").dt.cast_time_unit("ns").cast(pl.Int64) // interval) * interval
358
+ bars = (
359
+ trades.with_columns(window.alias("_window"))
360
+ .group_by("_window", maintain_order=True)
361
+ .agg(
362
+ pl.col("ts").first().alias("start_ts"),
363
+ pl.col("ts").last().alias("end_ts"),
364
+ pl.col("price").first().alias("open"),
365
+ pl.col("price").max().alias("high"),
366
+ pl.col("price").min().alias("low"),
367
+ pl.col("price").last().alias("close"),
368
+ pl.col("size").sum().alias("volume"),
369
+ (pl.col("size").cast(pl.Float64) * pl.col("price"))
370
+ .sum()
371
+ .alias("notional"),
372
+ pl.len().alias("n_trades"),
373
+ )
374
+ .sort("_window")
375
+ )
376
+
377
+ bars = bars.with_columns(
378
+ pl.int_range(pl.len()).alias("bar_id"),
379
+ (pl.col("end_ts") - pl.col("start_ts")).alias("duration"),
380
+ (pl.col("notional") / pl.col("volume")).alias("vwap"),
381
+ pl.lit(False).alias("is_partial"),
382
+ )
383
+
384
+ return bars.select(_BAR_COLUMNS)
385
+
386
+
387
+ def resample(
388
+ trades: pl.DataFrame,
389
+ kind: BarKind = "dollar",
390
+ *,
391
+ threshold: float | None = None,
392
+ every: str | None = None,
393
+ session_starts: pl.Series | Sequence[datetime] | None = None,
394
+ ) -> pl.DataFrame:
395
+ """Build bars from a trades frame.
396
+
397
+ Parameters
398
+ ----------
399
+ trades
400
+ Frame with ``ts`` (timezone-aware datetime), ``price``, ``size``.
401
+ Must be sorted ascending by ``ts``.
402
+ kind
403
+ ``"tick"``, ``"volume"``, ``"dollar"``, or ``"time"``.
404
+ threshold
405
+ Accumulated quantity that closes a bar. Required for ``tick`` (number of
406
+ trades), ``volume`` (units), and ``dollar`` (quote-currency notional).
407
+ For ``tick`` the threshold is effectively rounded up: a threshold of
408
+ 2.5 closes bars of 3 trades, because a bar closes when the count
409
+ *reaches* the threshold.
410
+ every
411
+ Window for ``kind="time"``, e.g. ``"5m"``, ``"1h"``, ``"1h30m"``.
412
+ Windows are half-open ``[start, start + every)`` and aligned to
413
+ wall-clock boundaries, so a 1-minute window starting at 09:30:30 still
414
+ begins at 09:30:00.
415
+ session_starts
416
+ Session boundary timestamps (timezone-aware, ascending). Threshold bars
417
+ restart accumulation at each boundary, so a bar never straddles a
418
+ rollover, and a trade exactly on a boundary belongs to the new session.
419
+ Each session's final bar carries ``is_partial=True`` if it fell short of
420
+ the threshold. Time bars need no cuts — the clock already makes them —
421
+ and passing both raises rather than guessing a precedence.
422
+
423
+ Returns
424
+ -------
425
+ polars.DataFrame
426
+ Columns: ``bar_id``, ``start_ts``, ``end_ts``, ``duration``, ``open``,
427
+ ``high``, ``low``, ``close``, ``volume``, ``notional``, ``vwap``,
428
+ ``n_trades``, ``is_partial``.
429
+
430
+ Notes
431
+ -----
432
+ ``is_partial`` is ``True`` for a bar whose segment ended before it filled —
433
+ the end of the stream, or the end of a session. Time bars never set it,
434
+ because a time window has no volume target to miss.
435
+ """
436
+ if kind == "time":
437
+ if every is None:
438
+ raise ValueError("kind='time' requires every=..., e.g. every='1m'")
439
+ if threshold is not None:
440
+ raise ValueError("kind='time' takes every=..., not threshold=")
441
+ if session_starts is not None:
442
+ raise ValueError(
443
+ "kind='time' takes no session_starts: the clock already cuts time bars"
444
+ )
445
+ return _time_bars(trades, every)
446
+
447
+ if kind not in ("tick", "volume", "dollar"):
448
+ raise ValueError(
449
+ f"unknown kind {kind!r}; expected 'tick', 'volume', 'dollar', or 'time'"
450
+ )
451
+ if threshold is None:
452
+ raise ValueError(f"kind={kind!r} requires threshold=")
453
+ if every is not None:
454
+ raise ValueError(f"kind={kind!r} takes threshold=..., not every=")
455
+
456
+ return _threshold_bars(trades, kind, threshold, session_starts)
clockbars/py.typed ADDED
@@ -0,0 +1 @@
1
+ """PEP 561 marker: this package ships inline type information."""
clockbars/synthetic.py ADDED
@@ -0,0 +1,142 @@
1
+ """Deterministic synthetic trade data.
2
+
3
+ Real trade data is licensed and large, so the examples and tests here run on a
4
+ generated stream with a realistic *shape* rather than licensed content:
5
+
6
+ - one session per business day, starting from ``start_date``;
7
+ - a U-shaped arrival pattern across each session;
8
+ - trade sizes that cluster at the open and the close;
9
+ - per-trade volatility that scales with trade size, so volume and volatility
10
+ move together the way they do in real markets.
11
+
12
+ Timestamps are truncated to whole seconds, so a generated stream contains
13
+ duplicate timestamps by construction — which is also a deliberate exercise of
14
+ the library's duplicate-timestamp path. Nothing here predicts or resembles any
15
+ actual market; it exists so every figure and number in the documentation can be
16
+ reproduced from a seed.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import numpy as np
22
+ import polars as pl
23
+
24
+ __all__ = ["synthetic_ticks"]
25
+
26
+ _SESSION_OPEN_UTC_MIN = 14 * 60 + 30 # 09:30 America/New_York, standard time
27
+ _SESSION_MINUTES = 390
28
+
29
+
30
+ def _session_dates(start_date: str, n_sessions: int) -> np.ndarray:
31
+ """First `n_sessions` business days on or after `start_date`.
32
+
33
+ Dates are unique and never weekend days, whatever `n_sessions` is. An
34
+ earlier version hardcoded ten offsets, which silently interleaved two
35
+ sessions into the same day (with duplicated timestamps) as soon as anyone
36
+ asked for more than ten sessions.
37
+ """
38
+ day = np.datetime64(start_date, "D")
39
+ dates: list[np.datetime64] = []
40
+ while len(dates) < n_sessions:
41
+ if np.is_busday(day):
42
+ dates.append(day)
43
+ day = day + np.timedelta64(1, "D")
44
+ return np.asarray(dates, dtype="datetime64[D]")
45
+
46
+
47
+ def _intraday_fraction(rng: np.random.Generator, n: int) -> np.ndarray:
48
+ """U-shaped position within the session, as a fraction in [0, 1)."""
49
+ weight_open = rng.random(n)
50
+ shape = rng.random(n)
51
+ opening = rng.beta(0.8, 3.2, n)
52
+ closing = 1.0 - rng.beta(0.8, 3.2, n)
53
+ uniform = rng.random(n)
54
+
55
+ return np.where(
56
+ weight_open < 0.40,
57
+ opening,
58
+ np.where(shape < 0.60, closing, uniform),
59
+ )
60
+
61
+
62
+ def synthetic_ticks(
63
+ n_trades: int = 200_000,
64
+ *,
65
+ seed: int = 7,
66
+ start_price: float = 5000.0,
67
+ tick_size: float = 0.25,
68
+ n_sessions: int = 10,
69
+ base_sigma: float = 2.0e-5,
70
+ start_date: str = "2019-01-02",
71
+ ) -> pl.DataFrame:
72
+ """Generate reproducible synthetic trades.
73
+
74
+ Parameters
75
+ ----------
76
+ n_trades
77
+ Approximate total number of trades across all sessions.
78
+ seed
79
+ Seed for ``numpy.random.default_rng``; output is bit-for-bit stable.
80
+ start_price
81
+ Price of the first trade.
82
+ tick_size
83
+ All prices are rounded to this grid.
84
+ n_sessions
85
+ Number of trading sessions to spread the trades across (weekdays).
86
+ base_sigma
87
+ Per-trade log-return scale before size scaling.
88
+ start_date
89
+ First session date, ``YYYY-MM-DD``.
90
+
91
+ Returns
92
+ -------
93
+ polars.DataFrame
94
+ ``ts`` (``Datetime("ns", "UTC")``), ``price``, ``size``.
95
+ """
96
+ if n_trades <= 0:
97
+ raise ValueError("n_trades must be positive")
98
+ if n_sessions <= 0:
99
+ raise ValueError("n_sessions must be positive")
100
+
101
+ rng = np.random.default_rng(seed)
102
+ per_session = int(np.ceil(n_trades / n_sessions))
103
+ dates = _session_dates(start_date, n_sessions)
104
+
105
+ ts_parts: list[np.ndarray] = []
106
+ size_parts: list[np.ndarray] = []
107
+ for session in range(n_sessions):
108
+ frac = _intraday_fraction(rng, per_session)
109
+ minutes = _SESSION_OPEN_UTC_MIN + frac * _SESSION_MINUTES
110
+ seconds = (minutes * 60.0).astype("int64")
111
+ ts_parts.append(
112
+ dates[session].astype("datetime64[s]") + seconds.astype("timedelta64[s]")
113
+ )
114
+
115
+ # Size clustering: fatter trades at the open and the close.
116
+ edge_weight = 1.0 + 5.0 * np.abs(frac - 0.5)
117
+ size_parts.append(np.exp(rng.normal(0.0, 0.7, per_session)) * edge_weight)
118
+
119
+ ts = np.concatenate(ts_parts)
120
+ size = np.concatenate(size_parts)
121
+
122
+ order = np.argsort(ts, kind="stable")
123
+ ts, size = ts[order], size[order]
124
+
125
+ # Volatility scales with trade size, giving the volume/volatility link that
126
+ # makes dollar bars meaningfully different from time bars.
127
+ scale = size / size.mean()
128
+ sigma = base_sigma * np.sqrt(scale)
129
+ log_returns = rng.normal(0.0, 1.0, ts.size) * sigma
130
+ price = start_price * np.exp(np.cumsum(log_returns))
131
+ price = np.round(price / tick_size) * tick_size
132
+ price = np.maximum(price, tick_size)
133
+
134
+ return pl.DataFrame(
135
+ {
136
+ "ts": pl.Series(ts.astype("datetime64[ns]"))
137
+ .cast(pl.Datetime("ns"))
138
+ .dt.replace_time_zone("UTC"),
139
+ "price": pl.Series(price, dtype=pl.Float64),
140
+ "size": pl.Series(np.round(size, 4), dtype=pl.Float64),
141
+ }
142
+ ).sort("ts")
@@ -0,0 +1,331 @@
1
+ Metadata-Version: 2.5
2
+ Name: clockbars
3
+ Version: 0.1.0
4
+ Summary: Bars sampled on the market's own clock: tick, volume, and dollar bars in Polars, batch and streaming with proven parity.
5
+ Project-URL: Homepage, https://github.com/zzionz/clockbars
6
+ Project-URL: Issues, https://github.com/zzionz/clockbars/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: dev
26
+ Requires-Dist: matplotlib>=3.8; extra == 'dev'
27
+ Requires-Dist: mypy>=1.11; extra == 'dev'
28
+ Requires-Dist: pandas-stubs>=2.2; extra == 'dev'
29
+ Requires-Dist: pandas>=2.0; extra == 'dev'
30
+ Requires-Dist: pyarrow>=15; extra == 'dev'
31
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
32
+ Requires-Dist: pytest>=8.0; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # clockbars
37
+
38
+ **Bars sampled on the market's own clock.** Tick, volume, and dollar bars in
39
+ Polars — one explicit rule, two execution paths, and a test suite that holds
40
+ both to the same contract.
41
+
42
+ [![CI](https://github.com/zzionz/clockbars/actions/workflows/ci.yml/badge.svg)](https://github.com/zzionz/clockbars/actions/workflows/ci.yml)
43
+ ![Python](https://img.shields.io/badge/python-3.11%2B-blue)
44
+ ![Typed](https://img.shields.io/badge/typing-mypy_strict-blue)
45
+ ![License](https://img.shields.io/badge/license-MIT-green)
46
+
47
+ ---
48
+
49
+ Most people build bars by clock: take all the trades in each minute and call it
50
+ a bar. The problem is that markets don't produce information at a constant
51
+ rate. The first and last half hour of a session carry several times the volume
52
+ of midday, so a 1-minute bar at 09:31 and a 1-minute bar at 12:31 contain wildly
53
+ different amounts of trading, while downstream code treats them as
54
+ interchangeable. The result is a series with uneven information content per
55
+ observation, and every statistic computed on it inherits that unevenness.
56
+
57
+ Sampling by activity instead of clock is an old idea. Mandelbrot and Taylor
58
+ noted in 1967 that price changes over a fixed number of transactions behave
59
+ far better than price changes over fixed time; Clark's 1973 model treated
60
+ volume as the clock; Easley, López de Prado, and O'Hara built a whole
61
+ microstructure framework on "volume buckets."
62
+
63
+ This problem has existing software — see [Related work](#related-work). What
64
+ none of it offers is a Polars-native path: one call from `DataFrame` to
65
+ `DataFrame` with a fixed schema, ready to drop into a pipeline that already
66
+ speaks Polars. That is the gap this fills, and two properties come with it
67
+ that the free ecosystem currently lacks: a streaming builder that provably
68
+ produces the same bars as the batch path, and session-aware construction so a
69
+ bar never straddles an exchange close.
70
+
71
+ ![Time bars vs dollar bars](docs/hero.png)
72
+
73
+ Same 400,000-trade synthetic stream, 20 sessions. Top row: volume per bar is a
74
+ long right tail for time bars and a spike for dollar bars. Bottom row: across a
75
+ single session, time-bar volume traces the intraday U while dollar bars stay
76
+ flat. The stream is synthetic (seeded, reproducible) because trade data is
77
+ licensed; the mechanism being demonstrated is real.
78
+
79
+ ## Install
80
+
81
+ Not on PyPI yet — install from source:
82
+
83
+ ```bash
84
+ pip install git+https://github.com/zzionz/clockbars.git
85
+ ```
86
+
87
+ For development:
88
+
89
+ ```bash
90
+ git clone https://github.com/zzionz/clockbars.git
91
+ cd clockbars
92
+ uv sync --all-extras
93
+ uv run pytest -q # 171 passed, 100% coverage enforced
94
+ ```
95
+
96
+ CI runs the full gate set on every push: ruff, strict mypy, and the test
97
+ suite with coverage required at 100% — on Ubuntu and Windows across Python
98
+ 3.11–3.14. The package ships a `py.typed` marker, so if you use clockbars
99
+ under mypy you get its types, not `Any`.
100
+
101
+ ## Quickstart
102
+
103
+ ```python
104
+ import polars as pl
105
+ from clockbars import resample
106
+
107
+ trades = pl.read_parquet("trades.parquet") # ts, price, size — sorted by ts
108
+
109
+ dollar = resample(trades, kind="dollar", threshold=1_000_000)
110
+ volume = resample(trades, kind="volume", threshold=500)
111
+ ticks = resample(trades, kind="tick", threshold=250)
112
+ minute = resample(trades, kind="time", every="1m")
113
+ ```
114
+
115
+ The same stream can be cut so that no bar straddles a session boundary —
116
+ pass the rollover times and accumulation restarts at each one:
117
+
118
+ ```python
119
+ from datetime import datetime, timezone
120
+
121
+ rollovers = pl.Series([datetime(2026, 1, 6, 23, 0, tzinfo=timezone.utc)])
122
+
123
+ # A dollar bar never spans the overnight close, and every session's final
124
+ # bar is flagged partial if it fell short of the threshold.
125
+ daily = resample(trades, kind="dollar", threshold=1_000_000,
126
+ session_starts=rollovers)
127
+ ```
128
+
129
+ And the same rule runs one trade at a time, for live streams:
130
+
131
+ ```python
132
+ from clockbars import BarBuilder
133
+
134
+ builder = BarBuilder(kind="dollar", threshold=1_000_000)
135
+ for ts, price, size in feed:
136
+ bar = builder.push(ts, price, size) # completed bar, or None
137
+ if bar is not None:
138
+ emit(bar)
139
+
140
+ trailing = builder.flush() # the final partial bar
141
+ ```
142
+
143
+ A parity test asserts that `BarBuilder` over the batch input agrees with
144
+ `resample` on everything that decides what a bar *is* — boundaries, ids,
145
+ timestamps, OHLC, counts, partial flags — at 200,000 trades, for all four
146
+ kinds, session cuts included. Per-bar volume and notional agree to within
147
+ float-summation order (≤ 1e-12 relative): a vectorised group sum and a
148
+ sequential accumulator sum the same numbers in different orders, and
149
+ claiming bit-equality there would be a claim floating point cannot support.
150
+ The bar your backtest computed and the bar your live process computed are
151
+ the same object, or you find out in a test, not in production.
152
+
153
+ All four kinds return the same schema, so nothing downstream has to branch on
154
+ how the bars were made:
155
+
156
+ | Column | Meaning |
157
+ | :--- | :--- |
158
+ | `bar_id` | zero-based bar index |
159
+ | `start_ts`, `end_ts` | first and last trade timestamp in the bar |
160
+ | `duration` | `end_ts - start_ts` |
161
+ | `open`, `high`, `low`, `close` | first price, max, min, last price |
162
+ | `volume` | units traded |
163
+ | `notional` | price × size summed |
164
+ | `vwap` | `notional / volume` |
165
+ | `n_trades` | trade count |
166
+ | `is_partial` | `True` only if the bar fell short of its threshold |
167
+
168
+ ## The rule, and the decisions inside it
169
+
170
+ A bar closes on the trade that pushes its running total to the threshold, and
171
+ that trade is included in the closing bar. Each bar then restarts from zero.
172
+ Everything else follows:
173
+
174
+ 1. **A closed bar's total is always at least its threshold.** It can overshoot,
175
+ but only by the size of its own final trade.
176
+ 2. **Overshoot does not leak into the next bar.** This is a deliberate choice.
177
+ A global cumulative sum — the "obvious" vectorised implementation — charges
178
+ each bar's overshoot to the *following* bar, which then closes below
179
+ threshold in the middle of the series. Bar 0 of a 128-bar run reached
180
+ threshold; bar 1, docked 50 units for bar 0's overshoot, closed at 200 with a
181
+ threshold of 250. Restarting from zero makes every bar answerable on its own.
182
+ `test_overshoot_is_not_carried_into_the_next_bar` pins this.
183
+ 3. **The final bar of any segment is kept, flagged, and never dropped.**
184
+ `is_partial=True` means "the segment ended before this bar filled" — the
185
+ end of the stream, or the end of a session. Without session cuts there is
186
+ one segment, so only the last bar can be partial. Throwing a partial bar
187
+ away would silently rewrite history.
188
+ 4. **Naive timestamps are rejected.** If your data says 14:30 with no time
189
+ zone, no guessing happens; you get an error telling you to declare the
190
+ zone. Silently assuming UTC is how a DST bug gets born.
191
+ 5. **NaN and inf are rejected before they can look like data.** In
192
+ floating-point comparison, `NaN <= 0` is `False`, so a sign check alone
193
+ accepts NaN — and one NaN price poisons every bar after it. Finiteness is
194
+ checked separately from sign.
195
+ 6. **Threshold comparisons carry a `1e-9` relative tolerance.** Summing a few
196
+ thousand floats lands on `499.9999999999999` more often than anyone wants
197
+ to admit. Without the tolerance, those are phantom partial bars.
198
+ 7. **Duplicate timestamps are fine.** Trades share timestamps in real data;
199
+ input order is preserved within a bar, so `open`/`close` are stable.
200
+ 8. **Input must be sorted.** Unsorted input is an error, not a silent
201
+ `sort()`. Sorting implicitly is a policy decision about your data, and it
202
+ is not this library's to make.
203
+
204
+ Time bars follow the same schema with `is_partial` always `False`. Windows
205
+ are half-open `[start, start + every)` and align to wall-clock boundaries: a
206
+ frame that begins at 09:30:30 still produces windows that begin on the minute.
207
+ Empty windows are not emitted. Session cuts do not apply to time bars — the
208
+ clock already cuts them — and passing both raises rather than guessing which
209
+ rule wins.
210
+
211
+ ## What the tests actually check
212
+
213
+ Not "the code runs" — the properties that make the output trustworthy:
214
+
215
+ - volume, notional, and trade counts are conserved exactly across bars;
216
+ - bars are chronological and non-overlapping, with `bar_id` contiguous from zero;
217
+ - every closed bar meets its threshold, and overshoots by at most one trade;
218
+ - only the final bar of a segment can be partial, and the flag agrees with the
219
+ bar's own total;
220
+ - OHLC and VWAP are internally consistent (`low ≤ vwap ≤ high`);
221
+ - identical input yields identical output;
222
+ - bars never straddle a session boundary, with the boundary trade going to
223
+ the new session;
224
+ - the streaming `BarBuilder` matches `resample` exactly on boundaries,
225
+ timestamps, OHLC, counts, and flags, and to ≤ 1e-12 relative on sums;
226
+ - the whole suite of invariants also runs at 200,000-trade scale, streaming
227
+ parity included.
228
+
229
+ Plus every validation rule above, each with the input that breaks it.
230
+
231
+ ## What the difference looks like, measured
232
+
233
+ `examples/make_hero.py` builds the figure and prints this table (seed 7,
234
+ threshold matched to median 1-minute notional so the comparison is fair):
235
+
236
+ | Sampling | Bars | Volume CV | Excess kurtosis |
237
+ | :--- | ---: | ---: | ---: |
238
+ | time (1m) | 7,800 | 0.7734 | 1.422 |
239
+ | dollar | 10,232 | 0.0255 | −0.007 |
240
+
241
+ Volume CV is the coefficient of variation of per-bar volume — near zero means
242
+ each bar carries about the same amount of trading. Excess kurtosis near zero
243
+ means returns closer to Gaussian.
244
+
245
+ On this stream, dollar bars hold per-bar volume roughly **30× steadier** than
246
+ time bars. Be careful how far you take the kurtosis number: the academic
247
+ record on whether activity clocks "normalize" returns is genuinely mixed —
248
+ Ané and Geman (2000) reported near-normality under a transaction clock, and
249
+ Murphy and Izzeldin's follow-up found the effect does not survive scrutiny on
250
+ their data. What is not controversial is the mechanical claim: sampling by
251
+ activity gives bars of near-constant information content, sampling by clock
252
+ does not. That mechanical claim is what the table measures, on synthetic data
253
+ chosen so it can be reproduced exactly.
254
+
255
+ ## pandas input
256
+
257
+ If pandas is installed, a `pandas.DataFrame` is accepted and held to the same
258
+ validation — with one caveat: Polars converts pandas' timezone-aware datetime
259
+ columns through pyarrow, so pandas users need pyarrow too. Naive pandas
260
+ timestamps are rejected, same as naive Polars ones.
261
+
262
+ ## Limitations
263
+
264
+ - Thresholds are absolute. Choosing one is still your job; a defensible
265
+ default is the median per-minute notional over your sample (that is what
266
+ the example does).
267
+ - Threshold bars are not uniform in time. Anything that assumes a fixed bar
268
+ duration — annualisation factors, some indicator definitions — needs
269
+ rethinking before it runs on them.
270
+ - Imbalance and run bars are not implemented. Fixed-threshold versions exist
271
+ in bar-forge and EWMA-adaptive versions in mlfinpy; a Polars-native
272
+ implementation is on the roadmap, not in this release.
273
+ - Session awareness means *your* boundaries: the library does not ship
274
+ exchange calendars. You provide the rollover times; `resample` guarantees
275
+ the cut. Rollover contract-adjustment is still your problem.
276
+ - Bar segmentation scans over bars, not trades: `O(n_bars · log n_trades)`.
277
+ With a realistic threshold there are far fewer bars than trades. A tick
278
+ threshold of 1 on a million trades is inherently one bar per trade and will
279
+ not be fast; nothing makes that a good idea.
280
+
281
+ ## Roadmap
282
+
283
+ - [ ] Imbalance bars, EWMA-adaptive (fixed-threshold versions exist in
284
+ bar-forge; adaptive ones in mlfinpy — a Polars-native port needs a
285
+ reason beyond porting)
286
+ - [ ] Run bars
287
+ - [ ] Out-of-core chunked batch construction
288
+
289
+ ## Related work
290
+
291
+ Three implementations matter, and pretending otherwise would be the first
292
+ sign of a promotional README.
293
+
294
+ **[bar-forge](https://github.com/bmouler/bar-forge)** (Mouler, 2026) is the
295
+ closest contemporary: tick, volume, dollar, and fixed-threshold imbalance
296
+ bars over NumPy trade records, plus strictly causal normalization transforms,
297
+ with 100% coverage, strict mypy, and a mutation-testing run (1,208 mutants,
298
+ 92.96% killed). Its bar conventions agree with ours where they overlap, which
299
+ we read as both libraries deriving from the same source. It does not do
300
+ sessions, streaming, or DataFrames, and it cites no literature; we do the
301
+ first three and ship [a paper](docs/paper.md).
302
+
303
+ **mlfinpy** is a free port of the mlfinlab data structures, including the
304
+ EWMA-adaptive imbalance and run bars from López de Prado ch. 2, which we do
305
+ not yet implement.
306
+
307
+ **[mlfinlab](https://github.com/hudson-and-thames/mlfinlab)** (Hudson &
308
+ Thames) implements the full López de Prado catalogue; it began open source
309
+ and is now a commercial product.
310
+
311
+ ## Paper
312
+
313
+ A short paper — why bar construction matters, the history behind it, the
314
+ implementation errors this library exists to prevent, and why batch and
315
+ streaming must provably agree — is in
316
+ [docs/paper.md](docs/paper.md).
317
+
318
+ If you use clockbars in research, cite it:
319
+
320
+ ```bibtex
321
+ @software{clockbars,
322
+ author = {zzionz},
323
+ title = {clockbars: bars sampled on the market's own clock},
324
+ url = {https://github.com/zzionz/clockbars},
325
+ year = {2026}
326
+ }
327
+ ```
328
+
329
+ ## License
330
+
331
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ clockbars/__init__.py,sha256=PiXqZiBJ8TyEfGI7VSAkdO3XAm4bFPEdDhRKlr_BLcI,932
2
+ clockbars/builder.py,sha256=GRmtgJEmaNK7uaaLTUawo0gbQYFF1qIk5Y8RTACu7iM,12565
3
+ clockbars/core.py,sha256=TpRfG_4kODjk2pKbeNStnsipWVG8q_YOo_dMKvxIby0,17091
4
+ clockbars/py.typed,sha256=7uInVRI1Fo5-1RgVepJYlUOeGcruKJB2WzYuUtIPoxo,66
5
+ clockbars/synthetic.py,sha256=CmXgOSjDyQ5n1vTHLlKD__pHlVT4fWyn31lI4uKrJhU,4894
6
+ clockbars-0.1.0.dist-info/METADATA,sha256=LAAEuSsllnhaX8blIqRESunBCusXs_kq1F6_UJKhYUA,14802
7
+ clockbars-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ clockbars-0.1.0.dist-info/licenses/LICENSE,sha256=YFbNRVk36qT22u0PWVAYOooIuwUh9LXZgwoJHUWDNF8,1063
9
+ clockbars-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.