Metadata-Version: 2.5
Name: liquilens
Version: 0.2.1
Summary: Python client for the LiquiLens public API: canonical ids for Indian lenders, places and publishers, and portable identity bundles.
Project-URL: Homepage, https://liquilens.in
Project-URL: Documentation, https://liquilens.in/developers/
Author: LiquiLens Private Limited
License-Expression: MIT
License-File: LICENSE
Keywords: banks,entity-resolution,financial-data,india,liquilens,nbfc,odata,ontology
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: jsonschema<5,>=4.18
Provides-Extra: charts
Requires-Dist: matplotlib>=3.7; extra == 'charts'
Requires-Dist: plotly>=5; extra == 'charts'
Provides-Extra: duckdb
Requires-Dist: duckdb>=1.0; extra == 'duckdb'
Provides-Extra: matplotlib
Requires-Dist: matplotlib>=3.7; extra == 'matplotlib'
Provides-Extra: pandas
Requires-Dist: pandas>=1.5; extra == 'pandas'
Provides-Extra: parquet
Requires-Dist: pyarrow>=14; extra == 'parquet'
Provides-Extra: plotly
Requires-Dist: plotly>=5; extra == 'plotly'
Description-Content-Type: text/markdown

# liquilens

Python client for the LiquiLens public API.

LiquiLens publishes research screens over public records about Indian lenders. Every institution,
place and publisher it describes has one canonical id, such as `inst:in/rbi/dena-bank`, with the
keys each dataset uses for it (a CIN, an RBI label, a geography id) and typed links between them.
This package reads that free identity layer, follows succession links to the identity that carries
an institution today, and builds portable identity bundles in CSV, Parquet or DuckDB that join to
your own data on the same ids.

The package holds no scoring or engine logic. Every answer comes from the public HTTP API at
`https://api.liquilens.in`, and the package keeps nothing on disk unless you ask it to build a
bundle.

- Typed results for `resolve`, `describe`, `links`, `current_identity` and `census`
- `ontology_context` and `liquilens lens`: where each product in the family holds data about one
  object, with the exact MCP tool, REST URL or site page to ask
- Typed errors: `KeyRequired` (401), `PaidKeyRequired` (402), `RateLimited` (429) and more
- Retries with exponential backoff for 429 and 5xx, honouring `Retry-After`
- An OData identity feed reader that follows every page
- `liquilens bundle build`, with a manifest validated against the published bundle schema

An OpenBB provider lives in [`integrations/openbb`](integrations/openbb) as the separate
distribution `openbb-liquilens`.

## Install

```bash
pip install liquilens
```

Optional extras keep the core install light (httpx and jsonschema only):

```bash
pip install "liquilens[pandas]"    # FeedResult.to_pandas()
pip install "liquilens[parquet]"   # Parquet bundles (pyarrow)
pip install "liquilens[duckdb]"    # DuckDB bundles
pip install "liquilens[charts]"    # liquilens.charts for Plotly and Matplotlib
```

Python 3.10 or later. To install from a checkout instead: `pip install .`

## Quickstart

```python
from liquilens import Client

with Client() as ll:  # reads LIQUILENS_API_KEY when it is set
    hit = ll.resolve("Dena Bank")
    hit.status, hit.id, hit.rule  # ('resolved', 'inst:in/rbi/dena-bank', 'rbi_label')

    ll.resolve("Aurangabad").candidates  # two districts share the name: ambiguous, never guessed
    ll.resolve("No Such Lender").status  # 'not_found': nothing is minted for an unknown name

    dena = ll.describe(hit.id)
    dena.label, dict(dena.keys)  # ('Dena Bank', {'rbi_label': 'Dena Bank'})
    for link in dena.links_in:  # links are src -> dst, each with its basis in note
        print(link.src, link.kind, link.dst, link.note)

    today = ll.current_identity(hit.id)
    today.id, today.chain  # follows the dated 'succeeds' link to Bank of Baroda
    today.stopped  # 'no_successor'

    census = ll.census()  # counts the API generates, by kind and key space
    census.by_kind, census.key_spaces
```

