Metadata-Version: 2.4
Name: immix_datasets
Version: 0.1.0
Summary: The Python client for Immix Datasets — historical market data as files
Keywords: immix,market data,historical data,datasets,crypto
Author: Immix
License-Expression: MIT
License-File: LICENSE
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
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: Typing :: Typed
Requires-Dist: httpx>=0.28,<1
Requires-Dist: pandas>=2.2,<4 ; extra == 'pandas'
Requires-Dist: pyarrow>=18 ; extra == 'pandas'
Requires-Python: >=3.11
Project-URL: Documentation, https://docs.immix.xyz
Project-URL: Homepage, https://immix.xyz
Provides-Extra: pandas
Description-Content-Type: text/markdown

# Immix Datasets — Python client

`immix_datasets` is the Python client for Immix Datasets: historical market data as files (trades,
quotes, order books and derivatives data), one file per family, exchange, day and symbol.

It is on PyPI:

```bash
pip install immix_datasets
```

What each version changes is in `CHANGELOG.md`, which the source distribution carries.

Today it reads the catalogue (what the dataset holds, a day's files, what an account has used),
downloads files to disk, and loads them into pandas data frames.

```python
from immix_datasets import Datasets

with Datasets() as data:  # the key comes from IMMIX_DATASETS_API_KEY
    for exchange in data.coverage():
        print(exchange.exchange, exchange.first_day, exchange.published_through, exchange.families)

    okx = data.coverage("OKX")  # each closed day, and each family's symbols
    day = data.manifest("OKX", okx.published_through)  # the day's files, gaps and failed hours
    for file in day.files:
        print(file.family, file.symbol, file.rows, file.bytes, file.sha256)

    # A week of trades and quotes for two symbols, to disk: to_day is the day after the last.
    paths = data.download("OKX", ["trades", "quotes"], ["BTC/USDT", "ETH/USDT"], "2026-11-01", "2026-11-08")

    # The week's trades as one pandas data frame, read from those files: nothing is fetched twice.
    trades = data.load("OKX", "trades", ["BTC/USDT", "ETH/USDT"], "2026-11-01", "2026-11-08")

    usage = data.usage()  # this month's bytes against the plan
    print(usage.bytes, usage.monthly_bytes, usage.remaining_bytes)
```

A call the service refuses raises `ApiError`, which carries the service's `code`
(`DAY_NOT_PUBLISHED`, `DAY_UNDER_REPAIR`, ...), its message and the request id to quote to support.

## Where the files are kept

A client keeps its files in one directory. It is said once, when the client is made, and not to
each call:

```python
Datasets()  # ~/immix_datasets
Datasets(download_dir="/data/immix")  # or set IMMIX_DATASETS_DOWNLOAD_DIR=/data/immix
```

- **Unless told otherwise it is `immix_datasets` in your home directory**: `~/immix_datasets`, on
  Linux and macOS alike. It does not depend on where a script is run from, so the same script run
  from another directory finds the files it fetched before. `data.download_dir` says where it is.
- **`download`, `load` and `instruments` all keep their files there**, and look there before
  asking the service for one. A range that was downloaded is loaded from disk.
- **A leading `~` is your home directory**, and a relative path is taken from where the client was
  made. The directory is made when the first file is put in it.

### How the files are named

Inside the directory a file is kept under its key in the dataset, which holds the first 12 hex
digits of its SHA-256:

```
trades/OKX/2026-11-01/BTC-USDT.55b1844a9178.csv.gz
```

- **A file is never anything but the bytes its name says.** A result can name the files it was
  computed from, and they will not change under it.
- **A file in place is believed without being hashed again.** It took its name only once its hash
  was checked, so a download run again compares sizes and reads nothing.
- **A repaired day's file arrives beside the one it replaces**, which stays. The paths `download`
  returns, and the rows `load` reads, are the dataset's as it is now: read those, and not a
  pattern such as `BTC-USDT.*.csv.gz`, which matches both.

To name the files another way, give the client a `get_filename`, as Tardis's client takes one: a
function of the file's exchange, family, day, symbol and format, in that order, that returns a
path relative to the directory. A function that takes a sixth argument is given the file's hash
too, those 12 digits.

```python
def flat(exchange, family, day, symbol, format, hash):
    # OKX_trades_2026-11-01_BTC-USDT.55b1844a9178.csv.gz
    return f"{exchange}_{family}_{day}_{symbol}.{hash}.{format}.gz"


def by_symbol(exchange, family, day, symbol, format, hash):
    # OKX/BTC-USDT/trades/2026-11-01.55b1844a9178.csv.gz
    return f"{exchange}/{symbol}/{family}/{day}.{hash}.{format}.gz"


def without_the_hash(exchange, family, day, symbol, format):  # Tardis's five arguments
    # trades/OKX/2026-11-01/BTC-USDT.csv.gz
    return f"{family}/{exchange}/{day}/{symbol}.{format}.gz"


with Datasets(download_dir="/data/immix", get_filename=flat) as data:
    data.download("OKX", ["trades"], ["BTC/USDT"], "2026-11-01", "2026-11-08")
```

The day is a `datetime.date`. The symbol is as a file name spells it, `BTC-USDT` for `BTC/USDT` and
`BTC-USDT_USDT` for `BTC/USDT:USDT`, so it is one name with no `/` in it. The format is `csv`, and
the files are gzipped: the function adds `.gz`. A function written for Tardis's `get_filename`
works as it is.

A name that holds the hash is believed as the key is. One without it can be had, and costs two
things: a download run again reads every file in place to hash it, and a repaired day's file takes
the old one's place, so a path no longer says which bytes it holds. A name outside the directory,
or one two files share, is refused before anything is counted. A day's instruments file is not a
data file and is not named this way: it sits at `instruments/OKX/2026-11-01.csv`.

## Downloading

`download` puts files on disk, and is the way to have a large range of data locally. It reads
nothing into memory and needs neither pandas nor pyarrow.

```python
from immix_datasets import Datasets, DaysUnavailableError

with Datasets() as data:
    try:
        paths = data.download(
            "OKX",
            ["trades", "quotes", "book_snapshot_25"],  # one family, or several
            ["BTC/USDT", "ETH/USDT"],
            "2026-01-01",
            "2026-11-08",  # the day after the last
        )
    except DaysUnavailableError as missing:
        print(missing.days, [missing.refusals[day].code for day in missing.days])
        paths = missing.paths
```

- **It syncs.** A download run again asks only for what is missing, so the same call brings a
  directory up to date each day, and finishes one that was interrupted. A file in place is left
  alone, and the file of a day repaired since is fetched.
- **A file in place is complete.** Every file is checked against the SHA-256 its day's manifest
  gives before it takes its name.
- **A file is counted when it is asked for, whole.** A download that needs more bytes than the
  plan has left this month is refused before any of those bytes is counted (`OverBudgetError`).
  The plan is checked again when a day that was under repair comes to be served: refused then, the
  files fetched before are in place and were counted.
- **A day that cannot be served yet does not stop the others.** A day under repair is set aside
  and asked for again each minute, for up to `repair_wait` (two hours unless told otherwise). Days
  still missing then, and days not published yet, are named by `DaysUnavailableError`, which also
  carries the paths of the files that were fetched.
- **A symbol with no file is warned about.** A file exists only for a day its symbol had rows, so
  fewer files than days is ordinary. A family's symbol with no file on any day of the range is
  what a misspelt one looks like, and `coverage("OKX")` lists each family's symbols as they are
  written.

`concurrency` is how many files are fetched at a time, five unless told otherwise. The client
logs to the `immix_datasets` logger: each file fetched at `INFO`, and the first wait for a day
that cannot be served yet at `WARNING`.

## Loading into pandas

`load` returns one family's rows for some symbols over a range of days as one pandas data frame.
It needs pandas and pyarrow, which the package does not install unless asked:

```bash
pip install "immix_datasets[pandas]"
```

```python
from immix_datasets import Datasets

with Datasets() as data:
    trades = data.load("OKX", "trades", ["BTC/USDT"], "2026-11-01", "2026-11-08")
    instruments = data.instruments("OKX", "2026-11-01")  # the day's instruments; never counted

notional = (trades["price"] * trades["amount"]).sum()  # exact: a Decimal
by_minute = trades.set_index("timestamp")["amount"].resample("1min").sum()
```

- **It has its files as `download` has them**, in the same directory, with the same counting and
  the same errors. Files that are there are read from disk; the rest are fetched first, and kept.
  A range loaded again asks the service for no file and counts nothing.
- **Each column is the type the file contract gives it**, and nothing is guessed from the cells. A
  time is `datetime64[ns, UTC]`, exact to the nanosecond, and `NaT` where the file has none. A
  whole number is `int64`, or `Int64` where it can be missing. A name (`symbol`, `side`) is a
  `category`.
- **A price, an amount or a rate is an exact decimal**: an Arrow `decimal128(18, scale)` at the
  digits the file is written with, whose cells read as Python `Decimal`s. Two such columns add,
  subtract, multiply, divide, compare, sort and sum with no rounding. Exact decimals do not do
  everything a float does: `cumsum`, `describe` and `resample(...).ohlc()` refuse them, so does a
  product of three columns, and `mean` is rounded to the column's digits. A sum by group or by
  time can be 38 digits wide, the most an exact decimal holds, and Arrow refuses arithmetic that
  would take it past that: take a quotient of two such sums, such as a VWAP, in floats. Pass
  `decimals="float"` to read those columns as `float64` instead, or convert one with
  `.astype("float64")`.
- **The range's gaps come with the frame.** A gap is a time the dataset was not watching, which a
  frame cannot show: the rows either side of it look adjacent. `frame.attrs["gaps"]` lists the
  gaps for the family and the symbols asked for, and a frame with any is warned of with
  `GapsWarning`. `data.gaps(...)`, with the same arguments, reads them without fetching a file.
- **A frame holds its whole range in memory.** A busy symbol's day of `book_snapshot_25` is about
  1.2 GB as exact decimals and 0.6 GB as floats: load a long range a day at a time, or `download`
  it and read the files with whatever suits them.
- **Rows are in the files' order**: by day, then as the symbols were asked for, and within a file
  in the order of the stream. `frame.sort_values("global_sequence", kind="stable")` puts several
  symbols' rows in the stream's one order.

## What it needs

Python 3.11 or newer, and one dependency, `httpx`. Data frames need pandas 2.2 or newer and pyarrow
18 or newer, which the `pandas` extra installs. It does not need the trading SDK, `immix_sdk`:
Datasets is a product of its own, with its own keys.

## Developing

```bash
uv sync
uv run pytest -q
```

`DEVELOPING.md`, beside this file in the repository, has the rest: how the repository changes, how
a version ships, and the decisions the client is built to. Beside it, `examples/` holds a script for
each recipe of the cookbook, and `notebooks/` a week of trades and quotes run against the service.
