Metadata-Version: 2.5
Name: clockbars
Version: 0.1.0
Summary: Bars sampled on the market's own clock: tick, volume, and dollar bars in Polars, batch and streaming with proven parity.
Project-URL: Homepage, https://github.com/zzionz/clockbars
Project-URL: Issues, https://github.com/zzionz/clockbars/issues
Author: zzionz
License: MIT
License-File: LICENSE
Keywords: financial-data,market-microstructure,order-flow,polars,quantitative-finance
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: numpy>=1.26
Requires-Dist: polars>=1.0
Provides-Extra: dev
Requires-Dist: matplotlib>=3.8; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pandas-stubs>=2.2; extra == 'dev'
Requires-Dist: pandas>=2.0; extra == 'dev'
Requires-Dist: pyarrow>=15; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# clockbars

**Bars sampled on the market's own clock.** Tick, volume, and dollar bars in
Polars — one explicit rule, two execution paths, and a test suite that holds
both to the same contract.

[![CI](https://github.com/zzionz/clockbars/actions/workflows/ci.yml/badge.svg)](https://github.com/zzionz/clockbars/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.11%2B-blue)
![Typed](https://img.shields.io/badge/typing-mypy_strict-blue)
![License](https://img.shields.io/badge/license-MIT-green)

---

Most people build bars by clock: take all the trades in each minute and call it
a bar. The problem is that markets don't produce information at a constant
rate. The first and last half hour of a session carry several times the volume
of midday, so a 1-minute bar at 09:31 and a 1-minute bar at 12:31 contain wildly
different amounts of trading, while downstream code treats them as
interchangeable. The result is a series with uneven information content per
observation, and every statistic computed on it inherits that unevenness.

Sampling by activity instead of clock is an old idea. Mandelbrot and Taylor
noted in 1967 that price changes over a fixed number of transactions behave
far better than price changes over fixed time; Clark's 1973 model treated
volume as the clock; Easley, López de Prado, and O'Hara built a whole
microstructure framework on "volume buckets."

This problem has existing software — see [Related work](#related-work). What
none of it offers is a Polars-native path: one call from `DataFrame` to
`DataFrame` with a fixed schema, ready to drop into a pipeline that already
speaks Polars. That is the gap this fills, and two properties come with it
that the free ecosystem currently lacks: a streaming builder that provably
produces the same bars as the batch path, and session-aware construction so a
bar never straddles an exchange close.

![Time bars vs dollar bars](docs/hero.png)

Same 400,000-trade synthetic stream, 20 sessions. Top row: volume per bar is a
long right tail for time bars and a spike for dollar bars. Bottom row: across a
single session, time-bar volume traces the intraday U while dollar bars stay
flat. The stream is synthetic (seeded, reproducible) because trade data is
licensed; the mechanism being demonstrated is real.

## Install

Not on PyPI yet — install from source:

```bash
pip install git+https://github.com/zzionz/clockbars.git
```

For development:

```bash
git clone https://github.com/zzionz/clockbars.git
cd clockbars
uv sync --all-extras
uv run pytest -q   # 171 passed, 100% coverage enforced
```

CI runs the full gate set on every push: ruff, strict mypy, and the test
suite with coverage required at 100% — on Ubuntu and Windows across Python
3.11–3.14. The package ships a `py.typed` marker, so if you use clockbars
under mypy you get its types, not `Any`.

## Quickstart

```python
import polars as pl
from clockbars import resample

trades = pl.read_parquet("trades.parquet")  # ts, price, size — sorted by ts

dollar = resample(trades, kind="dollar", threshold=1_000_000)
volume = resample(trades, kind="volume", threshold=500)
ticks  = resample(trades, kind="tick",   threshold=250)
minute = resample(trades, kind="time",   every="1m")
```

The same stream can be cut so that no bar straddles a session boundary —
pass the rollover times and accumulation restarts at each one:

```python
from datetime import datetime, timezone

rollovers = pl.Series([datetime(2026, 1, 6, 23, 0, tzinfo=timezone.utc)])

# A dollar bar never spans the overnight close, and every session's final
# bar is flagged partial if it fell short of the threshold.
daily = resample(trades, kind="dollar", threshold=1_000_000,
                 session_starts=rollovers)
```

And the same rule runs one trade at a time, for live streams:

```python
from clockbars import BarBuilder

builder = BarBuilder(kind="dollar", threshold=1_000_000)
for ts, price, size in feed:
    bar = builder.push(ts, price, size)   # completed bar, or None
    if bar is not None:
        emit(bar)

trailing = builder.flush()                # the final partial bar
```

A parity test asserts that `BarBuilder` over the batch input agrees with
`resample` on everything that decides what a bar *is* — boundaries, ids,
timestamps, OHLC, counts, partial flags — at 200,000 trades, for all four
kinds, session cuts included. Per-bar volume and notional agree to within
float-summation order (≤ 1e-12 relative): a vectorised group sum and a
sequential accumulator sum the same numbers in different orders, and
claiming bit-equality there would be a claim floating point cannot support.
The bar your backtest computed and the bar your live process computed are
the same object, or you find out in a test, not in production.

All four kinds return the same schema, so nothing downstream has to branch on
how the bars were made:

| Column | Meaning |
| :--- | :--- |
| `bar_id` | zero-based bar index |
| `start_ts`, `end_ts` | first and last trade timestamp in the bar |
| `duration` | `end_ts - start_ts` |
| `open`, `high`, `low`, `close` | first price, max, min, last price |
| `volume` | units traded |
| `notional` | price × size summed |
| `vwap` | `notional / volume` |
| `n_trades` | trade count |
| `is_partial` | `True` only if the bar fell short of its threshold |

## The rule, and the decisions inside it

A bar closes on the trade that pushes its running total to the threshold, and
that trade is included in the closing bar. Each bar then restarts from zero.
Everything else follows:

1. **A closed bar's total is always at least its threshold.** It can overshoot,
   but only by the size of its own final trade.
2. **Overshoot does not leak into the next bar.** This is a deliberate choice.
   A global cumulative sum — the "obvious" vectorised implementation — charges
   each bar's overshoot to the *following* bar, which then closes below
   threshold in the middle of the series. Bar 0 of a 128-bar run reached
   threshold; bar 1, docked 50 units for bar 0's overshoot, closed at 200 with a
   threshold of 250. Restarting from zero makes every bar answerable on its own.
   `test_overshoot_is_not_carried_into_the_next_bar` pins this.
3. **The final bar of any segment is kept, flagged, and never dropped.**
   `is_partial=True` means "the segment ended before this bar filled" — the
   end of the stream, or the end of a session. Without session cuts there is
   one segment, so only the last bar can be partial. Throwing a partial bar
   away would silently rewrite history.
4. **Naive timestamps are rejected.** If your data says 14:30 with no time
   zone, no guessing happens; you get an error telling you to declare the
   zone. Silently assuming UTC is how a DST bug gets born.
5. **NaN and inf are rejected before they can look like data.** In
   floating-point comparison, `NaN <= 0` is `False`, so a sign check alone
   accepts NaN — and one NaN price poisons every bar after it. Finiteness is
   checked separately from sign.
6. **Threshold comparisons carry a `1e-9` relative tolerance.** Summing a few
   thousand floats lands on `499.9999999999999` more often than anyone wants
   to admit. Without the tolerance, those are phantom partial bars.
7. **Duplicate timestamps are fine.** Trades share timestamps in real data;
   input order is preserved within a bar, so `open`/`close` are stable.
8. **Input must be sorted.** Unsorted input is an error, not a silent
   `sort()`. Sorting implicitly is a policy decision about your data, and it
   is not this library's to make.

Time bars follow the same schema with `is_partial` always `False`. Windows
are half-open `[start, start + every)` and align to wall-clock boundaries: a
frame that begins at 09:30:30 still produces windows that begin on the minute.
Empty windows are not emitted. Session cuts do not apply to time bars — the
clock already cuts them — and passing both raises rather than guessing which
rule wins.

## What the tests actually check

Not "the code runs" — the properties that make the output trustworthy:

- volume, notional, and trade counts are conserved exactly across bars;
- bars are chronological and non-overlapping, with `bar_id` contiguous from zero;
- every closed bar meets its threshold, and overshoots by at most one trade;
- only the final bar of a segment can be partial, and the flag agrees with the
  bar's own total;
- OHLC and VWAP are internally consistent (`low ≤ vwap ≤ high`);
- identical input yields identical output;
- bars never straddle a session boundary, with the boundary trade going to
  the new session;
- the streaming `BarBuilder` matches `resample` exactly on boundaries,
  timestamps, OHLC, counts, and flags, and to ≤ 1e-12 relative on sums;
- the whole suite of invariants also runs at 200,000-trade scale, streaming
  parity included.

Plus every validation rule above, each with the input that breaks it.

## What the difference looks like, measured

`examples/make_hero.py` builds the figure and prints this table (seed 7,
threshold matched to median 1-minute notional so the comparison is fair):

| Sampling | Bars | Volume CV | Excess kurtosis |
| :--- | ---: | ---: | ---: |
| time (1m) | 7,800 | 0.7734 | 1.422 |
| dollar | 10,232 | 0.0255 | −0.007 |

Volume CV is the coefficient of variation of per-bar volume — near zero means
each bar carries about the same amount of trading. Excess kurtosis near zero
means returns closer to Gaussian.

On this stream, dollar bars hold per-bar volume roughly **30× steadier** than
time bars. Be careful how far you take the kurtosis number: the academic
record on whether activity clocks "normalize" returns is genuinely mixed —
Ané and Geman (2000) reported near-normality under a transaction clock, and
Murphy and Izzeldin's follow-up found the effect does not survive scrutiny on
their data. What is not controversial is the mechanical claim: sampling by
activity gives bars of near-constant information content, sampling by clock
does not. That mechanical claim is what the table measures, on synthetic data
chosen so it can be reproduced exactly.

## pandas input

If pandas is installed, a `pandas.DataFrame` is accepted and held to the same
validation — with one caveat: Polars converts pandas' timezone-aware datetime
columns through pyarrow, so pandas users need pyarrow too. Naive pandas
timestamps are rejected, same as naive Polars ones.

## Limitations

- Thresholds are absolute. Choosing one is still your job; a defensible
  default is the median per-minute notional over your sample (that is what
  the example does).
- Threshold bars are not uniform in time. Anything that assumes a fixed bar
  duration — annualisation factors, some indicator definitions — needs
  rethinking before it runs on them.
- Imbalance and run bars are not implemented. Fixed-threshold versions exist
  in bar-forge and EWMA-adaptive versions in mlfinpy; a Polars-native
  implementation is on the roadmap, not in this release.
- Session awareness means *your* boundaries: the library does not ship
  exchange calendars. You provide the rollover times; `resample` guarantees
  the cut. Rollover contract-adjustment is still your problem.
- Bar segmentation scans over bars, not trades: `O(n_bars · log n_trades)`.
  With a realistic threshold there are far fewer bars than trades. A tick
  threshold of 1 on a million trades is inherently one bar per trade and will
  not be fast; nothing makes that a good idea.

## Roadmap

- [ ] Imbalance bars, EWMA-adaptive (fixed-threshold versions exist in
      bar-forge; adaptive ones in mlfinpy — a Polars-native port needs a
      reason beyond porting)
- [ ] Run bars
- [ ] Out-of-core chunked batch construction

## Related work

Three implementations matter, and pretending otherwise would be the first
sign of a promotional README.

**[bar-forge](https://github.com/bmouler/bar-forge)** (Mouler, 2026) is the
closest contemporary: tick, volume, dollar, and fixed-threshold imbalance
bars over NumPy trade records, plus strictly causal normalization transforms,
with 100% coverage, strict mypy, and a mutation-testing run (1,208 mutants,
92.96% killed). Its bar conventions agree with ours where they overlap, which
we read as both libraries deriving from the same source. It does not do
sessions, streaming, or DataFrames, and it cites no literature; we do the
first three and ship [a paper](docs/paper.md).

**mlfinpy** is a free port of the mlfinlab data structures, including the
EWMA-adaptive imbalance and run bars from López de Prado ch. 2, which we do
not yet implement.

**[mlfinlab](https://github.com/hudson-and-thames/mlfinlab)** (Hudson &
Thames) implements the full López de Prado catalogue; it began open source
and is now a commercial product.

## Paper

A short paper — why bar construction matters, the history behind it, the
implementation errors this library exists to prevent, and why batch and
streaming must provably agree — is in
[docs/paper.md](docs/paper.md).

If you use clockbars in research, cite it:

```bibtex
@software{clockbars,
  author = {zzionz},
  title  = {clockbars: bars sampled on the market's own clock},
  url    = {https://github.com/zzionz/clockbars},
  year   = {2026}
}
```

## License

MIT. See [LICENSE](LICENSE).