Resolution never guesses. `status` is `resolved`, `ambiguous` (the candidates are listed and none is
picked) or `not_found`; the last two are results, not errors. `current_identity` stops and returns
the candidates when a predecessor has more than one successor, and says so in `stopped` when the
API capped the links it could check.

A predecessor keeps its own id and every figure printed under its name. Join on canonical ids or
keys, never on labels.

`OntologyObject.note` is the API's free-text context exactly as served. The identity feed, the
bundles and the OpenBB provider show only its type code and registered city or state.

### The ontology lens: where each product holds data about an object

`ontology_context` resolves a name, any key (a CIN, LEI, ISIN, CUSIP, slug or printed label) or a
canonical id, then reads the object's context: its identity, its public keys, a sample of its links,
the events that concern it, and `coverage`, one entry for every product read (LiquiLens, Seiche,
Undertow or Palimpsest) that serves data about it, the most specific first. Each entry names an MCP
tool with its exact arguments, a REST URL or a site page, so an agent or a person can go straight to
the product that holds the data.

```python
from liquilens import Client

with Client() as ll:
    lens = ll.ontology_context("IDBI Bank Ltd")
    lens.status, lens.id  # ('resolved', 'inst:in/rbi/idbi-bank-limited')
    lens.keys, lens.events  # public keys only; events that concern the object, newest first
    for entry in lens.coverage:  # most specific read first
        print(entry.product, entry.topic, entry.mcp or entry.rest or entry.site)

    ll.ontology_context("Aurangabad").candidates  # ambiguous: the ids are listed, none is picked
    ll.ontology_context("IDBI Bank Ltd", view="timeline", as_of="2020-01-01").view  # one bounded read model
```

```bash
liquilens lens "IDBI Bank Ltd"                           # identity, keys, links, events and coverage
liquilens lens "IDBI Bank Ltd" --view timeline --json    # the typed result as JSON
```

The context is identity and routing only. A coverage entry says that a product serves data about the
object and how to ask for it; it is not evidence, freshness or a score, and the product that answers
owns its answer. `ambiguous` and `not_found` are results, not errors, and no context is requested for
them. `view` adds one bounded read model (`relationships`, `timeline`, `provenance` or
`neighbourhood`), and `as_of` reads the name and the view on that date. The API keeps every context
within a size budget: `trimmed` counts what it cut, `access` names any depth it withheld from this
caller, `partial` is True when either happened, and `liquilens lens` prints both.

**Status (22 Nov 2026):** works once the LiquiLens API release that serves the context route
(`GET /api/experimental/v1/ontology/objects/{id}/context`) is live; the resolve step is live today.
Until then `ontology_context` resolves the query and raises `NotFound` saying the API does not serve
the route, and `liquilens lens` exits 1 with that message.

### The OData identity feed

```python
from liquilens import Client, quote_literal

with Client() as ll:
    banks = ll.feed("Institutions", filter=f"Category eq {quote_literal('Small finance bank (SFB)')}")
    banks.rows[0]["Id"], banks.total, banks.complete
    frame = banks.to_pandas()  # needs liquilens[pandas]
```

The feed has five entity sets: `Institutions`, `Places`, `Publishers`, `Links` and `TextAliases`
(reviewed short forms, each with its risk level and the dates it is valid). `feed()` follows
every `@odata.nextLink`, always from your configured origin, so a key is never sent to a host named
inside a response. Build string literals with `quote_literal`, never by pasting text into a filter.

### Identity bundles

```bash
liquilens bundle build ./ll-identity                                # CSV
liquilens bundle build ./ll-identity --format parquet --format duckdb --overwrite
liquilens bundle verify ./ll-identity
```

```python
from liquilens.bundle import build_bundle, verify_bundle

result = build_bundle("./ll-identity", formats=["csv", "duckdb"])
result.partial, result.reasons
verify_bundle(result.path).ok
```

