Metadata-Version: 2.4
Name: quantile-edges
Version: 0.1.0
Summary: Data-driven bin edges: bins are built from the data itself, not pre-set ranges, and each bin carries enough observations to be statistically reliable.
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Provides-Extra: fast
Requires-Dist: numpy; extra == "fast"
Dynamic: description
Dynamic: description-content-type
Dynamic: provides-extra
Dynamic: requires-python
Dynamic: summary

# quantile-edges

**Data-driven bin edges that keep every bin statistically reliable.**

`quantile-edges` builds bins from the data itself, not from ranges you decide in advance. It guarantees that each bin carries a minimum number of observations, so any statistic you compute per bin (an average, a rate, a share) rests on enough data to mean something.

```python
from quantile_edges import bin_edges

values = list(range(1, 101))

# 1. Bins of 25% each -> 4 bins, 10 ranges in total
bin_edges(values, ranges=True, bin_pct=25)
# [(1, 25), (26, 50), (51, 75), (76, 100),
#  (1, 50), (1, 75), (1, 100),
#  (26, 75), (26, 100),
#  (51, 100)]

# 2. The same bins, returned as boundaries
bin_edges(values, ranges=False, bin_pct=25)
# [1, 26, 51, 76, 100]
```

`ranges` is required, and every option after `values` is keyword-only. By default each call also prints a small summary table of the bins; pass `display=False` to turn it off. The examples here show return values only.

---

## Purpose

A statistic is only as trustworthy as the number of observations behind it. A bin holding 4 rows gives a wild average, while a bin holding 4,000 gives a stable one, and comparing the two is misleading.

`quantile-edges` solves this at the source:

- **Bins come from the data.** Edges are calculated from what is in your data, so they adapt when the data changes and need no hand-picked ranges.
- **Every bin carries enough data.** A minimum bin size (`min_bin_n`) is always enforced, so averages, rates and shares computed per bin rest on a sample that means something.
- **Identical values stay together.** Ties are never split across bins, so a value always belongs to exactly one bin.

This is useful for charts, scorecards, risk bands, cohort analysis and anywhere you group a numeric column before aggregating.

Bins do **not** have to be equal. They are as even as the rules allow, and uneven only where ties or the minimum size require it.

**Two terms are used throughout:** a **bin** is a base slice of the population, and a **range** is a `(lower, upper)` pair that can span one bin or several neighbouring bins.

---

## Parameters

```python
bin_edges(
    values,
    *,
    ranges,
    bin_pct=20,
    min_bin_n=10,
    display=True,
)
```

| Parameter | Type | Default | Meaning |
|---|---|---|---|
| `values` | array-like | required | Numeric observations (list, tuple, numpy array, pandas Series). Must be finite numbers; empty input raises. |
| `ranges` | bool | required | `True` returns every range that can be built from the bins (the bins themselves first, then wider ranges). `False` returns the bin boundaries as one sorted list: the lower edge of every bin, then the upper edge of the last bin. |
| `bin_pct` | number, `0 < x <= 100` | `20` | Share of the data each bin should carry. |
| `min_bin_n` | int, `>= 1` | `10` | Minimum observations in any bin. **Always enforced**: the larger of this and what `bin_pct` asks for wins. |
| `display` | bool | `True` | Prints a small table with one row per bin (its range, count and share); the combined ranges are not listed. The return value is the same either way. Pass `False` to print nothing. |

---

## What you get back

### `ranges=True`: every range the bins can form

A range starts at the lower edge of one bin and ends at the upper edge of the same or a later bin, so the bins act as the guide for where every range starts and ends. The base bins come first, then the wider ranges grouped by start bin.

```python
bin_edges(range(1, 101), ranges=True)   # default bin_pct=20 -> 5 bins
# [(1, 20), (21, 40), (41, 60), (61, 80), (81, 100),
#  (1, 40), (1, 60), (1, 80), (1, 100),
#  (21, 60), (21, 80), (21, 100),
#  (41, 80), (41, 100),
#  (61, 100)]
```

