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 ADDED
@@ -0,0 +1,30 @@
1
+ """A typed Python wrapper for the Banco de Portugal BPstat statistics API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Re-export the public surface so callers can do `from bpstat import BPStatClient`
6
+ # without reaching into the private submodules.
7
+ from bpstat.client import BPStatClient
8
+ from bpstat.exceptions import (
9
+ BPStatError,
10
+ BPStatHTTPError,
11
+ SeriesNotFoundError,
12
+ )
13
+ from bpstat.jsonstat import jsonstat_to_dataframe
14
+ from bpstat.models import Dataset, Domain, Series
15
+
16
+ # Keep in sync with [project.version] in pyproject.toml and CITATION.cff.
17
+ __version__ = "0.6.0"
18
+
19
+ # __all__ defines the supported API and what `from bpstat import *` exposes.
20
+ __all__ = [
21
+ "BPStatClient",
22
+ "BPStatError",
23
+ "BPStatHTTPError",
24
+ "Dataset",
25
+ "Domain",
26
+ "Series",
27
+ "SeriesNotFoundError",
28
+ "__version__",
29
+ "jsonstat_to_dataframe",
30
+ ]
bpstat/__main__.py ADDED
@@ -0,0 +1,450 @@
1
+ """Command-line interface for the :mod:`bpstat` package, powered by python-fire.
2
+
3
+ `Fire <https://github.com/google/python-fire>`_ turns the :class:`BPStatCLI`
4
+ class into a CLI: each public method becomes a subcommand and its parameters
5
+ become flags. ``--lang``, ``--log-level``, ``--log-file`` and
6
+ ``--requests-per-second`` are constructor flags shared by every subcommand.
7
+
8
+ Examples:
9
+ List domains::
10
+
11
+ bpstat domains
12
+
13
+ Show metadata for several series::
14
+
15
+ bpstat series 88877 88878
16
+
17
+ Stream observations to stdout, or write them to CSV / Excel::
18
+
19
+ bpstat observations 88877 --start 2000 --wide
20
+ bpstat to-csv vat.csv 88877 88878
21
+ bpstat to-excel vat.xlsx 88877
22
+ bpstat to-parquet vat.parquet 88877 --tidy
23
+
24
+ The tidy shape shared with the other wrappers::
25
+
26
+ bpstat observations 88877 --tidy
27
+
28
+ Keep a CSV up to date incrementally::
29
+
30
+ bpstat update-csv tax.csv 88877 88878
31
+
32
+ Show progress on stderr, and keep a full debug log::
33
+
34
+ bpstat to-csv vat.csv 88877 --log-level info --log-file bpstat.log
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import sys
40
+ from typing import Any
41
+
42
+ import requests
43
+ from wrapkit.cli import as_text, bind_bool_flags
44
+ from wrapkit.log import LOG_LEVELS, PlainFormatter, configure_logging, package_logger
45
+
46
+ from bpstat.client import DEFAULT_LOOKBACK_DAYS, BPStatClient
47
+ from bpstat.exceptions import BPStatError
48
+
49
+ # The package logger (the client logs to it); the CLI attaches its handlers here.
50
+ _log = package_logger("bpstat")
51
+
52
+ # Levels accepted by the ``--log-level`` flag.
53
+ _LOG_LEVELS = LOG_LEVELS
54
+
55
+ # Marks the handlers the CLI installs, so reconfiguring replaces them instead of
56
+ # stacking duplicates.
57
+ _CLI_HANDLER_FLAG = "_bpstat_cli_handler"
58
+
59
+ # Boolean subcommand flags, pinned to ``True`` so a bare flag works in any
60
+ # position (``bpstat observations --tidy 88877``).
61
+ _BOOL_FLAGS = ("dimensions", "wide", "tidy")
62
+
63
+ # The log-file formatter: always renders tracebacks without color.
64
+ _PlainFormatter = PlainFormatter
65
+
66
+
67
+ def _configure_logging(level: str = "WARNING", log_file: str | None = None) -> None:
68
+ """Attach the CLI's console (and optional file) handlers to the package logger.
69
+
70
+ Only the command line calls this; the library itself never configures
71
+ logging. The console handler writes colored records to stderr, so stdout
72
+ keeps only the command's output and can still be piped. The file handler,
73
+ when requested, appends every record down to DEBUG with full timestamps,
74
+ whatever the console level. Calling it again replaces the handlers it added
75
+ earlier rather than stacking duplicates.
76
+
77
+ Args:
78
+ level: Console threshold, one of ``DEBUG``, ``INFO``, ``WARNING`` or
79
+ ``ERROR`` (case-insensitive).
80
+ log_file: Path of a log file to append to, or ``None`` for console
81
+ logging only.
82
+
83
+ Raises:
84
+ ValueError: If ``level`` is not one of the accepted names.
85
+ """
86
+ # Validated here, not only in wrapkit: Fire may hand over a non-string
87
+ # (``--log-level 10``), which this message reports as given.
88
+ name = str(level).upper()
89
+ if name not in _LOG_LEVELS:
90
+ msg = f"log_level must be one of {', '.join(_LOG_LEVELS)}, got {level!r}."
91
+ raise ValueError(msg)
92
+ configure_logging(_log, name, log_file, flag=_CLI_HANDLER_FLAG)
93
+
94
+
95
+ # Return a CLI date bound as text, leaving ``None`` alone. Fire converts
96
+ # number-like values, so ``--start 2025`` arrives as the int ``2025``; pandas
97
+ # would read a bare int as nanoseconds since 1970 (keeping every row), so the
98
+ # text is passed on and a bare year keeps meaning that year.
99
+ _as_text = as_text
100
+
101
+
102
+ def _ids(series_ids: tuple[Any, ...]) -> list[int]:
103
+ """Flatten the positional series ids Fire hands over into a list of ints.
104
+
105
+ Fire reads ``bpstat series 1,2`` (or ``[1,2]``) as one tuple (list)
106
+ argument rather than two ids, so nested tuples and lists are unpacked.
107
+
108
+ Args:
109
+ series_ids: The positional ids, each an id or a tuple/list of ids.
110
+
111
+ Returns:
112
+ The ids, in order, as ints.
113
+
114
+ Raises:
115
+ ValueError: If an id is not a whole number.
116
+ """
117
+ flat: list[Any] = []
118
+ for sid in series_ids:
119
+ if isinstance(sid, (tuple, list)):
120
+ flat.extend(sid)
121
+ else:
122
+ flat.append(sid)
123
+ ids: list[int] = []
124
+ for sid in flat:
125
+ # Digits only: int() would truncate a float, and bool is an int.
126
+ if isinstance(sid, bool) or not str(sid).strip().isdigit():
127
+ msg = f"series ids must be whole numbers, got {sid!r}."
128
+ raise ValueError(msg)
129
+ ids.append(int(str(sid)))
130
+ return ids
131
+
132
+
133
+ def _lookback_days(value: Any) -> int:
134
+ """Validate the ``--lookback-days`` flag as a whole number of days.
135
+
136
+ Args:
137
+ value: What Fire parsed (an int, or text it could not read as one).
138
+
139
+ Returns:
140
+ The number of days.
141
+
142
+ Raises:
143
+ ValueError: If ``value`` is not a whole number.
144
+ """
145
+ if isinstance(value, int) and not isinstance(value, bool):
146
+ return value
147
+ msg = f"--lookback-days must be a whole number of days, got {value!r}."
148
+ raise ValueError(msg)
149
+
150
+
151
+ class BPStatCLI:
152
+ """Query the Banco de Portugal BPstat API from the command line."""
153
+
154
+ def __init__(
155
+ self,
156
+ lang: str = "EN",
157
+ log_level: str = "WARNING",
158
+ log_file: str | None = None,
159
+ requests_per_second: float | None = None,
160
+ ) -> None:
161
+ """Capture options shared by every subcommand and set up logging.
162
+
163
+ Args:
164
+ lang: Label language for all requests (``"EN"`` or ``"PT"``).
165
+ log_level: Console log threshold: ``DEBUG``, ``INFO``, ``WARNING``
166
+ (default, quiet) or ``ERROR``. Log lines go to stderr, so command
167
+ output on stdout stays clean.
168
+ log_file: Append a full DEBUG log with timestamps to this file.
169
+ requests_per_second: Request rate; default one per second, the
170
+ most allowed. A slower rate is fine; a faster one is an error.
171
+ """
172
+ _configure_logging(log_level, str(log_file) if log_file else None)
173
+ # Stored privately so Fire does not expose them as their own subcommands.
174
+ self._lang = lang
175
+ self._requests_per_second = requests_per_second
176
+
177
+ def _client(self) -> BPStatClient:
178
+ """Build a client configured with the shared options.
179
+
180
+ Returns:
181
+ A new :class:`BPStatClient` using the CLI's ``--lang``
182
+ and ``--requests-per-second`` values.
183
+ """
184
+ return BPStatClient(
185
+ lang=self._lang,
186
+ requests_per_second=self._requests_per_second,
187
+ )
188
+
189
+ def domains(self) -> dict[int, str]:
190
+ """List statistical domains as ``{id: label}``.
191
+
192
+ Returns:
193
+ A mapping of domain id to domain label.
194
+ """
195
+ with self._client() as client:
196
+ return {domain.id: domain.label for domain in client.get_domains()}
197
+
198
+ def series(self, *series_ids: int) -> dict[int, str]:
199
+ """Show metadata for one or more series ids.
200
+
201
+ Args:
202
+ *series_ids: BPstat series ids.
203
+
204
+ Returns:
205
+ A mapping of series id to ``"label - description"``.
206
+ """
207
+ with self._client() as client:
208
+ return {
209
+ s.id: f"{s.label} - {s.description}"
210
+ for s in client.get_series(_ids(series_ids))
211
+ }
212
+
213
+ def observations(
214
+ self,
215
+ *series_ids: int,
216
+ start: str | None = None,
217
+ end: str | None = None,
218
+ dimensions: bool = False,
219
+ wide: bool = False,
220
+ tidy: bool = False,
221
+ ) -> str:
222
+ """Fetch observations and return them as CSV text (printed to stdout).
223
+
224
+ Args:
225
+ *series_ids: BPstat series ids.
226
+ start: Optional inclusive lower date bound.
227
+ end: Optional inclusive upper date bound (partial periods expand).
228
+ dimensions: Add one column per non-time dimension.
229
+ wide: Pivot to one column per series id.
230
+ tidy: Use the tidy shape (``date``, ``series_id``, ``value``,
231
+ ``unit``).
232
+
233
+ Returns:
234
+ The observations rendered as CSV text.
235
+ """
236
+ with self._client() as client:
237
+ frame = client.get_observations(
238
+ _ids(series_ids),
239
+ start=_as_text(start),
240
+ end=_as_text(end),
241
+ include_dimensions=dimensions,
242
+ wide=wide,
243
+ tidy=tidy,
244
+ )
245
+ return frame.to_csv(index=False)
246
+
247
+ def to_csv(
248
+ self,
249
+ output: str,
250
+ *series_ids: int,
251
+ start: str | None = None,
252
+ end: str | None = None,
253
+ dimensions: bool = False,
254
+ wide: bool = False,
255
+ tidy: bool = False,
256
+ ) -> str:
257
+ """Write observations to a CSV file (``bpstat to-csv PATH IDS...``).
258
+
259
+ Args:
260
+ output: Destination CSV path.
261
+ *series_ids: BPstat series ids.
262
+ start: Optional inclusive lower date bound.
263
+ end: Optional inclusive upper date bound (partial periods expand).
264
+ dimensions: Add one column per non-time dimension.
265
+ wide: Pivot to one column per series id.
266
+ tidy: Use the tidy shape (``date``, ``series_id``, ``value``,
267
+ ``unit``).
268
+
269
+ Returns:
270
+ A status line with the number of rows written.
271
+ """
272
+ with self._client() as client:
273
+ rows = client.to_csv(
274
+ output,
275
+ _ids(series_ids),
276
+ start=_as_text(start),
277
+ end=_as_text(end),
278
+ include_dimensions=dimensions,
279
+ wide=wide,
280
+ tidy=tidy,
281
+ )
282
+ return f"Wrote {rows} rows to {output}"
283
+
284
+ def to_excel(
285
+ self,
286
+ output: str,
287
+ *series_ids: int,
288
+ start: str | None = None,
289
+ end: str | None = None,
290
+ dimensions: bool = False,
291
+ wide: bool = False,
292
+ tidy: bool = False,
293
+ ) -> str:
294
+ """Write observations to an Excel workbook (``bpstat to-excel PATH IDS...``).
295
+
296
+ Args:
297
+ output: Destination ``.xlsx`` path.
298
+ *series_ids: BPstat series ids.
299
+ start: Optional inclusive lower date bound.
300
+ end: Optional inclusive upper date bound (partial periods expand).
301
+ dimensions: Add one column per non-time dimension.
302
+ wide: Pivot to one column per series id.
303
+ tidy: Use the tidy shape (``date``, ``series_id``, ``value``,
304
+ ``unit``).
305
+
306
+ Returns:
307
+ A status line with the number of rows written.
308
+ """
309
+ with self._client() as client:
310
+ rows = client.to_excel(
311
+ output,
312
+ _ids(series_ids),
313
+ start=_as_text(start),
314
+ end=_as_text(end),
315
+ include_dimensions=dimensions,
316
+ wide=wide,
317
+ tidy=tidy,
318
+ )
319
+ return f"Wrote {rows} rows to {output}"
320
+
321
+ def to_parquet(
322
+ self,
323
+ output: str,
324
+ *series_ids: int,
325
+ start: str | None = None,
326
+ end: str | None = None,
327
+ dimensions: bool = False,
328
+ wide: bool = False,
329
+ tidy: bool = False,
330
+ ) -> str:
331
+ """Write observations to a Parquet file (``bpstat to-parquet PATH IDS...``).
332
+
333
+ Args:
334
+ output: Destination ``.parquet`` path.
335
+ *series_ids: BPstat series ids.
336
+ start: Optional inclusive lower date bound.
337
+ end: Optional inclusive upper date bound (partial periods expand).
338
+ dimensions: Add one column per non-time dimension.
339
+ wide: Pivot to one column per series id.
340
+ tidy: Use the tidy shape (``date``, ``series_id``, ``value``,
341
+ ``unit``).
342
+
343
+ Returns:
344
+ A status line naming the file written.
345
+ """
346
+ with self._client() as client:
347
+ path = client.to_parquet(
348
+ output,
349
+ _ids(series_ids),
350
+ start=_as_text(start),
351
+ end=_as_text(end),
352
+ include_dimensions=dimensions,
353
+ wide=wide,
354
+ tidy=tidy,
355
+ )
356
+ return f"Wrote {path}"
357
+
358
+ def update_csv(
359
+ self,
360
+ path: str,
361
+ *series_ids: int,
362
+ dimensions: bool = False,
363
+ tidy: bool = False,
364
+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,
365
+ ) -> str:
366
+ """Incrementally update a long-format CSV in place.
367
+
368
+ Args:
369
+ path: The CSV to create or extend.
370
+ *series_ids: Series to refresh; defaults to those already in the file.
371
+ dimensions: Add one column per non-time dimension.
372
+ tidy: Keep the file in the tidy shape (use the same shape each run).
373
+ lookback_days: Days before each series' last stored date that are
374
+ re-checked for revisions.
375
+
376
+ Returns:
377
+ A status line with the number of observations added or revised.
378
+ """
379
+ ids = _ids(series_ids) or None
380
+ days = _lookback_days(lookback_days)
381
+ with self._client() as client:
382
+ changed = client.update_csv(
383
+ path,
384
+ ids,
385
+ include_dimensions=dimensions,
386
+ tidy=tidy,
387
+ lookback_days=days,
388
+ )
389
+ return f"Added or revised {len(changed)} observations in {path}"
390
+
391
+ def new_observations(
392
+ self,
393
+ existing: str,
394
+ *series_ids: int,
395
+ dimensions: bool = False,
396
+ tidy: bool = False,
397
+ ) -> str:
398
+ """Print (as CSV) only the observations newer than those in a CSV.
399
+
400
+ Args:
401
+ existing: A CSV previously written by this library.
402
+ *series_ids: Series to check; defaults to those already in the file.
403
+ dimensions: Add one column per non-time dimension.
404
+ tidy: ``existing`` is in the tidy shape.
405
+
406
+ Returns:
407
+ The missing observations rendered as CSV text.
408
+ """
409
+ ids = _ids(series_ids) or None
410
+ with self._client() as client:
411
+ new_rows = client.new_observations(
412
+ existing, ids, include_dimensions=dimensions, tidy=tidy
413
+ )
414
+ return new_rows.to_csv(index=False)
415
+
416
+
417
+ def main(argv: list[str] | None = None) -> Any:
418
+ """Entry point for the ``bpstat`` console script.
419
+
420
+ Args:
421
+ argv: Optional argument list; defaults to ``sys.argv`` when ``None``.
422
+ Passing a list lets tests drive the CLI without touching argv.
423
+
424
+ Returns:
425
+ Whatever the invoked subcommand returns (also printed by Fire).
426
+
427
+ Raises:
428
+ SystemExit: With code 1 after printing a concise message for an expected
429
+ error (API failure, network failure, unknown series, invalid
430
+ arguments, an output path that cannot be written).
431
+ """
432
+ # Not wrapkit's run(): that returns None, and callers (and the tests) use
433
+ # the subcommand's return value.
434
+ import fire # Imported lazily so importing the library does not load Fire.
435
+
436
+ args = list(sys.argv[1:] if argv is None else argv)
437
+ try:
438
+ return fire.Fire(
439
+ BPStatCLI, command=bind_bool_flags(args, _BOOL_FLAGS), name="bpstat"
440
+ )
441
+ except (BPStatError, ValueError, requests.RequestException, OSError) as exc:
442
+ # The traceback still goes to the log (shown with --log-level DEBUG and
443
+ # always written to --log-file).
444
+ _log.debug("Command failed", exc_info=True)
445
+ print(f"Error: {exc}", file=sys.stderr) # ruff: ignore[print] - CLI error output
446
+ raise SystemExit(1) from exc
447
+
448
+
449
+ if __name__ == "__main__":
450
+ main()