A bundle folder holds:

| File | Contents |
| --- | --- |
| `objects` | One row per object: `id`, `kind`, `label`, `jurisdiction`, `authority`, `note` |
| `keys` | One row per `(object_id, space, key)` |
| `aliases` | One row per `(object_id, alias)` |
| `links` | One row per link: `src`, `kind`, `dst`, `note` (the link's basis) |
| `text_aliases` | One row per reviewed short form: `alias`, `object_id`, `kind`, `risk`, `valid_from`, `valid_until`; present when the API serves the short forms |
| `manifest.json` | Build time, the API's source commit, transaction-time horizon, row counts and a digest for every file (for DuckDB, one per table, of its content) |
| `rights-rule.json` | The rights rule the bundle applied; its sha256 is the manifest's `register_sha256` |
| `NOTICE.txt` | What the bundle is, whether it is complete, and how to verify it |

The tables follow the bundle layout of the LiquiLens ontology specification (version 1, section
9.2), with the same ids the API serves. CSV writes one file per table, Parquet one file per table,
DuckDB one `liquilens.duckdb` database holding every table, with primary keys on `objects`, `keys`,
`aliases` and `links` that enforce their invariants. A DuckDB file's bytes differ from build to
build, so the manifest lists each of its tables by `content_sha256`, the sha256 of the table's
canonical export, and two builds of the same feed write the same entries; CSV and Parquet files are
listed by the sha256 of their bytes. `liquilens bundle verify` checks a DuckDB table's content when
duckdb is installed and lists it as unchecked otherwise. Bundles written by liquilens 0.1.0 and
0.1.1 still verify.

Notes on the columns:

- `jurisdiction` and `authority` are the id's own lowercase segments (`in`, `rbi`), as the id
  grammar defines them.
- `note` is the feed's plain-English category for an institution and the level (`state`,
  `district`) for a place.
- The feed joins aliases with `"; "`, and the builder splits them on that separator.
- The feed leaves out every object, key and link known only through a source that may not be
  redistributed in bulk. `describe` still serves those one at a time.
- `text_aliases` is written only when the feed serves the `TextAliases` set; a bundle from an API
  release that does not serve it has no such table and is not partial for that. `risk` is `low` or
  `context`: the merge kit joins a low-risk form on a date it is valid, and a context form only
  feeds suggestions. A short form with a risk level this client does not know is left out, and the
  bundle is labelled partial with the count.

The manifest validates against the published `bundle-manifest.schema.json`, which the package
vendors. It records `spec_version` 1.0, because the bundle section of the specification is a
proposal for version 1.1 that has not been released. `source_commit` comes from the API's
`GET /api/v1/release/identity`; if the API releases a new version while a bundle is being read,
the build stops rather than mix two versions. A bundle holds identity only, no facts, so
`commercial_only` is false and no source verdict was applied; `rights-rule.json` states that rule.

**Without a key a bundle is partial, and says so.** The feed gives a caller without a key the first
50 positions of any query and a daily budget of 500 rows, so a keyless build is a sample of each
entity set. The manifest sets `scope.partial` with a reason per entity set, `NOTICE.txt` opens with
`Status: PARTIAL`, and the command prints the same. With a key, every page is followed and the
bundle is complete. The API key is never written to a bundle.

## What is free and what needs a key

**Free, without a key** (within rate limits): the identity layer. Canonical ids, names, keys,
aliases, typed links and the census, through `resolve`, `describe`, `links`, `current_identity` and
`census`, the ontology lens through `ontology_context`, plus the OData identity feed for lookups: the
first 50 positions of any query and 500 rows a day, with no range comparisons or ordered walks.

**Needs an API key:**

- The whole identity feed in bulk, every row and every query option: a free key.
- Facts, point-in-time (as-of) history and bulk depth on the research routes: a free or a paid key,
  depending on the sources a response cites.
