Metadata-Version: 2.5
Name: arcobi-sdk
Version: 0.2.0b2
Summary: Fetch, align and export energy-market time-series data (Datahub), with an optional shared credential pool.
Project-URL: Documentation, https://sdk.arcobi.com
Author: Arcobi
License-Expression: LicenseRef-Proprietary
License-File: LICENSE
Keywords: aeso,data,datahub,energy,ercot,ieso,time-series
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.25
Requires-Dist: numpy>=1.24
Requires-Dist: pandas<4,>=2.2
Requires-Dist: pydantic>=2.0
Requires-Dist: websockets>=12
Provides-Extra: all
Requires-Dist: fastapi>=0.110; extra == 'all'
Requires-Dist: psycopg[binary,pool]>=3.1; extra == 'all'
Requires-Dist: pyarrow>=14; extra == 'all'
Requires-Dist: pydantic-settings>=2.0; extra == 'all'
Requires-Dist: pyyaml>=6.0; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.27; extra == 'all'
Provides-Extra: excel
Requires-Dist: xlwings>=0.30; extra == 'excel'
Provides-Extra: parquet
Requires-Dist: pyarrow>=14; extra == 'parquet'
Provides-Extra: pool-server
Requires-Dist: fastapi>=0.110; extra == 'pool-server'
Requires-Dist: psycopg[binary,pool]>=3.1; extra == 'pool-server'
Requires-Dist: pydantic-settings>=2.0; extra == 'pool-server'
Requires-Dist: pyyaml>=6.0; extra == 'pool-server'
Requires-Dist: uvicorn[standard]>=0.27; extra == 'pool-server'
Description-Content-Type: text/markdown

# arcobi-sdk

Load energy-market time-series data from Datahub, align it on a time grid, and export it to a
DataFrame, CSV, Parquet or JSON. Optionally share a pool of vendor credentials across many jobs
through a small lease service. It takes you from the API to a clean, aligned frame or file,
ready for the features and models you build on top.

```bash
pip install --pre arcobi-sdk                 # extraction + export + pool client
pip install --pre "arcobi-sdk[parquet]"      # + Parquet export
pip install --pre "arcobi-sdk[pool-server]"  # + the credential-pool service
```

`--pre` is needed while the package is in beta.

## Quick start

```python
from datetime import datetime, timedelta

from arcobi_sdk import DatahubClient, StreamSpec, fetch_streams, to_csv

end = datetime.now()
start = end - timedelta(days=7)

with DatahubClient(username="...", password="...") as client:
    df = fetch_streams(
        client,
        streams=[
            StreamSpec(stream_id=59242, name="demand"),              # CA - Total Load DAM
            StreamSpec(stream_id=59233, name="price", column="Price"),  # CA - TH_SP15 DAM LMP
        ],
        start=start,
        end=end,
    )

to_csv(df, "week.csv")
```

```
                     demand     price
Date/Time
2026-11-09 21:00:00   25208  58.22430
2026-11-09 22:00:00   23676  57.86549
2026-11-09 23:00:00   22138  57.31887
```

The LMP stream publishes `Price`, `Loss` and `Congestion`, so it needs a `column`; a
single-column stream such as the load one does not.

