parsimony-bde 0.0.1__tar.gz

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.
@@ -0,0 +1,40 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.so
5
+
6
+ .Python
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ *.egg
11
+
12
+ .venv/
13
+ .env
14
+ .env.*
15
+ !.env.example
16
+
17
+ .pytest_cache/
18
+ .mypy_cache/
19
+ .ruff_cache/
20
+ .coverage
21
+ htmlcov/
22
+ coverage.xml
23
+
24
+ uv.lock
25
+
26
+ .vscode/
27
+ .council/
28
+ PLAN-*.md
29
+ .idea/
30
+ *.swp
31
+ .DS_Store
32
+
33
+ outputs/
34
+ logs/
35
+ # Recorded HTTP cassettes must never be committed — respx mocks are hand-authored
36
+ # from upstream API documentation. A pre-commit / CI regex scan is the belt; this
37
+ # ignore is the braces. Override per-file via `!` if you need a hand-authored
38
+ # fixture checked in.
39
+ packages/*/tests/fixtures/**
40
+ !packages/*/tests/fixtures/README.md
@@ -0,0 +1,64 @@
1
+ # Changelog — parsimony-bde
2
+
3
+ All notable changes to `parsimony-bde` will be documented in this file. The
4
+ format is based on [Keep a Changelog](https://keepachangelog.com/) and
5
+ this project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.8.0] — 2026-06-08
8
+
9
+ A full-process completeness pass over the connector (documentation re-compiled
10
+ and every claim re-verified against the live BIEST endpoints).
11
+
12
+ ### Added
13
+
14
+ - **Bank Lending Survey recovered.** The `pb` catalog chapter lists family/table
15
+ aliases (`PB_1_1.1`) that the BIEST web service rejects with HTTP 412
16
+ ("no existe"), so all 262 of those series were previously un-fetchable. The
17
+ real fetchable codes (`DPB…`) live only inside the bulk `pb.zip`; the
18
+ enumerator now reads them from there, recovering ~350 Bank Lending Survey
19
+ series as searchable and fetchable (`enumerate.py`, `_catalog.parse_pb_zip`).
20
+ - **Bilingual catalog.** The published catalog CSVs are Spanish-only, so search
21
+ used to be Spanish-only (the discovery index is lexical/BM25 at this
22
+ cardinality — no multilingual embedding bridge). `build_bde_catalog` now
23
+ enriches each entry's `title` with the English short description from
24
+ `favoritas(idioma=en)` where BdE serves one (Spanish title kept as fallback),
25
+ while the Spanish long description rides along in `description` — both are
26
+ indexed, so an agent searching in English or Spanish gets lexical hits
27
+ (`enrich.py`). The enrichment is batched, retried, and split-on-failure so a
28
+ flaky network can't silently drop a batch's English titles.
29
+
30
+ ### Fixed
31
+
32
+ - **Catalog de-duplication.** A series can be listed under more than one thematic
33
+ chapter (~24% of raw rows were cross-chapter repeats). `enumerate_bde` now
34
+ de-dups by series code (first chapter in order wins), so the catalog is the
35
+ ~15.5k unique series rather than ~20.5k rows with non-deterministic per-row
36
+ `category`.
37
+ - **Frequency-dependent `time_range`.** `bde_fetch` rejected valid daily-series
38
+ ranges (`3M`/`12M`/`36M`) and accepted `MAX` that BdE 412s for daily series.
39
+ The accepted set is now the documented union and BdE validates the
40
+ frequency-specific rule server-side.
41
+ - **Typed error for invalid requests.** An unknown series code or a
42
+ frequency-incompatible range (BdE HTTP 412) now surfaces as
43
+ `InvalidParameterError` carrying BdE's own message, instead of a generic
44
+ `ProviderError(412)` that reads like a transient server fault.
45
+
46
+ ## [0.5.0] — 2026-05-06
47
+
48
+ ### Changed
49
+
50
+ - Adapted to `parsimony-core==0.5`. Connector code no longer constructs `Provenance` directly; the framework authors all provenance fields in `Connector._wrap_result`. Source-specific extras (where present) move to `Result.with_properties(**kwargs)`. Drops the `provenance=` and `params=` kwargs from `OutputConfig.build_table_result` / `Result.from_dataframe` call sites.
51
+ - Bump `parsimony-core` pin from `>=0.4.0,<0.5` to `>=0.5.0,<0.6` (and `[standard-onnx]` extra accordingly on catalog-publishing packages).
52
+ ## [0.4.0] — 2026-04-24
53
+
54
+ Part of the first coordinated release of the
55
+ [`parsimony-connectors`](https://github.com/ockham-sh/parsimony-connectors)
56
+ monorepo under `parsimony-core==0.4`.
57
+
58
+ ### Changed
59
+
60
+ - Connector rewritten against the kernel's `parsimony.discover` surface
61
+ (`iter_providers`, `load`, `load_all`) and the `@connector(env=...)`
62
+ decorator-level env-var declaration that replaced module-level
63
+ `ENV_VARS`.
64
+ - Pin bumped to `parsimony-core>=0.4,<0.5`.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Ockham.sh
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: parsimony-bde
3
+ Version: 0.0.1
4
+ Summary: Banco de España connector for the parsimony framework
5
+ Project-URL: Homepage, https://www.bde.es
6
+ Project-URL: Repository, https://github.com/ockham-sh/parsimony-connectors
7
+ Project-URL: Issues, https://github.com/ockham-sh/parsimony-connectors/issues
8
+ Author-email: "Ockham.sh" <team@ockham.sh>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: bde,connectors,data,finance,parsimony
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business :: Financial
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: pandas<3,>=2.3.0
25
+ Requires-Dist: parsimony-core[catalog]>=0.0.1
26
+ Requires-Dist: parsimony-shared>=0.0.1
27
+ Requires-Dist: pydantic<3,>=2.11.1
28
+ Provides-Extra: dev
29
+ Requires-Dist: mypy>=1.10; extra == 'dev'
30
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
31
+ Requires-Dist: pytest>=9.0.3; extra == 'dev'
32
+ Requires-Dist: respx>=0.22.0; extra == 'dev'
33
+ Requires-Dist: ruff>=0.15.10; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # parsimony-bde
37
+
38
+ Banco de España connector — Spanish macroeconomic, monetary, and financial time series via the BIEST REST API.
39
+
40
+ Part of the [parsimony-connectors](https://github.com/ockham-sh/parsimony-connectors) monorepo. Distributed standalone on PyPI as `parsimony-bde`.
41
+
42
+ ## Connectors
43
+
44
+ | Name | Kind | Description |
45
+ |---|---|---|
46
+ | `bde_fetch` | connector | Fetch one or more BdE time series by series code (comma-separated). |
47
+ | `enumerate_bde` | enumerator | Discover BdE series from six catalog CSV chapters plus the Bank Lending Survey (recovered from `pb.zip`). |
48
+ | `bde_search` | connector | Semantic-search the published BdE catalog snapshot; returns ranked series codes. |
49
+
50
+ `bde_fetch`'s `time_range` is frequency-dependent (BdE validates it): monthly /
51
+ quarterly series take `30M`/`60M`/`MAX`, daily series take `3M`/`12M`/`36M` (not
52
+ `MAX`), and any frequency accepts a 4-digit year (e.g. `2024`). A range that
53
+ doesn't fit a series' frequency is reported as an `InvalidParameterError`.
54
+
55
+ ## Install
56
+
57
+ ```bash
58
+ pip install parsimony-bde
59
+ ```
60
+
61
+ Pulls in `parsimony-core>=0.7,<0.8` automatically. Verify discovery:
62
+
63
+ ```bash
64
+ python -c "from parsimony import discover; print([p.name for p in discover.iter_providers()])"
65
+ ```
66
+
67
+ ## Configuration
68
+
69
+ No API key required — the BdE BIEST API is open and unauthenticated.
70
+
71
+ `bde_search` reads a published catalog snapshot (default `hf://parsimony-dev/bde`).
72
+ Override the snapshot location with the `PARSIMONY_BDE_CATALOG_URL` environment
73
+ variable, or pass `catalog_url=` at call time.
74
+
75
+ ## Quick start
76
+
77
+ ```python
78
+ from parsimony_bde import CONNECTORS
79
+
80
+ result = CONNECTORS["bde_fetch"](key="D_1NBAF472")
81
+ print(result.data.head())
82
+ ```
83
+
84
+ For multi-plugin composition (autoloads everything installed):
85
+
86
+ ```python
87
+ from parsimony import discover
88
+ connectors = discover.load_all()
89
+ ```
90
+
91
+ ## Catalogs
92
+
93
+ `enumerate_bde` discovers the full BdE series catalog — ~15.5k unique series
94
+ across six published CSV chapters (`be`, `cf`, `ie`, `si`, `tc`, `ti`), plus the
95
+ Bank Lending Survey. The survey's CSV chapter lists only un-fetchable family
96
+ aliases (`PB_1_1.1`), so its real fetchable codes (`DPB…`) are recovered from the
97
+ bulk `pb.zip`. Rows are de-duplicated by series code (a series can appear under
98
+ more than one thematic chapter). Maintainers build a `Catalog` snapshot from the
99
+ enumerator (see `scripts/build_catalog.py`) and push it to the snapshot URL that
100
+ `bde_search` reads. The crawl is expensive (the CF/Financial-Accounts chapter
101
+ alone is several thousand series), so it runs offline as a publish job — never at
102
+ query time.
103
+
104
+ A small tail (~1% of catalog codes, mostly dollar-denominated `…$…` financial
105
+ accounts variants and a handful of external-sector series) is listed in the CSV
106
+ catalog but not served by the web service; fetching such a code returns a clear
107
+ `InvalidParameterError` rather than data.
108
+
109
+ ## Provider
110
+
111
+ - Homepage: https://www.bde.es
112
+ - API docs: https://www.bde.es/webbe/en/estadisticas/recursos/api-estadisticas-bde.html
113
+ - Series browser: https://app.bde.es/bie_www/bie_wwwias/xml/Arranque.html (BIEST)
114
+
115
+ ## License
116
+
117
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,82 @@
1
+ # parsimony-bde
2
+
3
+ Banco de España connector — Spanish macroeconomic, monetary, and financial time series via the BIEST REST API.
4
+
5
+ Part of the [parsimony-connectors](https://github.com/ockham-sh/parsimony-connectors) monorepo. Distributed standalone on PyPI as `parsimony-bde`.
6
+
7
+ ## Connectors
8
+
9
+ | Name | Kind | Description |
10
+ |---|---|---|
11
+ | `bde_fetch` | connector | Fetch one or more BdE time series by series code (comma-separated). |
12
+ | `enumerate_bde` | enumerator | Discover BdE series from six catalog CSV chapters plus the Bank Lending Survey (recovered from `pb.zip`). |
13
+ | `bde_search` | connector | Semantic-search the published BdE catalog snapshot; returns ranked series codes. |
14
+
15
+ `bde_fetch`'s `time_range` is frequency-dependent (BdE validates it): monthly /
16
+ quarterly series take `30M`/`60M`/`MAX`, daily series take `3M`/`12M`/`36M` (not
17
+ `MAX`), and any frequency accepts a 4-digit year (e.g. `2024`). A range that
18
+ doesn't fit a series' frequency is reported as an `InvalidParameterError`.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install parsimony-bde
24
+ ```
25
+
26
+ Pulls in `parsimony-core>=0.7,<0.8` automatically. Verify discovery:
27
+
28
+ ```bash
29
+ python -c "from parsimony import discover; print([p.name for p in discover.iter_providers()])"
30
+ ```
31
+
32
+ ## Configuration
33
+
34
+ No API key required — the BdE BIEST API is open and unauthenticated.
35
+
36
+ `bde_search` reads a published catalog snapshot (default `hf://parsimony-dev/bde`).
37
+ Override the snapshot location with the `PARSIMONY_BDE_CATALOG_URL` environment
38
+ variable, or pass `catalog_url=` at call time.
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ from parsimony_bde import CONNECTORS
44
+
45
+ result = CONNECTORS["bde_fetch"](key="D_1NBAF472")
46
+ print(result.data.head())
47
+ ```
48
+
49
+ For multi-plugin composition (autoloads everything installed):
50
+
51
+ ```python
52
+ from parsimony import discover
53
+ connectors = discover.load_all()
54
+ ```
55
+
56
+ ## Catalogs
57
+
58
+ `enumerate_bde` discovers the full BdE series catalog — ~15.5k unique series
59
+ across six published CSV chapters (`be`, `cf`, `ie`, `si`, `tc`, `ti`), plus the
60
+ Bank Lending Survey. The survey's CSV chapter lists only un-fetchable family
61
+ aliases (`PB_1_1.1`), so its real fetchable codes (`DPB…`) are recovered from the
62
+ bulk `pb.zip`. Rows are de-duplicated by series code (a series can appear under
63
+ more than one thematic chapter). Maintainers build a `Catalog` snapshot from the
64
+ enumerator (see `scripts/build_catalog.py`) and push it to the snapshot URL that
65
+ `bde_search` reads. The crawl is expensive (the CF/Financial-Accounts chapter
66
+ alone is several thousand series), so it runs offline as a publish job — never at
67
+ query time.
68
+
69
+ A small tail (~1% of catalog codes, mostly dollar-denominated `…$…` financial
70
+ accounts variants and a handful of external-sector series) is listed in the CSV
71
+ catalog but not served by the web service; fetching such a code returns a clear
72
+ `InvalidParameterError` rather than data.
73
+
74
+ ## Provider
75
+
76
+ - Homepage: https://www.bde.es
77
+ - API docs: https://www.bde.es/webbe/en/estadisticas/recursos/api-estadisticas-bde.html
78
+ - Series browser: https://app.bde.es/bie_www/bie_wwwias/xml/Arranque.html (BIEST)
79
+
80
+ ## License
81
+
82
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,10 @@
1
+ """Banco de España (BdE): fetch + catalog enumeration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from parsimony_bde.connectors import CONNECTORS, load
6
+ from parsimony_bde.connectors.enumerate import enumerate_bde
7
+ from parsimony_bde.connectors.fetch import bde_fetch
8
+ from parsimony_bde.search import bde_search
9
+
10
+ __all__ = ["CONNECTORS", "load", "bde_fetch", "enumerate_bde", "bde_search"]
@@ -0,0 +1,82 @@
1
+ """BdE REST and catalog CSV transport."""
2
+
3
+ from __future__ import annotations
4
+
5
+ BASE_URL = "https://app.bde.es/bierest/resources/srdatosapp"
6
+ CATALOG_CSV_BASE_URL = "https://www.bde.es/webbe/es/estadisticas/compartido/datos/csv"
7
+ CATALOG_ZIP_BASE_URL = "https://www.bde.es/webbe/es/estadisticas/compartido/datos/zip"
8
+
9
+ # Six of the seven published catalog chapters list API-fetchable ``serie`` codes
10
+ # directly in their CSV. The seventh — ``pb`` (Bank Lending Survey) — is the
11
+ # odd one out: its CSV ``serie`` column holds *family/table* codes (``PB_1_1.1``)
12
+ # that the BIEST web service rejects with HTTP 412 "no existe". The real
13
+ # fetchable codes for that survey live only inside the bulk ``pb.zip`` value
14
+ # files, so ``pb`` is enumerated from the ZIP instead (see ``PB_ZIP_URL`` and
15
+ # ``connectors/_catalog.parse_pb_zip``). Live-verified 2026-06-08.
16
+ CATALOG_CHAPTERS: tuple[tuple[str, str], ...] = (
17
+ ("be", "General Statistics"),
18
+ ("cf", "Financial Accounts"),
19
+ ("ie", "International Economy"),
20
+ ("si", "Financial Indicators"),
21
+ ("tc", "Exchange Rates"),
22
+ ("ti", "Interest Rates"),
23
+ )
24
+
25
+ # Bank Lending Survey — recovered from the bulk ZIP, not the CSV catalog.
26
+ PB_ZIP_URL = f"{CATALOG_ZIP_BASE_URL}/pb.zip"
27
+ PB_CATEGORY = "Bank Lending Survey"
28
+
29
+ CSV_ENCODING = "cp1252"
30
+ CSV_HEADERS: tuple[str, ...] = (
31
+ "serie",
32
+ "seq",
33
+ "alias",
34
+ "file",
35
+ "description",
36
+ "var_type",
37
+ "unit_code",
38
+ "exponent",
39
+ "decimals",
40
+ "unit_desc",
41
+ "frequency_raw",
42
+ "start_date",
43
+ "end_date",
44
+ "n_obs",
45
+ "title",
46
+ "source_org",
47
+ "notes",
48
+ )
49
+
50
+ FREQ_MAP_RAW = {
51
+ "DIARIA": "Daily",
52
+ "LABORABLE": "Business Daily",
53
+ "SEMANAL": "Weekly",
54
+ "QUINCENAL": "Bi-weekly",
55
+ "MENSUAL": "Monthly",
56
+ "TRIMESTRAL": "Quarterly",
57
+ "SEMESTRAL": "Semi-annual",
58
+ "ANUAL": "Annual",
59
+ }
60
+
61
+ FREQ_MAP = {
62
+ "D": "Daily",
63
+ "M": "Monthly",
64
+ "Q": "Quarterly",
65
+ "A": "Annual",
66
+ "S": "Semi-annual",
67
+ "W": "Weekly",
68
+ "B": "Business Daily",
69
+ }
70
+
71
+ COLUMN_MAP = {
72
+ "serie": "key",
73
+ "descripcion": "description",
74
+ "descripcionCorta": "title",
75
+ "codFrecuencia": "freq",
76
+ "decimales": "decimals",
77
+ "simbolo": "symbol",
78
+ "fechaInicio": "start_date",
79
+ "fechaFin": "end_date",
80
+ "fechas": "date",
81
+ "valores": "value",
82
+ }
@@ -0,0 +1,35 @@
1
+ """Build the Banco de España catalog snapshot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ from parsimony.catalog import Catalog
8
+ from parsimony.catalog.policy import discovery_indexes
9
+ from parsimony.catalog.source import entities_from_raw
10
+
11
+ from parsimony_bde.connectors.enumerate import enumerate_bde
12
+ from parsimony_bde.outputs import BDE_ENUMERATE_OUTPUT
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ CATALOG_NAMESPACE = "bde"
17
+
18
+
19
+ def build_bde_catalog() -> Catalog:
20
+ """Enumerate and build the Banco de España catalog.
21
+
22
+ Titles and descriptions are in Spanish — BdE's published catalog CSV
23
+ chapters have no English variant.
24
+ """
25
+ result = enumerate_bde()
26
+ df = result.data
27
+
28
+ entries = entities_from_raw(df, BDE_ENUMERATE_OUTPUT)
29
+ catalog = Catalog(CATALOG_NAMESPACE, indexes=discovery_indexes(entries), default_field="title")
30
+ catalog.set_entities(entries)
31
+ catalog.build()
32
+ return catalog
33
+
34
+
35
+ __all__ = ["CATALOG_NAMESPACE", "build_bde_catalog"]
@@ -0,0 +1,21 @@
1
+ """bde connector registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from parsimony.connector import Connectors
6
+
7
+ from parsimony_bde.connectors.enumerate import enumerate_bde
8
+ from parsimony_bde.connectors.fetch import bde_fetch
9
+ from parsimony_bde.search import bde_search
10
+
11
+ CONNECTORS = Connectors([bde_fetch, enumerate_bde, bde_search])
12
+
13
+
14
+ def load(*, catalog_url: str | None = None) -> Connectors:
15
+ """Return :data:`CONNECTORS` with an optional catalog URL bound on search."""
16
+ if catalog_url is None:
17
+ return CONNECTORS
18
+ return CONNECTORS.bind(catalog_url=catalog_url)
19
+
20
+
21
+ __all__ = ["CONNECTORS", "load"]
@@ -0,0 +1,199 @@
1
+ """BdE catalog CSV parsing helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ import logging
8
+ import unicodedata
9
+ import zipfile
10
+
11
+ from parsimony_bde._http import CSV_HEADERS, FREQ_MAP_RAW, PB_CATEGORY
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def _fold(text: str) -> str:
17
+ """Upper-case and strip accents so Spanish row labels match regardless of
18
+ encoding round-trips (``DESCRIPCIÓN`` == ``DESCRIPCION``)."""
19
+ nfkd = unicodedata.normalize("NFKD", text)
20
+ return "".join(c for c in nfkd if not unicodedata.combining(c)).strip().upper()
21
+
22
+
23
+ # Row labels (accent-folded) in the transposed ``pb.zip`` value files.
24
+ _PB_NOMBRE = "NOMBRE DE LA SERIE"
25
+ _PB_ALIAS = "ALIAS DE LA SERIE"
26
+ _PB_DESC = "DESCRIPCION DE LA SERIE"
27
+ _PB_UNIT = "DESCRIPCION DE LAS UNIDADES"
28
+ _PB_FREQ = "FRECUENCIA"
29
+ _PB_SEQ = "NUMERO SECUENCIAL"
30
+ _PB_META_LABELS = frozenset({_PB_NOMBRE, _PB_ALIAS, _PB_DESC, _PB_UNIT, _PB_FREQ, _PB_SEQ})
31
+
32
+
33
+ def split_title_path(raw: str) -> tuple[str, str]:
34
+ """Split a "/"-separated BdE title-path into (dataset, leaf_title)."""
35
+ if "/" not in raw:
36
+ return "", raw.strip()
37
+ parts = [p.strip() for p in raw.split("/") if p.strip()]
38
+ if not parts:
39
+ return "", raw.strip()
40
+ if len(parts) == 1:
41
+ return "", parts[0]
42
+ if all(":" in p for p in parts):
43
+ return " › ".join(parts), ""
44
+ return " › ".join(parts[:-1]), parts[-1]
45
+
46
+
47
+ def parse_catalog_csv(text: str, *, category: str) -> list[dict[str, str]]:
48
+ """Parse one ``catalogo_*.csv`` payload into enumerator rows."""
49
+ reader = csv.reader(io.StringIO(text))
50
+ rows: list[dict[str, str]] = []
51
+
52
+ header_seen = False
53
+ for raw_row in reader:
54
+ if not raw_row:
55
+ continue
56
+ if not header_seen:
57
+ header_seen = True
58
+ continue
59
+ if len(raw_row) < len(CSV_HEADERS):
60
+ logger.debug(
61
+ "skipping malformed BdE catalog row (got %d cols, expected %d)",
62
+ len(raw_row),
63
+ len(CSV_HEADERS),
64
+ )
65
+ continue
66
+
67
+ record = dict(zip(CSV_HEADERS, raw_row, strict=False))
68
+ serie = (record.get("serie") or "").strip()
69
+ if not serie:
70
+ continue
71
+
72
+ title_raw = (record.get("title") or "").strip()
73
+ dataset, leaf_title = split_title_path(title_raw)
74
+ title = leaf_title or (record.get("description") or "").strip() or serie
75
+
76
+ freq_raw = (record.get("frequency_raw") or "").strip().upper()
77
+ frequency = FREQ_MAP_RAW.get(freq_raw, freq_raw.title() if freq_raw else "")
78
+
79
+ rows.append(
80
+ {
81
+ "key": serie,
82
+ "title": title,
83
+ "description": (record.get("description") or "").strip(),
84
+ "source": "bde_biest",
85
+ "alias": (record.get("alias") or "").strip(),
86
+ "dataset": dataset,
87
+ "category": category,
88
+ "frequency": frequency,
89
+ "unit": (record.get("unit_desc") or record.get("unit_code") or "").strip(),
90
+ "decimals": (record.get("decimals") or "").strip(),
91
+ "start_date": (record.get("start_date") or "").strip(),
92
+ "end_date": (record.get("end_date") or "").strip(),
93
+ "n_obs": (record.get("n_obs") or "").strip(),
94
+ "source_org": (record.get("source_org") or "").strip(),
95
+ }
96
+ )
97
+ return rows
98
+
99
+
100
+ def _parse_pb_member(text: str) -> list[dict[str, str]]:
101
+ """Parse one transposed ``pb_*.csv`` value file from ``pb.zip``.
102
+
103
+ The Bank Lending Survey files are laid out column-per-series: row 0 holds the
104
+ real fetchable ``serie`` codes (``DPB…``), row 2 their ``PB_x_y.z`` aliases,
105
+ plus description / units / frequency rows, then one row per observation date.
106
+ We read the metadata rows (the values are fetched live by ``bde_fetch``) and
107
+ derive ``start_date`` / ``end_date`` / ``n_obs`` per column from the date
108
+ rows so the catalog entry matches the richness of the CSV chapters.
109
+ """
110
+ reader = csv.reader(io.StringIO(text))
111
+ by_label: dict[str, list[str]] = {}
112
+ date_rows: list[tuple[str, list[str]]] = []
113
+ for raw_row in reader:
114
+ if not raw_row:
115
+ continue
116
+ label = _fold(raw_row[0])
117
+ cells = [c.strip() for c in raw_row[1:]]
118
+ if label in _PB_META_LABELS:
119
+ by_label[label] = cells
120
+ elif label:
121
+ date_rows.append((raw_row[0].strip(), cells))
122
+
123
+ names = by_label.get(_PB_NOMBRE, [])
124
+ if not names:
125
+ return []
126
+ aliases = by_label.get(_PB_ALIAS, [])
127
+ descs = by_label.get(_PB_DESC, [])
128
+ units = by_label.get(_PB_UNIT, [])
129
+ freqs = by_label.get(_PB_FREQ, [])
130
+
131
+ rows: list[dict[str, str]] = []
132
+ for j, raw_key in enumerate(names):
133
+ key = raw_key.strip()
134
+ # Real BdE series codes never contain whitespace; a value with a space is
135
+ # a stray header label from a non-transposed member and is skipped.
136
+ if not key or " " in key:
137
+ continue
138
+ # Span/count from the date rows where this column carries a value.
139
+ present = [label for label, cells in date_rows if j < len(cells) and cells[j] != ""]
140
+ desc = descs[j].strip() if j < len(descs) else ""
141
+ freq_raw = (freqs[j].strip().upper() if j < len(freqs) else "")
142
+ rows.append(
143
+ {
144
+ "key": key,
145
+ "title": desc or key,
146
+ "description": desc,
147
+ "source": "bde_biest",
148
+ "alias": aliases[j].strip() if j < len(aliases) else "",
149
+ "dataset": "",
150
+ "category": PB_CATEGORY,
151
+ "frequency": FREQ_MAP_RAW.get(freq_raw, freq_raw.title() if freq_raw else ""),
152
+ "unit": units[j].strip() if j < len(units) else "",
153
+ "decimals": "",
154
+ "start_date": present[0] if present else "",
155
+ "end_date": present[-1] if present else "",
156
+ "n_obs": str(len(present)) if present else "",
157
+ "source_org": "Banco de España",
158
+ }
159
+ )
160
+ return rows
161
+
162
+
163
+ def parse_pb_zip(zip_bytes: bytes) -> list[dict[str, str]]:
164
+ """Parse every member of the Bank Lending Survey ``pb.zip`` into enumerator
165
+ rows keyed by the real fetchable ``DPB…`` series code.
166
+
167
+ Best-effort, mirroring the CSV crawl: a corrupt member is logged and skipped
168
+ so a partial survey still enumerates. De-dups within the archive by key
169
+ (a series can recur across family files)."""
170
+ rows: list[dict[str, str]] = []
171
+ seen: set[str] = set()
172
+ try:
173
+ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as archive:
174
+ for member in archive.namelist():
175
+ basename = member.rsplit("/", 1)[-1].lower()
176
+ # The archive bundles the standard ``catalogo_pb.csv``
177
+ # (un-fetchable alias catalog) next to the transposed
178
+ # ``pb_*.csv`` value files. Only the value files carry the real
179
+ # fetchable codes.
180
+ if not (basename.startswith("pb_") and basename.endswith(".csv")):
181
+ continue
182
+ try:
183
+ raw = archive.read(member)
184
+ except (KeyError, zipfile.BadZipFile):
185
+ logger.warning("BdE pb.zip member %r unreadable; skipping", member)
186
+ continue
187
+ try:
188
+ text = raw.decode("cp1252")
189
+ except UnicodeDecodeError:
190
+ text = raw.decode("latin-1", errors="replace")
191
+ for row in _parse_pb_member(text):
192
+ if row["key"] in seen:
193
+ continue
194
+ seen.add(row["key"])
195
+ rows.append(row)
196
+ except zipfile.BadZipFile:
197
+ logger.warning("BdE pb.zip is not a valid archive; skipping Bank Lending Survey")
198
+ return []
199
+ return rows
@@ -0,0 +1,112 @@
1
+ """BdE catalog enumeration connector.
2
+
3
+ Discovers BdE statistical series from the published catalog. Six of the seven
4
+ chapters are crawled as ``catalogo_*.csv`` files; the seventh, the Bank Lending
5
+ Survey (``pb``), is recovered from the bulk ``pb.zip`` because its CSV lists
6
+ un-fetchable family aliases rather than real series codes (see ``_http`` and
7
+ ``_catalog.parse_pb_zip``). The crawl uses the shared ``ThrottledJsonFetcher``
8
+ (throttled, retrying serial fan-out over a raw ``httpx.Client``).
9
+
10
+ Best-effort by design: a per-source failure is logged and skipped so a partial
11
+ catalog is still produced (catalog publish jobs check ``len(df) == 0``
12
+ separately). The combined rows are de-duplicated by ``key`` — a series can be
13
+ listed under more than one thematic chapter (≈24% of raw rows are such
14
+ cross-chapter repeats), and the first occurrence in chapter order wins so the
15
+ result is deterministic. The returned frame matches ``ENUMERATE_COLUMNS``
16
+ exactly, as the ``@enumerator`` contract requires (it drops unmapped columns
17
+ then demands an exact match against the declared schema).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+
24
+ import httpx
25
+ import pandas as pd
26
+ from parsimony.connector import enumerator
27
+ from parsimony_shared.cb_enumerate import MetadataCrawlConfig, ThrottledJsonFetcher
28
+
29
+ from parsimony_bde._http import (
30
+ CATALOG_CHAPTERS,
31
+ CATALOG_CSV_BASE_URL,
32
+ CSV_ENCODING,
33
+ PB_ZIP_URL,
34
+ )
35
+ from parsimony_bde.connectors._catalog import parse_catalog_csv, parse_pb_zip
36
+ from parsimony_bde.outputs import BDE_ENUMERATE_OUTPUT, ENUMERATE_COLUMNS
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ METADATA_CRAWL = MetadataCrawlConfig(inter_request_delay_s=0.25)
41
+
42
+
43
+ def _fetch_catalog_chapter(
44
+ fetcher: ThrottledJsonFetcher,
45
+ chapter: str,
46
+ category: str,
47
+ ) -> list[dict[str, str]]:
48
+ """Fetch + decode + parse one ``catalogo_*.csv`` chapter into enumerator rows."""
49
+ url = f"{CATALOG_CSV_BASE_URL}/catalogo_{chapter}.csv"
50
+ raw_bytes = fetcher.get_content(url, label=f"catalogo_{chapter}")
51
+ if raw_bytes is None:
52
+ logger.warning("BdE catalog chapter %r unavailable after retries", chapter)
53
+ return []
54
+ try:
55
+ text = raw_bytes.decode(CSV_ENCODING)
56
+ except UnicodeDecodeError:
57
+ text = raw_bytes.decode("latin-1", errors="replace")
58
+ return parse_catalog_csv(text, category=category)
59
+
60
+
61
+ def _fetch_pb_survey(fetcher: ThrottledJsonFetcher) -> list[dict[str, str]]:
62
+ """Fetch + parse the Bank Lending Survey bulk ``pb.zip`` into enumerator rows."""
63
+ raw_bytes = fetcher.get_content(PB_ZIP_URL, label="pb_zip")
64
+ if raw_bytes is None:
65
+ logger.warning("BdE Bank Lending Survey (pb.zip) unavailable after retries")
66
+ return []
67
+ return parse_pb_zip(raw_bytes)
68
+
69
+
70
+ def _dedupe_by_key(rows: list[dict[str, str]]) -> list[dict[str, str]]:
71
+ """Keep the first row per ``key`` (cross-chapter repeats collapse here)."""
72
+ seen: set[str] = set()
73
+ deduped: list[dict[str, str]] = []
74
+ for row in rows:
75
+ key = row["key"]
76
+ if key in seen:
77
+ continue
78
+ seen.add(key)
79
+ deduped.append(row)
80
+ return deduped
81
+
82
+
83
+ @enumerator(output=BDE_ENUMERATE_OUTPUT, tags=["macro", "es"])
84
+ def enumerate_bde() -> pd.DataFrame:
85
+ """Enumerate BdE statistical series from the published catalog (6 CSV chapters
86
+ + the Bank Lending Survey recovered from ``pb.zip``), de-duplicated by code.
87
+
88
+ Titles and descriptions are in Spanish — BdE's catalog CSV chapters have no
89
+ English variant.
90
+ """
91
+ rows: list[dict[str, str]] = []
92
+ with httpx.Client(timeout=60.0, follow_redirects=True) as client:
93
+ fetcher = ThrottledJsonFetcher(
94
+ client,
95
+ provider="bde",
96
+ config=METADATA_CRAWL,
97
+ logger=logger,
98
+ )
99
+
100
+ def _one(chapter: str, category: str) -> list[dict[str, str]]:
101
+ return _fetch_catalog_chapter(fetcher, chapter, category)
102
+
103
+ # Order matters: CSV chapters come before pb.zip so that on a
104
+ # cross-source duplicate the CSV chapter wins in _dedupe_by_key (first
105
+ # occurrence). Process serially to preserve that order.
106
+ for chapter, category in CATALOG_CHAPTERS:
107
+ rows.extend(_one(chapter, category))
108
+ rows.extend(_fetch_pb_survey(fetcher))
109
+
110
+ # @enumerator drops unmapped columns then requires an EXACT match — build
111
+ # the frame with exactly the declared columns (header-only if all failed).
112
+ return pd.DataFrame(_dedupe_by_key(rows), columns=list(ENUMERATE_COLUMNS))
@@ -0,0 +1,175 @@
1
+ """BdE series fetch connector.
2
+
3
+ Banco de España BIEST is a **keyless** public JSON API — no api_key, no
4
+ ``secrets=``/``bind()``/``load()``, no ``UnauthorizedError``. The
5
+ ``listaSeries`` endpoint returns long-format JSON (``fechas``/``valores``
6
+ parallel arrays) which we reshape into one row per (series, observation).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ from datetime import datetime
13
+ from typing import Annotated, Any, NoReturn
14
+
15
+ import httpx
16
+ import pandas as pd
17
+ from parsimony import Namespace
18
+ from parsimony.connector import connector
19
+ from parsimony.errors import EmptyDataError, InvalidParameterError, ParseError
20
+ from parsimony.transport import map_http_error, map_timeout_error
21
+ from parsimony.transport.helpers import make_http_client
22
+
23
+ from parsimony_bde._http import BASE_URL
24
+ from parsimony_bde.outputs import BDE_FETCH_OUTPUT
25
+
26
+ # ``rango`` is frequency-dependent and BdE validates it server-side:
27
+ # monthly / quarterly / semestral : 30M, 60M, MAX, or a 4-digit year
28
+ # daily / business-daily : 3M, 12M, 36M, or a 4-digit year (NOT MAX)
29
+ # annual : 60M, MAX, or a 4-digit year
30
+ # A single request may mix frequencies, so the connector can't know the right
31
+ # vocabulary up front. We accept the union of literal codes here and let BdE
32
+ # reject a code that doesn't apply to a series' frequency — its HTTP 412 is
33
+ # surfaced as InvalidParameterError (see ``_raise_bde_http_error``).
34
+ _VALID_RANGES = frozenset({"3M", "12M", "36M", "30M", "60M", "MAX"})
35
+ _VALID_LANGS = frozenset({"en", "es"})
36
+
37
+
38
+ def _validate_time_range(time_range: str | None) -> str | None:
39
+ """Normalise and validate the ``time_range`` argument.
40
+
41
+ Accepts ``3M``/``12M``/``36M``/``30M``/``60M``/``MAX`` (case-insensitive) or
42
+ a 4-digit year. Which codes are valid depends on the series frequency (BdE
43
+ enforces that), so this only screens out plainly malformed values. Returns
44
+ the validated value, or ``None`` for the default range.
45
+ """
46
+ if time_range is None:
47
+ return None
48
+ value = time_range.strip()
49
+ if not value:
50
+ return None
51
+ if value.upper() in _VALID_RANGES:
52
+ return value.upper()
53
+ if value.isdigit() and len(value) == 4: # a 4-digit calendar year
54
+ return value
55
+ raise InvalidParameterError(
56
+ "bde",
57
+ f"Invalid time_range '{time_range}'. Use 3M/12M/36M/30M/60M/MAX "
58
+ "(frequency-dependent) or a 4-digit year (e.g. 2024).",
59
+ )
60
+
61
+
62
+ def _raise_bde_http_error(exc: httpx.HTTPStatusError, keys: list[str]) -> NoReturn:
63
+ """Map a BdE ``listaSeries`` HTTP error to a typed connector error.
64
+
65
+ BdE answers an invalid series code or a frequency-incompatible ``rango`` with
66
+ HTTP 412 and a ``{"errNum", "errMsgUsr", "errMsgDebug"}`` body — a caller
67
+ input problem, so it surfaces as :class:`InvalidParameterError` carrying
68
+ BdE's own message. Everything else defers to the canonical mapping.
69
+ """
70
+ if exc.response.status_code == 412:
71
+ detail = ""
72
+ with contextlib.suppress(Exception):
73
+ body = exc.response.json()
74
+ if isinstance(body, dict):
75
+ detail = (body.get("errMsgDebug") or body.get("errMsgUsr") or "").strip()
76
+ raise InvalidParameterError(
77
+ "bde",
78
+ detail or f"BdE rejected the request for series: {','.join(keys)}",
79
+ ) from exc
80
+ map_http_error(exc, provider="bde", op_name="series")
81
+
82
+
83
+ def _parse_bde_response(json_data: list[dict[str, Any]]) -> pd.DataFrame:
84
+ """Parse BdE long-format JSON into a flat ``key,title,date,value`` frame."""
85
+ all_rows: list[dict[str, Any]] = []
86
+
87
+ for series in json_data:
88
+ key = series.get("serie", "")
89
+ title = series.get("descripcionCorta") or series.get("descripcion") or key
90
+ dates = series.get("fechas", [])
91
+ values = series.get("valores", [])
92
+
93
+ if not dates or not values:
94
+ continue
95
+
96
+ for date_str, raw_value in zip(dates, values, strict=False):
97
+ try:
98
+ value = float(raw_value) if raw_value not in (None, "", "NaN") else None
99
+ except (ValueError, TypeError):
100
+ value = None
101
+
102
+ date_val = date_str
103
+ if isinstance(date_str, str) and "T" in date_str:
104
+ with contextlib.suppress(ValueError):
105
+ date_val = datetime.strptime(date_str[:10], "%Y-%m-%d").strftime("%Y-%m-%d")
106
+
107
+ all_rows.append({"key": key, "title": title, "date": date_val, "value": value})
108
+
109
+ if not all_rows:
110
+ return pd.DataFrame(columns=["key", "title", "date", "value"])
111
+ return pd.DataFrame(all_rows)
112
+
113
+
114
+ @connector(output=BDE_FETCH_OUTPUT, tags=["macro", "es"])
115
+ def bde_fetch(
116
+ key: Annotated[str, Namespace("bde")],
117
+ time_range: str | None = None,
118
+ lang: str = "en",
119
+ ) -> pd.DataFrame:
120
+ """Fetch Banco de España time series by series code(s).
121
+
122
+ ``key`` is one or more comma-separated BdE series codes (e.g.
123
+ ``D_1NBAF472,DTCCBCEUSDEUR.B``); all are fetched in a single request.
124
+ ``time_range`` is frequency-dependent: monthly/quarterly series take
125
+ ``30M``/``60M``/``MAX``, daily series take ``3M``/``12M``/``36M`` (not
126
+ ``MAX``), and any frequency accepts a 4-digit year (e.g. ``2024``); ``None``
127
+ returns BdE's default range. A range that doesn't fit a series' frequency is
128
+ rejected by BdE as an ``InvalidParameterError``. ``lang`` selects the title
129
+ language (``en`` or ``es``). Returns one row per observation with ``key``,
130
+ ``title``, ``date``, ``value``.
131
+ """
132
+ keys = [k.strip() for k in key.split(",") if k.strip()]
133
+ if not keys:
134
+ raise InvalidParameterError("bde", "At least one series code required")
135
+ if lang not in _VALID_LANGS:
136
+ raise InvalidParameterError("bde", "lang must be 'en' or 'es'")
137
+ resolved_range = _validate_time_range(time_range)
138
+
139
+ req_params: dict[str, Any] = {
140
+ "idioma": lang,
141
+ "series": ",".join(keys),
142
+ "rango": resolved_range,
143
+ }
144
+ http = make_http_client(BASE_URL, timeout=60.0)
145
+ filtered = {k: v for k, v in req_params.items() if v is not None}
146
+ try:
147
+ response = http.request("GET", "/listaSeries", params=filtered or None)
148
+ response.raise_for_status()
149
+ except httpx.HTTPStatusError as exc:
150
+ _raise_bde_http_error(exc, keys)
151
+ except httpx.TimeoutException as exc:
152
+ map_timeout_error(exc, provider="bde", op_name="series")
153
+ try:
154
+ body = response.json()
155
+ except ValueError as exc:
156
+ raise ParseError(provider="bde") from exc
157
+
158
+ if not isinstance(body, list):
159
+ raise ParseError("bde", f"unexpected response shape for series: {','.join(keys)}")
160
+ if not body:
161
+ raise EmptyDataError(
162
+ "bde",
163
+ message=f"BdE returned no series for: {','.join(keys)}",
164
+ query_params={"key": key, "time_range": time_range, "lang": lang},
165
+ )
166
+
167
+ df = _parse_bde_response(body)
168
+ if df.empty:
169
+ raise EmptyDataError(
170
+ "bde",
171
+ message=f"No observations parsed for: {','.join(keys)}",
172
+ query_params={"key": key, "time_range": time_range, "lang": lang},
173
+ )
174
+
175
+ return df
@@ -0,0 +1,50 @@
1
+ """BdE connector output schemas."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from parsimony.result import Column, ColumnRole, OutputConfig
6
+
7
+ BDE_ENUMERATE_OUTPUT = OutputConfig(
8
+ columns=[
9
+ Column(name="key", role=ColumnRole.KEY, namespace="bde"),
10
+ Column(name="title", role=ColumnRole.TITLE),
11
+ Column(name="description", role=ColumnRole.METADATA),
12
+ Column(name="source", role=ColumnRole.METADATA),
13
+ Column(name="alias", role=ColumnRole.METADATA),
14
+ Column(name="dataset", role=ColumnRole.METADATA),
15
+ Column(name="category", role=ColumnRole.METADATA),
16
+ Column(name="frequency", role=ColumnRole.METADATA),
17
+ Column(name="unit", role=ColumnRole.METADATA),
18
+ Column(name="decimals", role=ColumnRole.METADATA),
19
+ Column(name="start_date", role=ColumnRole.METADATA),
20
+ Column(name="end_date", role=ColumnRole.METADATA),
21
+ Column(name="n_obs", role=ColumnRole.METADATA),
22
+ Column(name="source_org", role=ColumnRole.METADATA),
23
+ ]
24
+ )
25
+
26
+ BDE_FETCH_OUTPUT = OutputConfig(
27
+ columns=[
28
+ Column(name="key", role=ColumnRole.KEY, namespace="bde"),
29
+ Column(name="title", role=ColumnRole.TITLE),
30
+ Column(name="date", dtype="datetime", role=ColumnRole.DATA),
31
+ Column(name="value", dtype="numeric", role=ColumnRole.DATA),
32
+ ]
33
+ )
34
+
35
+ ENUMERATE_COLUMNS: tuple[str, ...] = (
36
+ "key",
37
+ "title",
38
+ "description",
39
+ "source",
40
+ "alias",
41
+ "dataset",
42
+ "category",
43
+ "frequency",
44
+ "unit",
45
+ "decimals",
46
+ "start_date",
47
+ "end_date",
48
+ "n_obs",
49
+ "source_org",
50
+ )
File without changes
@@ -0,0 +1,34 @@
1
+ """Semantic search over the published Banco de España (BdE) catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from parsimony.catalog.search import CatalogSearchParams, make_local_search_connector
6
+ from parsimony.result import Column, ColumnRole, OutputConfig
7
+
8
+ from parsimony_bde.catalog_build import build_bde_catalog
9
+
10
+ BdeSearchParams = CatalogSearchParams
11
+
12
+ PARSIMONY_BDE_CATALOG_URL_ENV = "PARSIMONY_BDE_CATALOG_URL"
13
+
14
+ BDE_SEARCH_OUTPUT = OutputConfig(
15
+ columns=[
16
+ Column(name="code", role=ColumnRole.KEY, namespace="bde"),
17
+ Column(name="title", role=ColumnRole.TITLE),
18
+ Column(name="score", role=ColumnRole.DATA),
19
+ ]
20
+ )
21
+
22
+ bde_search = make_local_search_connector(
23
+ provider="bde",
24
+ default_url="hf://parsimony-dev/bde",
25
+ catalog_url_env_var=PARSIMONY_BDE_CATALOG_URL_ENV,
26
+ build_catalog=build_bde_catalog,
27
+ tags=["macro", "es", "tool"],
28
+ description=(
29
+ "Semantic-search the Banco de España (BdE) catalog. "
30
+ "Titles and descriptions are in Spanish. "
31
+ "Pass returned serie code to bde_fetch(key=...)."
32
+ ),
33
+ output_columns=BDE_SEARCH_OUTPUT.columns,
34
+ )
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "parsimony-bde"
3
+ version = "0.0.1"
4
+ description = "Banco de España connector for the parsimony framework"
5
+ authors = [{ name = "Ockham.sh", email = "team@ockham.sh" }]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ requires-python = ">=3.11"
9
+ keywords = ["finance", "data", "connectors", "parsimony", "bde"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Developers",
13
+ "Intended Audience :: Financial and Insurance Industry",
14
+ "License :: OSI Approved :: Apache Software License",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Office/Business :: Financial",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = [
24
+ "parsimony-core[catalog]>=0.0.1",
25
+ "parsimony-shared>=0.0.1",
26
+ "pydantic>=2.11.1,<3",
27
+ "pandas>=2.3.0,<3",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=9.0.3",
33
+ "pytest-cov>=5.0",
34
+ "respx>=0.22.0",
35
+ "ruff>=0.15.10",
36
+ "mypy>=1.10",
37
+ ]
38
+
39
+ [project.urls]
40
+ Homepage = "https://www.bde.es"
41
+ Repository = "https://github.com/ockham-sh/parsimony-connectors"
42
+ Issues = "https://github.com/ockham-sh/parsimony-connectors/issues"
43
+
44
+ [project.entry-points."parsimony.providers"]
45
+ bde = "parsimony_bde"
46
+
47
+
48
+ [build-system]
49
+ requires = ["hatchling"]
50
+ build-backend = "hatchling.build"
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["parsimony_bde"]
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = ["parsimony_bde", "README.md", "LICENSE", "CHANGELOG.md"]
57
+
58
+ [tool.ruff]
59
+ target-version = "py311"
60
+ line-length = 120
61
+
62
+ [tool.ruff.lint]
63
+ select = ["E", "F", "I", "UP", "B", "SIM"]
64
+
65
+ [tool.ruff.lint.per-file-ignores]
66
+ # Publish scripts call logging.basicConfig() before importing parsimony so
67
+ # the kernel's INFO logs surface during the long-running publish pipeline.
68
+ "scripts/*" = ["E402"]
69
+
70
+ [tool.mypy]
71
+ python_version = "3.11"
72
+ warn_return_any = true
73
+ warn_unused_ignores = true
74
+ ignore_missing_imports = true
75
+
76
+ [tool.pytest.ini_options]
77
+ addopts = "--import-mode=importlib -m 'not integration'"
78
+ markers = [
79
+ "integration: hits live APIs (may be slow, requires env vars)",
80
+ ]