- The source link behind each figure: a paid key.

This client reads only the identity layer. The API names anything it withholds:
`OntologyObject.access`, `OntologyContext.access`, `Census.access` and `FeedResult.access` carry its
note, and a refused request raises `KeyRequired` or `PaidKeyRequired` with the API's own
`how_to_get_access` text. The limits above are the API's at the time of writing; the API's notes are
authoritative. For a key, see [liquilens.in](https://liquilens.in).

Set the key in the environment rather than in code:

```bash
export LIQUILENS_API_KEY=llk_v1_...
```

## Examples

Two notebooks in [`examples/`](examples) call the live free endpoints. They are committed without
outputs, so this repository redistributes no figures; run them to see results.

- [`01_resolve_your_institution_list.ipynb`](examples/01_resolve_your_institution_list.ipynb):
  resolve a list of Indian lender names to canonical ids, keep ambiguous and unknown names as
  results, follow succession links, and see where point-in-time facts need a key.
- [`02_real_signal_or_noise.ipynb`](examples/02_real_signal_or_noise.ipynb): ask whether a public
  money-market spread from Seiche really changed, with NoiseFloor's change tests, and how the same
  tests apply to LiquiLens lender panels named by canonical id.

```bash
pip install . noisefloor jupyterlab    # from a checkout
jupyter lab examples/
```

Without a key neither notebook calls a route that needs one. Drafts for publishing the identity
bundle on Hugging Face and Kaggle are in [`datasets/`](datasets); nothing has been uploaded.

## Charts

`liquilens.charts` draws line charts in the family style specified for LiquiLens, Seiche and
Undertow. It needs an extra: `pip install "liquilens[charts]"` for both libraries, or
`liquilens[plotly]` or `liquilens[matplotlib]` alone.

```python
import matplotlib.pyplot as plt

from liquilens import charts

# Synthetic figures. Series A has no value for 2026-09-30.
series = {
    "Series A": [("2026-03-31", 11.2), ("2026-06-30", 11.6), ("2026-09-30", None), ("2026-12-31", 12.9)],
    "Series B": [("2026-03-31", 9.4), ("2026-06-30", 9.8), ("2026-09-30", 10.1), ("2026-12-31", 10.0)],
}

fig = charts.plotly_lines(series)                # a Plotly figure in the family template
fig.update_layout(title="Example ratio", yaxis_title="%")
fig.show()

with charts.matplotlib_style():                  # the family Matplotlib style
    figure, ax = plt.subplots()
    charts.matplotlib_lines(ax, series)
    ax.set_title("Example ratio")
    figure.savefig("example-ratio.png")
```

Series A breaks at 2026-09-30, and its 2026-12-31 value, with no value beside it, is drawn as a
dot. Both backends keep the same rules:

- A missing value (`None` or NaN) breaks the line: nothing is interpolated, carried forward or
  drawn as 0. List a missing period as `None`; a period left out of a series is not known to be
  missing, so the line joins its neighbours.
- A value with no value beside it on either side is drawn as a dot.
- Each series pairs a colour with a dash pattern (solid, dash, dot, dash-dot), so colour is never
  the only channel and one chart holds up to four series.
- A period that appears twice in one series is withheld and drawn as a gap, with a
  `LiquiLensWarning`, rather than choosing one of its values.
- Values are plotted as given. A point's time is a date (a period), a timezone-aware UTC datetime
  (an instant) or the ISO 8601 text of either; another zone is refused, never converted. Axes print
  ISO dates.

`charts.plotly_template()` returns the Plotly template and `charts.apply_plotly_template(fig)`
applies it to a figure of your own. The family design system publishes the template at
<https://liquilens.in/design/plotly-template.json> and the style at
<https://liquilens.in/design/liquilens.mplstyle>. The package ships pinned copies of both, byte for
byte, and never fetches them: [`src/liquilens/design/VENDORED.json`](src/liquilens/design/VENDORED.json)
records the source commit, each file's public URL and its sha256, and the tests check both digests.

## Excel and Power BI

The identity feed is an OData v4 service, so Excel and Power BI read it without an add-in.

Feed URL:

```
https://api.liquilens.in/api/experimental/v1/ontology/odata
```

**Excel (Microsoft 365, Windows):** Data > Get Data > From Other Sources > From OData Feed. Paste
the feed URL, choose Anonymous, then pick `Institutions`, `Places`, `Publishers`, `Links` or
`TextAliases` in the Navigator and load them. Excel for Mac offers the OData feed source only in
some builds; check yours before relying on it.

**Power BI Desktop:** Get data > OData feed, paste the feed URL, choose Anonymous, and pick the tables.

Join your sheets on the `Id` column. To attach your own list of lenders, resolve each name or CIN once
(`liquilens resolve "Dena Bank"`) and keep the returned id.

Without a key each table loads its first 50 rows. To load every row with a key, add the header in
Power Query's Advanced Editor, keeping the key in a Power Query parameter rather than in the query
text:

```
OData.Feed(
    "https://api.liquilens.in/api/experimental/v1/ontology/odata/Institutions",
    [Authorization = "Bearer " & LiquiLensKey]
)
```

Do not share a workbook that holds a key.

## Errors

| Exception | When |
| --- | --- |
| `KeyRequired` | HTTP 401: the request needs a free API key, or the keyless allowance is used up |
| `PaidKeyRequired` | HTTP 402: the request needs a paid API key |
| `RateLimited` | HTTP 429 after retries; `retry_after` holds the API's wait in seconds |
| `ObjectNotFound` | `describe` of an id no object has |
| `NotFound` | Other 404s, including an API release that does not serve the ontology context route |
| `InvalidRequest`, `ServerError`, `APIError` | Other HTTP errors |
| `TransportError` | Connection failures and timeouts after retries |
| `UnexpectedResponse` | A response this client does not recognise |

`KeyRequired` and `PaidKeyRequired` are `AccessError`s and carry `depth`, `what`, `requires`, `tier`,
`message` and `how_to_get_access` when the API sent them. Every error derives from `LiquiLensError`.

## Retries and limits

```python
Client(
    api_key=None,  # or LIQUILENS_API_KEY
    base_url=None,  # or LIQUILENS_BASE_URL, else https://api.liquilens.in
    timeout=30.0,
    retries=3,  # timeouts, network errors, 429 and 5xx
    backoff=0.5,  # 0.5 s, 1 s, 2 s ... capped at 30 s
    max_retry_wait=60.0,  # a longer Retry-After is raised as RateLimited at once
)
```

A daily allowance refusal carries a long `Retry-After`; the client raises it instead of sleeping.

## Security and privacy

- The key is read from the `api_key` argument or `LIQUILENS_API_KEY`, sent only to the configured
  origin as `Authorization: Bearer`, never logged, never shown in `repr`, and never written to a
  bundle. The command line reads it from the environment only.
- `base_url` must be HTTPS (plain HTTP only on a loopback address) and a bare origin.
- Redirects are never followed, responses are size-capped, and paging links are requested from the
  configured origin only.
- If the API reports that it did not accept a key, the client warns once (`LiquiLensWarning`).

See [SECURITY.md](SECURITY.md) to report a vulnerability.

## Development

```bash
python -m pip install -e . --group dev        # pip 25.1 or later
python -m pip install -e ".[charts]" --group dev   # also runs the chart tests
pytest                                        # offline: every request is mocked
ruff check . && ruff format --check . && mypy
LIQUILENS_LIVE=1 pytest tests/test_live.py    # about a dozen requests to the real API
```

The tests never touch the network unless `LIQUILENS_LIVE=1` is set. The OpenBB provider has its own
tests under `integrations/openbb/tests`.

## Licence

MIT, see [LICENSE](LICENSE). Data served by the API stays subject to the terms LiquiLens and its
sources state for it.
