pyfred-client 0.2.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.
pyfred/core.py ADDED
@@ -0,0 +1,2257 @@
1
+ """
2
+ Client and helpers for the St. Louis Fed's FRED and ALFRED API.
3
+
4
+ FRED (Federal Reserve Economic Data) publishes several hundred thousand
5
+ economic time series; ALFRED, served by the same API, keeps every past vintage
6
+ of them, so a series can be read as it stood on any date since its first
7
+ release. The API lives at ``https://api.stlouisfed.org/fred/``: one GET per
8
+ endpoint (``series``, ``series/observations``, ``series/search``,
9
+ ``category/series``, ``release/series``, ``tags``, ...), every request carrying
10
+ an ``api_key`` and ``file_type=json``, list answers paged by ``limit`` and
11
+ ``offset``, every observation value as text (``"."`` when missing).
12
+
13
+ This module hides that behind a small, typed client. :class:`FredClient`:
14
+
15
+ * reads series observations into a typed DataFrame
16
+ (:meth:`~FredClient.observations`), one request per series and paged for
17
+ you, with FRED's own transformations (``units``: changes, percent changes,
18
+ logs), frequency aggregation and the ALFRED real-time options
19
+ (``realtime_start``/``realtime_end``, ``vintage_dates``, ``output_type``),
20
+ * reshapes it to the tidy long shape shared with the other wrappers
21
+ (``tidy=True``), with the unit taken from the series metadata,
22
+ * describes series (:meth:`~FredClient.series`), searches them
23
+ (:meth:`~FredClient.search`), lists their vintages
24
+ (:meth:`~FredClient.vintage_dates`) and walks categories, releases and
25
+ tags,
26
+ * calls any other endpoint (:meth:`~FredClient.raw`), writes CSV/Excel/
27
+ Parquet/JSON and keeps a CSV current with incremental upserts
28
+ (:meth:`~FredClient.update_csv`).
29
+
30
+ The API key is a secret that travels in the query string: it is never logged
31
+ and never quoted in an error message.
32
+
33
+ The module also defines a small :class:`_Cli` facade that `python-fire
34
+ <https://github.com/google/python-fire>`_ turns into a command-line interface.
35
+
36
+ Data source (a free API key is required):
37
+ https://fred.stlouisfed.org/docs/api/fred/
38
+
39
+ Example:
40
+ >>> from pyfred import FredClient
41
+ >>> fred = FredClient() # reads FRED_API_KEY
42
+ >>> fred.search("consumer price index", max_results=10)
43
+ >>> fred.observations(["GDP", "UNRATE"], start="2020", tidy=True)
44
+ >>> fred.observations("GDP", realtime_start="1776-07-04", realtime_end="9999-12-31")
45
+
46
+ Command line:
47
+ pyfred-client search "industrial production" --max-results 5
48
+ pyfred-client observations GDP,GDPC1 --start 2000 --units pc1 --out gdp.csv
49
+ pyfred-client update-csv rates.csv DGS10,DGS2 --start 2020 --tidy
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import datetime as dt # Validates ISO dates, including FRED's 9999-12-31.
55
+ import json # Renders raw answers in the CLI.
56
+ import os # Reads the API key from the environment.
57
+ import re # Splits series ids, recognises vintage keys and dates.
58
+ from collections.abc import Iterable # Tells one value from several.
59
+ from pathlib import Path # Cross-platform paths for the outputs.
60
+ from typing import TYPE_CHECKING, Any, Literal, overload
61
+
62
+ import pandas as pd # The tabular data type returned throughout.
63
+ import requests # HTTP client for the FRED API.
64
+
65
+ # Shared plumbing of the wrappers (logging, retries, frames, CLI).
66
+ from wrapkit.cli import as_text, resolve_out, run, set_parse_fns
67
+ from wrapkit.frames import as_polars as _to_polars
68
+ from wrapkit.frames import period_end, period_start, tidy_frame
69
+ from wrapkit.http import (
70
+ RateLimit,
71
+ RateLimitError,
72
+ RetryPolicy,
73
+ Throttle,
74
+ get_with_retries,
75
+ user_agent,
76
+ )
77
+ from wrapkit.incremental import read_existing, select_new, upsert
78
+ from wrapkit.io import write_frame
79
+ from wrapkit.log import RedactFilter, configure_logging, loggable, package_logger
80
+
81
+ if TYPE_CHECKING:
82
+ # Imported only for type checking; these names are used purely in annotations.
83
+ from collections.abc import Mapping, Sequence
84
+
85
+ import polars as pl
86
+ from wrapkit.io import FrameFormat
87
+
88
+ # Only the public surface is exported; helpers and the CLI facade stay private.
89
+ __all__ = [
90
+ "AGGREGATIONS",
91
+ "BASE_URL",
92
+ "EARLIEST",
93
+ "FREQUENCIES",
94
+ "KEY_ENV",
95
+ "LATEST",
96
+ "OUTPUT_TYPES",
97
+ "RATE_LIMIT",
98
+ "UNITS",
99
+ "FredClient",
100
+ "RateLimitError",
101
+ "main",
102
+ ]
103
+
104
+ # Package name.
105
+ _PACKAGE = "pyfred"
106
+
107
+ # Distribution name, for the polars install hint.
108
+ _DIST = "pyfred-client"
109
+
110
+ #: Root of the FRED API.
111
+ BASE_URL = "https://api.stlouisfed.org/fred"
112
+
113
+ #: Environment variable read for the API key.
114
+ KEY_ENV = "FRED_API_KEY"
115
+
116
+ #: The earliest real-time date FRED knows (``realtime_start`` for all vintages).
117
+ EARLIEST = "1776-07-04"
118
+
119
+ #: The latest real-time date: a ``realtime_end`` of this means "still current".
120
+ LATEST = "9999-12-31"
121
+
122
+ #: FRED's ``units`` transformations: code to description.
123
+ UNITS: dict[str, str] = {
124
+ "lin": "Levels (No transformation)",
125
+ "chg": "Change",
126
+ "ch1": "Change from Year Ago",
127
+ "pch": "Percent Change",
128
+ "pc1": "Percent Change from Year Ago",
129
+ "pca": "Compounded Annual Rate of Change",
130
+ "cch": "Continuously Compounded Rate of Change",
131
+ "cca": "Continuously Compounded Annual Rate of Change",
132
+ "log": "Natural Log",
133
+ }
134
+
135
+ #: FRED's ``frequency`` codes, for aggregating to a lower frequency.
136
+ FREQUENCIES: dict[str, str] = {
137
+ "d": "Daily",
138
+ "w": "Weekly",
139
+ "bw": "Biweekly",
140
+ "m": "Monthly",
141
+ "q": "Quarterly",
142
+ "sa": "Semiannual",
143
+ "a": "Annual",
144
+ "wef": "Weekly, Ending Friday",
145
+ "weth": "Weekly, Ending Thursday",
146
+ "wew": "Weekly, Ending Wednesday",
147
+ "wetu": "Weekly, Ending Tuesday",
148
+ "wem": "Weekly, Ending Monday",
149
+ "wesu": "Weekly, Ending Sunday",
150
+ "wesa": "Weekly, Ending Saturday",
151
+ "bwew": "Biweekly, Ending Wednesday",
152
+ "bwem": "Biweekly, Ending Monday",
153
+ }
154
+
155
+ #: FRED's ``aggregation_method`` codes (used with ``frequency``).
156
+ AGGREGATIONS: dict[str, str] = {
157
+ "avg": "Average",
158
+ "sum": "Sum",
159
+ "eop": "End of Period",
160
+ }
161
+
162
+ #: FRED's ``output_type`` codes for observations.
163
+ OUTPUT_TYPES: dict[int, str] = {
164
+ 1: "Observations by real-time period",
165
+ 2: "Observations by vintage date, all observations",
166
+ 3: "Observations by vintage date, new and revised observations only",
167
+ 4: "Observations, initial release only",
168
+ }
169
+
170
+ # Browser-like User-Agent naming this project.
171
+ _USER_AGENT = user_agent(
172
+ "pyfred-client", "0.1", "https://github.com/hmorao95/pyfred-client"
173
+ )
174
+
175
+ # The query parameter that carries the key.
176
+ _KEY_PARAM = "api_key"
177
+
178
+ #: FRED's request limit: 120 requests a minute per key (``errors.html``) and
179
+ #: ``Crawl-delay: 2`` in the robots.txt of the API host, so one request every
180
+ #: 2 seconds. Every network request waits on a throttle built from it.
181
+ RATE_LIMIT = RateLimit(
182
+ requests_per_second=0.5,
183
+ per_minute=120,
184
+ source=(
185
+ "https://fred.stlouisfed.org/docs/api/fred/errors.html (120 requests "
186
+ "a minute) and https://api.stlouisfed.org/robots.txt (Crawl-delay: 2), "
187
+ "read 2026-12-05"
188
+ ),
189
+ )
190
+
191
+ # Throttle key: every client in the process shares one budget for this host.
192
+ _RATE_KEY = "api.stlouisfed.org"
193
+
194
+ # FRED counts its limit per minute and sends no Retry-After, so a 429 is only
195
+ # retried once a whole minute has passed.
196
+ _RATE_WINDOW = 60.0
197
+
198
+
199
+ class _FredRetryPolicy(RetryPolicy):
200
+ """A :class:`RetryPolicy` that waits out FRED's one-minute window on a 429."""
201
+
202
+ def wait(
203
+ self, attempt: int, status: int | None = None, retry_after: str | None = None
204
+ ) -> float:
205
+ """
206
+ Return how long to wait after failed attempt ``attempt``.
207
+
208
+ A 429 waits at least :data:`_RATE_WINDOW` seconds, so the retry falls
209
+ in a fresh window; other failures back off as usual.
210
+
211
+ Args:
212
+ attempt (int): The attempt that just failed, starting at 1.
213
+ status (int | None): Its HTTP status, or ``None`` for a transport
214
+ error.
215
+ retry_after (str | None): Its ``Retry-After`` header, if any.
216
+
217
+ Returns:
218
+ float: Seconds to wait.
219
+ """
220
+ wait = super().wait(attempt, status, retry_after)
221
+ if status == 429: # ruff: ignore[magic-value-comparison] - HTTP Too Many Requests
222
+ return max(wait, _RATE_WINDOW)
223
+ return wait
224
+
225
+
226
+ # Page sizes: the documented maximum ``limit`` of each kind of list.
227
+ _OBSERVATION_PAGE = 100_000
228
+ _VINTAGE_PAGE = 10_000
229
+ _LIST_PAGE = 1_000
230
+
231
+ # Vintage dates per JSON request (the documented cap for output types 1-4).
232
+ _MAX_VINTAGES = 2_000
233
+
234
+ # A plain ISO day; FRED's 9999-12-31 is one, though pandas cannot hold it.
235
+ _ISO_DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")
236
+
237
+ # A UTC offset given in hours only (FRED's ``2013-07-31 09:26:16-05``).
238
+ _HOUR_OFFSET = re.compile(r"[+-]\d{2}$")
239
+
240
+ # Columns of the observation frames.
241
+ _REALTIME = ("realtime_start", "realtime_end")
242
+
243
+ # Typed columns of the listing frames (series, releases, categories, tags).
244
+ _DAY_COLUMNS = (
245
+ "realtime_start",
246
+ "realtime_end",
247
+ "observation_start",
248
+ "observation_end",
249
+ )
250
+ _STAMP_COLUMNS = ("last_updated", "created")
251
+ _INT_COLUMNS = ("popularity", "group_popularity", "series_count", "parent_id")
252
+
253
+ # Columns left out when a series listing is printed.
254
+ _LONG_TEXT = ("notes",)
255
+
256
+ # The package logger. As a library it only emits records; the NullHandler keeps
257
+ # them silent until an application (or the CLI) attaches a handler.
258
+ _log = package_logger(_PACKAGE)
259
+
260
+ # Masks ``api_key=<value>`` and every registered key in any log record, on the
261
+ # package logger and on the HTTP loggers (urllib3 logs full URLs at DEBUG).
262
+ _REDACT = RedactFilter([_KEY_PARAM]).install(_PACKAGE)
263
+
264
+ # Marks the handlers the CLI installs, so reconfiguring replaces them.
265
+ _CLI_HANDLER_FLAG = "_pyfred_cli_handler"
266
+
267
+
268
+ # --------------------------------------------------------------------------- #
269
+ # Arguments
270
+ # --------------------------------------------------------------------------- #
271
+ # FRED's semicolon-delimited list parameters; the others (``vintage_dates``)
272
+ # are comma-separated.
273
+ _SEMICOLON_LISTS = frozenset({"tag_names", "exclude_tag_names"})
274
+
275
+
276
+ def _texts(values: object, seps: str = r"[,;\s]+") -> list[str]:
277
+ """
278
+ Normalise a multi-value argument to a list of trimmed strings.
279
+
280
+ A string is split on ``seps``: by default commas, semicolons and blanks
281
+ (FRED ids and dates contain none).
282
+
283
+ Args:
284
+ values (object): A string, a scalar or an iterable of them.
285
+ seps (str): The separator pattern for a string.
286
+
287
+ Returns:
288
+ list[str]: The non-empty values.
289
+ """
290
+ if isinstance(values, str):
291
+ items: Iterable[object] = re.split(seps, values)
292
+ elif isinstance(values, Iterable):
293
+ items = values
294
+ else:
295
+ items = [values]
296
+ return [str(v).strip() for v in items if str(v).strip()]
297
+
298
+
299
+ def _ids(values: object) -> list[str]:
300
+ """
301
+ Normalise series ids (``"gdp, unrate"``) to an upper-case list.
302
+
303
+ Args:
304
+ values (object): One id, a comma-separated string or several ids.
305
+
306
+ Returns:
307
+ list[str]: The ids, in order, without duplicates.
308
+
309
+ Raises:
310
+ ValueError: If no id is given.
311
+ """
312
+ ids = list(dict.fromkeys(v.upper() for v in _texts(values)))
313
+ if not ids:
314
+ msg = "No series id given."
315
+ raise ValueError(msg)
316
+ return ids
317
+
318
+
319
+ def _day(value: str | dt.date | None, *, end: bool = False) -> str | None:
320
+ """
321
+ Turn a date argument into the ``YYYY-MM-DD`` text FRED expects.
322
+
323
+ An ISO day is passed through (``9999-12-31`` included). A coarser period
324
+ label (``2024``, ``2024-Q2``, ``2024-06``) means its first day, or with
325
+ ``end`` its last day, so an end bound covers its whole period.
326
+
327
+ Args:
328
+ value (str | dt.date | None): A day, a period label or ``None``.
329
+ end (bool): Read a period label as an end bound.
330
+
331
+ Returns:
332
+ str | None: The day, or ``None`` when not given.
333
+
334
+ Raises:
335
+ ValueError: If the value cannot be parsed.
336
+ """
337
+ if value is None:
338
+ return None
339
+ if isinstance(value, dt.datetime):
340
+ return value.date().isoformat()
341
+ if isinstance(value, dt.date):
342
+ return value.isoformat()
343
+ text = str(value).strip()
344
+ if _ISO_DAY.match(text):
345
+ try:
346
+ return dt.date.fromisoformat(text).isoformat()
347
+ except ValueError as exc:
348
+ msg = f"Cannot parse date {value!r}."
349
+ raise ValueError(msg) from exc
350
+ first = period_start(text)
351
+ if not end:
352
+ return first.date().isoformat()
353
+ upper = period_end(text)
354
+ if upper != first: # a year, quarter or month: the day before the next one
355
+ upper -= pd.Timedelta(days=1)
356
+ return upper.date().isoformat()
357
+
358
+
359
+ def _span(
360
+ start: str | dt.date | None, end: str | dt.date | None, what: str
361
+ ) -> tuple[str | None, str | None]:
362
+ """
363
+ Parse an inclusive pair of date bounds.
364
+
365
+ Args:
366
+ start (str | dt.date | None): The first day or period.
367
+ end (str | dt.date | None): The last day or period.
368
+ what (str): What the bounds are, for the error message.
369
+
370
+ Returns:
371
+ tuple[str | None, str | None]: The two days.
372
+
373
+ Raises:
374
+ ValueError: If ``start`` is after ``end``.
375
+ """
376
+ lower, upper = _day(start), _day(end, end=True)
377
+ if lower is not None and upper is not None and lower > upper:
378
+ msg = f"{what} start ({start}) is after its end ({end})."
379
+ raise ValueError(msg)
380
+ return lower, upper
381
+
382
+
383
+ def _choice(name: str, value: str | None, allowed: Mapping[str, str]) -> str | None:
384
+ """
385
+ Check a coded option against FRED's documented values.
386
+
387
+ Args:
388
+ name (str): The option.
389
+ value (str | None): The value given, or ``None``.
390
+ allowed (Mapping[str, str]): The documented codes.
391
+
392
+ Returns:
393
+ str | None: The code in lower case, or ``None``.
394
+
395
+ Raises:
396
+ ValueError: If the code is not documented.
397
+ """
398
+ if value is None:
399
+ return None
400
+ code = str(value).strip().lower()
401
+ if code not in allowed:
402
+ msg = f"Unknown {name} {value!r}: use one of {', '.join(allowed)}."
403
+ raise ValueError(msg)
404
+ return code
405
+
406
+
407
+ def _output_type(value: int | str | None) -> int | None:
408
+ """
409
+ Check an ``output_type`` (1 to 4).
410
+
411
+ Args:
412
+ value (int | str | None): The value given, or ``None``.
413
+
414
+ Returns:
415
+ int | None: The type, or ``None``.
416
+
417
+ Raises:
418
+ ValueError: If it is not 1, 2, 3 or 4.
419
+ """
420
+ if value is None:
421
+ return None
422
+ try:
423
+ code = int(value)
424
+ except (TypeError, ValueError):
425
+ code = 0
426
+ if code not in OUTPUT_TYPES:
427
+ msg = f"Unknown output_type {value!r}: use 1, 2, 3 or 4."
428
+ raise ValueError(msg)
429
+ return code
430
+
431
+
432
+ def _vintages(values: object) -> list[str]:
433
+ """
434
+ Normalise ``vintage_dates`` to a sorted list of ISO days.
435
+
436
+ Args:
437
+ values (object): Comma-separated text, or dates.
438
+
439
+ Returns:
440
+ list[str]: The days, sorted and without duplicates.
441
+
442
+ Raises:
443
+ ValueError: If no date is given.
444
+ """
445
+ if isinstance(values, str):
446
+ items: list[object] = list(_texts(values))
447
+ elif isinstance(values, Iterable):
448
+ items = list(values)
449
+ else:
450
+ items = [values]
451
+ days = sorted(
452
+ {d for v in items if (d := _day(v if isinstance(v, dt.date) else str(v)))}
453
+ )
454
+ if not days:
455
+ msg = "vintage_dates is empty."
456
+ raise ValueError(msg)
457
+ return days
458
+
459
+
460
+ def _tag_list(values: object) -> str | None:
461
+ """
462
+ Join tag names the way FRED wants them (``usa;m2``).
463
+
464
+ Tag names may contain blanks (``interest rate``), so a string is split on
465
+ ``;`` and ``,`` only.
466
+
467
+ Args:
468
+ values (object): Tags separated by ``;`` or ``,``, or a list of tags,
469
+ or ``None``.
470
+
471
+ Returns:
472
+ str | None: The semicolon-delimited tags, or ``None``.
473
+ """
474
+ if values is None:
475
+ return None
476
+ return ";".join(_texts(values, r"[,;]+")) or None
477
+
478
+
479
+ def _raw_value(name: str, value: object) -> str:
480
+ """
481
+ Render one :meth:`FredClient.raw` parameter as query text.
482
+
483
+ Args:
484
+ name (str): The parameter name.
485
+ value (object): Its value; a list or tuple is joined.
486
+
487
+ Returns:
488
+ str: The text sent to the API.
489
+ """
490
+ if isinstance(value, (list, tuple)):
491
+ sep = ";" if name in _SEMICOLON_LISTS else ","
492
+ return sep.join(str(v).strip() for v in value)
493
+ return str(value)
494
+
495
+
496
+ def _observation_queries(
497
+ start: str | dt.date | None,
498
+ end: str | dt.date | None,
499
+ units: str | None,
500
+ frequency: str | None,
501
+ aggregation_method: str | None,
502
+ realtime_start: str | dt.date | None,
503
+ realtime_end: str | dt.date | None,
504
+ vintage_dates: object,
505
+ output_type: int | str | None,
506
+ ) -> list[list[tuple[str, str]]]:
507
+ """
508
+ Check the observation options and build their query parameters.
509
+
510
+ Args:
511
+ start (str | dt.date | None): First observation date or period.
512
+ end (str | dt.date | None): Last observation date or period.
513
+ units (str | None): A code of :data:`UNITS`.
514
+ frequency (str | None): A code of :data:`FREQUENCIES`.
515
+ aggregation_method (str | None): A code of :data:`AGGREGATIONS`.
516
+ realtime_start (str | dt.date | None): First real-time day.
517
+ realtime_end (str | dt.date | None): Last real-time day.
518
+ vintage_dates (object): Vintage days, or ``None``.
519
+ output_type (int | str | None): A key of :data:`OUTPUT_TYPES`.
520
+
521
+ Returns:
522
+ list[list[tuple[str, str]]]: The parameters of each request a series
523
+ needs (one, or one per 2,000 vintage dates), without ``series_id``.
524
+
525
+ Raises:
526
+ ValueError: If an option is unknown or the options contradict each
527
+ other.
528
+ """
529
+ obs_start, obs_end = _span(start, end, "Observation")
530
+ rt_start, rt_end = _span(realtime_start, realtime_end, "Real-time")
531
+ options = {
532
+ "observation_start": obs_start,
533
+ "observation_end": obs_end,
534
+ "units": _choice("units", units, UNITS),
535
+ "frequency": _choice("frequency", frequency, FREQUENCIES),
536
+ "aggregation_method": _choice(
537
+ "aggregation_method", aggregation_method, AGGREGATIONS
538
+ ),
539
+ "output_type": _output_type(output_type),
540
+ "realtime_start": rt_start,
541
+ "realtime_end": rt_end,
542
+ }
543
+ if options["aggregation_method"] is not None and options["frequency"] is None:
544
+ msg = "aggregation_method needs a frequency."
545
+ raise ValueError(msg)
546
+ base = [(k, str(v)) for k, v in options.items() if v is not None]
547
+ if vintage_dates is None:
548
+ return [base]
549
+ if rt_start is not None or rt_end is not None:
550
+ msg = "Pass either vintage_dates or a real-time period, not both."
551
+ raise ValueError(msg)
552
+ days = _vintages(vintage_dates)
553
+ return [
554
+ [*base, ("vintage_dates", ",".join(days[i : i + _MAX_VINTAGES]))]
555
+ for i in range(0, len(days), _MAX_VINTAGES)
556
+ ]
557
+
558
+
559
+ def _realtime_params(start: str | None, end: str | None) -> list[tuple[str, str]]:
560
+ """
561
+ Return the real-time period parameters that are set.
562
+
563
+ Args:
564
+ start (str | None): ``realtime_start``.
565
+ end (str | None): ``realtime_end``.
566
+
567
+ Returns:
568
+ list[tuple[str, str]]: Zero, one or two parameters.
569
+ """
570
+ period = {"realtime_start": start, "realtime_end": end}
571
+ return [(k, v) for k, v in period.items() if v is not None]
572
+
573
+
574
+ def _is_realtime(options: Mapping[str, Any]) -> bool:
575
+ """
576
+ Tell whether observation options ask for real-time (ALFRED) data.
577
+
578
+ Args:
579
+ options (Mapping[str, Any]): :meth:`FredClient.observations` arguments.
580
+
581
+ Returns:
582
+ bool: True when a real-time period, vintage dates or an output type
583
+ other than 1 is given.
584
+ """
585
+ if any(options.get(k) is not None for k in (*_REALTIME, "vintage_dates")):
586
+ return True
587
+ return _output_type(options.get("output_type")) in {2, 3, 4}
588
+
589
+
590
+ # --------------------------------------------------------------------------- #
591
+ # Frames
592
+ # --------------------------------------------------------------------------- #
593
+ def _days(values: pd.Series) -> pd.Series:
594
+ """
595
+ Parse FRED day strings; ``9999-12-31`` (still current) becomes NaT.
596
+
597
+ Args:
598
+ values (pd.Series): ``YYYY-MM-DD`` text.
599
+
600
+ Returns:
601
+ pd.Series: ``datetime64[ns]`` values.
602
+ """
603
+ text = values.astype("string")
604
+ return pd.to_datetime(
605
+ text.mask(text.eq(LATEST)), format="%Y-%m-%d", errors="coerce"
606
+ ).astype("datetime64[ns]")
607
+
608
+
609
+ def _stamps(values: pd.Series) -> pd.Series:
610
+ """
611
+ Parse FRED timestamps (``2013-07-31 09:26:16-05``) to UTC.
612
+
613
+ Args:
614
+ values (pd.Series): The text.
615
+
616
+ Returns:
617
+ pd.Series: Time-zone aware UTC timestamps.
618
+ """
619
+ text = values.astype("string").str.strip()
620
+ text = text.where(~text.str.contains(_HOUR_OFFSET, na=False), text + "00")
621
+ return pd.to_datetime(text, format="%Y-%m-%d %H:%M:%S%z", errors="coerce", utc=True)
622
+
623
+
624
+ def _numbers(values: pd.Series) -> pd.Series:
625
+ """
626
+ Parse observation values; FRED's ``"."`` (missing) becomes NaN.
627
+
628
+ Args:
629
+ values (pd.Series): The text values.
630
+
631
+ Returns:
632
+ pd.Series: float64 values.
633
+ """
634
+ return pd.to_numeric(values.mask(values.eq(".")), errors="coerce").astype("float64")
635
+
636
+
637
+ def _listing(
638
+ items: Sequence[Mapping[str, Any]], id_name: str | None = None
639
+ ) -> pd.DataFrame:
640
+ """
641
+ Build a typed frame of series, releases, categories or tags.
642
+
643
+ Args:
644
+ items (Sequence[Mapping[str, Any]]): The decoded objects.
645
+ id_name (str | None): What to call their ``id`` (``series_id``, ...);
646
+ tags have none.
647
+
648
+ Returns:
649
+ pd.DataFrame: One row per object; days as timestamps (``9999-12-31``
650
+ as NaT), ``last_updated``/``created`` as UTC timestamps, counts as
651
+ nullable integers.
652
+ """
653
+ frame = pd.DataFrame(list(items))
654
+ if id_name:
655
+ frame = frame.rename(columns={"id": id_name})
656
+ for col in frame.columns:
657
+ if col in _DAY_COLUMNS:
658
+ frame[col] = _days(frame[col])
659
+ elif col in _STAMP_COLUMNS:
660
+ frame[col] = _stamps(frame[col])
661
+ elif col in _INT_COLUMNS:
662
+ frame[col] = pd.to_numeric(frame[col], errors="coerce").astype("Int64")
663
+ return frame
664
+
665
+
666
+ def _observation_rows(
667
+ observations: Sequence[Mapping[str, Any]], series_id: str, output_type: int | None
668
+ ) -> pd.DataFrame:
669
+ """
670
+ Turn one series' observations into long rows.
671
+
672
+ Output types 1 and 4 answer one object per observation and real-time
673
+ period. Output types 2 and 3 answer one object per date with a key per
674
+ vintage (``GDP_20130731``, with a leading ``_`` for an id that starts with
675
+ a digit); each becomes a row whose real-time period is that vintage day.
676
+
677
+ Args:
678
+ observations (Sequence[Mapping[str, Any]]): The ``observations`` list.
679
+ series_id (str): The series.
680
+ output_type (int | None): The output type asked for.
681
+
682
+ Returns:
683
+ pd.DataFrame: Columns ``series_id``, ``date``, ``realtime_start``,
684
+ ``realtime_end``, ``value``, as text.
685
+ """
686
+ rows: list[tuple[Any, Any, Any, Any]] = []
687
+ if output_type in {2, 3}:
688
+ vintage = re.compile(rf"^_?{re.escape(series_id)}_(\d{{8}})$", re.IGNORECASE)
689
+ for obs in observations:
690
+ for key, value in obs.items():
691
+ if match := vintage.match(str(key)):
692
+ day = f"{match[1][:4]}-{match[1][4:6]}-{match[1][6:]}"
693
+ rows.append((obs.get("date"), day, day, value))
694
+ else:
695
+ rows = [
696
+ (
697
+ o.get("date"),
698
+ o.get("realtime_start"),
699
+ o.get("realtime_end"),
700
+ o.get("value"),
701
+ )
702
+ for o in observations
703
+ ]
704
+ frame = pd.DataFrame(rows, columns=["date", *_REALTIME, "value"], dtype=object)
705
+ frame.insert(0, "series_id", series_id)
706
+ return frame
707
+
708
+
709
+ def _observation_frame(
710
+ parts: Sequence[pd.DataFrame], *, realtime: bool
711
+ ) -> pd.DataFrame:
712
+ """
713
+ Stack and type the observation rows of several series.
714
+
715
+ Args:
716
+ parts (Sequence[pd.DataFrame]): Rows from :func:`_observation_rows`.
717
+ realtime (bool): Keep the real-time period columns.
718
+
719
+ Returns:
720
+ pd.DataFrame: ``series_id``, ``date``, (``realtime_start``,
721
+ ``realtime_end``,) ``value``; sorted by series, date and real-time
722
+ start.
723
+ """
724
+ columns = ["series_id", "date", *(_REALTIME if realtime else ()), "value"]
725
+ frame = (
726
+ pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=columns)
727
+ )
728
+ frame = frame[columns].copy()
729
+ frame["series_id"] = frame["series_id"].astype("string")
730
+ for col in ("date", *(_REALTIME if realtime else ())):
731
+ frame[col] = _days(frame[col])
732
+ frame["value"] = _numbers(frame["value"])
733
+ order = ["series_id", "date", *(("realtime_start",) if realtime else ())]
734
+ return frame.sort_values(order, kind="stable").reset_index(drop=True)
735
+
736
+
737
+ def _unit_label(base: str | None, units: str | None) -> str | None:
738
+ """
739
+ Describe the unit of transformed values.
740
+
741
+ Args:
742
+ base (str | None): The series' own unit (``Billions of Dollars``).
743
+ units (str | None): The ``units`` transformation, or ``None``.
744
+
745
+ Returns:
746
+ str | None: ``base`` for levels, otherwise the transformation with the
747
+ base in brackets (``Percent Change (Billions of Dollars)``).
748
+ """
749
+ if units in {None, "lin"}:
750
+ return base
751
+ label = UNITS[str(units)]
752
+ return f"{label} ({base})" if base else label
753
+
754
+
755
+ # --------------------------------------------------------------------------- #
756
+ # Client
757
+ # --------------------------------------------------------------------------- #
758
+ class FredClient:
759
+ """
760
+ Client for the FRED and ALFRED API of the Federal Reserve Bank of St. Louis.
761
+
762
+ One instance describes, searches and browses series and reads their
763
+ observations (current or as of past vintages) into typed DataFrames,
764
+ paging for you. Network access, retries, the throttle and the API key
765
+ are handled internally; every call goes to the API.
766
+
767
+ Args:
768
+ api_key (str | None): FRED API key (free, from
769
+ https://fredaccount.stlouisfed.org/apikeys). Defaults to the
770
+ ``FRED_API_KEY`` environment variable. It is sent as a query
771
+ parameter, never logged and never quoted in an error.
772
+ timeout (float): Per-request timeout in seconds.
773
+ requests_per_second (float | None): Rate of network requests.
774
+ ``None`` (the default) or ``0`` means
775
+ :data:`RATE_LIMIT`, one request every 2 seconds; a slower rate is
776
+ allowed, a faster one raises ``RateLimitError``. The throttle
777
+ cannot be turned off.
778
+ max_retries (int): Retries after a 429/5xx answer or a dropped
779
+ connection, with exponential back-off; a 429 waits a full minute.
780
+ session (requests.Session | None): Optional pre-configured session.
781
+ """
782
+
783
+ def __init__(
784
+ self,
785
+ api_key: str | None = None,
786
+ timeout: float = 60.0,
787
+ requests_per_second: float | None = None,
788
+ max_retries: int = 4,
789
+ session: requests.Session | None = None,
790
+ ) -> None:
791
+ """
792
+ Initialise the client; performs no network access.
793
+
794
+ Args:
795
+ api_key (str | None): FRED API key; the ``FRED_API_KEY``
796
+ environment variable when ``None``.
797
+ timeout (float): Per-request timeout in seconds.
798
+ requests_per_second (float | None): Network-request rate, at most
799
+ :data:`RATE_LIMIT`; ``None`` or ``0`` for the limit's rate.
800
+ max_retries (int): Retries for 429/5xx answers and transport errors.
801
+ session (requests.Session | None): Optional pre-built HTTP session.
802
+
803
+ Raises:
804
+ ValueError: If no API key is given or set in ``FRED_API_KEY``
805
+ (and ``RateLimitError``, a ``ValueError``, if
806
+ ``requests_per_second`` is faster than :data:`RATE_LIMIT`).
807
+ """
808
+ key = (api_key if api_key is not None else os.environ.get(KEY_ENV, "")).strip()
809
+ if not key:
810
+ msg = (
811
+ f"No FRED API key: pass FredClient(api_key=...) or set the {KEY_ENV} "
812
+ "environment variable. Keys are free: "
813
+ "https://fredaccount.stlouisfed.org/apikeys"
814
+ )
815
+ raise ValueError(msg)
816
+ self._api_key = key
817
+ # Belt and braces: log lines are built without the key, but should one
818
+ # ever quote it (urllib3 logs full URLs), it is masked.
819
+ _REDACT.register(key)
820
+ self.timeout = timeout
821
+ self._policy = _FredRetryPolicy(max_retries=max_retries)
822
+ if session is None:
823
+ session = requests.Session()
824
+ session.headers["User-Agent"] = _USER_AGENT
825
+ self.session = session
826
+ # Shared by every client in the process: one budget per host.
827
+ self._throttle = Throttle(
828
+ requests_per_second, _log, limit=RATE_LIMIT, key=_RATE_KEY
829
+ )
830
+ # Per-process memo of series metadata, for the tidy units.
831
+ self._meta: dict[str, dict[str, Any]] = {}
832
+
833
+ def __repr__(self) -> str:
834
+ """
835
+ Describe the client without revealing the API key.
836
+
837
+ Returns:
838
+ str: ``FredClient(api_key=set)``.
839
+ """
840
+ return "FredClient(api_key=set)"
841
+
842
+ # ------------------------------------------------------------------ #
843
+ # HTTP
844
+ # ------------------------------------------------------------------ #
845
+ def _request(
846
+ self, endpoint: str, params: Sequence[tuple[str, str]] = ()
847
+ ) -> dict[str, Any]:
848
+ """
849
+ Perform one GET below :data:`BASE_URL` and return the decoded JSON.
850
+
851
+ Calls the API (retrying 429/5xx answers and dropped connections) and
852
+ turns an error answer into a short message. The key is added only to
853
+ the request itself: the log lines and any error message are built
854
+ without it.
855
+
856
+ Args:
857
+ endpoint (str): Path below the base URL, e.g. ``"series/observations"``.
858
+ params (Sequence[tuple[str, str]]): Query parameters, without the
859
+ key and ``file_type``.
860
+
861
+ Returns:
862
+ dict[str, Any]: The decoded JSON object.
863
+
864
+ A transport failure (refused connection, timeout) re-raises the
865
+ ``requests`` error with the key masked in its message and without the
866
+ original chained to it.
867
+
868
+ Raises:
869
+ RuntimeError: If the API answers with an error or not with a JSON
870
+ object.
871
+ """
872
+ url = f"{BASE_URL}/{endpoint}"
873
+ query = [*params, ("file_type", "json")]
874
+ _log.debug("GET %s %s", endpoint, loggable(query, (_KEY_PARAM,)))
875
+ try:
876
+ resp = get_with_retries(
877
+ self.session,
878
+ url,
879
+ policy=self._policy,
880
+ throttle=self._throttle,
881
+ logger=_log,
882
+ label=endpoint,
883
+ params=[*query, (_KEY_PARAM, self._api_key)],
884
+ timeout=self.timeout,
885
+ )
886
+ except requests.RequestException as exc:
887
+ # The message of a transport error quotes the URL, key included.
888
+ # ``from None`` keeps the original (and its text) out of tracebacks.
889
+ error = _redacted(exc)
890
+ raise error from None
891
+ if resp.status_code >= 400: # ruff: ignore[magic-value-comparison] - HTTP error statuses
892
+ msg = f"FRED API error (HTTP {resp.status_code}) for {endpoint}: {_error_text(resp)}"
893
+ raise RuntimeError(_REDACT.redact(msg))
894
+ try:
895
+ payload = resp.json()
896
+ except ValueError:
897
+ payload = None
898
+ if not isinstance(payload, dict):
899
+ msg = f"Unexpected answer for {endpoint}: {resp.text.strip()[:200]}"
900
+ raise RuntimeError(_REDACT.redact(msg)) # ruff: ignore[type-check-without-type-error] - a bad payload, not a bad argument
901
+ if "error_message" in payload:
902
+ msg = f"FRED API error for {endpoint}: {payload['error_message']}"
903
+ raise RuntimeError(_REDACT.redact(msg))
904
+ return payload
905
+
906
+ def _paged(
907
+ self,
908
+ endpoint: str,
909
+ params: Sequence[tuple[str, str]],
910
+ field: str,
911
+ page_size: int,
912
+ max_rows: int | None = None,
913
+ ) -> list[Any]:
914
+ """
915
+ Read every item of a list endpoint, one page of ``page_size`` at a time.
916
+
917
+ Args:
918
+ endpoint (str): The endpoint.
919
+ params (Sequence[tuple[str, str]]): Its parameters, without
920
+ ``limit`` and ``offset``.
921
+ field (str): The answer's list field (``seriess``, ``observations``).
922
+ page_size (int): The endpoint's maximum ``limit``.
923
+ max_rows (int | None): Stop after this many items.
924
+
925
+ Returns:
926
+ list[Any]: The items.
927
+
928
+ Raises:
929
+ RuntimeError: If an answer's list field is not a list.
930
+ """
931
+ items: list[Any] = []
932
+ while max_rows is None or len(items) < max_rows:
933
+ limit = (
934
+ page_size if max_rows is None else min(page_size, max_rows - len(items))
935
+ )
936
+ payload = self._request(
937
+ endpoint, [*params, ("limit", str(limit)), ("offset", str(len(items)))]
938
+ )
939
+ page = payload.get(field, [])
940
+ if not isinstance(page, list):
941
+ msg = f"Unexpected answer for {endpoint}: {field} is not a list."
942
+ raise RuntimeError(msg) # ruff: ignore[type-check-without-type-error] - a bad payload, not a bad argument
943
+ items.extend(page)
944
+ count = payload.get("count")
945
+ _log.debug(
946
+ "%s: page of %d %s (%d so far, of %s)",
947
+ endpoint,
948
+ len(page),
949
+ field,
950
+ len(items),
951
+ count,
952
+ )
953
+ if len(page) < limit or (isinstance(count, int) and len(items) >= count):
954
+ break
955
+ return items
956
+
957
+ def raw(
958
+ self, endpoint: str, **params: str | int | Sequence[str | int]
959
+ ) -> dict[str, Any]:
960
+ """
961
+ Call any FRED endpoint and return its decoded JSON answer.
962
+
963
+ The escape hatch for endpoints without a method here (``sources``,
964
+ ``release/dates``, ``series/categories``, ``related_tags``, ...). The
965
+ client adds the key and ``file_type=json``; nothing is paged. A list
966
+ or tuple value is joined the way FRED documents its list parameters:
967
+ with ``;`` for ``tag_names`` and ``exclude_tag_names``, with ``,``
968
+ otherwise (``vintage_dates``).
969
+
970
+ Args:
971
+ endpoint (str): The endpoint below ``/fred/``, such as
972
+ ``"release/dates"`` (a leading ``/`` or ``fred/`` is ignored).
973
+ **params (str | int | Sequence[str | int]): Its query parameters.
974
+
975
+ Returns:
976
+ dict[str, Any]: The answer.
977
+
978
+ Raises:
979
+ ValueError: If ``api_key`` or ``file_type`` is passed.
980
+
981
+ Example:
982
+ >>> fred.raw("release/dates", release_id=53, limit=5)
983
+ """
984
+ if {_KEY_PARAM, "file_type"} & set(params):
985
+ msg = "raw() sets api_key and file_type itself."
986
+ raise ValueError(msg)
987
+ path = endpoint.strip().strip("/").removeprefix("fred/")
988
+ return self._request(path, [(k, _raw_value(k, v)) for k, v in params.items()])
989
+
990
+ # ------------------------------------------------------------------ #
991
+ # Series metadata and browsing
992
+ # ------------------------------------------------------------------ #
993
+ def series(
994
+ self,
995
+ series_ids: str | Iterable[str],
996
+ realtime_start: str | dt.date | None = None,
997
+ realtime_end: str | dt.date | None = None,
998
+ ) -> pd.DataFrame:
999
+ """
1000
+ Describe one or more series (one request per series).
1001
+
1002
+ Args:
1003
+ series_ids (str | Iterable[str]): Series ids, such as ``"GDP"`` or
1004
+ ``"GDP,UNRATE"``.
1005
+ realtime_start (str | dt.date | None): Describe the series as of
1006
+ this real-time period (ALFRED); today when ``None``.
1007
+ realtime_end (str | dt.date | None): End of that period.
1008
+
1009
+ Returns:
1010
+ pd.DataFrame: One row per series (and real-time period):
1011
+ ``series_id``, ``title``, ``frequency``, ``units``,
1012
+ ``seasonal_adjustment`` (each with a ``_short`` twin),
1013
+ ``observation_start``, ``observation_end``, ``last_updated``
1014
+ (UTC), ``popularity``, ``notes``, ``realtime_start``,
1015
+ ``realtime_end``.
1016
+ """
1017
+ start, end = _span(realtime_start, realtime_end, "Real-time")
1018
+ items: list[dict[str, Any]] = []
1019
+ for series_id in _ids(series_ids):
1020
+ params = [("series_id", series_id)]
1021
+ params += _realtime_params(start, end)
1022
+ found = self._request("series", params).get("seriess") or []
1023
+ items.extend(found)
1024
+ if start is None and end is None and found:
1025
+ self._meta[series_id] = found[-1]
1026
+ return _listing(items, "series_id")
1027
+
1028
+ def search(
1029
+ self,
1030
+ text: str,
1031
+ *,
1032
+ search_type: Literal["full_text", "series_id"] = "full_text",
1033
+ tags: str | Iterable[str] | None = None,
1034
+ exclude_tags: str | Iterable[str] | None = None,
1035
+ filter_variable: Literal["frequency", "units", "seasonal_adjustment"]
1036
+ | None = None,
1037
+ filter_value: str | None = None,
1038
+ order_by: str | None = None,
1039
+ sort_order: Literal["asc", "desc"] | None = None,
1040
+ max_results: int | None = 1000,
1041
+ ) -> pd.DataFrame:
1042
+ """
1043
+ Search series by words in their title and notes, or by id.
1044
+
1045
+ Args:
1046
+ text (str): The words (``"real gdp"``); with
1047
+ ``search_type="series_id"`` an id pattern (``"GDP*"``).
1048
+ search_type (str): ``full_text`` or ``series_id``.
1049
+ tags (str | Iterable[str] | None): Keep series with all these tags
1050
+ (``"usa;quarterly"``).
1051
+ exclude_tags (str | Iterable[str] | None): Drop series with any of
1052
+ these tags (needs ``tags``).
1053
+ filter_variable (str | None): ``frequency``, ``units`` or
1054
+ ``seasonal_adjustment``.
1055
+ filter_value (str | None): The value it must have (``"Monthly"``).
1056
+ order_by (str | None): ``search_rank`` (default), ``popularity``,
1057
+ ``title``, ``last_updated``, ``observation_start``, ...
1058
+ sort_order (str | None): ``asc`` or ``desc``.
1059
+ max_results (int | None): Stop after this many series (1,000 by
1060
+ default); ``None`` for every match.
1061
+
1062
+ Returns:
1063
+ pd.DataFrame: One row per series, as in :meth:`series` plus
1064
+ ``group_popularity``.
1065
+ """
1066
+ params = [("search_text", text), ("search_type", search_type)]
1067
+ params += self._series_filters(
1068
+ tags, exclude_tags, filter_variable, filter_value, order_by, sort_order
1069
+ )
1070
+ items = self._paged("series/search", params, "seriess", _LIST_PAGE, max_results)
1071
+ _log.info("Search %r: %d series", text, len(items))
1072
+ return _listing(items, "series_id")
1073
+
1074
+ @staticmethod
1075
+ def _series_filters(
1076
+ tags: str | Iterable[str] | None,
1077
+ exclude_tags: str | Iterable[str] | None,
1078
+ filter_variable: str | None,
1079
+ filter_value: str | None,
1080
+ order_by: str | None,
1081
+ sort_order: str | None,
1082
+ ) -> list[tuple[str, str]]:
1083
+ """
1084
+ Build the filter and order parameters shared by the series lists.
1085
+
1086
+ Args:
1087
+ tags (str | Iterable[str] | None): Required tags.
1088
+ exclude_tags (str | Iterable[str] | None): Excluded tags.
1089
+ filter_variable (str | None): The attribute to filter on.
1090
+ filter_value (str | None): Its value.
1091
+ order_by (str | None): Sort attribute.
1092
+ sort_order (str | None): ``asc`` or ``desc``.
1093
+
1094
+ Returns:
1095
+ list[tuple[str, str]]: The parameters that are set.
1096
+
1097
+ Raises:
1098
+ ValueError: If only one of ``filter_variable`` and
1099
+ ``filter_value`` is given.
1100
+ """
1101
+ if (filter_variable is None) != (filter_value is None):
1102
+ msg = "Pass filter_variable and filter_value together."
1103
+ raise ValueError(msg)
1104
+ options = {
1105
+ "tag_names": _tag_list(tags),
1106
+ "exclude_tag_names": _tag_list(exclude_tags),
1107
+ "filter_variable": filter_variable,
1108
+ "filter_value": filter_value,
1109
+ "order_by": order_by,
1110
+ "sort_order": sort_order,
1111
+ }
1112
+ return [(k, str(v)) for k, v in options.items() if v is not None]
1113
+
1114
+ def vintage_dates(
1115
+ self,
1116
+ series_id: str,
1117
+ realtime_start: str | dt.date | None = None,
1118
+ realtime_end: str | dt.date | None = None,
1119
+ ) -> pd.DataFrame:
1120
+ """
1121
+ List the dates on which a series was released or revised (ALFRED).
1122
+
1123
+ Pass any of them back as ``vintage_dates`` to
1124
+ :meth:`observations` to read the series as it stood that day.
1125
+
1126
+ Args:
1127
+ series_id (str): The series.
1128
+ realtime_start (str | dt.date | None): First vintage to list (all
1129
+ of them by default).
1130
+ realtime_end (str | dt.date | None): Last vintage to list.
1131
+
1132
+ Returns:
1133
+ pd.DataFrame: Columns ``series_id`` and ``vintage_date``, oldest
1134
+ first.
1135
+ """
1136
+ sid = _ids(series_id)[0]
1137
+ start, end = _span(realtime_start, realtime_end, "Real-time")
1138
+ params = [("series_id", sid)]
1139
+ params += _realtime_params(start, end)
1140
+ days = self._paged(
1141
+ "series/vintagedates", params, "vintage_dates", _VINTAGE_PAGE
1142
+ )
1143
+ return pd.DataFrame(
1144
+ {
1145
+ "series_id": pd.Series([sid] * len(days), dtype="string"),
1146
+ "vintage_date": _days(pd.Series(days, dtype="string")),
1147
+ }
1148
+ )
1149
+
1150
+ def category(self, category_id: int = 0) -> pd.DataFrame:
1151
+ """
1152
+ Describe a category (``0`` is the root).
1153
+
1154
+ Args:
1155
+ category_id (int): The category.
1156
+
1157
+ Returns:
1158
+ pd.DataFrame: One row: ``category_id``, ``name``, ``parent_id``.
1159
+ """
1160
+ found = self._request("category", [("category_id", str(category_id))])
1161
+ return _listing(found.get("categories") or [], "category_id")
1162
+
1163
+ def categories(self, parent_id: int = 0) -> pd.DataFrame:
1164
+ """
1165
+ List the child categories of a category (the top level by default).
1166
+
1167
+ Args:
1168
+ parent_id (int): The parent category; ``0`` is the root.
1169
+
1170
+ Returns:
1171
+ pd.DataFrame: ``category_id``, ``name``, ``parent_id``.
1172
+ """
1173
+ found = self._request("category/children", [("category_id", str(parent_id))])
1174
+ return _listing(found.get("categories") or [], "category_id")
1175
+
1176
+ def category_series(
1177
+ self,
1178
+ category_id: int,
1179
+ *,
1180
+ tags: str | Iterable[str] | None = None,
1181
+ exclude_tags: str | Iterable[str] | None = None,
1182
+ filter_variable: Literal["frequency", "units", "seasonal_adjustment"]
1183
+ | None = None,
1184
+ filter_value: str | None = None,
1185
+ order_by: str | None = None,
1186
+ sort_order: Literal["asc", "desc"] | None = None,
1187
+ max_results: int | None = None,
1188
+ ) -> pd.DataFrame:
1189
+ """
1190
+ List the series in a category.
1191
+
1192
+ Args:
1193
+ category_id (int): The category.
1194
+ tags (str | Iterable[str] | None): Keep series with all these tags.
1195
+ exclude_tags (str | Iterable[str] | None): Drop series with any of
1196
+ these tags (needs ``tags``).
1197
+ filter_variable (str | None): ``frequency``, ``units`` or
1198
+ ``seasonal_adjustment``.
1199
+ filter_value (str | None): The value it must have.
1200
+ order_by (str | None): Sort attribute (``series_id`` by default).
1201
+ sort_order (str | None): ``asc`` or ``desc``.
1202
+ max_results (int | None): Stop after this many series.
1203
+
1204
+ Returns:
1205
+ pd.DataFrame: One row per series, as in :meth:`series`.
1206
+ """
1207
+ params = [("category_id", str(category_id))]
1208
+ params += self._series_filters(
1209
+ tags, exclude_tags, filter_variable, filter_value, order_by, sort_order
1210
+ )
1211
+ items = self._paged(
1212
+ "category/series", params, "seriess", _LIST_PAGE, max_results
1213
+ )
1214
+ return _listing(items, "series_id")
1215
+
1216
+ def releases(self, max_results: int | None = None) -> pd.DataFrame:
1217
+ """
1218
+ List every release of economic data (GDP, the employment situation, ...).
1219
+
1220
+ Args:
1221
+ max_results (int | None): Stop after this many releases.
1222
+
1223
+ Returns:
1224
+ pd.DataFrame: ``release_id``, ``name``, ``press_release``,
1225
+ ``link``, ``notes`` (when given), ``realtime_start``,
1226
+ ``realtime_end``.
1227
+ """
1228
+ items = self._paged("releases", [], "releases", _LIST_PAGE, max_results)
1229
+ return _listing(items, "release_id")
1230
+
1231
+ def release(self, release_id: int) -> pd.DataFrame:
1232
+ """
1233
+ Describe one release.
1234
+
1235
+ Args:
1236
+ release_id (int): The release (``53`` is Gross Domestic Product).
1237
+
1238
+ Returns:
1239
+ pd.DataFrame: One row, as in :meth:`releases`.
1240
+ """
1241
+ found = self._request("release", [("release_id", str(release_id))])
1242
+ return _listing(found.get("releases") or [], "release_id")
1243
+
1244
+ def release_series(
1245
+ self,
1246
+ release_id: int,
1247
+ *,
1248
+ tags: str | Iterable[str] | None = None,
1249
+ exclude_tags: str | Iterable[str] | None = None,
1250
+ filter_variable: Literal["frequency", "units", "seasonal_adjustment"]
1251
+ | None = None,
1252
+ filter_value: str | None = None,
1253
+ order_by: str | None = None,
1254
+ sort_order: Literal["asc", "desc"] | None = None,
1255
+ max_results: int | None = None,
1256
+ ) -> pd.DataFrame:
1257
+ """
1258
+ List the series of a release.
1259
+
1260
+ Args:
1261
+ release_id (int): The release.
1262
+ tags (str | Iterable[str] | None): Keep series with all these tags.
1263
+ exclude_tags (str | Iterable[str] | None): Drop series with any of
1264
+ these tags (needs ``tags``).
1265
+ filter_variable (str | None): ``frequency``, ``units`` or
1266
+ ``seasonal_adjustment``.
1267
+ filter_value (str | None): The value it must have.
1268
+ order_by (str | None): Sort attribute (``series_id`` by default).
1269
+ sort_order (str | None): ``asc`` or ``desc``.
1270
+ max_results (int | None): Stop after this many series.
1271
+
1272
+ Returns:
1273
+ pd.DataFrame: One row per series, as in :meth:`series`.
1274
+ """
1275
+ params = [("release_id", str(release_id))]
1276
+ params += self._series_filters(
1277
+ tags, exclude_tags, filter_variable, filter_value, order_by, sort_order
1278
+ )
1279
+ items = self._paged(
1280
+ "release/series", params, "seriess", _LIST_PAGE, max_results
1281
+ )
1282
+ return _listing(items, "series_id")
1283
+
1284
+ def tags(
1285
+ self,
1286
+ search_text: str | None = None,
1287
+ *,
1288
+ tag_names: str | Iterable[str] | None = None,
1289
+ tag_group_id: str | None = None,
1290
+ order_by: str | None = None,
1291
+ sort_order: Literal["asc", "desc"] | None = None,
1292
+ max_results: int | None = 1000,
1293
+ ) -> pd.DataFrame:
1294
+ """
1295
+ List FRED tags (the labels series are filtered by).
1296
+
1297
+ Args:
1298
+ search_text (str | None): Words to match in tag names and notes.
1299
+ tag_names (str | Iterable[str] | None): Only these tags.
1300
+ tag_group_id (str | None): Only this group: ``freq``, ``gen``,
1301
+ ``geo``, ``geot``, ``rls``, ``seas``, ``src`` or ``cc``.
1302
+ order_by (str | None): ``series_count`` (default), ``popularity``,
1303
+ ``created``, ``name`` or ``group_id``.
1304
+ sort_order (str | None): ``asc`` or ``desc``.
1305
+ max_results (int | None): Stop after this many tags (1,000 by
1306
+ default); ``None`` for all.
1307
+
1308
+ Returns:
1309
+ pd.DataFrame: ``name``, ``group_id``, ``notes``, ``created``
1310
+ (UTC), ``popularity``, ``series_count``.
1311
+ """
1312
+ options = {
1313
+ "search_text": search_text,
1314
+ "tag_names": _tag_list(tag_names),
1315
+ "tag_group_id": tag_group_id,
1316
+ "order_by": order_by,
1317
+ "sort_order": sort_order,
1318
+ }
1319
+ params = [(k, str(v)) for k, v in options.items() if v is not None]
1320
+ items = self._paged("tags", params, "tags", _LIST_PAGE, max_results)
1321
+ return _listing(items)
1322
+
1323
+ # ------------------------------------------------------------------ #
1324
+ # Observations
1325
+ # ------------------------------------------------------------------ #
1326
+ def _unit(self, series_id: str, units: str | None) -> str | None:
1327
+ """
1328
+ Return the unit of a series' values, fetching its metadata once.
1329
+
1330
+ Args:
1331
+ series_id (str): The series.
1332
+ units (str | None): The ``units`` transformation applied.
1333
+
1334
+ Returns:
1335
+ str | None: The unit (see :func:`_unit_label`).
1336
+ """
1337
+ if series_id not in self._meta:
1338
+ self.series(series_id)
1339
+ base = self._meta.get(series_id, {}).get("units")
1340
+ return _unit_label(str(base) if base else None, units)
1341
+
1342
+ @overload
1343
+ def observations(
1344
+ self,
1345
+ series_ids: str | Iterable[str],
1346
+ start: str | dt.date | None = ...,
1347
+ end: str | dt.date | None = ...,
1348
+ *,
1349
+ units: str | None = ...,
1350
+ frequency: str | None = ...,
1351
+ aggregation_method: str | None = ...,
1352
+ realtime_start: str | dt.date | None = ...,
1353
+ realtime_end: str | dt.date | None = ...,
1354
+ vintage_dates: str | Iterable[str | dt.date] | None = ...,
1355
+ output_type: int | None = ...,
1356
+ tidy: bool = ...,
1357
+ as_polars: Literal[False] = ...,
1358
+ ) -> pd.DataFrame: ...
1359
+
1360
+ @overload
1361
+ def observations(
1362
+ self,
1363
+ series_ids: str | Iterable[str],
1364
+ start: str | dt.date | None = ...,
1365
+ end: str | dt.date | None = ...,
1366
+ *,
1367
+ units: str | None = ...,
1368
+ frequency: str | None = ...,
1369
+ aggregation_method: str | None = ...,
1370
+ realtime_start: str | dt.date | None = ...,
1371
+ realtime_end: str | dt.date | None = ...,
1372
+ vintage_dates: str | Iterable[str | dt.date] | None = ...,
1373
+ output_type: int | None = ...,
1374
+ tidy: bool = ...,
1375
+ as_polars: Literal[True],
1376
+ ) -> pl.DataFrame: ...
1377
+
1378
+ def observations(
1379
+ self,
1380
+ series_ids: str | Iterable[str],
1381
+ start: str | dt.date | None = None,
1382
+ end: str | dt.date | None = None,
1383
+ *,
1384
+ units: str | None = None,
1385
+ frequency: str | None = None,
1386
+ aggregation_method: str | None = None,
1387
+ realtime_start: str | dt.date | None = None,
1388
+ realtime_end: str | dt.date | None = None,
1389
+ vintage_dates: str | Iterable[str | dt.date] | None = None,
1390
+ output_type: int | None = None,
1391
+ tidy: bool = False,
1392
+ as_polars: bool = False,
1393
+ ) -> pd.DataFrame | pl.DataFrame:
1394
+ """
1395
+ Fetch the observations of one or more series, paging automatically.
1396
+
1397
+ The default frame holds the API's rows, stacked: ``series_id``,
1398
+ ``date`` and ``value`` (float64; FRED's ``"."`` for a missing value
1399
+ becomes NaN), sorted by series and date. A real-time query (any of
1400
+ ``realtime_start``, ``realtime_end``, ``vintage_dates`` or an
1401
+ ``output_type`` of 2 to 4) adds ``realtime_start`` and
1402
+ ``realtime_end``: the real-time period during which each value was
1403
+ the published one (``realtime_end`` NaT for "still current"). Output
1404
+ types 2 and 3 come back one row per date and vintage, with the vintage
1405
+ day as both ends of the period.
1406
+
1407
+ With ``tidy=True`` the result is the long shape shared with the other
1408
+ wrappers: ``date``, ``series_id`` (and the real-time columns),
1409
+ ``value`` and ``unit`` (from the series metadata, with the
1410
+ transformation, such as ``Percent Change (Billions of Dollars)``).
1411
+
1412
+ ``start`` and ``end`` bound the observation dates and are inclusive
1413
+ periods: ``2024``, ``2024-Q2``, ``2024-06`` or a day.
1414
+
1415
+ An unknown option, a bad date, ``start`` after ``end`` or both a
1416
+ real-time period and vintage dates raise ``ValueError``; an error
1417
+ answer from the API raises ``RuntimeError``.
1418
+
1419
+ Args:
1420
+ series_ids (str | Iterable[str]): Series ids (``"GDP"``,
1421
+ ``"GDP,UNRATE"`` or a list); one request per series.
1422
+ start (str | dt.date | None): First observation date.
1423
+ end (str | dt.date | None): Last observation date.
1424
+ units (str | None): A transformation of :data:`UNITS`: ``chg``,
1425
+ ``ch1``, ``pch``, ``pc1``, ``pca``, ``cch``, ``cca`` or
1426
+ ``log`` (``lin``, levels, by default).
1427
+ frequency (str | None): Aggregate to a lower frequency of
1428
+ :data:`FREQUENCIES` (``m``, ``q``, ``a``, ``wef``, ...).
1429
+ aggregation_method (str | None): How to aggregate: ``avg``
1430
+ (default), ``sum`` or ``eop``; needs ``frequency``.
1431
+ realtime_start (str | dt.date | None): First day of the real-time
1432
+ period (ALFRED); :data:`EARLIEST` for every vintage.
1433
+ realtime_end (str | dt.date | None): Last day of the real-time
1434
+ period; :data:`LATEST` for "until now".
1435
+ vintage_dates (str | Iterable[str | dt.date] | None): Read the
1436
+ series as it stood on these days instead of a real-time period
1437
+ (sent 2,000 at a time).
1438
+ output_type (int | None): A key of :data:`OUTPUT_TYPES`: 1 by
1439
+ real-time period (default), 2 by vintage date, 3 new and
1440
+ revised observations by vintage date, 4 initial release only.
1441
+ tidy (bool): Return the tidy long shape.
1442
+ as_polars (bool): Return a polars DataFrame (needs the ``polars``
1443
+ extra).
1444
+
1445
+ Returns:
1446
+ pd.DataFrame | pl.DataFrame: The observations.
1447
+ """
1448
+ ids = _ids(series_ids)
1449
+ queries = _observation_queries(
1450
+ start, end, units, frequency, aggregation_method,
1451
+ realtime_start, realtime_end, vintage_dates, output_type,
1452
+ ) # fmt: skip
1453
+ kind = _output_type(output_type)
1454
+ parts = []
1455
+ for series_id in ids:
1456
+ for query in queries:
1457
+ params = [("series_id", series_id), *query]
1458
+ rows = self._paged(
1459
+ "series/observations", params, "observations", _OBSERVATION_PAGE
1460
+ )
1461
+ parts.append(_observation_rows(rows, series_id, kind))
1462
+ realtime = _is_realtime(
1463
+ {
1464
+ "realtime_start": realtime_start,
1465
+ "realtime_end": realtime_end,
1466
+ "vintage_dates": vintage_dates,
1467
+ "output_type": kind,
1468
+ }
1469
+ )
1470
+ frame = _observation_frame(parts, realtime=realtime)
1471
+ _log.info("Fetched %d observations of %s", len(frame), ", ".join(ids))
1472
+ if tidy:
1473
+ frame = self._to_tidy(
1474
+ frame, _choice("units", units, UNITS), realtime=realtime
1475
+ )
1476
+ return _to_polars(frame, _DIST) if as_polars else frame
1477
+
1478
+ def _to_tidy(
1479
+ self, frame: pd.DataFrame, units: str | None, *, realtime: bool
1480
+ ) -> pd.DataFrame:
1481
+ """
1482
+ Put an observation frame into the shared tidy shape.
1483
+
1484
+ Args:
1485
+ frame (pd.DataFrame): From :func:`_observation_frame`.
1486
+ units (str | None): The transformation applied.
1487
+ realtime (bool): Whether it has the real-time columns.
1488
+
1489
+ Returns:
1490
+ pd.DataFrame: ``date``, ``series_id`` (``realtime_start``,
1491
+ ``realtime_end``), ``value``, ``unit``.
1492
+ """
1493
+ dims = ["series_id", *(_REALTIME if realtime else ())]
1494
+ long = frame.copy()
1495
+ long["unit"] = long["series_id"].map(
1496
+ {s: self._unit(s, units) for s in long["series_id"].dropna().unique()}
1497
+ )
1498
+ tidy = tidy_frame(long, dims)
1499
+ # tidy_frame makes every dimension text; the real-time days stay days.
1500
+ for col in _REALTIME if realtime else ():
1501
+ tidy[col] = pd.to_datetime(tidy[col]).astype("datetime64[ns]")
1502
+ return tidy
1503
+
1504
+ def _fetch(
1505
+ self, series_ids: str | Iterable[str], kwargs: Mapping[str, Any]
1506
+ ) -> pd.DataFrame:
1507
+ """
1508
+ Run :meth:`observations` for a pandas result, ignoring ``as_polars``.
1509
+
1510
+ Args:
1511
+ series_ids (str | Iterable[str]): The series.
1512
+ kwargs (Mapping[str, Any]): Further :meth:`observations` arguments.
1513
+
1514
+ Returns:
1515
+ pd.DataFrame: The observations.
1516
+ """
1517
+ options = {k: v for k, v in kwargs.items() if k != "as_polars"}
1518
+ return self.observations(series_ids, **options, as_polars=False)
1519
+
1520
+ # ------------------------------------------------------------------ #
1521
+ # Export
1522
+ # ------------------------------------------------------------------ #
1523
+ def _write(
1524
+ self,
1525
+ path: str | Path,
1526
+ fmt: FrameFormat,
1527
+ series_ids: str | Iterable[str],
1528
+ kwargs: Mapping[str, Any],
1529
+ ) -> Path:
1530
+ """
1531
+ Fetch with :meth:`observations` and write the result.
1532
+
1533
+ Args:
1534
+ path (str | Path): Destination.
1535
+ fmt (FrameFormat): Output format.
1536
+ series_ids (str | Iterable[str]): The series.
1537
+ kwargs (Mapping[str, Any]): Further :meth:`observations` arguments.
1538
+
1539
+ Returns:
1540
+ Path: The path written.
1541
+ """
1542
+ frame = self._fetch(series_ids, kwargs)
1543
+ written = write_frame(frame, path, fmt)
1544
+ _log.info("Wrote %d rows to %s", len(frame), written)
1545
+ return written
1546
+
1547
+ def to_csv(
1548
+ self, path: str | Path, series_ids: str | Iterable[str], **kwargs: Any
1549
+ ) -> Path:
1550
+ """
1551
+ Fetch with :meth:`observations` and write a CSV.
1552
+
1553
+ Args:
1554
+ path (str | Path): Destination ``.csv`` path.
1555
+ series_ids (str | Iterable[str]): The series.
1556
+ **kwargs (Any): Further :meth:`observations` arguments.
1557
+
1558
+ Returns:
1559
+ Path: The path written.
1560
+ """
1561
+ return self._write(path, "csv", series_ids, kwargs)
1562
+
1563
+ def to_excel(
1564
+ self, path: str | Path, series_ids: str | Iterable[str], **kwargs: Any
1565
+ ) -> Path:
1566
+ """
1567
+ Fetch with :meth:`observations` and write an Excel workbook (sheet ``data``).
1568
+
1569
+ Args:
1570
+ path (str | Path): Destination ``.xlsx`` path.
1571
+ series_ids (str | Iterable[str]): The series.
1572
+ **kwargs (Any): Further :meth:`observations` arguments.
1573
+
1574
+ Returns:
1575
+ Path: The path written.
1576
+ """
1577
+ return self._write(path, "excel", series_ids, kwargs)
1578
+
1579
+ def to_parquet(
1580
+ self, path: str | Path, series_ids: str | Iterable[str], **kwargs: Any
1581
+ ) -> Path:
1582
+ """
1583
+ Fetch with :meth:`observations` and write a Parquet file.
1584
+
1585
+ Args:
1586
+ path (str | Path): Destination ``.parquet`` path.
1587
+ series_ids (str | Iterable[str]): The series.
1588
+ **kwargs (Any): Further :meth:`observations` arguments.
1589
+
1590
+ Returns:
1591
+ Path: The path written.
1592
+ """
1593
+ return self._write(path, "parquet", series_ids, kwargs)
1594
+
1595
+ def to_json(
1596
+ self, path: str | Path, series_ids: str | Iterable[str], **kwargs: Any
1597
+ ) -> Path:
1598
+ """
1599
+ Fetch with :meth:`observations` and write JSON records (ISO dates).
1600
+
1601
+ Args:
1602
+ path (str | Path): Destination ``.json`` path.
1603
+ series_ids (str | Iterable[str]): The series.
1604
+ **kwargs (Any): Further :meth:`observations` arguments.
1605
+
1606
+ Returns:
1607
+ Path: The path written.
1608
+ """
1609
+ return self._write(path, "json", series_ids, kwargs)
1610
+
1611
+ # ------------------------------------------------------------------ #
1612
+ # Incremental update
1613
+ # ------------------------------------------------------------------ #
1614
+ @staticmethod
1615
+ def _keys(
1616
+ kwargs: Mapping[str, Any],
1617
+ ) -> tuple[list[str], list[str], tuple[str, ...]]:
1618
+ """
1619
+ Return the key, compared and date columns of an extract.
1620
+
1621
+ A plain extract is keyed by series and observation date; a real-time
1622
+ one also by ``realtime_start``, so every vintage of a value is its own
1623
+ row. Only the value (and the unit, in the tidy shape) is compared: the
1624
+ default real-time period of a plain request is today, which would
1625
+ otherwise make every row look revised every day.
1626
+
1627
+ Args:
1628
+ kwargs (Mapping[str, Any]): The :meth:`observations` arguments.
1629
+
1630
+ Returns:
1631
+ tuple[list[str], list[str], tuple[str, ...]]: Key columns, value
1632
+ columns and the date columns present.
1633
+ """
1634
+ realtime = _is_realtime(kwargs)
1635
+ keys = ["series_id", "date", *(["realtime_start"] if realtime else [])]
1636
+ values = ["value", *(["unit"] if kwargs.get("tidy") else [])]
1637
+ dates = ("date", *(_REALTIME if realtime else ()))
1638
+ return keys, values, dates
1639
+
1640
+ def new_observations(
1641
+ self,
1642
+ existing: pd.DataFrame | str | Path,
1643
+ series_ids: str | Iterable[str],
1644
+ *,
1645
+ include_revisions: bool = True,
1646
+ **kwargs: Any,
1647
+ ) -> pd.DataFrame:
1648
+ """
1649
+ Fetch only the observations missing from an already-extracted set.
1650
+
1651
+ The file-free building block behind :meth:`update_csv`: it fetches with
1652
+ :meth:`observations` and returns the rows whose key (series and date;
1653
+ for a real-time query also ``realtime_start``) is not in ``existing``,
1654
+ plus, with ``include_revisions``, rows whose value has since changed.
1655
+ Pass ``start`` to limit the fetch.
1656
+
1657
+ Args:
1658
+ existing (pd.DataFrame | str | Path): The prior extract, or a path
1659
+ to its CSV (a missing file counts as empty).
1660
+ series_ids (str | Iterable[str]): The series.
1661
+ include_revisions (bool): Also return revised rows.
1662
+ **kwargs (Any): Further :meth:`observations` arguments (``start``,
1663
+ ``units``, ``realtime_start``, ``tidy``, ...).
1664
+
1665
+ Returns:
1666
+ pd.DataFrame: The new (and revised) rows.
1667
+ """
1668
+ fresh = self._fetch(series_ids, kwargs)
1669
+ keys, values, dates = self._keys(kwargs)
1670
+ prior = read_existing(existing, fresh, ["value"])
1671
+ new = select_new(
1672
+ fresh,
1673
+ prior,
1674
+ keys,
1675
+ values,
1676
+ include_revisions=include_revisions,
1677
+ date_cols=dates,
1678
+ )
1679
+ _log.info("%d new/revised observations versus the existing extract", len(new))
1680
+ return new
1681
+
1682
+ def update_csv(
1683
+ self,
1684
+ path: str | Path,
1685
+ series_ids: str | Iterable[str],
1686
+ lookback_days: int = 730,
1687
+ **kwargs: Any,
1688
+ ) -> pd.DataFrame:
1689
+ """
1690
+ Incrementally update a CSV with new and revised observations.
1691
+
1692
+ On the first run the full extract is written. Later runs of a plain
1693
+ query re-fetch only from ``lookback_days`` (two years by default)
1694
+ before the last stored date of the series that lags most, since
1695
+ FRED's sources revise recent history; a real-time query is re-fetched
1696
+ whole. The fresh rows are then upserted on the key (series and date;
1697
+ for a real-time query also ``realtime_start``): new rows are appended
1698
+ and changed values overwrite stale ones; stored history is kept. Use
1699
+ the same series and options on every run.
1700
+
1701
+ Args:
1702
+ path (str | Path): CSV to create or update in place.
1703
+ series_ids (str | Iterable[str]): The series.
1704
+ lookback_days (int): Days re-fetched before the last stored date.
1705
+ **kwargs (Any): Further :meth:`observations` arguments (``units``,
1706
+ ``frequency``, ``realtime_start``, ``tidy``, ...). An explicit
1707
+ ``start`` overrides the look-back.
1708
+
1709
+ Returns:
1710
+ pd.DataFrame: The rows newly added or revised; empty when the file
1711
+ was already up to date.
1712
+ """
1713
+ path = Path(path)
1714
+ options = dict(kwargs)
1715
+ keys, values, dates = self._keys(options)
1716
+ if (
1717
+ "start" not in options
1718
+ and not _is_realtime(options)
1719
+ and (last := _last_date(path)) is not None
1720
+ ):
1721
+ options["start"] = (last - pd.Timedelta(days=lookback_days)).date()
1722
+ fresh = self._fetch(series_ids, options)
1723
+ prior = read_existing(path, fresh, ["value"])
1724
+ if prior.empty:
1725
+ write_frame(fresh, path, "csv")
1726
+ _log.info("Created %s with %d rows", path, len(fresh))
1727
+ return fresh
1728
+ delta = select_new(fresh, prior, keys, values, date_cols=dates)
1729
+ if delta.empty:
1730
+ _log.info("%s is already up to date", path)
1731
+ return delta
1732
+ combined = upsert(prior, fresh, keys, date_cols=dates)
1733
+ write_frame(combined, path, "csv")
1734
+ _log.info(
1735
+ "Upserted %d new/revised rows into %s (%d rows total)",
1736
+ len(delta),
1737
+ path,
1738
+ len(combined),
1739
+ )
1740
+ return delta
1741
+
1742
+
1743
+ def _last_date(path: Path) -> pd.Timestamp | None:
1744
+ """
1745
+ Return the last stored date of the series that lags most in a CSV.
1746
+
1747
+ Args:
1748
+ path (Path): The CSV.
1749
+
1750
+ Returns:
1751
+ pd.Timestamp | None: The earliest of the series' last dates, or
1752
+ ``None`` for a missing or empty file.
1753
+
1754
+ Raises:
1755
+ ValueError: If the file has no ``series_id`` and ``date`` columns.
1756
+ """
1757
+ if not path.exists() or not path.stat().st_size:
1758
+ return None
1759
+ header = pd.read_csv(path, nrows=0).columns
1760
+ if not {"series_id", "date"} <= set(header):
1761
+ msg = f"{path} has no 'series_id' and 'date' columns; is it a FRED extract?"
1762
+ raise ValueError(msg)
1763
+ stored = pd.read_csv(path, usecols=["series_id", "date"], dtype=str).dropna()
1764
+ if stored.empty:
1765
+ return None
1766
+ dates = pd.to_datetime(stored["date"], format="ISO8601")
1767
+ return dates.groupby(stored["series_id"]).max().min()
1768
+
1769
+
1770
+ def _error_text(resp: requests.Response) -> str:
1771
+ """
1772
+ Extract a short error message from a FRED error answer.
1773
+
1774
+ FRED answers errors with JSON such as ``{"error_code": 400,
1775
+ "error_message": "Bad Request. ..."}``. Anything else is shown as
1776
+ (truncated) text.
1777
+
1778
+ Args:
1779
+ resp (requests.Response): The failed answer.
1780
+
1781
+ Returns:
1782
+ str: The message.
1783
+ """
1784
+ try:
1785
+ body = resp.json()
1786
+ except ValueError:
1787
+ return resp.text.strip()[:200] or resp.reason or "no details"
1788
+ if isinstance(body, dict) and body.get("error_message"):
1789
+ return " ".join(str(body["error_message"]).split())[:300]
1790
+ return str(body)[:200]
1791
+
1792
+
1793
+ def _redacted(exc: requests.RequestException) -> requests.RequestException:
1794
+ """
1795
+ Copy a transport error with the API key masked in its message.
1796
+
1797
+ Args:
1798
+ exc (requests.RequestException): The error, whose message may quote
1799
+ the request URL.
1800
+
1801
+ Returns:
1802
+ requests.RequestException: An error of the same type (or a plain
1803
+ ``RequestException``) with a redacted message.
1804
+ """
1805
+ text = _REDACT.redact(str(exc))
1806
+ try:
1807
+ return type(exc)(text)
1808
+ except TypeError: # pragma: no cover - every requests error takes a message
1809
+ return requests.RequestException(text)
1810
+
1811
+
1812
+ # --------------------------------------------------------------------------- #
1813
+ # Command line
1814
+ # --------------------------------------------------------------------------- #
1815
+ # Bare boolean flags pinned to True by main(), so ``--tidy`` works anywhere.
1816
+ _BOOL_FLAGS = ("tidy",)
1817
+
1818
+ # CLI arguments kept as typed: python-fire would read ``GDP,UNRATE`` as a
1819
+ # tuple, ``2024-01-01`` as a subtraction and ``2024`` as a number.
1820
+ _RAW_TEXT_ARGS = (
1821
+ "series_ids",
1822
+ "series_id",
1823
+ "text",
1824
+ "start",
1825
+ "end",
1826
+ "realtime_start",
1827
+ "realtime_end",
1828
+ "vintage_dates",
1829
+ "tags",
1830
+ "exclude_tags",
1831
+ "filter_value",
1832
+ "search_text",
1833
+ "tag_names",
1834
+ "endpoint",
1835
+ )
1836
+
1837
+
1838
+ class _Cli:
1839
+ """
1840
+ Command-line facade over :class:`FredClient`, exposed through python-fire.
1841
+
1842
+ Each method becomes a subcommand. Tables are returned as text; with
1843
+ ``--out`` the result is written instead (the suffix picks CSV, Excel,
1844
+ Parquet or JSON) and a bare filename goes into ``outputs/``. Several
1845
+ series ids, vintage dates or tags are separated by ``,`` or ``;``.
1846
+
1847
+ The constructor's parameters become global flags, accepted with any
1848
+ command: ``--log-level`` and ``--log-file``. The API key is read from the
1849
+ ``FRED_API_KEY`` environment variable, never from a flag (flags end up in
1850
+ shell histories and process listings).
1851
+ """
1852
+
1853
+ def __init__(self, log_level: str = "WARNING", log_file: str | None = None) -> None:
1854
+ """
1855
+ Set up CLI logging and a default :class:`FredClient`.
1856
+
1857
+ Tests replace ``FredClient`` with a client fed by a fake API.
1858
+
1859
+ Args:
1860
+ log_level (str): Console log threshold: ``DEBUG``, ``INFO``,
1861
+ ``WARNING`` (default, quiet) or ``ERROR``. Log lines go to
1862
+ stderr, so command output on stdout stays clean.
1863
+ log_file (str | None): Append a full DEBUG log with timestamps to
1864
+ this file. A bare filename is written into ``outputs/``.
1865
+ """
1866
+ configure_logging(
1867
+ _log,
1868
+ log_level,
1869
+ resolve_out(log_file) if log_file else None,
1870
+ flag=_CLI_HANDLER_FLAG,
1871
+ )
1872
+ self._fred = FredClient()
1873
+
1874
+ @staticmethod
1875
+ def _show(frame: pd.DataFrame, out: str | None) -> str:
1876
+ """
1877
+ Render a frame as text, or write it to ``out``.
1878
+
1879
+ Args:
1880
+ frame (pd.DataFrame): The result.
1881
+ out (str | None): Destination; the suffix picks the format.
1882
+
1883
+ Returns:
1884
+ str: The table (without long notes), or a status line naming the
1885
+ file written.
1886
+ """
1887
+ if out:
1888
+ written = write_frame(frame, resolve_out(out))
1889
+ _log.info("Wrote %d rows to %s", len(frame), written)
1890
+ return f"Wrote {len(frame):,} rows -> {written}"
1891
+ shown = frame.drop(columns=[c for c in _LONG_TEXT if c in frame.columns])
1892
+ return shown.to_string(index=False)
1893
+
1894
+ def series(
1895
+ self,
1896
+ series_ids: str,
1897
+ realtime_start: str | None = None,
1898
+ realtime_end: str | None = None,
1899
+ out: str | None = None,
1900
+ ) -> str:
1901
+ """
1902
+ Describe series.
1903
+
1904
+ Args:
1905
+ series_ids (str): Series ids, separated by ``,`` or ``;``.
1906
+ realtime_start (str | None): Describe them as of this real-time
1907
+ period.
1908
+ realtime_end (str | None): End of that period.
1909
+ out (str | None): Write here instead of printing.
1910
+
1911
+ Returns:
1912
+ str: The table, or a status line when ``out`` is used.
1913
+ """
1914
+ frame = self._fred.series(series_ids, realtime_start, realtime_end)
1915
+ return self._show(frame, out)
1916
+
1917
+ def search(
1918
+ self,
1919
+ text: str,
1920
+ search_type: Literal["full_text", "series_id"] = "full_text",
1921
+ tags: str | None = None,
1922
+ exclude_tags: str | None = None,
1923
+ filter_variable: Literal["frequency", "units", "seasonal_adjustment"]
1924
+ | None = None,
1925
+ filter_value: str | None = None,
1926
+ order_by: str | None = None,
1927
+ sort_order: Literal["asc", "desc"] | None = None,
1928
+ max_results: int = 1000,
1929
+ out: str | None = None,
1930
+ ) -> str:
1931
+ """
1932
+ Search series.
1933
+
1934
+ Args:
1935
+ text (str): The words, or an id pattern with ``--search-type series_id``.
1936
+ search_type (str): ``full_text`` or ``series_id``.
1937
+ tags (str | None): Required tags, separated by ``;``.
1938
+ exclude_tags (str | None): Excluded tags, separated by ``;``.
1939
+ filter_variable (str | None): ``frequency``, ``units`` or
1940
+ ``seasonal_adjustment``.
1941
+ filter_value (str | None): The value it must have.
1942
+ order_by (str | None): Sort attribute.
1943
+ sort_order (str | None): ``asc`` or ``desc``.
1944
+ max_results (int): Stop after this many series.
1945
+ out (str | None): Write here instead of printing.
1946
+
1947
+ Returns:
1948
+ str: The table, or a status line when ``out`` is used.
1949
+ """
1950
+ frame = self._fred.search(
1951
+ text, search_type=search_type, tags=tags, exclude_tags=exclude_tags,
1952
+ filter_variable=filter_variable, filter_value=filter_value,
1953
+ order_by=order_by, sort_order=sort_order, max_results=max_results,
1954
+ ) # fmt: skip
1955
+ return self._show(frame, out)
1956
+
1957
+ def observations(
1958
+ self,
1959
+ series_ids: str,
1960
+ start: str | None = None,
1961
+ end: str | None = None,
1962
+ units: str | None = None,
1963
+ frequency: str | None = None,
1964
+ aggregation_method: str | None = None,
1965
+ realtime_start: str | None = None,
1966
+ realtime_end: str | None = None,
1967
+ vintage_dates: str | None = None,
1968
+ output_type: int | None = None,
1969
+ out: str | None = None,
1970
+ *,
1971
+ tidy: bool = False,
1972
+ ) -> str:
1973
+ """
1974
+ Fetch observations and print them or write them to ``out``.
1975
+
1976
+ Args:
1977
+ series_ids (str): Series ids, separated by ``,`` or ``;``.
1978
+ start (str | None): First observation date or period.
1979
+ end (str | None): Last observation date or period.
1980
+ units (str | None): Transformation (``pch``, ``pc1``, ``log``, ...).
1981
+ frequency (str | None): Aggregate to this frequency (``m``, ``q``, ``a``).
1982
+ aggregation_method (str | None): ``avg``, ``sum`` or ``eop``.
1983
+ realtime_start (str | None): First day of the real-time period.
1984
+ realtime_end (str | None): Last day of the real-time period.
1985
+ vintage_dates (str | None): Vintage days, separated by ``,``.
1986
+ output_type (int | None): 1 to 4 (see the library docs).
1987
+ out (str | None): Write here instead of printing.
1988
+ tidy (bool): Return the tidy long shape.
1989
+
1990
+ Returns:
1991
+ str: The table, or a status line when ``out`` is used.
1992
+ """
1993
+ frame = self._fred.observations(
1994
+ series_ids, as_text(start), as_text(end), units=units, frequency=frequency,
1995
+ aggregation_method=aggregation_method, realtime_start=as_text(realtime_start),
1996
+ realtime_end=as_text(realtime_end), vintage_dates=vintage_dates,
1997
+ output_type=output_type, tidy=tidy,
1998
+ ) # fmt: skip
1999
+ return self._show(frame, out)
2000
+
2001
+ def vintage_dates(
2002
+ self,
2003
+ series_id: str,
2004
+ realtime_start: str | None = None,
2005
+ realtime_end: str | None = None,
2006
+ out: str | None = None,
2007
+ ) -> str:
2008
+ """
2009
+ List the vintage dates of a series.
2010
+
2011
+ Args:
2012
+ series_id (str): The series.
2013
+ realtime_start (str | None): First vintage to list.
2014
+ realtime_end (str | None): Last vintage to list.
2015
+ out (str | None): Write here instead of printing.
2016
+
2017
+ Returns:
2018
+ str: The table, or a status line when ``out`` is used.
2019
+ """
2020
+ frame = self._fred.vintage_dates(
2021
+ series_id, as_text(realtime_start), as_text(realtime_end)
2022
+ )
2023
+ return self._show(frame, out)
2024
+
2025
+ def category(self, category_id: int = 0) -> str:
2026
+ """
2027
+ Describe a category.
2028
+
2029
+ Args:
2030
+ category_id (int): The category (``0``, the root, by default).
2031
+
2032
+ Returns:
2033
+ str: The table.
2034
+ """
2035
+ return self._show(self._fred.category(category_id), None)
2036
+
2037
+ def categories(self, parent_id: int = 0, out: str | None = None) -> str:
2038
+ """
2039
+ List the child categories of a category.
2040
+
2041
+ Args:
2042
+ parent_id (int): The parent (``0``, the root, by default).
2043
+ out (str | None): Write here instead of printing.
2044
+
2045
+ Returns:
2046
+ str: The table, or a status line when ``out`` is used.
2047
+ """
2048
+ return self._show(self._fred.categories(parent_id), out)
2049
+
2050
+ def category_series(
2051
+ self,
2052
+ category_id: int,
2053
+ tags: str | None = None,
2054
+ filter_variable: Literal["frequency", "units", "seasonal_adjustment"]
2055
+ | None = None,
2056
+ filter_value: str | None = None,
2057
+ max_results: int | None = None,
2058
+ out: str | None = None,
2059
+ ) -> str:
2060
+ """
2061
+ List the series in a category.
2062
+
2063
+ Args:
2064
+ category_id (int): The category.
2065
+ tags (str | None): Required tags, separated by ``;``.
2066
+ filter_variable (str | None): ``frequency``, ``units`` or
2067
+ ``seasonal_adjustment``.
2068
+ filter_value (str | None): The value it must have.
2069
+ max_results (int | None): Stop after this many series.
2070
+ out (str | None): Write here instead of printing.
2071
+
2072
+ Returns:
2073
+ str: The table, or a status line when ``out`` is used.
2074
+ """
2075
+ frame = self._fred.category_series(
2076
+ category_id, tags=tags, filter_variable=filter_variable,
2077
+ filter_value=filter_value, max_results=max_results,
2078
+ ) # fmt: skip
2079
+ return self._show(frame, out)
2080
+
2081
+ def releases(self, out: str | None = None) -> str:
2082
+ """
2083
+ List every release.
2084
+
2085
+ Args:
2086
+ out (str | None): Write here instead of printing.
2087
+
2088
+ Returns:
2089
+ str: The table, or a status line when ``out`` is used.
2090
+ """
2091
+ return self._show(self._fred.releases(), out)
2092
+
2093
+ def release(self, release_id: int) -> str:
2094
+ """
2095
+ Describe a release.
2096
+
2097
+ Args:
2098
+ release_id (int): The release.
2099
+
2100
+ Returns:
2101
+ str: The table.
2102
+ """
2103
+ return self._show(self._fred.release(release_id), None)
2104
+
2105
+ def release_series(
2106
+ self,
2107
+ release_id: int,
2108
+ tags: str | None = None,
2109
+ filter_variable: Literal["frequency", "units", "seasonal_adjustment"]
2110
+ | None = None,
2111
+ filter_value: str | None = None,
2112
+ max_results: int | None = None,
2113
+ out: str | None = None,
2114
+ ) -> str:
2115
+ """
2116
+ List the series of a release.
2117
+
2118
+ Args:
2119
+ release_id (int): The release.
2120
+ tags (str | None): Required tags, separated by ``;``.
2121
+ filter_variable (str | None): ``frequency``, ``units`` or
2122
+ ``seasonal_adjustment``.
2123
+ filter_value (str | None): The value it must have.
2124
+ max_results (int | None): Stop after this many series.
2125
+ out (str | None): Write here instead of printing.
2126
+
2127
+ Returns:
2128
+ str: The table, or a status line when ``out`` is used.
2129
+ """
2130
+ frame = self._fred.release_series(
2131
+ release_id, tags=tags, filter_variable=filter_variable,
2132
+ filter_value=filter_value, max_results=max_results,
2133
+ ) # fmt: skip
2134
+ return self._show(frame, out)
2135
+
2136
+ def tags(
2137
+ self,
2138
+ search_text: str | None = None,
2139
+ tag_names: str | None = None,
2140
+ tag_group_id: str | None = None,
2141
+ max_results: int = 1000,
2142
+ out: str | None = None,
2143
+ ) -> str:
2144
+ """
2145
+ List tags.
2146
+
2147
+ Args:
2148
+ search_text (str | None): Words to match.
2149
+ tag_names (str | None): Only these tags, separated by ``;``.
2150
+ tag_group_id (str | None): Only this group (``geo``, ``freq``, ...).
2151
+ max_results (int): Stop after this many tags.
2152
+ out (str | None): Write here instead of printing.
2153
+
2154
+ Returns:
2155
+ str: The table, or a status line when ``out`` is used.
2156
+ """
2157
+ frame = self._fred.tags(
2158
+ search_text, tag_names=tag_names, tag_group_id=tag_group_id,
2159
+ max_results=max_results,
2160
+ ) # fmt: skip
2161
+ return self._show(frame, out)
2162
+
2163
+ def raw(self, endpoint: str, **params: str | int | Sequence[str | int]) -> str:
2164
+ """
2165
+ Call any endpoint and print its JSON answer.
2166
+
2167
+ Args:
2168
+ endpoint (str): The endpoint below ``/fred/`` (``release/dates``).
2169
+ **params (str | int | Sequence[str | int]): Its query parameters
2170
+ (``--release-id 53``); a list (``--tag-names usa,m2``, which
2171
+ fire reads as a tuple) is joined as FRED expects.
2172
+
2173
+ Returns:
2174
+ str: The answer as indented JSON.
2175
+ """
2176
+ return json.dumps(self._fred.raw(endpoint, **params), indent=2)
2177
+
2178
+ def update_csv(
2179
+ self,
2180
+ path: str,
2181
+ series_ids: str,
2182
+ start: str | None = None,
2183
+ lookback_days: int = 730,
2184
+ units: str | None = None,
2185
+ frequency: str | None = None,
2186
+ aggregation_method: str | None = None,
2187
+ realtime_start: str | None = None,
2188
+ realtime_end: str | None = None,
2189
+ *,
2190
+ tidy: bool = False,
2191
+ ) -> str:
2192
+ """
2193
+ Incrementally update a CSV and report the row count.
2194
+
2195
+ Args:
2196
+ path (str): CSV to create or update; a bare name goes to ``outputs/``.
2197
+ series_ids (str): Series ids, separated by ``,`` or ``;``.
2198
+ start (str | None): First observation date on the initial run
2199
+ (while the CSV is missing, empty or holds no rows). Later
2200
+ runs re-fetch from the look-back instead, so the same command
2201
+ can be scheduled; to re-fetch from an earlier date, pass
2202
+ ``start`` to :meth:`FredClient.update_csv`.
2203
+ lookback_days (int): Days re-fetched before the last stored date.
2204
+ units (str | None): Transformation (``pch``, ``pc1``, ...).
2205
+ frequency (str | None): Aggregate to this frequency.
2206
+ aggregation_method (str | None): ``avg``, ``sum`` or ``eop``.
2207
+ realtime_start (str | None): First day of the real-time period.
2208
+ realtime_end (str | None): Last day of the real-time period.
2209
+ tidy (bool): Keep the CSV in the tidy long shape.
2210
+
2211
+ Returns:
2212
+ str: A status line with the number of rows added or revised.
2213
+ """
2214
+ path = resolve_out(path)
2215
+ options = {
2216
+ "units": units,
2217
+ "frequency": frequency,
2218
+ "aggregation_method": aggregation_method,
2219
+ "realtime_start": as_text(realtime_start),
2220
+ "realtime_end": as_text(realtime_end),
2221
+ }
2222
+ kwargs: dict[str, Any] = {k: v for k, v in options.items() if v is not None}
2223
+ kwargs["tidy"] = tidy
2224
+ # --start applies until the file holds an observation: a missing,
2225
+ # zero-byte or header-only CSV is still a first run.
2226
+ if start and _last_date(Path(path)) is None:
2227
+ kwargs["start"] = as_text(start)
2228
+ changed = self._fred.update_csv(
2229
+ path, series_ids, lookback_days=lookback_days, **kwargs
2230
+ )
2231
+ return f"Wrote {len(changed):,} new/revised rows -> {path}"
2232
+
2233
+
2234
+ # Fire stores parse functions on the methods themselves; registering them here
2235
+ # means fire.Fire(_Cli, ...) behaves the same in tests as through main().
2236
+ set_parse_fns(_Cli, dict.fromkeys(_RAW_TEXT_ARGS, str))
2237
+
2238
+
2239
+ def main() -> None:
2240
+ """
2241
+ Run the Fire-generated command-line interface.
2242
+
2243
+ An expected error (missing API key, unknown option, bad date, HTTP
2244
+ failure) prints a concise ``Error: ...`` message on stderr and exits with
2245
+ code 1 (a :class:`SystemExit`); the traceback goes to the log.
2246
+ """
2247
+ run(
2248
+ _Cli,
2249
+ name="pyfred-client",
2250
+ logger=_log,
2251
+ expected=(ValueError, RuntimeError, requests.RequestException),
2252
+ bool_flags=_BOOL_FLAGS,
2253
+ )
2254
+
2255
+
2256
+ if __name__ == "__main__":
2257
+ main()