All 15 possible ranges: the 5 base bins, then the 4 ranges starting at 1, the 3 starting at 21, the 2 starting at 41 and the 1 starting at 61.

Every returned range contains at least `min_bin_n` observations, because each one includes at least one full bin.

**The output grows quickly with the number of bins.** `k` bins give `k * (k + 1) / 2` ranges:

| Bins | Ranges returned |
|---|---|
| 5 | 15 |
| 10 | 55 |
| 20 | 210 |
| 50 | 1,275 |
| 100 | 5,050 |
| 1,000 | 500,500 |

The number of bins comes from `bin_pct` (100 / `bin_pct`, roughly) and is limited by `min_bin_n`. A very small `bin_pct` on a large dataset can therefore produce a very large list, so keep `bin_pct` in a sensible range for the size of your data.

### `ranges=False`: the bin boundaries

One sorted list: the lower edge of every bin, followed by the upper edge of the last bin. Each bin runs from its own value up to, but not including, the next value in the list, and the last bin also includes its final value.

```python
bin_edges(range(1, 1000), ranges=False, bin_pct=20, display=False)
# [1, 201, 401, 601, 999]
```

These boundaries describe the bins 1 to 200, 201 to 400, 401 to 600 and 601 to 999. The last bin is larger because a small leftover was merged into it (see How it works).

If the last bin holds a single repeated value, that value appears twice at the end, so that bin keeps its own interval:

```python
bin_edges([1]*10 + [2]*10, ranges=False, bin_pct=50, min_bin_n=5, display=False)
# [1, 2, 2]
```

A single bin is allowed. If `bin_pct` and `min_bin_n` ask for as much as the data holds, one bin carries all of it (see the example below).

---

## How it works

1. The values are sorted and grouped by distinct value.
2. Each bin's **target size** is set: `max(share, min_bin_n)`, where the share is `bin_pct` percent of all the data.
3. Distinct values are added to the current bin until it reaches its target, then it closes. **A group of identical values is never split**, so a bin can end up slightly larger than its target.
4. If the last bin is left below target, it is **merged into the previous one**.
5. The lowest and highest value actually found in each bin become its edges.
6. With `ranges=True`, every continuous range is then built from the bins: start at the lower edge of one bin and end at the upper edge of the same or a later bin.
7. With `ranges=False`, the lower edge of every bin is returned, followed by the upper edge of the last bin.

---

## Examples

### Ties are never split

```python
ties = [1]*30 + [2]*5 + [3]*25 + [4]*20 + [5]*20

bin_edges(ties, ranges=True, bin_pct=25, min_bin_n=10)
```

```
Quantile_edges

           bin_pct = 25%
min_bin_n = 10  |  100 observations

-----------------------------------
  #     Range     Count         %
-----------------------------------
  1     1 to 1       30     30.0%
  2     2 to 3       30     30.0%
  3     4 to 5       40     40.0%
-----------------------------------
        Total       100    100.0%
```

Every value `1` stays together even though that bin (30) is bigger than the 25% target. The table lists the 3 bins; the function itself returns all 6 ranges built from them.

### One bin carries everything

```python
bin_edges(range(1, 21), ranges=True, min_bin_n=50, display=False)
# [(1, 20)]

bin_edges(range(1, 21), ranges=False, min_bin_n=50, display=False)
# [1, 20]
```

`min_bin_n=50` asks for more observations than the 20 available, so a single bin holds them all.

### A minimum bin size you can rely on

```python
bin_edges(range(1, 101), ranges=True, bin_pct=5, min_bin_n=30, display=False)
# [(1, 30), (31, 60), (61, 100), (1, 60), (1, 100), (31, 100)]
# 5% bins were asked for, but no bin holds fewer than 30 rows
```

---

## Errors

All problems raise `ValueError` with a message that says how to fix it. Common ones:

| Situation | Message (shortened) |
|---|---|
| Empty input | `values is empty.` |
| NaN, infinity, text or booleans in `values` | `values must contain finite numeric values.` |
| `bin_pct` outside 0 to 100 | `bin_pct must be a number between 0 and 100.` |