`fetch_streams` fetches the streams one after another. To fetch in parallel, share the same
client across threads: it is thread-safe and holds the account's single token. Never open a
second client with the same account, Datahub allows one session per account (see the
[credentials guide](https://sdk.arcobi.com/credentials)).

Credentials can also come from the environment (`DATAHUB_USERNAME` / `DATAHUB_PASSWORD`,
or a pre-issued `DATAHUB_BEARER_TOKEN`), or from a local `.env` file loaded with
`arcobi_sdk.load_env()`. The [credentials guide](https://sdk.arcobi.com/credentials) covers every
option and the live smoke test.

## Finding streams

The catalog lists every stream the account can see. It is one large response -- around 440,000
entries -- so filter it rather than pulling the lot, and expect the unfiltered call to take a
while:

```python
with DatahubClient() as client:
    gas = client.list_streams(region="ICE", name_contains="citygate")
    print(gas[["streamId", "streamName", "unitOfMeasure", "dataInterval"]])
```

Each row carries the catalog's own fields: `streamId`, `streamName`, `regionTypeCode`,
`marketTypeCode`, `dataTypeCode`, `commodityName`, `dataTimeZone`, `unitOfMeasure`,
`dataInterval`, `availFromDate`, `latestData` and `discontinued`. There is no description field;
`streamName` is the label. A longer description for one stream is in
`client.fetch_stream_raw(stream_id, start, end)["metaData"]["streamDescription"]`.

Discontinued streams -- about a fifth of the catalog -- are dropped unless you pass
`include_discontinued=True`. Nothing calls the catalog on your behalf.

## Tables that are not time series

`fetch_stream` indexes by time, which suits a price or demand series but not an outage list,
where a day holds many rows and no single column is "the" timestamp. Use `fetch_stream_table`,
which keeps every row and column exactly as published:

```python
with DatahubClient() as client:
    gen = client.fetch_stream_table(85086, "2026-11-01 00:00:00", "2026-11-10 23:59:59")
    tx = client.fetch_stream_table(327409, "2026-11-01 00:00:00", "2026-11-10 23:59:59")

gen["Effective Day"] = pd.to_datetime(gen["Effective Day"], format="mixed")
gen["Curtailed"] = pd.to_numeric(gen["Curtailed"], errors="coerce")

tx["Planned Start"] = pd.to_datetime(tx["Planned Start"], format="mixed")
tx["Actual Start"] = pd.to_datetime(tx["Actual Start"], format="mixed", errors="coerce")
```

Values arrive as the API sent them, so parse the columns you need. Blank actual dates stay
blank. One resource can appear several times a day and one outage ID can carry several
statuses, so do not deduplicate on an ID alone.

## Forward curves

A curve stream has two date dimensions: the day a price was observed, and the month the
contract delivers. Ask for a ten-day window and the API answers with one row per contract,
**averaged over the window** -- the observation day is gone. That is why a plain
`fetch_stream` on a curve is hard to interpret.

`fetch_curve_history` rebuilds the daily history, one request per day:

```python
from arcobi_sdk import DatahubClient, fetch_curve_history

with DatahubClient() as client:
    december = fetch_curve_history(
        client, 101225, "2026-11-01", "2026-11-10", contract_start="2026-12-01"
    )
    every_contract = fetch_curve_history(client, 101225, "2026-11-01", "2026-11-10")
```

```
  settlement_date Contract Start  Avg Open  Avg High  Avg Low  Avg Settle
0      2026-11-02     2026-12-01    0.6500     0.650   0.6350      0.6450
1      2026-11-03     2026-12-01    0.5600     0.575   0.5600      0.5725
2      2026-11-04     2026-12-01    0.5850     0.650   0.5850      0.6400
```

Days the vendor has not published -- weekends, holidays, today before the close -- are absent,
never zero and never carried forward; they are listed in `frame.attrs["missing_days"]`. The
contract set can shrink mid-window as the front month rolls off, which is why the frame is long
rather than one column per contract. `start` and `end` are calendar days in the stream's own
timezone (`frame.attrs["timezone"]`), so pass naive dates.

Because it costs one request per day, the window is capped at 400 days; raise `max_days`
deliberately.

## Sharing credentials across jobs

If several processes share a handful of vendor accounts, run the pool service once and let each
job lease a token. Leases carry a generic **priority level**: `0` is served first, then `1`, then
`2`; the default names are `high`, `normal`, `low` and deployments may rename them.

```python
from arcobi_sdk import DatahubClient, fetch_streams
from arcobi_sdk.pool import PoolClient

pool = PoolClient("http://localhost:8002", api_key="...")
with pool.lease(holder_id="nightly-report", priority="high") as lease:
    with DatahubClient(token_provider=lease.token_provider) as client:
        df = fetch_streams(client, [59242], start, end)
```

The token is refreshed by the service before it expires and the client picks the new one up
mid-extraction. Running the service is described in the
[credential-pool guide](https://sdk.arcobi.com/examples/credential-pool).

## Command line and Excel

Every install also provides a small CLI, handy for scripts, schedulers and spreadsheet macros:

```bash
arcobi-sdk check                                   # authenticate, print token expiry, release
arcobi-sdk fetch --streams 59242 --names demand \
    --start 2026-11-01 --end 2026-11-08 --out week.csv
```

Exit codes are stable (0 ok, 2 bad arguments or config, 3 vendor or auth error, 4 no data) and
errors are one `error: ...` line on stderr, so a VBA `Shell` call can act on them. For Excel,
`ArcobiSdk.bas` is a ready-made macro module that runs the CLI and imports the CSV onto a
sheet. It ships inside the installed package:

```bash
python -c "import importlib.resources as r; print(r.files('arcobi_sdk.excel') / 'vba')"
```

`pip install "arcobi-sdk[excel]"` additionally provides xlwings-based functions (`datahub_fetch`,
`datahub_fetch_to_sheet`, `datahub_check`) for spill formulas and `RunPython`. The
[Excel guide](https://sdk.arcobi.com/excel) walks through both paths.

## What is in the box

| Module | Purpose |
|---|---|
| `arcobi_sdk.datahub` | `DatahubClient`, `fetch_streams`, extraction planning, time-grid alignment, gap interpolation |
| `arcobi_sdk.timeutils` | local-to-UTC conversion, timestamp naming |
| `arcobi_sdk.io` | `to_csv`, `to_parquet`, `to_json`, timestamped output folders |
| `arcobi_sdk.pool` | credential-pool client, priorities, wire protocol; server behind an extra |
| `arcobi_sdk.cli` | `arcobi-sdk fetch / check / version` command line |
| `arcobi_sdk.excel` | Excel helpers: value conversion, xlwings UDFs (extra `excel`), VBA module |

## Documentation

**<https://sdk.arcobi.com>** -- the guides referred to above, plus the API reference generated
from these docstrings:

| Guide | |
|---|---|
| [Installation](https://sdk.arcobi.com/installation) | extras, supported versions |
| [Quick start](https://sdk.arcobi.com/quickstart) | first extraction end to end |
| [Credentials](https://sdk.arcobi.com/credentials) | every way to authenticate, and the live smoke test |
| [Credential pool](https://sdk.arcobi.com/examples/credential-pool) | running and deploying the pool service |
| [Excel](https://sdk.arcobi.com/excel) | the VBA module and the xlwings UDFs |

The same material ships in the source distribution on PyPI, under `docs/` and
`deploy/pool-server/`. A wheel install carries the package only.

## Development

```bash
uv sync --all-extras --dev
uv run pytest
uv run ruff check . && uv run ruff format --check .
```

Tests do not need a database or network access. Tests marked `postgres` run only when
`POOL_TEST_DATABASE_URL` points at a reachable PostgreSQL. Tests marked `live` call the real
Datahub API and run only with `DATAHUB_LIVE=1`, credentials, and `DATAHUB_TEST_STREAM_ID`
set (`uv run pytest -m live`).
