bpstat-pt-api 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bpstat/__init__.py +30 -0
- bpstat/__main__.py +450 -0
- bpstat/client.py +1156 -0
- bpstat/exceptions.py +41 -0
- bpstat/jsonstat.py +212 -0
- bpstat/models.py +127 -0
- bpstat/py.typed +0 -0
- bpstat_pt_api-0.6.0.dist-info/METADATA +445 -0
- bpstat_pt_api-0.6.0.dist-info/RECORD +12 -0
- bpstat_pt_api-0.6.0.dist-info/WHEEL +4 -0
- bpstat_pt_api-0.6.0.dist-info/entry_points.txt +2 -0
- bpstat_pt_api-0.6.0.dist-info/licenses/LICENSE +21 -0
bpstat/client.py
ADDED
|
@@ -0,0 +1,1156 @@
|
|
|
1
|
+
"""HTTP client for the Banco de Portugal BPstat data API.
|
|
2
|
+
|
|
3
|
+
The public entry point is :class:`BPStatClient`. It wraps the REST endpoints
|
|
4
|
+
under ``https://bpstat.bportugal.pt/data/v1`` and returns typed models or tidy
|
|
5
|
+
:class:`pandas.DataFrame` objects.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
import unicodedata
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Any, Literal, cast, overload
|
|
14
|
+
from urllib.parse import urlencode, urlsplit
|
|
15
|
+
|
|
16
|
+
import pandas as pd
|
|
17
|
+
import requests
|
|
18
|
+
from wrapkit.frames import as_polars, empty_tidy, tidy_frame
|
|
19
|
+
from wrapkit.http import RateLimit, RetryPolicy, Throttle, get_with_retries
|
|
20
|
+
from wrapkit.incremental import select_new, upsert
|
|
21
|
+
from wrapkit.io import write_frame
|
|
22
|
+
from wrapkit.log import package_logger
|
|
23
|
+
|
|
24
|
+
from bpstat.exceptions import BPStatHTTPError, SeriesNotFoundError
|
|
25
|
+
from bpstat.jsonstat import jsonstat_to_dataframe
|
|
26
|
+
from bpstat.models import Dataset, Domain, Series
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from collections.abc import Iterable
|
|
30
|
+
from typing import Self
|
|
31
|
+
|
|
32
|
+
import polars as pl
|
|
33
|
+
|
|
34
|
+
DEFAULT_BASE_URL = "https://bpstat.bportugal.pt/data/v1"
|
|
35
|
+
DEFAULT_TIMEOUT = 30.0
|
|
36
|
+
# update_csv re-checks this many days before each series' last stored date for
|
|
37
|
+
# revisions: two years, enough for revised monthly and quarterly releases.
|
|
38
|
+
DEFAULT_LOOKBACK_DAYS = 730
|
|
39
|
+
|
|
40
|
+
# Most series ids the API takes in one ``series_ids`` parameter; a longer list
|
|
41
|
+
# is answered with HTTP 400 ("no more than 100 elements").
|
|
42
|
+
_MAX_IDS_PER_REQUEST = 100
|
|
43
|
+
|
|
44
|
+
# BPstat publishes no request limit. Its API guide only asks users to avoid
|
|
45
|
+
# unnecessary requests ("Evitar pedidos desnecessários"), and a web application
|
|
46
|
+
# firewall sits in front of the API, so the client keeps to one request per
|
|
47
|
+
# second. Every client of the same host shares this budget in the process.
|
|
48
|
+
RATE_LIMIT = RateLimit(
|
|
49
|
+
requests_per_second=1.0,
|
|
50
|
+
source=(
|
|
51
|
+
"no published limit; client default (the API guide asks to avoid "
|
|
52
|
+
"unnecessary requests: https://bpstat.bportugal.pt/api/media/files/"
|
|
53
|
+
"scripts/menu/api.html, read 2026-12-05)"
|
|
54
|
+
),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Retries for transient failures (429, 5xx, dropped connections). A numeric
|
|
58
|
+
# Retry-After is honoured in full up to two minutes; every attempt waits on
|
|
59
|
+
# the throttle.
|
|
60
|
+
RETRY_POLICY = RetryPolicy()
|
|
61
|
+
|
|
62
|
+
# The package logger. As a library it only emits records; its NullHandler keeps
|
|
63
|
+
# them silent until an application (or the CLI, see ``bpstat.__main__``)
|
|
64
|
+
# attaches a handler, e.g. ``logging.getLogger("bpstat").setLevel("DEBUG")``.
|
|
65
|
+
# The API is public and keyless, so there is nothing to redact.
|
|
66
|
+
_log = package_logger("bpstat")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class BPStatClient:
|
|
70
|
+
"""A thin, typed wrapper over the BPstat REST API.
|
|
71
|
+
|
|
72
|
+
Example:
|
|
73
|
+
>>> client = BPStatClient()
|
|
74
|
+
>>> df = client.get_observations(88877)
|
|
75
|
+
>>> df.columns.tolist()
|
|
76
|
+
['reference_date', 'value']
|
|
77
|
+
|
|
78
|
+
The client can be used as a context manager to ensure the underlying HTTP
|
|
79
|
+
session is closed::
|
|
80
|
+
|
|
81
|
+
with BPStatClient() as client:
|
|
82
|
+
frame = client.get_observations([88877, 88878])
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
*,
|
|
88
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
89
|
+
lang: str = "EN",
|
|
90
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
91
|
+
session: requests.Session | None = None,
|
|
92
|
+
requests_per_second: float | None = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""Configure the client.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
base_url: Root URL of the BPstat data API.
|
|
98
|
+
lang: Language code for labels (``"EN"`` or ``"PT"``).
|
|
99
|
+
timeout: Per-request timeout in seconds.
|
|
100
|
+
session: An existing :class:`requests.Session` to reuse. When
|
|
101
|
+
omitted, the client creates and owns one.
|
|
102
|
+
requests_per_second: Request rate. ``None`` (default) or ``0``
|
|
103
|
+
means :data:`RATE_LIMIT`, one request per second; a slower rate
|
|
104
|
+
is allowed. Every client of the same host shares one budget.
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
RateLimitError: If ``requests_per_second`` is faster than
|
|
108
|
+
:data:`RATE_LIMIT` (``wrapkit.http.RateLimitError``).
|
|
109
|
+
""" # ruff: ignore[docstring-extraneous-exception] - RateLimitError propagates from wrapkit Throttle
|
|
110
|
+
# Strip a trailing slash so path joins never produce a double slash.
|
|
111
|
+
self.base_url = base_url.rstrip("/")
|
|
112
|
+
self.lang = lang
|
|
113
|
+
self.timeout = timeout
|
|
114
|
+
# Reuse the caller's session when given (enables shared pools/retries);
|
|
115
|
+
# otherwise create one we own and are responsible for closing.
|
|
116
|
+
self._session = session or requests.Session()
|
|
117
|
+
self._owns_session = session is None
|
|
118
|
+
# One throttle per host, shared by every client in the process, gates
|
|
119
|
+
# every network request (retries included).
|
|
120
|
+
self._throttle = Throttle(
|
|
121
|
+
requests_per_second,
|
|
122
|
+
_log,
|
|
123
|
+
limit=RATE_LIMIT,
|
|
124
|
+
key=urlsplit(self.base_url).netloc or self.base_url,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def __enter__(self) -> Self:
|
|
128
|
+
"""Return ``self`` for use in a ``with`` block."""
|
|
129
|
+
return self
|
|
130
|
+
|
|
131
|
+
def __exit__(self, *_exc: object) -> None:
|
|
132
|
+
"""Close the session on context-manager exit."""
|
|
133
|
+
self.close()
|
|
134
|
+
|
|
135
|
+
def close(self) -> None:
|
|
136
|
+
"""Close the underlying HTTP session if this client created it."""
|
|
137
|
+
if self._owns_session:
|
|
138
|
+
self._session.close()
|
|
139
|
+
|
|
140
|
+
# -- low-level ---------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
def _get(self, path: str, params: dict[str, Any] | None = None) -> Any:
|
|
143
|
+
"""Perform a GET request and return the decoded JSON body.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
path: Path relative to :attr:`base_url` (leading slash optional).
|
|
147
|
+
params: Extra query parameters; ``lang`` is added automatically.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
The decoded JSON payload.
|
|
151
|
+
|
|
152
|
+
Raises:
|
|
153
|
+
BPStatHTTPError: If the response status is not a success code.
|
|
154
|
+
"""
|
|
155
|
+
# lstrip so an accidental leading slash on `path` doesn't double up.
|
|
156
|
+
url = f"{self.base_url}/{path.lstrip('/')}"
|
|
157
|
+
# `lang` is sent on every request; caller params can override/extend it.
|
|
158
|
+
query = {"lang": self.lang, **(params or {})}
|
|
159
|
+
|
|
160
|
+
_log.debug("GET %s %s", path, urlencode(query))
|
|
161
|
+
started = time.monotonic()
|
|
162
|
+
response = get_with_retries(
|
|
163
|
+
self._session,
|
|
164
|
+
url,
|
|
165
|
+
policy=RETRY_POLICY,
|
|
166
|
+
throttle=self._throttle,
|
|
167
|
+
logger=_log,
|
|
168
|
+
label=path,
|
|
169
|
+
params=query,
|
|
170
|
+
timeout=self.timeout,
|
|
171
|
+
)
|
|
172
|
+
_log.debug(
|
|
173
|
+
"HTTP %s for %s in %.2fs",
|
|
174
|
+
response.status_code,
|
|
175
|
+
path,
|
|
176
|
+
time.monotonic() - started,
|
|
177
|
+
)
|
|
178
|
+
if not response.ok:
|
|
179
|
+
# Wrap transport-level failures in our own type, keeping a short
|
|
180
|
+
# slice of the body (full HTML error pages would be noise).
|
|
181
|
+
raise BPStatHTTPError(
|
|
182
|
+
response.status_code, response.url, response.text[:200]
|
|
183
|
+
)
|
|
184
|
+
# Every call goes to the API; no answer is stored on disk.
|
|
185
|
+
return response.json()
|
|
186
|
+
|
|
187
|
+
# -- discovery ---------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
def get_domains(self) -> list[Domain]:
|
|
190
|
+
"""List all statistical domains.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
Every domain exposed by BPstat.
|
|
194
|
+
"""
|
|
195
|
+
payload = self._get("/domains/")
|
|
196
|
+
return [Domain.from_dict(item) for item in payload]
|
|
197
|
+
|
|
198
|
+
def get_datasets(self, domain_id: int) -> list[Dataset]:
|
|
199
|
+
"""List the datasets belonging to a domain.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
domain_id: The domain whose datasets to list.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
The datasets within ``domain_id``.
|
|
206
|
+
"""
|
|
207
|
+
payload = self._get(f"/domains/{domain_id}/datasets/")
|
|
208
|
+
return [Dataset.from_dict(item, domain_id) for item in payload]
|
|
209
|
+
|
|
210
|
+
# -- series metadata ---------------------------------------------------
|
|
211
|
+
|
|
212
|
+
def get_series(self, series_ids: int | Iterable[int]) -> list[Series]:
|
|
213
|
+
"""Fetch metadata for one or more series.
|
|
214
|
+
|
|
215
|
+
More than 100 ids are requested in chunks of 100 (the API rejects
|
|
216
|
+
longer lists) and the results are combined.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
series_ids: A single id or an iterable of ids.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
One :class:`Series` per id that BPstat knows about, preserving the
|
|
223
|
+
requested order. Unknown ids are silently skipped by the API.
|
|
224
|
+
"""
|
|
225
|
+
ids = _normalise_ids(series_ids)
|
|
226
|
+
results: list[Series] = []
|
|
227
|
+
# The API takes a single comma-separated `series_ids` query parameter,
|
|
228
|
+
# of at most _MAX_IDS_PER_REQUEST ids.
|
|
229
|
+
# (An empty list still makes the one request it always made.)
|
|
230
|
+
for start in range(0, max(len(ids), 1), _MAX_IDS_PER_REQUEST):
|
|
231
|
+
chunk = ids[start : start + _MAX_IDS_PER_REQUEST]
|
|
232
|
+
payload = self._get("/series/", {"series_ids": ",".join(map(str, chunk))})
|
|
233
|
+
results.extend(Series.from_dict(item) for item in payload)
|
|
234
|
+
return results
|
|
235
|
+
|
|
236
|
+
def get_series_one(self, series_id: int) -> Series:
|
|
237
|
+
"""Fetch metadata for exactly one series.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
series_id: The series id to resolve.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
The series metadata.
|
|
244
|
+
|
|
245
|
+
Raises:
|
|
246
|
+
SeriesNotFoundError: If BPstat returns no metadata for the id.
|
|
247
|
+
"""
|
|
248
|
+
results = self.get_series(series_id)
|
|
249
|
+
for series in results:
|
|
250
|
+
if series.id == series_id:
|
|
251
|
+
return series
|
|
252
|
+
raise SeriesNotFoundError(series_id)
|
|
253
|
+
|
|
254
|
+
# -- observations ------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
def get_dataset_jsonstat(
|
|
257
|
+
self,
|
|
258
|
+
domain_id: int,
|
|
259
|
+
dataset_id: str,
|
|
260
|
+
series_ids: int | Iterable[int],
|
|
261
|
+
) -> dict[str, Any]:
|
|
262
|
+
"""Fetch the raw JSON-stat payload for series within a dataset.
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
domain_id: The domain that owns the dataset.
|
|
266
|
+
dataset_id: The dataset identifier.
|
|
267
|
+
series_ids: The series to include in the response.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
The decoded JSON-stat 2.0 object.
|
|
271
|
+
|
|
272
|
+
Note:
|
|
273
|
+
When several series from the same dataset are requested together,
|
|
274
|
+
they are distinguished only by a non-time dimension in the returned
|
|
275
|
+
cube. Parsing that cube with ``include_dimensions=False`` collapses
|
|
276
|
+
the series into duplicated dates. Prefer :meth:`get_observations`
|
|
277
|
+
(one request per series) unless you handle the dimensions yourself.
|
|
278
|
+
"""
|
|
279
|
+
ids = _normalise_ids(series_ids)
|
|
280
|
+
payload = self._get(
|
|
281
|
+
f"/domains/{domain_id}/datasets/{dataset_id}/",
|
|
282
|
+
{"series_ids": ",".join(map(str, ids))},
|
|
283
|
+
)
|
|
284
|
+
return cast("dict[str, Any]", payload)
|
|
285
|
+
|
|
286
|
+
@overload
|
|
287
|
+
def get_observations(
|
|
288
|
+
self,
|
|
289
|
+
series_ids: int | Iterable[int],
|
|
290
|
+
*,
|
|
291
|
+
start: str | None = ...,
|
|
292
|
+
end: str | None = ...,
|
|
293
|
+
include_dimensions: bool = ...,
|
|
294
|
+
wide: bool = ...,
|
|
295
|
+
tidy: bool = ...,
|
|
296
|
+
as_polars: Literal[False] = ...,
|
|
297
|
+
) -> pd.DataFrame: ...
|
|
298
|
+
|
|
299
|
+
@overload
|
|
300
|
+
def get_observations(
|
|
301
|
+
self,
|
|
302
|
+
series_ids: int | Iterable[int],
|
|
303
|
+
*,
|
|
304
|
+
start: str | None = ...,
|
|
305
|
+
end: str | None = ...,
|
|
306
|
+
include_dimensions: bool = ...,
|
|
307
|
+
wide: bool = ...,
|
|
308
|
+
tidy: bool = ...,
|
|
309
|
+
as_polars: Literal[True],
|
|
310
|
+
) -> pl.DataFrame: ...
|
|
311
|
+
|
|
312
|
+
def get_observations( # ruff: ignore[too-many-arguments] - keyword-only output options
|
|
313
|
+
self,
|
|
314
|
+
series_ids: int | Iterable[int],
|
|
315
|
+
*,
|
|
316
|
+
start: str | None = None,
|
|
317
|
+
end: str | None = None,
|
|
318
|
+
include_dimensions: bool = False,
|
|
319
|
+
wide: bool = False,
|
|
320
|
+
tidy: bool = False,
|
|
321
|
+
as_polars: bool = False,
|
|
322
|
+
) -> pd.DataFrame | pl.DataFrame:
|
|
323
|
+
"""Fetch observations for one or more series as a tidy DataFrame.
|
|
324
|
+
|
|
325
|
+
Metadata is resolved first to locate each series' domain and dataset,
|
|
326
|
+
then observations are fetched (one request per series) and concatenated.
|
|
327
|
+
|
|
328
|
+
Args:
|
|
329
|
+
series_ids: A single id or an iterable of ids.
|
|
330
|
+
start: Keep only observations on or after this date (any value
|
|
331
|
+
:func:`pandas.to_datetime` accepts, e.g. ``"2000"`` or
|
|
332
|
+
``"2000-01"``, or a compact ``"200001"`` month). ``None``
|
|
333
|
+
means no lower bound.
|
|
334
|
+
end: Keep only observations on or before this date. ``None`` means
|
|
335
|
+
no upper bound.
|
|
336
|
+
include_dimensions: Forwarded to
|
|
337
|
+
:func:`bpstat.jsonstat.jsonstat_to_dataframe`; adds one column
|
|
338
|
+
per non-time dimension. Mutually exclusive with ``wide``.
|
|
339
|
+
wide: When ``True``, pivot to one column per ``series_id`` indexed by
|
|
340
|
+
``reference_date`` (reset to a column). When ``False`` (default),
|
|
341
|
+
return long format.
|
|
342
|
+
tidy: When ``True``, return the long shape shared by the author's
|
|
343
|
+
other API wrappers: ``date`` (the period *start*, derived from
|
|
344
|
+
BPstat's period-end ``reference_date`` and the series'
|
|
345
|
+
``Periodicity`` dimension), ``series_id`` (string), ``value``
|
|
346
|
+
(``float64``) and ``unit`` (the series' ``Unit of measure``
|
|
347
|
+
dimension, ``<NA>`` when absent), sorted by ``series_id`` then
|
|
348
|
+
``date``. Cannot be combined with ``wide`` or
|
|
349
|
+
``include_dimensions``.
|
|
350
|
+
as_polars: When ``True``, return a :class:`polars.DataFrame`
|
|
351
|
+
(requires the ``polars`` extra); works with ``tidy`` too.
|
|
352
|
+
|
|
353
|
+
Returns:
|
|
354
|
+
A long-format DataFrame with columns ``series_id``,
|
|
355
|
+
``series_label``, ``reference_date`` and ``value`` (plus dimension
|
|
356
|
+
columns when requested), a wide frame when ``wide=True``, or the
|
|
357
|
+
tidy shape when ``tidy=True``.
|
|
358
|
+
|
|
359
|
+
Raises:
|
|
360
|
+
SeriesNotFoundError: If a requested id has no metadata.
|
|
361
|
+
ValueError: If ``wide`` and ``include_dimensions`` are both set, or
|
|
362
|
+
``tidy`` is combined with either.
|
|
363
|
+
"""
|
|
364
|
+
if wide and include_dimensions:
|
|
365
|
+
msg = "wide=True and include_dimensions=True are mutually exclusive"
|
|
366
|
+
raise ValueError(msg)
|
|
367
|
+
if tidy and (wide or include_dimensions):
|
|
368
|
+
msg = "tidy=True cannot be combined with wide or include_dimensions"
|
|
369
|
+
raise ValueError(msg)
|
|
370
|
+
|
|
371
|
+
ids = _normalise_ids(series_ids)
|
|
372
|
+
# Resolve all metadata in one request, then index by id for O(1) lookup
|
|
373
|
+
# while iterating `ids` in the caller's requested order.
|
|
374
|
+
metadata = {s.id: s for s in self.get_series(ids)}
|
|
375
|
+
|
|
376
|
+
frames: list[pd.DataFrame] = []
|
|
377
|
+
# Per-series unit and periodicity labels, read from the cube (tidy only).
|
|
378
|
+
units: dict[int, str | None] = {}
|
|
379
|
+
periodicities: dict[int, str | None] = {}
|
|
380
|
+
for series_id in ids:
|
|
381
|
+
series = metadata.get(series_id)
|
|
382
|
+
if series is None:
|
|
383
|
+
# The API silently drops unknown ids; surface that explicitly.
|
|
384
|
+
raise SeriesNotFoundError(series_id)
|
|
385
|
+
domain_id = series.primary_domain_id
|
|
386
|
+
if domain_id is None:
|
|
387
|
+
# No domain means no observations endpoint to hit; skip it.
|
|
388
|
+
continue
|
|
389
|
+
# One request per series: a single-series cube collapses every
|
|
390
|
+
# non-time dimension to size 1, so values map cleanly to this id
|
|
391
|
+
# (requesting several at once would interleave them ambiguously).
|
|
392
|
+
payload = self.get_dataset_jsonstat(domain_id, series.dataset_id, series_id)
|
|
393
|
+
frame = jsonstat_to_dataframe(
|
|
394
|
+
payload, include_dimensions=include_dimensions
|
|
395
|
+
)
|
|
396
|
+
_log.debug("Series %d: %d observations", series_id, len(frame))
|
|
397
|
+
units[series.id] = _cube_attribute(payload, _UNIT_LABELS)
|
|
398
|
+
periodicities[series.id] = _cube_attribute(payload, _PERIODICITY_LABELS)
|
|
399
|
+
if frame.empty:
|
|
400
|
+
continue
|
|
401
|
+
# Prepend identity columns so the concatenated frame is self-describing.
|
|
402
|
+
frame.insert(0, "series_label", series.label)
|
|
403
|
+
frame.insert(0, "series_id", series.id)
|
|
404
|
+
frames.append(frame)
|
|
405
|
+
|
|
406
|
+
if not frames:
|
|
407
|
+
_log.info("Fetched 0 observations for %d series", len(ids))
|
|
408
|
+
# Return an empty but correctly-typed frame rather than a bare one.
|
|
409
|
+
result = pd.DataFrame(
|
|
410
|
+
columns=["series_id", "series_label", "reference_date", "value"]
|
|
411
|
+
)
|
|
412
|
+
else:
|
|
413
|
+
result = pd.concat(frames, ignore_index=True)
|
|
414
|
+
result = _filter_dates(result, start, end)
|
|
415
|
+
_log.info("Fetched %d observations for %d series", len(result), len(ids))
|
|
416
|
+
if tidy:
|
|
417
|
+
result = _to_tidy(result, units, periodicities)
|
|
418
|
+
elif wide:
|
|
419
|
+
result = _to_wide(result)
|
|
420
|
+
return _as_polars(result) if as_polars else result
|
|
421
|
+
|
|
422
|
+
def to_csv( # ruff: ignore[too-many-arguments] - keyword-only output options
|
|
423
|
+
self,
|
|
424
|
+
path: str | Path,
|
|
425
|
+
series_ids: int | Iterable[int],
|
|
426
|
+
*,
|
|
427
|
+
start: str | None = None,
|
|
428
|
+
end: str | None = None,
|
|
429
|
+
include_dimensions: bool = False,
|
|
430
|
+
wide: bool = False,
|
|
431
|
+
tidy: bool = False,
|
|
432
|
+
) -> int:
|
|
433
|
+
"""Fetch observations and write them to a CSV file.
|
|
434
|
+
|
|
435
|
+
Args:
|
|
436
|
+
path: Destination CSV path.
|
|
437
|
+
series_ids: A single id or an iterable of ids.
|
|
438
|
+
start: Lower date bound (see :meth:`get_observations`).
|
|
439
|
+
end: Upper date bound (see :meth:`get_observations`).
|
|
440
|
+
include_dimensions: Keep non-time dimension columns.
|
|
441
|
+
wide: Write wide format (one column per series).
|
|
442
|
+
tidy: Write the tidy shape (see :meth:`get_observations`).
|
|
443
|
+
|
|
444
|
+
Returns:
|
|
445
|
+
The number of rows written.
|
|
446
|
+
"""
|
|
447
|
+
frame = self.get_observations(
|
|
448
|
+
series_ids,
|
|
449
|
+
start=start,
|
|
450
|
+
end=end,
|
|
451
|
+
include_dimensions=include_dimensions,
|
|
452
|
+
wide=wide,
|
|
453
|
+
tidy=tidy,
|
|
454
|
+
)
|
|
455
|
+
write_frame(frame, path, "csv")
|
|
456
|
+
_log.info("Wrote %d rows to %s", len(frame), path)
|
|
457
|
+
return len(frame)
|
|
458
|
+
|
|
459
|
+
def to_excel( # ruff: ignore[too-many-arguments] - keyword-only output options
|
|
460
|
+
self,
|
|
461
|
+
path: str | Path,
|
|
462
|
+
series_ids: int | Iterable[int],
|
|
463
|
+
*,
|
|
464
|
+
start: str | None = None,
|
|
465
|
+
end: str | None = None,
|
|
466
|
+
include_dimensions: bool = False,
|
|
467
|
+
wide: bool = False,
|
|
468
|
+
tidy: bool = False,
|
|
469
|
+
) -> int:
|
|
470
|
+
"""Fetch observations and write them to an Excel workbook.
|
|
471
|
+
|
|
472
|
+
Requires the ``openpyxl`` engine (installed as a dependency).
|
|
473
|
+
|
|
474
|
+
Args:
|
|
475
|
+
path: Destination ``.xlsx`` path.
|
|
476
|
+
series_ids: A single id or an iterable of ids.
|
|
477
|
+
start: Lower date bound (see :meth:`get_observations`).
|
|
478
|
+
end: Upper date bound (see :meth:`get_observations`).
|
|
479
|
+
include_dimensions: Keep non-time dimension columns.
|
|
480
|
+
wide: Write wide format (one column per series).
|
|
481
|
+
tidy: Write the tidy shape (see :meth:`get_observations`).
|
|
482
|
+
|
|
483
|
+
Returns:
|
|
484
|
+
The number of rows written.
|
|
485
|
+
"""
|
|
486
|
+
frame = self.get_observations(
|
|
487
|
+
series_ids,
|
|
488
|
+
start=start,
|
|
489
|
+
end=end,
|
|
490
|
+
include_dimensions=include_dimensions,
|
|
491
|
+
wide=wide,
|
|
492
|
+
tidy=tidy,
|
|
493
|
+
)
|
|
494
|
+
frame.to_excel(path, index=False)
|
|
495
|
+
_log.info("Wrote %d rows to %s", len(frame), path)
|
|
496
|
+
return len(frame)
|
|
497
|
+
|
|
498
|
+
def to_parquet( # ruff: ignore[too-many-arguments] - keyword-only output options
|
|
499
|
+
self,
|
|
500
|
+
path: str | Path,
|
|
501
|
+
series_ids: int | Iterable[int],
|
|
502
|
+
*,
|
|
503
|
+
start: str | None = None,
|
|
504
|
+
end: str | None = None,
|
|
505
|
+
include_dimensions: bool = False,
|
|
506
|
+
wide: bool = False,
|
|
507
|
+
tidy: bool = False,
|
|
508
|
+
) -> Path:
|
|
509
|
+
"""Fetch observations and write them to a Parquet file.
|
|
510
|
+
|
|
511
|
+
Uses the ``pyarrow`` engine (installed as a dependency).
|
|
512
|
+
|
|
513
|
+
Args:
|
|
514
|
+
path: Destination ``.parquet`` path.
|
|
515
|
+
series_ids: A single id or an iterable of ids.
|
|
516
|
+
start: Lower date bound (see :meth:`get_observations`).
|
|
517
|
+
end: Upper date bound (see :meth:`get_observations`).
|
|
518
|
+
include_dimensions: Keep non-time dimension columns.
|
|
519
|
+
wide: Write wide format (one column per series).
|
|
520
|
+
tidy: Write the tidy shape (see :meth:`get_observations`).
|
|
521
|
+
|
|
522
|
+
Returns:
|
|
523
|
+
The path that was written.
|
|
524
|
+
"""
|
|
525
|
+
frame = self.get_observations(
|
|
526
|
+
series_ids,
|
|
527
|
+
start=start,
|
|
528
|
+
end=end,
|
|
529
|
+
include_dimensions=include_dimensions,
|
|
530
|
+
wide=wide,
|
|
531
|
+
tidy=tidy,
|
|
532
|
+
)
|
|
533
|
+
if wide:
|
|
534
|
+
# Parquet column names must be strings; wide columns are series ids.
|
|
535
|
+
frame.columns = [str(c) for c in frame.columns]
|
|
536
|
+
parquet_path = write_frame(frame, path, "parquet")
|
|
537
|
+
_log.info("Wrote %d rows to %s", len(frame), parquet_path)
|
|
538
|
+
return parquet_path
|
|
539
|
+
|
|
540
|
+
def new_observations(
|
|
541
|
+
self,
|
|
542
|
+
existing: pd.DataFrame | str | Path | None,
|
|
543
|
+
series_ids: int | Iterable[int] | None = None,
|
|
544
|
+
*,
|
|
545
|
+
include_dimensions: bool = False,
|
|
546
|
+
tidy: bool = False,
|
|
547
|
+
) -> pd.DataFrame:
|
|
548
|
+
"""Return only the observations newer than what ``existing`` holds.
|
|
549
|
+
|
|
550
|
+
Give it what you already have and it returns just the missing rows
|
|
551
|
+
(strictly newer dates; unlike :meth:`update_csv`, it does not look back
|
|
552
|
+
for revised values). It is equivalent to :meth:`update_observations`
|
|
553
|
+
with ``new_only=True``.
|
|
554
|
+
|
|
555
|
+
Args:
|
|
556
|
+
existing: A long DataFrame, a CSV path, or ``None`` for a first run.
|
|
557
|
+
series_ids: Series to refresh; inferred from ``existing`` when
|
|
558
|
+
``None``.
|
|
559
|
+
include_dimensions: Keep non-time dimension columns.
|
|
560
|
+
tidy: ``existing`` and the result use the tidy shape (see
|
|
561
|
+
:meth:`get_observations`).
|
|
562
|
+
|
|
563
|
+
Returns:
|
|
564
|
+
Only the new rows.
|
|
565
|
+
"""
|
|
566
|
+
return self.update_observations(
|
|
567
|
+
existing,
|
|
568
|
+
series_ids,
|
|
569
|
+
include_dimensions=include_dimensions,
|
|
570
|
+
tidy=tidy,
|
|
571
|
+
new_only=True,
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
def update_csv(
|
|
575
|
+
self,
|
|
576
|
+
path: str | Path,
|
|
577
|
+
series_ids: int | Iterable[int] | None = None,
|
|
578
|
+
*,
|
|
579
|
+
include_dimensions: bool = False,
|
|
580
|
+
tidy: bool = False,
|
|
581
|
+
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
|
|
582
|
+
) -> pd.DataFrame:
|
|
583
|
+
"""Incrementally update a long-format CSV file in place.
|
|
584
|
+
|
|
585
|
+
On the first run (file missing) the full history is written. Later runs
|
|
586
|
+
read the file and, for each series, compare the fetched observations
|
|
587
|
+
from ``lookback_days`` before its last stored date onwards with what
|
|
588
|
+
the file holds, since Banco de Portugal revises recent figures. The
|
|
589
|
+
rows are upserted on series and date: new dates are appended and
|
|
590
|
+
revised values overwrite the stored ones; older history is kept as
|
|
591
|
+
stored. Series not yet in the file are added in full. The file is left
|
|
592
|
+
untouched when nothing is new or revised.
|
|
593
|
+
|
|
594
|
+
Args:
|
|
595
|
+
path: The CSV file to create or update.
|
|
596
|
+
series_ids: Series to refresh; required on the first run, otherwise
|
|
597
|
+
inferred from the file.
|
|
598
|
+
include_dimensions: Keep non-time dimension columns.
|
|
599
|
+
tidy: Keep the file in the tidy shape (see
|
|
600
|
+
:meth:`get_observations`); use the same shape for a given file.
|
|
601
|
+
lookback_days: Days before each series' last stored date that are
|
|
602
|
+
re-checked for revisions (two years by default; ``0`` re-checks
|
|
603
|
+
only the last stored date).
|
|
604
|
+
|
|
605
|
+
Returns:
|
|
606
|
+
The rows newly added or revised (empty when the file was already
|
|
607
|
+
current).
|
|
608
|
+
|
|
609
|
+
Raises:
|
|
610
|
+
ValueError: If ``lookback_days`` is negative.
|
|
611
|
+
"""
|
|
612
|
+
if lookback_days < 0:
|
|
613
|
+
msg = f"lookback_days must be zero or more, got {lookback_days!r}"
|
|
614
|
+
raise ValueError(msg)
|
|
615
|
+
csv_path = Path(path)
|
|
616
|
+
existing: str | None = str(csv_path) if csv_path.exists() else None
|
|
617
|
+
existing_df = _load_existing(existing, tidy=tidy)
|
|
618
|
+
date_col = _date_column(tidy=tidy)
|
|
619
|
+
fresh = self._fetch_after(
|
|
620
|
+
existing_df,
|
|
621
|
+
series_ids,
|
|
622
|
+
include_dimensions=include_dimensions,
|
|
623
|
+
tidy=tidy,
|
|
624
|
+
lookback_days=lookback_days,
|
|
625
|
+
)
|
|
626
|
+
keys = ["series_id", date_col]
|
|
627
|
+
# A changed unit label is a revision too (only the tidy shape has one).
|
|
628
|
+
values = ["value", "unit"] if tidy else ["value"]
|
|
629
|
+
changed = select_new(fresh, existing_df, keys, values, date_cols=[date_col])
|
|
630
|
+
if changed.empty and existing is not None:
|
|
631
|
+
# Nothing new or revised and the file exists: leave it as-is.
|
|
632
|
+
_log.info("%s is already up to date", csv_path)
|
|
633
|
+
return changed
|
|
634
|
+
if existing_df.empty:
|
|
635
|
+
combined = changed.sort_values(keys).reset_index(drop=True)
|
|
636
|
+
else:
|
|
637
|
+
# The fresh row wins on a key clash. Long series ids are integers
|
|
638
|
+
# and sort as numbers; tidy ones are strings and sort as text.
|
|
639
|
+
combined = upsert(
|
|
640
|
+
existing_df,
|
|
641
|
+
changed,
|
|
642
|
+
keys,
|
|
643
|
+
date_cols=[date_col],
|
|
644
|
+
numeric_cols=[] if tidy else ["series_id"],
|
|
645
|
+
)
|
|
646
|
+
combined.to_csv(csv_path, index=False)
|
|
647
|
+
if existing is None:
|
|
648
|
+
_log.info("Created %s with %d rows", csv_path, len(combined))
|
|
649
|
+
else:
|
|
650
|
+
_log.info(
|
|
651
|
+
"Added or revised %d observations in %s (%d rows total)",
|
|
652
|
+
len(changed),
|
|
653
|
+
csv_path,
|
|
654
|
+
len(combined),
|
|
655
|
+
)
|
|
656
|
+
return changed
|
|
657
|
+
|
|
658
|
+
def update_observations(
|
|
659
|
+
self,
|
|
660
|
+
existing: pd.DataFrame | str | Path | None,
|
|
661
|
+
series_ids: int | Iterable[int] | None = None,
|
|
662
|
+
*,
|
|
663
|
+
include_dimensions: bool = False,
|
|
664
|
+
tidy: bool = False,
|
|
665
|
+
new_only: bool = False,
|
|
666
|
+
) -> pd.DataFrame:
|
|
667
|
+
"""Incrementally fetch only observations newer than those already held.
|
|
668
|
+
|
|
669
|
+
For every target series the latest ``reference_date`` present in
|
|
670
|
+
``existing`` is computed; the series is re-fetched and only rows
|
|
671
|
+
strictly after that date are kept. Series absent from ``existing`` are
|
|
672
|
+
extracted in full. Repeated runs are therefore incremental: data that
|
|
673
|
+
is already stored is never re-added to the result.
|
|
674
|
+
|
|
675
|
+
This assumes each stored series is contiguous up to its latest date;
|
|
676
|
+
gaps *below* a series' maximum date are not backfilled.
|
|
677
|
+
|
|
678
|
+
Args:
|
|
679
|
+
existing: Previously extracted observations, as a DataFrame, a path
|
|
680
|
+
to a CSV written by this library, or ``None`` for a first run.
|
|
681
|
+
Must contain ``series_id`` and ``reference_date`` columns.
|
|
682
|
+
series_ids: Series to refresh. When ``None``, the distinct
|
|
683
|
+
``series_id`` values in ``existing`` are used; ids passed here
|
|
684
|
+
that are absent from ``existing`` are extracted in full.
|
|
685
|
+
include_dimensions: Forwarded to :meth:`get_observations`.
|
|
686
|
+
tidy: Work in the tidy shape (see :meth:`get_observations`):
|
|
687
|
+
``existing`` must then have ``series_id`` and ``date``, and the
|
|
688
|
+
cutoff is applied to ``date``.
|
|
689
|
+
new_only: When ``True``, return only the newly fetched rows;
|
|
690
|
+
otherwise (default) return ``existing`` concatenated with them,
|
|
691
|
+
sorted by series then date.
|
|
692
|
+
|
|
693
|
+
Returns:
|
|
694
|
+
The new rows alone (``new_only=True``) or the combined dataset.
|
|
695
|
+
|
|
696
|
+
Raises:
|
|
697
|
+
SeriesNotFoundError: If a requested id has no metadata.
|
|
698
|
+
ValueError: If ``existing`` lacks the required columns, or if no
|
|
699
|
+
series can be determined (empty ``existing`` and no
|
|
700
|
+
``series_ids``).
|
|
701
|
+
|
|
702
|
+
Note:
|
|
703
|
+
BPstat's dataset endpoint ignores server-side date filters, so the
|
|
704
|
+
full series is fetched over the wire and trimmed client-side; the
|
|
705
|
+
saving is in the rows returned/appended, not in bandwidth.
|
|
706
|
+
""" # ruff: ignore[docstring-extraneous-exception] - SeriesNotFoundError propagates from get_observations
|
|
707
|
+
existing_df = _load_existing(existing, tidy=tidy)
|
|
708
|
+
date_col = _date_column(tidy=tidy)
|
|
709
|
+
fresh = self._fetch_after(
|
|
710
|
+
existing_df,
|
|
711
|
+
series_ids,
|
|
712
|
+
include_dimensions=include_dimensions,
|
|
713
|
+
tidy=tidy,
|
|
714
|
+
lookback_days=None,
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
if new_only:
|
|
718
|
+
return fresh
|
|
719
|
+
|
|
720
|
+
# Only concatenate non-empty frames: joining an empty (all-object)
|
|
721
|
+
# frame would emit a pandas FutureWarning about all-NA concatenation.
|
|
722
|
+
parts = [frame for frame in (existing_df, fresh) if not frame.empty]
|
|
723
|
+
if not parts:
|
|
724
|
+
return existing_df
|
|
725
|
+
combined = pd.concat(parts, ignore_index=True)
|
|
726
|
+
return combined.sort_values(["series_id", date_col]).reset_index(drop=True)
|
|
727
|
+
|
|
728
|
+
def _fetch_after(
|
|
729
|
+
self,
|
|
730
|
+
existing_df: pd.DataFrame,
|
|
731
|
+
series_ids: int | Iterable[int] | None,
|
|
732
|
+
*,
|
|
733
|
+
include_dimensions: bool,
|
|
734
|
+
tidy: bool,
|
|
735
|
+
lookback_days: int | None,
|
|
736
|
+
) -> pd.DataFrame:
|
|
737
|
+
"""Fetch the target series, keeping rows past each stored series' cutoff.
|
|
738
|
+
|
|
739
|
+
The cutoff is the latest date ``existing_df`` holds for the series.
|
|
740
|
+
With ``lookback_days=None`` only rows strictly after it are kept;
|
|
741
|
+
otherwise rows on or after ``lookback_days`` before it are kept, so
|
|
742
|
+
that revised values can be compared. Series absent from
|
|
743
|
+
``existing_df`` are kept in full.
|
|
744
|
+
|
|
745
|
+
Args:
|
|
746
|
+
existing_df: The stored rows, as returned by :func:`_load_existing`.
|
|
747
|
+
series_ids: Series to refresh; inferred from ``existing_df`` when
|
|
748
|
+
``None``.
|
|
749
|
+
include_dimensions: Forwarded to :meth:`get_observations`.
|
|
750
|
+
tidy: Work in the tidy shape (the cutoff applies to ``date``).
|
|
751
|
+
lookback_days: Days re-checked before the cutoff, or ``None`` for a
|
|
752
|
+
strictly-newer cutoff.
|
|
753
|
+
|
|
754
|
+
Returns:
|
|
755
|
+
The fetched rows past each series' cutoff.
|
|
756
|
+
|
|
757
|
+
Raises:
|
|
758
|
+
ValueError: If no series can be determined (empty ``existing_df``
|
|
759
|
+
and no ``series_ids``).
|
|
760
|
+
"""
|
|
761
|
+
date_col = _date_column(tidy=tidy)
|
|
762
|
+
|
|
763
|
+
# Decide which series to refresh.
|
|
764
|
+
if series_ids is not None:
|
|
765
|
+
ids = _normalise_ids(series_ids)
|
|
766
|
+
elif not existing_df.empty:
|
|
767
|
+
ids = [int(sid) for sid in existing_df["series_id"].unique()]
|
|
768
|
+
else:
|
|
769
|
+
msg = "Provide series_ids when there is no existing data to update."
|
|
770
|
+
raise ValueError(msg)
|
|
771
|
+
|
|
772
|
+
# Latest date already stored per series (the per-series cutoff).
|
|
773
|
+
last_seen: dict[int, pd.Timestamp] = {}
|
|
774
|
+
if not existing_df.empty:
|
|
775
|
+
maxima = (
|
|
776
|
+
existing_df.dropna(subset=[date_col])
|
|
777
|
+
.groupby("series_id")[date_col]
|
|
778
|
+
.max()
|
|
779
|
+
)
|
|
780
|
+
# ``.items()`` types the key as ``Hashable``; the values are the
|
|
781
|
+
# series ids we grouped by, so coercion to ``int`` is safe.
|
|
782
|
+
last_seen = {int(cast("Any", sid)): ts for sid, ts in maxima.items()}
|
|
783
|
+
|
|
784
|
+
fresh = self.get_observations(
|
|
785
|
+
ids, include_dimensions=include_dimensions, tidy=tidy
|
|
786
|
+
)
|
|
787
|
+
|
|
788
|
+
# Series with no cutoff (never seen before) are kept in full.
|
|
789
|
+
if not fresh.empty and last_seen:
|
|
790
|
+
# Map each row to its series' cutoff (NaT for never-seen series).
|
|
791
|
+
# The tidy shape holds series_id as a string, hence the int cast.
|
|
792
|
+
cutoff = pd.to_datetime(fresh["series_id"].astype(int).map(last_seen))
|
|
793
|
+
# Without a look-back keep only strictly newer rows (the boundary
|
|
794
|
+
# is already stored); with one, keep the whole window to compare.
|
|
795
|
+
after = (
|
|
796
|
+
fresh[date_col] > cutoff
|
|
797
|
+
if lookback_days is None
|
|
798
|
+
else fresh[date_col] >= cutoff - pd.Timedelta(days=lookback_days)
|
|
799
|
+
)
|
|
800
|
+
keep = cutoff.isna() | after
|
|
801
|
+
fresh = fresh[keep].reset_index(drop=True)
|
|
802
|
+
_log.debug(
|
|
803
|
+
"%d observations across %d series past the existing data's cutoff",
|
|
804
|
+
len(fresh),
|
|
805
|
+
len(ids),
|
|
806
|
+
)
|
|
807
|
+
return fresh
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def _load_existing(
|
|
811
|
+
existing: pd.DataFrame | str | Path | None, *, tidy: bool = False
|
|
812
|
+
) -> pd.DataFrame:
|
|
813
|
+
"""Normalise the ``existing`` argument into a validated DataFrame.
|
|
814
|
+
|
|
815
|
+
Args:
|
|
816
|
+
existing: A DataFrame, a CSV path, or ``None``.
|
|
817
|
+
tidy: ``existing`` is in the tidy shape (``date`` rather than
|
|
818
|
+
``reference_date``; ``series_id`` and ``unit`` as strings).
|
|
819
|
+
|
|
820
|
+
Returns:
|
|
821
|
+
A DataFrame whose date column (if present and non-empty) is parsed to
|
|
822
|
+
``datetime64``. An empty, correctly-typed frame is returned for
|
|
823
|
+
``None`` and for an empty (zero-byte) CSV file.
|
|
824
|
+
|
|
825
|
+
Raises:
|
|
826
|
+
ValueError: If required columns are missing from a non-empty input.
|
|
827
|
+
"""
|
|
828
|
+
date_col = _date_column(tidy=tidy)
|
|
829
|
+
empty_cols = (
|
|
830
|
+
list(_TIDY_COLUMNS)
|
|
831
|
+
if tidy
|
|
832
|
+
else ["series_id", "series_label", "reference_date", "value"]
|
|
833
|
+
)
|
|
834
|
+
if existing is None:
|
|
835
|
+
return pd.DataFrame(columns=empty_cols)
|
|
836
|
+
|
|
837
|
+
# Accept either an in-memory frame or a CSV path on disk.
|
|
838
|
+
if isinstance(existing, (str, Path)):
|
|
839
|
+
# Read ``value`` as text and convert it with astype, which gives back
|
|
840
|
+
# exactly the floats to_csv wrote. pandas' default CSV parser (and
|
|
841
|
+
# pd.to_numeric before pandas 3.1) can be one unit in the last place
|
|
842
|
+
# off, which would look like a revision; float_precision="round_trip"
|
|
843
|
+
# is deprecated in pandas 3.1. Other columns keep their parsed dtypes.
|
|
844
|
+
# A zero-byte file holds no rows yet, like a missing one.
|
|
845
|
+
if Path(existing).stat().st_size == 0:
|
|
846
|
+
return pd.DataFrame(columns=empty_cols)
|
|
847
|
+
# Only an empty field is missing: a label or dimension code such as
|
|
848
|
+
# "NA" or "null" stays text instead of turning into NaN.
|
|
849
|
+
frame = pd.read_csv(
|
|
850
|
+
existing, dtype={"value": str}, keep_default_na=False, na_values=[""]
|
|
851
|
+
)
|
|
852
|
+
if "value" in frame.columns:
|
|
853
|
+
frame["value"] = frame["value"].astype("float64")
|
|
854
|
+
else:
|
|
855
|
+
frame = existing.copy()
|
|
856
|
+
|
|
857
|
+
if frame.empty:
|
|
858
|
+
return frame
|
|
859
|
+
|
|
860
|
+
required = {"series_id", date_col}
|
|
861
|
+
missing = required - set(frame.columns)
|
|
862
|
+
if missing:
|
|
863
|
+
msg = f"existing data is missing required column(s): {sorted(missing)}"
|
|
864
|
+
raise ValueError(msg)
|
|
865
|
+
|
|
866
|
+
# Comparisons rely on a real datetime dtype regardless of the source.
|
|
867
|
+
frame[date_col] = pd.to_datetime(frame[date_col], errors="coerce")
|
|
868
|
+
if tidy:
|
|
869
|
+
# Match the fresh tidy dtypes so concatenation and sorting line up after
|
|
870
|
+
# a CSV round-trip (which reads series_id back as an integer).
|
|
871
|
+
frame[date_col] = frame[date_col].astype("datetime64[ns]")
|
|
872
|
+
for col in ("series_id", "unit"):
|
|
873
|
+
if col in frame.columns:
|
|
874
|
+
frame[col] = frame[col].astype(pd.StringDtype())
|
|
875
|
+
return frame
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _filter_dates(
|
|
879
|
+
frame: pd.DataFrame,
|
|
880
|
+
start: str | None,
|
|
881
|
+
end: str | None,
|
|
882
|
+
) -> pd.DataFrame:
|
|
883
|
+
"""Restrict a long frame to a ``[start, end]`` reference-date window.
|
|
884
|
+
|
|
885
|
+
Args:
|
|
886
|
+
frame: A long frame with a datetime ``reference_date`` column.
|
|
887
|
+
start: Inclusive lower bound, or ``None``.
|
|
888
|
+
end: Inclusive upper bound, or ``None``.
|
|
889
|
+
|
|
890
|
+
Returns:
|
|
891
|
+
The filtered frame (unchanged when both bounds are ``None``).
|
|
892
|
+
"""
|
|
893
|
+
if frame.empty or (start is None and end is None):
|
|
894
|
+
return frame
|
|
895
|
+
dates = frame["reference_date"]
|
|
896
|
+
# Build a boolean mask, tightening it for whichever bounds were given.
|
|
897
|
+
mask = pd.Series(data=True, index=frame.index)
|
|
898
|
+
if start is not None:
|
|
899
|
+
# A partial `start` (e.g. "2025") resolves to the start of the period,
|
|
900
|
+
# which is already the inclusive lower bound we want.
|
|
901
|
+
# str(): a bare int such as 2025 would otherwise be read as nanoseconds
|
|
902
|
+
# since the epoch, keeping every row.
|
|
903
|
+
mask &= dates >= pd.Timestamp(_iso_month(str(start)))
|
|
904
|
+
if end is not None:
|
|
905
|
+
# A partial `end` must expand to the *end* of its period; otherwise
|
|
906
|
+
# "2025" would mean 2025-01-01 and exclude period-end-dated rows (BPstat
|
|
907
|
+
# observations are stamped at month/quarter/year end).
|
|
908
|
+
mask &= dates <= _period_end(_iso_month(str(end)))
|
|
909
|
+
return frame[mask].reset_index(drop=True)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def _iso_month(value: str) -> str:
|
|
913
|
+
"""Rewrite a compact ``YYYYMM`` month as ``YYYY-MM``.
|
|
914
|
+
|
|
915
|
+
pandas cannot parse ``"202402"`` (it is not read as February 2024), but it
|
|
916
|
+
reads ``"2024-02"``. Other values are returned unchanged.
|
|
917
|
+
|
|
918
|
+
Args:
|
|
919
|
+
value: A date bound as given by the caller.
|
|
920
|
+
|
|
921
|
+
Returns:
|
|
922
|
+
``value``, with a six-digit ``YYYYMM`` month rewritten as ``YYYY-MM``.
|
|
923
|
+
"""
|
|
924
|
+
if len(value) == len("YYYYMM") and value.isascii() and value.isdigit():
|
|
925
|
+
return f"{value[:4]}-{value[4:]}"
|
|
926
|
+
return value
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _period_end(value: str) -> pd.Timestamp:
|
|
930
|
+
"""Expand a (possibly partial) date to the last instant of its period.
|
|
931
|
+
|
|
932
|
+
``"2025"`` becomes ``2025-12-31 23:59:59...``, ``"2025-06"`` becomes the end
|
|
933
|
+
of June, and a full date is returned as the end of that day. Values pandas
|
|
934
|
+
cannot read as a period fall back to a plain timestamp.
|
|
935
|
+
|
|
936
|
+
Args:
|
|
937
|
+
value: A year, month, or date string.
|
|
938
|
+
|
|
939
|
+
Returns:
|
|
940
|
+
The inclusive upper bound for ``value``.
|
|
941
|
+
"""
|
|
942
|
+
try:
|
|
943
|
+
return pd.Period(value).end_time
|
|
944
|
+
except (ValueError, pd.errors.OutOfBoundsDatetime):
|
|
945
|
+
return pd.Timestamp(value)
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def _to_wide(frame: pd.DataFrame) -> pd.DataFrame:
|
|
949
|
+
"""Pivot a long frame to one column per series, indexed by date.
|
|
950
|
+
|
|
951
|
+
Args:
|
|
952
|
+
frame: A long frame with ``series_id``, ``reference_date`` and
|
|
953
|
+
``value`` columns.
|
|
954
|
+
|
|
955
|
+
Returns:
|
|
956
|
+
A wide frame: ``reference_date`` plus one value column per series id.
|
|
957
|
+
"""
|
|
958
|
+
if frame.empty:
|
|
959
|
+
return frame
|
|
960
|
+
# Each (series_id, reference_date) pair is unique in long form, so "first"
|
|
961
|
+
# just returns that value; reset_index keeps the date as a column.
|
|
962
|
+
wide = frame.pivot_table(
|
|
963
|
+
index="reference_date",
|
|
964
|
+
columns="series_id",
|
|
965
|
+
values="value",
|
|
966
|
+
aggfunc="first",
|
|
967
|
+
)
|
|
968
|
+
return wide.reset_index()
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
def _normalise_ids(series_ids: int | Iterable[int]) -> list[int]:
|
|
972
|
+
"""Coerce a single id or an iterable of ids into a list of ints.
|
|
973
|
+
|
|
974
|
+
Args:
|
|
975
|
+
series_ids: Either one id or an iterable of ids.
|
|
976
|
+
|
|
977
|
+
Returns:
|
|
978
|
+
A list of integer ids.
|
|
979
|
+
"""
|
|
980
|
+
# A lone int is the common case; wrap it so callers can pass either form.
|
|
981
|
+
if isinstance(series_ids, int):
|
|
982
|
+
return [series_ids]
|
|
983
|
+
# Otherwise coerce each element (e.g. numpy ints from a DataFrame) to int.
|
|
984
|
+
return [int(sid) for sid in series_ids]
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
# --------------------------------------------------------------------------- #
|
|
988
|
+
# Tidy output and polars
|
|
989
|
+
# --------------------------------------------------------------------------- #
|
|
990
|
+
|
|
991
|
+
# Column order of the tidy shape shared by the author's API wrappers.
|
|
992
|
+
_TIDY_COLUMNS = ("date", "series_id", "value", "unit")
|
|
993
|
+
|
|
994
|
+
# Cube dimension labels (EN and PT, accent-free and lower-case) that carry a
|
|
995
|
+
# series' unit of measure and its periodicity.
|
|
996
|
+
_UNIT_LABELS = ("unit of measure", "unidade de medida")
|
|
997
|
+
_PERIODICITY_LABELS = ("periodicity", "periodicidade")
|
|
998
|
+
|
|
999
|
+
# Last month of the first half-year.
|
|
1000
|
+
_MID_YEAR = 6
|
|
1001
|
+
|
|
1002
|
+
# Periodicity-label keywords mapped to a pandas period alias, checked in order
|
|
1003
|
+
# ("semi-annual" must win over "annual"). "H" stands for half-years, which
|
|
1004
|
+
# pandas has no period for and is handled by hand.
|
|
1005
|
+
_PERIOD_ALIASES = (
|
|
1006
|
+
("semi", "H"),
|
|
1007
|
+
("semest", "H"),
|
|
1008
|
+
("month", "M"),
|
|
1009
|
+
("mensal", "M"),
|
|
1010
|
+
("quarter", "Q"),
|
|
1011
|
+
("trimest", "Q"),
|
|
1012
|
+
("annual", "Y"),
|
|
1013
|
+
("year", "Y"),
|
|
1014
|
+
("anual", "Y"),
|
|
1015
|
+
)
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def _fold(text: object) -> str:
|
|
1019
|
+
"""Return ``text`` lower-cased and stripped of accents, for label matching.
|
|
1020
|
+
|
|
1021
|
+
Args:
|
|
1022
|
+
text: Any label.
|
|
1023
|
+
|
|
1024
|
+
Returns:
|
|
1025
|
+
The folded text.
|
|
1026
|
+
"""
|
|
1027
|
+
decomposed = unicodedata.normalize("NFKD", str(text))
|
|
1028
|
+
return "".join(c for c in decomposed if not unicodedata.combining(c)).lower()
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
def _cube_attribute(payload: dict[str, Any], names: tuple[str, ...]) -> str | None:
|
|
1032
|
+
"""Return the single category label of the cube dimension called ``names``.
|
|
1033
|
+
|
|
1034
|
+
In a single-series BPstat cube every non-time dimension has one category;
|
|
1035
|
+
this reads the one whose dimension label (EN or PT) matches, e.g. the
|
|
1036
|
+
"Unit of measure" or "Periodicity" dimension.
|
|
1037
|
+
|
|
1038
|
+
Args:
|
|
1039
|
+
payload: A decoded JSON-stat cube for one series.
|
|
1040
|
+
names: Accepted folded dimension labels.
|
|
1041
|
+
|
|
1042
|
+
Returns:
|
|
1043
|
+
The category label, or ``None`` when the dimension is absent or has
|
|
1044
|
+
more than one category.
|
|
1045
|
+
"""
|
|
1046
|
+
dimensions = payload.get("dimension", {})
|
|
1047
|
+
if not isinstance(dimensions, dict):
|
|
1048
|
+
return None
|
|
1049
|
+
for dim in dimensions.values():
|
|
1050
|
+
if not isinstance(dim, dict) or _fold(dim.get("label", "")) not in names:
|
|
1051
|
+
continue
|
|
1052
|
+
labels = dim.get("category", {}).get("label", {})
|
|
1053
|
+
if isinstance(labels, dict) and len(labels) == 1:
|
|
1054
|
+
return str(next(iter(labels.values())))
|
|
1055
|
+
return None
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
def _period_alias(periodicity: str | None) -> str | None:
|
|
1059
|
+
"""Map a BPstat periodicity label to a period alias (``None`` if unknown).
|
|
1060
|
+
|
|
1061
|
+
Args:
|
|
1062
|
+
periodicity: The series' periodicity label, in EN or PT.
|
|
1063
|
+
|
|
1064
|
+
Returns:
|
|
1065
|
+
``"M"``, ``"Q"``, ``"H"`` or ``"Y"``; ``None`` for daily, weekly or
|
|
1066
|
+
unrecognised periodicities (the date is then kept as it is).
|
|
1067
|
+
"""
|
|
1068
|
+
folded = _fold(periodicity or "")
|
|
1069
|
+
return next((alias for key, alias in _PERIOD_ALIASES if key in folded), None)
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _period_start(dates: pd.Series, periodicity: str | None) -> pd.Series:
|
|
1073
|
+
"""Move BPstat's period-end dates to the start of their period.
|
|
1074
|
+
|
|
1075
|
+
Args:
|
|
1076
|
+
dates: ``reference_date`` values of one series (period end).
|
|
1077
|
+
periodicity: That series' periodicity label.
|
|
1078
|
+
|
|
1079
|
+
Returns:
|
|
1080
|
+
The period-start dates (``datetime64[ns]``); daily, weekly and unknown
|
|
1081
|
+
periodicities keep the date, at midnight.
|
|
1082
|
+
"""
|
|
1083
|
+
dates = pd.to_datetime(dates).astype("datetime64[ns]")
|
|
1084
|
+
alias = _period_alias(periodicity)
|
|
1085
|
+
if alias is None:
|
|
1086
|
+
return dates.dt.normalize()
|
|
1087
|
+
if alias == "H":
|
|
1088
|
+
# First day of the half-year: January or July.
|
|
1089
|
+
month = (dates.dt.month > _MID_YEAR).map({True: 7, False: 1})
|
|
1090
|
+
return pd.to_datetime(
|
|
1091
|
+
pd.DataFrame({"year": dates.dt.year, "month": month, "day": 1})
|
|
1092
|
+
).astype("datetime64[ns]")
|
|
1093
|
+
return dates.dt.to_period(alias).dt.start_time.astype("datetime64[ns]")
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
def _to_tidy(
|
|
1097
|
+
frame: pd.DataFrame,
|
|
1098
|
+
units: dict[int, str | None],
|
|
1099
|
+
periodicities: dict[int, str | None],
|
|
1100
|
+
) -> pd.DataFrame:
|
|
1101
|
+
"""Convert a long observations frame into the shared tidy shape.
|
|
1102
|
+
|
|
1103
|
+
Args:
|
|
1104
|
+
frame: Long output of :meth:`BPStatClient.get_observations`.
|
|
1105
|
+
units: Unit-of-measure label per series id.
|
|
1106
|
+
periodicities: Periodicity label per series id.
|
|
1107
|
+
|
|
1108
|
+
Returns:
|
|
1109
|
+
A frame with exactly ``date``, ``series_id``, ``value`` and ``unit``,
|
|
1110
|
+
sorted by ``series_id`` then ``date``.
|
|
1111
|
+
"""
|
|
1112
|
+
if frame.empty:
|
|
1113
|
+
return empty_tidy(["series_id"])
|
|
1114
|
+
ids = frame["series_id"].astype(int)
|
|
1115
|
+
dates = pd.Series(pd.NaT, index=frame.index, dtype="datetime64[ns]")
|
|
1116
|
+
for series_id in ids.unique():
|
|
1117
|
+
rows = ids == series_id
|
|
1118
|
+
dates[rows] = _period_start(
|
|
1119
|
+
frame.loc[rows, "reference_date"], periodicities.get(int(series_id))
|
|
1120
|
+
)
|
|
1121
|
+
tidy = pd.DataFrame(
|
|
1122
|
+
{
|
|
1123
|
+
"date": dates,
|
|
1124
|
+
"series_id": ids.astype(str),
|
|
1125
|
+
"value": frame["value"],
|
|
1126
|
+
"unit": ids.map(lambda sid: units.get(int(sid))),
|
|
1127
|
+
}
|
|
1128
|
+
)
|
|
1129
|
+
# wrapkit applies the shared column order, dtypes (a missing or blank unit
|
|
1130
|
+
# is <NA>) and the sort by series_id, then date.
|
|
1131
|
+
return tidy_frame(tidy, ["series_id"])
|
|
1132
|
+
|
|
1133
|
+
|
|
1134
|
+
def _date_column(*, tidy: bool) -> str:
|
|
1135
|
+
"""Return the date column of the long (``reference_date``) or tidy shape.
|
|
1136
|
+
|
|
1137
|
+
Args:
|
|
1138
|
+
tidy: Whether the frame is in the tidy shape.
|
|
1139
|
+
|
|
1140
|
+
Returns:
|
|
1141
|
+
``"date"`` or ``"reference_date"``.
|
|
1142
|
+
"""
|
|
1143
|
+
return "date" if tidy else "reference_date"
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def _as_polars(frame: pd.DataFrame) -> pl.DataFrame:
|
|
1147
|
+
"""Convert a pandas frame to polars, importing polars only when asked.
|
|
1148
|
+
|
|
1149
|
+
Args:
|
|
1150
|
+
frame: The frame to convert.
|
|
1151
|
+
|
|
1152
|
+
Returns:
|
|
1153
|
+
The same data as a :class:`polars.DataFrame`; an ``ImportError`` naming
|
|
1154
|
+
the ``polars`` extra is raised if polars is not installed.
|
|
1155
|
+
"""
|
|
1156
|
+
return as_polars(frame, "bpstat-pt-api")
|