parsimony-bde 0.4.0__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.
- parsimony_bde-0.4.0/.gitignore +40 -0
- parsimony_bde-0.4.0/CHANGELOG.md +21 -0
- parsimony_bde-0.4.0/LICENSE +190 -0
- parsimony_bde-0.4.0/PKG-INFO +102 -0
- parsimony_bde-0.4.0/README.md +67 -0
- parsimony_bde-0.4.0/parsimony_bde/__init__.py +524 -0
- parsimony_bde-0.4.0/parsimony_bde/py.typed +0 -0
- parsimony_bde-0.4.0/parsimony_bde/search.py +112 -0
- parsimony_bde-0.4.0/pyproject.toml +76 -0
|
@@ -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
|
+
|
|
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,21 @@
|
|
|
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
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.4.0] — 2026-04-24
|
|
10
|
+
|
|
11
|
+
Part of the first coordinated release of the
|
|
12
|
+
[`parsimony-connectors`](https://github.com/ockham-sh/parsimony-connectors)
|
|
13
|
+
monorepo under `parsimony-core==0.4`.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- Connector rewritten against the kernel's `parsimony.discover` surface
|
|
18
|
+
(`iter_providers`, `load`, `load_all`) and the `@connector(env=...)`
|
|
19
|
+
decorator-level env-var declaration that replaced module-level
|
|
20
|
+
`ENV_VARS`.
|
|
21
|
+
- 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,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parsimony-bde
|
|
3
|
+
Version: 0.4.0
|
|
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<0.5,>=0.4.0
|
|
26
|
+
Requires-Dist: pydantic<3,>=2.11.1
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest-asyncio>=1.3.0; 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` | fetch | Fetch one or more BdE time series by series code (comma-separated). |
|
|
47
|
+
| `enumerate_bde` | enumerator | Enumerate BdE series by querying well-known series codes for catalog seeding. |
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install parsimony-bde
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Pulls in `parsimony-core>=0.4,<0.5` automatically. Verify discovery:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
python -c "from parsimony import discover; print([p.name for p in discover.iter_providers()])"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Configuration
|
|
62
|
+
|
|
63
|
+
No configuration required — the BdE BIEST API is open and unauthenticated.
|
|
64
|
+
|
|
65
|
+
## Quick start
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
import asyncio
|
|
69
|
+
from parsimony_bde import CONNECTORS
|
|
70
|
+
|
|
71
|
+
async def main():
|
|
72
|
+
connectors = CONNECTORS.bind_env()
|
|
73
|
+
result = await connectors["bde_fetch"](key="D_1NBAF472")
|
|
74
|
+
print(result.data.head())
|
|
75
|
+
|
|
76
|
+
asyncio.run(main())
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
For multi-plugin composition (autoloads everything installed):
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from parsimony import discover
|
|
83
|
+
connectors = discover.load_all().bind_env()
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Catalog publishing
|
|
87
|
+
|
|
88
|
+
This plugin publishes catalogs under the `bde` namespace. Build and push:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
parsimony publish --provider bde --target "hf://<your-org>/parsimony-bde"
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Provider
|
|
95
|
+
|
|
96
|
+
- Homepage: https://www.bde.es
|
|
97
|
+
- API docs: https://www.bde.es/webbe/en/estadisticas/recursos/api-estadisticas-bde.html
|
|
98
|
+
- Series browser: https://app.bde.es/bie_www/bie_wwwias/xml/Arranque.html (BIEST)
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
See [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,67 @@
|
|
|
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` | fetch | Fetch one or more BdE time series by series code (comma-separated). |
|
|
12
|
+
| `enumerate_bde` | enumerator | Enumerate BdE series by querying well-known series codes for catalog seeding. |
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install parsimony-bde
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Pulls in `parsimony-core>=0.4,<0.5` automatically. Verify discovery:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
python -c "from parsimony import discover; print([p.name for p in discover.iter_providers()])"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Configuration
|
|
27
|
+
|
|
28
|
+
No configuration required — the BdE BIEST API is open and unauthenticated.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import asyncio
|
|
34
|
+
from parsimony_bde import CONNECTORS
|
|
35
|
+
|
|
36
|
+
async def main():
|
|
37
|
+
connectors = CONNECTORS.bind_env()
|
|
38
|
+
result = await connectors["bde_fetch"](key="D_1NBAF472")
|
|
39
|
+
print(result.data.head())
|
|
40
|
+
|
|
41
|
+
asyncio.run(main())
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
For multi-plugin composition (autoloads everything installed):
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from parsimony import discover
|
|
48
|
+
connectors = discover.load_all().bind_env()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Catalog publishing
|
|
52
|
+
|
|
53
|
+
This plugin publishes catalogs under the `bde` namespace. Build and push:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
parsimony publish --provider bde --target "hf://<your-org>/parsimony-bde"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Provider
|
|
60
|
+
|
|
61
|
+
- Homepage: https://www.bde.es
|
|
62
|
+
- API docs: https://www.bde.es/webbe/en/estadisticas/recursos/api-estadisticas-bde.html
|
|
63
|
+
- Series browser: https://app.bde.es/bie_www/bie_wwwias/xml/Arranque.html (BIEST)
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
See [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""Banco de España (BdE): fetch + catalog enumeration.
|
|
2
|
+
|
|
3
|
+
API docs: https://www.bde.es/webbe/en/estadisticas/recursos/api-estadisticas-bde.html
|
|
4
|
+
Series search: https://app.bde.es/bie_www/bie_wwwias/xml/Arranque.html (BIEST)
|
|
5
|
+
No authentication required.
|
|
6
|
+
|
|
7
|
+
The catalog enumerator pulls BdE's own published catalog CSVs — seven chapters
|
|
8
|
+
(``catalogo_{be,cf,ie,pb,si,tc,ti}``) covering ~20,450 rows (≈15,500 unique
|
|
9
|
+
series codes after de-duplication across overlapping chapters) spanning general
|
|
10
|
+
statistics, financial accounts of the Spanish economy, international economy,
|
|
11
|
+
bank lending surveys, financial indicators, exchange rates, and interest rates.
|
|
12
|
+
BdE has no queryable list endpoint and no SDMX feed of its own; the CSV
|
|
13
|
+
directory is the only discovery surface, and it carries the descriptive prose,
|
|
14
|
+
frequency, units, date ranges, and dataset grouping needed for high-recall
|
|
15
|
+
semantic search. An exhaustive probe of ``catalogo_{aa..zz}.csv`` confirms no
|
|
16
|
+
other 2-letter chapter resolves to HTTP 200.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import contextlib
|
|
22
|
+
import csv
|
|
23
|
+
import io
|
|
24
|
+
import logging
|
|
25
|
+
from datetime import datetime
|
|
26
|
+
from typing import Annotated, Any
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
import pandas as pd
|
|
30
|
+
from parsimony.connector import Connectors, connector, enumerator
|
|
31
|
+
from parsimony.errors import EmptyDataError
|
|
32
|
+
from parsimony.result import (
|
|
33
|
+
Column,
|
|
34
|
+
ColumnRole,
|
|
35
|
+
OutputConfig,
|
|
36
|
+
Provenance,
|
|
37
|
+
Result,
|
|
38
|
+
)
|
|
39
|
+
from parsimony.transport import map_http_error
|
|
40
|
+
from pydantic import BaseModel, Field, field_validator
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger(__name__)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
_BASE_URL = "https://app.bde.es/bierest/resources/srdatosapp"
|
|
46
|
+
|
|
47
|
+
# BdE publishes its statistical catalog as seven CSV files, one per "chapter":
|
|
48
|
+
#
|
|
49
|
+
# * BE — General Statistics (national accounts, prices, employment, …)
|
|
50
|
+
# * CF — Financial Accounts of the Spanish Economy (CFEE, SEC2010 sector
|
|
51
|
+
# balance sheets; ~4.7k rows, several hundred overlap with BE).
|
|
52
|
+
# * IE — International Economy (world prices, commodity indices; ~93 rows,
|
|
53
|
+
# mostly overlapping BE but retained for category-filtered search).
|
|
54
|
+
# * PB — Bank Lending Survey
|
|
55
|
+
# * SI — Financial Indicators (confidence indices, retail trade, …)
|
|
56
|
+
# * TC — Exchange Rates
|
|
57
|
+
# * TI — Interest Rates
|
|
58
|
+
#
|
|
59
|
+
# An exhaustive probe of ``catalogo_{aa..zz}.csv`` (676 combinations) on
|
|
60
|
+
# 2026-04-24 confirms these seven are the complete published set; every other
|
|
61
|
+
# 2-letter code 302s to a 404 page. Only the Spanish (``es``) variant resolves;
|
|
62
|
+
# the ``en`` URL 302s to a 404. The catalog itself contains both Spanish and
|
|
63
|
+
# English-translatable descriptions in its ``descripcion`` and ``titulo``
|
|
64
|
+
# columns; we surface them as-is and let downstream embedders handle the
|
|
65
|
+
# bilingual content.
|
|
66
|
+
_CATALOG_CSV_BASE_URL = "https://www.bde.es/webbe/es/estadisticas/compartido/datos/csv"
|
|
67
|
+
_CATALOG_CHAPTERS: tuple[tuple[str, str], ...] = (
|
|
68
|
+
("be", "General Statistics"),
|
|
69
|
+
("cf", "Financial Accounts"),
|
|
70
|
+
("ie", "International Economy"),
|
|
71
|
+
("pb", "Bank Lending Survey"),
|
|
72
|
+
("si", "Financial Indicators"),
|
|
73
|
+
("tc", "Exchange Rates"),
|
|
74
|
+
("ti", "Interest Rates"),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# BdE catalog CSVs are encoded in CP1252 (Latin-1 superset). Lowercase column
|
|
78
|
+
# headers map onto our schema. Index keys match the ``Nombre de la serie``
|
|
79
|
+
# header (Spanish, with a trailing space the publisher kept since the 90s).
|
|
80
|
+
_CSV_ENCODING = "cp1252"
|
|
81
|
+
_CSV_HEADERS: tuple[str, ...] = (
|
|
82
|
+
"serie", # Internal API code — fed to /listaSeries.
|
|
83
|
+
"seq", # Numeric sequential id (unused).
|
|
84
|
+
"alias", # Public alias like "TI_1_1.1".
|
|
85
|
+
"file", # Source CSV file on bde.es.
|
|
86
|
+
"description", # Long descriptive prose (Spanish).
|
|
87
|
+
"var_type", # MEDIA / SUMA / FINAL aggregation kind.
|
|
88
|
+
"unit_code", # ISO/internal unit code (EUR, %, USD/EUR, …).
|
|
89
|
+
"exponent", # Power-of-ten scale on stored values.
|
|
90
|
+
"decimals", # Display precision.
|
|
91
|
+
"unit_desc", # Human-readable unit ("Millones de euros").
|
|
92
|
+
"frequency_raw", # MENSUAL / TRIMESTRAL / DIARIA / LABORABLE / ANUAL.
|
|
93
|
+
"start_date", # Spanish-format first observation ("MAR 1995").
|
|
94
|
+
"end_date", # Spanish-format last observation ("DIC 2025").
|
|
95
|
+
"n_obs", # Observation count.
|
|
96
|
+
"title", # "/"-separated taxonomic path.
|
|
97
|
+
"source_org", # Originating organisation (INE, BCE, BdE, …).
|
|
98
|
+
"notes", # Methodological remarks.
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# BdE chapter codes use Spanish frequency labels; we normalise to English to
|
|
102
|
+
# match Treasury / FRED conventions and so an agent searching "monthly" hits
|
|
103
|
+
# Spanish series that were originally labelled "MENSUAL".
|
|
104
|
+
_FREQ_MAP_RAW = {
|
|
105
|
+
"DIARIA": "Daily",
|
|
106
|
+
"LABORABLE": "Business Daily",
|
|
107
|
+
"SEMANAL": "Weekly",
|
|
108
|
+
"QUINCENAL": "Bi-weekly",
|
|
109
|
+
"MENSUAL": "Monthly",
|
|
110
|
+
"TRIMESTRAL": "Quarterly",
|
|
111
|
+
"SEMESTRAL": "Semi-annual",
|
|
112
|
+
"ANUAL": "Annual",
|
|
113
|
+
# The /listaSeries endpoint returns single-letter codes for the same
|
|
114
|
+
# frequencies; we keep both maps in sync so bde_fetch can label rows.
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
# Frequency single-letter code (from /favoritas, /listaSeries) → English.
|
|
118
|
+
_FREQ_MAP = {
|
|
119
|
+
"D": "Daily",
|
|
120
|
+
"M": "Monthly",
|
|
121
|
+
"Q": "Quarterly",
|
|
122
|
+
"A": "Annual",
|
|
123
|
+
"S": "Semi-annual",
|
|
124
|
+
"W": "Weekly",
|
|
125
|
+
"B": "Business Daily",
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
# Spanish ↔ English column mapping used by the fetch parser.
|
|
129
|
+
_COLUMN_MAP = {
|
|
130
|
+
"serie": "key",
|
|
131
|
+
"descripcion": "description",
|
|
132
|
+
"descripcionCorta": "title",
|
|
133
|
+
"codFrecuencia": "freq",
|
|
134
|
+
"decimales": "decimals",
|
|
135
|
+
"simbolo": "symbol",
|
|
136
|
+
"fechaInicio": "start_date",
|
|
137
|
+
"fechaFin": "end_date",
|
|
138
|
+
"fechas": "date",
|
|
139
|
+
"valores": "value",
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ---------------------------------------------------------------------------
|
|
144
|
+
# Parameter models
|
|
145
|
+
# ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class BdeFetchParams(BaseModel):
|
|
149
|
+
"""Parameters for fetching Banco de España time series."""
|
|
150
|
+
|
|
151
|
+
key: Annotated[str, "ns:bde"] = Field(
|
|
152
|
+
...,
|
|
153
|
+
description="Comma-separated BdE series codes (e.g. D_1NBAF472)",
|
|
154
|
+
)
|
|
155
|
+
time_range: str | None = Field(
|
|
156
|
+
default=None,
|
|
157
|
+
description=("Time range: 30M, 60M, MAX, or a year (e.g. 2024). Default uses the full available range."),
|
|
158
|
+
)
|
|
159
|
+
lang: str = Field(default="en", description="Language: en or es")
|
|
160
|
+
|
|
161
|
+
@field_validator("key")
|
|
162
|
+
@classmethod
|
|
163
|
+
def _non_empty(cls, v: str) -> str:
|
|
164
|
+
v = v.strip()
|
|
165
|
+
if not v:
|
|
166
|
+
raise ValueError("At least one series code required")
|
|
167
|
+
return v
|
|
168
|
+
|
|
169
|
+
@field_validator("time_range")
|
|
170
|
+
@classmethod
|
|
171
|
+
def _valid_range(cls, v: str | None) -> str | None:
|
|
172
|
+
if v is None:
|
|
173
|
+
return v
|
|
174
|
+
v = v.strip()
|
|
175
|
+
# BdE API rejects short range codes (3M, 12M); accept 30M, 60M, MAX, or year
|
|
176
|
+
_VALID_RANGES = {"30M", "60M", "MAX"}
|
|
177
|
+
if v.upper() in _VALID_RANGES or v.isdigit():
|
|
178
|
+
return v
|
|
179
|
+
raise ValueError(f"Invalid time_range '{v}'. Use 30M, 60M, MAX, or a year (e.g. 2024).")
|
|
180
|
+
|
|
181
|
+
@field_validator("lang")
|
|
182
|
+
@classmethod
|
|
183
|
+
def _valid_lang(cls, v: str) -> str:
|
|
184
|
+
if v not in ("en", "es"):
|
|
185
|
+
raise ValueError("lang must be 'en' or 'es'")
|
|
186
|
+
return v
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class BdeEnumerateParams(BaseModel):
|
|
190
|
+
"""No parameters needed — discovers series from BdE's published catalog CSVs."""
|
|
191
|
+
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------------------
|
|
196
|
+
# Output configs
|
|
197
|
+
# ---------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
BDE_ENUMERATE_OUTPUT = OutputConfig(
|
|
200
|
+
columns=[
|
|
201
|
+
Column(name="key", role=ColumnRole.KEY, namespace="bde"),
|
|
202
|
+
Column(name="title", role=ColumnRole.TITLE),
|
|
203
|
+
# ``description`` carries the upstream long-form prose. Lifted into
|
|
204
|
+
# DESCRIPTION (rather than METADATA) so the embedder sees it at index
|
|
205
|
+
# time — semantic recall on full sentences matters more than for
|
|
206
|
+
# categorical metadata.
|
|
207
|
+
Column(name="description", role=ColumnRole.DESCRIPTION),
|
|
208
|
+
# ``source`` lets agents dispatch the right fetch connector when more
|
|
209
|
+
# than one BdE source is wired. Today only ``bde_biest`` exists; the
|
|
210
|
+
# column is in place so adding (e.g.) an SDMX path later costs zero
|
|
211
|
+
# schema churn.
|
|
212
|
+
Column(name="source", role=ColumnRole.METADATA),
|
|
213
|
+
Column(name="alias", role=ColumnRole.METADATA),
|
|
214
|
+
Column(name="dataset", role=ColumnRole.METADATA),
|
|
215
|
+
Column(name="category", role=ColumnRole.METADATA),
|
|
216
|
+
Column(name="frequency", role=ColumnRole.METADATA),
|
|
217
|
+
Column(name="unit", role=ColumnRole.METADATA),
|
|
218
|
+
Column(name="decimals", role=ColumnRole.METADATA),
|
|
219
|
+
Column(name="start_date", role=ColumnRole.METADATA),
|
|
220
|
+
Column(name="end_date", role=ColumnRole.METADATA),
|
|
221
|
+
Column(name="n_obs", role=ColumnRole.METADATA),
|
|
222
|
+
Column(name="source_org", role=ColumnRole.METADATA),
|
|
223
|
+
]
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
BDE_FETCH_OUTPUT = OutputConfig(
|
|
227
|
+
columns=[
|
|
228
|
+
Column(name="key", role=ColumnRole.KEY, param_key="key", namespace="bde"),
|
|
229
|
+
Column(name="title", role=ColumnRole.TITLE),
|
|
230
|
+
Column(name="date", dtype="datetime", role=ColumnRole.DATA),
|
|
231
|
+
Column(name="value", dtype="numeric", role=ColumnRole.DATA),
|
|
232
|
+
]
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ---------------------------------------------------------------------------
|
|
237
|
+
# Helpers
|
|
238
|
+
# ---------------------------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _parse_bde_response(json_data: list[dict[str, Any]]) -> pd.DataFrame:
|
|
242
|
+
"""Parse BdE JSON response into a long-format DataFrame.
|
|
243
|
+
|
|
244
|
+
Each element in json_data represents one series with parallel
|
|
245
|
+
fechas (dates) and valores (values) arrays.
|
|
246
|
+
"""
|
|
247
|
+
all_rows: list[dict[str, Any]] = []
|
|
248
|
+
|
|
249
|
+
for series in json_data:
|
|
250
|
+
key = series.get("serie", "")
|
|
251
|
+
title = series.get("descripcionCorta", series.get("descripcion", key))
|
|
252
|
+
series.get("codFrecuencia", "")
|
|
253
|
+
dates = series.get("fechas", [])
|
|
254
|
+
values = series.get("valores", [])
|
|
255
|
+
|
|
256
|
+
if not dates or not values:
|
|
257
|
+
continue
|
|
258
|
+
|
|
259
|
+
for date_str, raw_value in zip(dates, values, strict=False):
|
|
260
|
+
try:
|
|
261
|
+
value = float(raw_value) if raw_value not in (None, "", "NaN") else None
|
|
262
|
+
except (ValueError, TypeError):
|
|
263
|
+
value = None
|
|
264
|
+
|
|
265
|
+
# Parse ISO datetime: "2024-01-31T00:00:00Z" → date
|
|
266
|
+
date_val = date_str
|
|
267
|
+
if isinstance(date_str, str) and "T" in date_str:
|
|
268
|
+
with contextlib.suppress(ValueError):
|
|
269
|
+
date_val = datetime.strptime(date_str[:10], "%Y-%m-%d").strftime("%Y-%m-%d")
|
|
270
|
+
|
|
271
|
+
all_rows.append(
|
|
272
|
+
{
|
|
273
|
+
"key": key,
|
|
274
|
+
"title": title,
|
|
275
|
+
"date": date_val,
|
|
276
|
+
"value": value,
|
|
277
|
+
}
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
return pd.DataFrame(all_rows) if all_rows else pd.DataFrame(columns=["key", "title", "date", "value"])
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _split_title_path(raw: str) -> tuple[str, str]:
|
|
284
|
+
"""Split a "/"-separated BdE title-path into (dataset, leaf_title).
|
|
285
|
+
|
|
286
|
+
BdE encodes a taxonomic path in the title column. Two shapes occur:
|
|
287
|
+
|
|
288
|
+
1. **Short path** (most TI/TC/PB/SI rows) — e.g.
|
|
289
|
+
``"Monetary policy/Eurosystem operations/Fixed rate auctions"``. The
|
|
290
|
+
leaf is the most specific bit and makes a good catalog title; the
|
|
291
|
+
prefix becomes ``dataset`` METADATA so agents can filter by family.
|
|
292
|
+
2. **Long faceted path** (most BE rows) — e.g.
|
|
293
|
+
``"Descripción de la DSD: ... / Metodología: ... / Año Base: ... /
|
|
294
|
+
Tipo de Transformación: ..."``. Each segment is a faceted ``key: value``
|
|
295
|
+
attribute, and the "leaf" is just the last facet — meaningless on its
|
|
296
|
+
own. In this case we leave the title to the caller (who falls back to
|
|
297
|
+
``description``) and put the whole faceted string in ``dataset``.
|
|
298
|
+
|
|
299
|
+
Heuristic for "faceted path": all segments contain ``:``. That distinguishes
|
|
300
|
+
BdE's DSD-encoded series (where every segment is ``Facet: value``) from
|
|
301
|
+
natural-language taxonomies (where slashes separate concept names).
|
|
302
|
+
"""
|
|
303
|
+
if "/" not in raw:
|
|
304
|
+
return "", raw.strip()
|
|
305
|
+
parts = [p.strip() for p in raw.split("/") if p.strip()]
|
|
306
|
+
if not parts:
|
|
307
|
+
return "", raw.strip()
|
|
308
|
+
if len(parts) == 1:
|
|
309
|
+
return "", parts[0]
|
|
310
|
+
if all(":" in p for p in parts):
|
|
311
|
+
# Faceted DSD-encoded path — no semantic leaf.
|
|
312
|
+
return " › ".join(parts), ""
|
|
313
|
+
return " › ".join(parts[:-1]), parts[-1]
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _parse_catalog_csv(text: str, *, category: str) -> list[dict[str, str]]:
|
|
317
|
+
"""Parse one ``catalogo_*.csv`` payload into enumerator rows.
|
|
318
|
+
|
|
319
|
+
The CSV is comma-delimited, double-quoted, with a 17-column header BdE
|
|
320
|
+
has been stable on for years. We keep the raw ``serie`` (the API code)
|
|
321
|
+
as ``key`` and pull every descriptive column we can use for retrieval.
|
|
322
|
+
Empty/whitespace-only rows are skipped; rows missing the ``serie`` key
|
|
323
|
+
can't be fetched and are filtered out here.
|
|
324
|
+
"""
|
|
325
|
+
reader = csv.reader(io.StringIO(text))
|
|
326
|
+
rows: list[dict[str, str]] = []
|
|
327
|
+
|
|
328
|
+
header_seen = False
|
|
329
|
+
for raw_row in reader:
|
|
330
|
+
if not raw_row:
|
|
331
|
+
continue
|
|
332
|
+
if not header_seen:
|
|
333
|
+
# First row is the schema; skip it. We rely on positional access.
|
|
334
|
+
header_seen = True
|
|
335
|
+
continue
|
|
336
|
+
if len(raw_row) < len(_CSV_HEADERS):
|
|
337
|
+
# Defensive: BdE has occasional malformed rows when their export
|
|
338
|
+
# job clips a description containing a literal ``"``. Skip rather
|
|
339
|
+
# than crash the enumerator.
|
|
340
|
+
logger.debug(
|
|
341
|
+
"skipping malformed BdE catalog row (got %d cols, expected %d)",
|
|
342
|
+
len(raw_row),
|
|
343
|
+
len(_CSV_HEADERS),
|
|
344
|
+
)
|
|
345
|
+
continue
|
|
346
|
+
|
|
347
|
+
record = dict(zip(_CSV_HEADERS, raw_row, strict=False))
|
|
348
|
+
serie = (record.get("serie") or "").strip()
|
|
349
|
+
if not serie:
|
|
350
|
+
continue
|
|
351
|
+
|
|
352
|
+
title_raw = (record.get("title") or "").strip()
|
|
353
|
+
dataset, leaf_title = _split_title_path(title_raw)
|
|
354
|
+
# Catalog title is the leaf if we have one, otherwise fall back to the
|
|
355
|
+
# description (always populated) so semantic_text is never empty.
|
|
356
|
+
title = leaf_title or (record.get("description") or "").strip() or serie
|
|
357
|
+
|
|
358
|
+
freq_raw = (record.get("frequency_raw") or "").strip().upper()
|
|
359
|
+
frequency = _FREQ_MAP_RAW.get(freq_raw, freq_raw.title() if freq_raw else "")
|
|
360
|
+
|
|
361
|
+
rows.append(
|
|
362
|
+
{
|
|
363
|
+
"key": serie,
|
|
364
|
+
"title": title,
|
|
365
|
+
"description": (record.get("description") or "").strip(),
|
|
366
|
+
"source": "bde_biest",
|
|
367
|
+
"alias": (record.get("alias") or "").strip(),
|
|
368
|
+
"dataset": dataset,
|
|
369
|
+
"category": category,
|
|
370
|
+
"frequency": frequency,
|
|
371
|
+
"unit": (record.get("unit_desc") or record.get("unit_code") or "").strip(),
|
|
372
|
+
"decimals": (record.get("decimals") or "").strip(),
|
|
373
|
+
"start_date": (record.get("start_date") or "").strip(),
|
|
374
|
+
"end_date": (record.get("end_date") or "").strip(),
|
|
375
|
+
"n_obs": (record.get("n_obs") or "").strip(),
|
|
376
|
+
"source_org": (record.get("source_org") or "").strip(),
|
|
377
|
+
}
|
|
378
|
+
)
|
|
379
|
+
return rows
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
async def _fetch_catalog_chapter(
|
|
383
|
+
client: httpx.AsyncClient,
|
|
384
|
+
chapter: str,
|
|
385
|
+
category: str,
|
|
386
|
+
) -> list[dict[str, str]]:
|
|
387
|
+
"""Fetch one ``catalogo_*.csv`` and return its parsed rows.
|
|
388
|
+
|
|
389
|
+
Per-chapter failures are logged and degrade to an empty list rather than
|
|
390
|
+
aborting the whole enumeration — so a transient outage on the bank lending
|
|
391
|
+
survey CSV doesn't lose the 11k+ general statistics rows.
|
|
392
|
+
"""
|
|
393
|
+
url = f"{_CATALOG_CSV_BASE_URL}/catalogo_{chapter}.csv"
|
|
394
|
+
try:
|
|
395
|
+
response = await client.get(url)
|
|
396
|
+
response.raise_for_status()
|
|
397
|
+
except httpx.HTTPError as exc:
|
|
398
|
+
logger.warning("BdE catalog chapter %r unavailable: %s", chapter, exc)
|
|
399
|
+
return []
|
|
400
|
+
# CSVs are CP1252-encoded; httpx's auto-detect can pick the wrong one if
|
|
401
|
+
# BdE forgets to send a charset header, so decode explicitly.
|
|
402
|
+
raw_bytes = response.content
|
|
403
|
+
try:
|
|
404
|
+
text = raw_bytes.decode(_CSV_ENCODING)
|
|
405
|
+
except UnicodeDecodeError:
|
|
406
|
+
# Fall back to latin-1 (strictly bigger than cp1252 in coverage); the
|
|
407
|
+
# only diff is a handful of typographic glyphs we don't index on.
|
|
408
|
+
text = raw_bytes.decode("latin-1", errors="replace")
|
|
409
|
+
return _parse_catalog_csv(text, category=category)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
# ---------------------------------------------------------------------------
|
|
413
|
+
# Connectors
|
|
414
|
+
# ---------------------------------------------------------------------------
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@connector(output=BDE_FETCH_OUTPUT, tags=["macro", "es"])
|
|
418
|
+
async def bde_fetch(params: BdeFetchParams) -> Result:
|
|
419
|
+
"""Fetch Banco de España time series by series code(s).
|
|
420
|
+
|
|
421
|
+
Uses the BdE REST API (BIEST). Returns date + value with series metadata.
|
|
422
|
+
"""
|
|
423
|
+
url = f"{_BASE_URL}/listaSeries"
|
|
424
|
+
|
|
425
|
+
# BdE API: fetch each series individually and merge results.
|
|
426
|
+
# Multi-series in a single request is unreliable (412 errors).
|
|
427
|
+
keys = [k.strip() for k in params.key.split(",") if k.strip()]
|
|
428
|
+
json_data: list[dict[str, Any]] = []
|
|
429
|
+
|
|
430
|
+
async with httpx.AsyncClient(timeout=60.0) as client:
|
|
431
|
+
for key in keys:
|
|
432
|
+
req_params: dict[str, str] = {
|
|
433
|
+
"idioma": params.lang,
|
|
434
|
+
"series": key,
|
|
435
|
+
}
|
|
436
|
+
if params.time_range is not None:
|
|
437
|
+
req_params["rango"] = str(params.time_range)
|
|
438
|
+
|
|
439
|
+
response = await client.get(url, params=req_params)
|
|
440
|
+
try:
|
|
441
|
+
response.raise_for_status()
|
|
442
|
+
except httpx.HTTPStatusError as exc:
|
|
443
|
+
map_http_error(exc, provider="bde", op_name="series")
|
|
444
|
+
data = response.json()
|
|
445
|
+
if isinstance(data, list):
|
|
446
|
+
json_data.extend(data)
|
|
447
|
+
|
|
448
|
+
if not isinstance(json_data, list) or not json_data:
|
|
449
|
+
raise EmptyDataError(provider="bde", message=f"BdE returned empty or invalid response for: {params.key}")
|
|
450
|
+
|
|
451
|
+
df = _parse_bde_response(json_data)
|
|
452
|
+
if df.empty:
|
|
453
|
+
raise EmptyDataError(provider="bde", message=f"No observations parsed for: {params.key}")
|
|
454
|
+
|
|
455
|
+
return Result.from_dataframe(
|
|
456
|
+
df,
|
|
457
|
+
Provenance(
|
|
458
|
+
source="bde",
|
|
459
|
+
params={"key": params.key, "time_range": params.time_range},
|
|
460
|
+
properties={
|
|
461
|
+
"source_url": "https://www.bde.es/webbe/en/estadisticas/recursos/api-estadisticas-bde.html",
|
|
462
|
+
},
|
|
463
|
+
),
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
@enumerator(
|
|
468
|
+
output=BDE_ENUMERATE_OUTPUT,
|
|
469
|
+
tags=["macro", "es"],
|
|
470
|
+
)
|
|
471
|
+
async def enumerate_bde(params: BdeEnumerateParams) -> pd.DataFrame:
|
|
472
|
+
"""Enumerate every BdE statistical series across the seven published catalog chapters.
|
|
473
|
+
|
|
474
|
+
BdE has no list endpoint or SDMX feed. The only authoritative discovery
|
|
475
|
+
surface is the ``catalogo_{be,cf,ie,pb,si,tc,ti}.csv`` files BdE publishes
|
|
476
|
+
alongside its statistical bulletin. Each row maps onto a series the
|
|
477
|
+
``/listaSeries`` API can fetch by ``serie`` code, and carries the
|
|
478
|
+
descriptive prose, frequency, units, and date range needed to rank it
|
|
479
|
+
in semantic search. Per-chapter network failures degrade gracefully —
|
|
480
|
+
the enumerator returns whatever chapters succeeded rather than empty.
|
|
481
|
+
Some ``serie`` codes appear in more than one chapter (e.g. a national
|
|
482
|
+
accounts series listed under both BE and CF); we keep all occurrences so
|
|
483
|
+
agents filtering by ``category`` see the series under every taxonomy it
|
|
484
|
+
belongs to. Downstream de-duplication by ``key`` is the caller's call.
|
|
485
|
+
"""
|
|
486
|
+
rows: list[dict[str, str]] = []
|
|
487
|
+
async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
|
|
488
|
+
for chapter, category in _CATALOG_CHAPTERS:
|
|
489
|
+
chapter_rows = await _fetch_catalog_chapter(client, chapter, category)
|
|
490
|
+
rows.extend(chapter_rows)
|
|
491
|
+
|
|
492
|
+
columns = [
|
|
493
|
+
"key",
|
|
494
|
+
"title",
|
|
495
|
+
"description",
|
|
496
|
+
"source",
|
|
497
|
+
"alias",
|
|
498
|
+
"dataset",
|
|
499
|
+
"category",
|
|
500
|
+
"frequency",
|
|
501
|
+
"unit",
|
|
502
|
+
"decimals",
|
|
503
|
+
"start_date",
|
|
504
|
+
"end_date",
|
|
505
|
+
"n_obs",
|
|
506
|
+
"source_org",
|
|
507
|
+
]
|
|
508
|
+
return pd.DataFrame(rows, columns=columns) if rows else pd.DataFrame(columns=columns)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
# ---------------------------------------------------------------------------
|
|
512
|
+
# Exports
|
|
513
|
+
# ---------------------------------------------------------------------------
|
|
514
|
+
|
|
515
|
+
from parsimony_bde.search import ( # noqa: E402, F401 (after public decorators; re-exported)
|
|
516
|
+
BDE_SEARCH_OUTPUT,
|
|
517
|
+
PARSIMONY_BDE_CATALOG_URL_ENV,
|
|
518
|
+
BdeSearchParams,
|
|
519
|
+
bde_search,
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
CATALOGS: list[tuple[str, object]] = [("bde", enumerate_bde)]
|
|
523
|
+
|
|
524
|
+
CONNECTORS = Connectors([bde_fetch, enumerate_bde, bde_search])
|
|
File without changes
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Semantic search over the published Banco de España (BdE) catalog.
|
|
2
|
+
|
|
3
|
+
Wraps the parquet+FAISS catalog at ``hf://parsimony-dev/bde`` (override with
|
|
4
|
+
``PARSIMONY_BDE_CATALOG_URL`` for local testing) as an MCP tool. The agent
|
|
5
|
+
calls :func:`bde_search` with a natural-language query and gets back the
|
|
6
|
+
top-N matches with their codes, titles, and similarity scores.
|
|
7
|
+
|
|
8
|
+
Codes returned by this tool are ``serie`` IDs that :func:`bde_fetch`
|
|
9
|
+
accepts directly via its ``key`` parameter — the discover→fetch handshake.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
from typing import Annotated
|
|
18
|
+
|
|
19
|
+
import pandas as pd
|
|
20
|
+
from parsimony.catalog import Catalog
|
|
21
|
+
from parsimony.connector import connector
|
|
22
|
+
from parsimony.result import Column, ColumnRole, OutputConfig
|
|
23
|
+
from pydantic import BaseModel, Field
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
#: Env var carrying the BdE catalog URL. Defaults to the canonical HF repo.
|
|
28
|
+
#: Override with e.g. ``file:///path/to/catalogs/bde/repo/bde`` for local testing.
|
|
29
|
+
PARSIMONY_BDE_CATALOG_URL_ENV = "PARSIMONY_BDE_CATALOG_URL"
|
|
30
|
+
_DEFAULT_CATALOG_URL = "hf://parsimony-dev/bde"
|
|
31
|
+
|
|
32
|
+
# Single-catalog cache. The BdE catalog is ~26 MB FAISS + 0.6 MB parquet —
|
|
33
|
+
# a one-time load amortizes across every search call in the MCP session.
|
|
34
|
+
_catalog: Catalog | None = None
|
|
35
|
+
_catalog_lock = asyncio.Lock()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def _get_catalog() -> Catalog:
|
|
39
|
+
"""Return the singleton BdE catalog, loading from URL on first use."""
|
|
40
|
+
global _catalog
|
|
41
|
+
if _catalog is not None:
|
|
42
|
+
return _catalog
|
|
43
|
+
async with _catalog_lock:
|
|
44
|
+
if _catalog is None: # double-checked under the lock
|
|
45
|
+
url = os.environ.get(PARSIMONY_BDE_CATALOG_URL_ENV, _DEFAULT_CATALOG_URL)
|
|
46
|
+
logger.info("loading BdE catalog from %s", url)
|
|
47
|
+
_catalog = await Catalog.from_url(url)
|
|
48
|
+
return _catalog
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
BDE_SEARCH_OUTPUT = OutputConfig(
|
|
52
|
+
columns=[
|
|
53
|
+
# ``code`` is the serie ID (e.g. ``D_1NBAF472``) that bde_fetch
|
|
54
|
+
# accepts via its ``key`` parameter — the search→fetch handshake.
|
|
55
|
+
Column(name="code", role=ColumnRole.KEY, namespace="bde"),
|
|
56
|
+
Column(name="title", role=ColumnRole.TITLE),
|
|
57
|
+
Column(name="similarity", role=ColumnRole.METADATA),
|
|
58
|
+
]
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class BdeSearchParams(BaseModel):
|
|
63
|
+
"""Parameters for :func:`bde_search`."""
|
|
64
|
+
|
|
65
|
+
query: Annotated[
|
|
66
|
+
str,
|
|
67
|
+
Field(
|
|
68
|
+
min_length=1,
|
|
69
|
+
max_length=512,
|
|
70
|
+
description=(
|
|
71
|
+
"Natural-language description of the BdE series you want "
|
|
72
|
+
"(e.g. 'Spanish 10-year bond yield', 'Euribor 3-month', "
|
|
73
|
+
"'monthly HICP Spain'). Spanish or English both work."
|
|
74
|
+
),
|
|
75
|
+
),
|
|
76
|
+
]
|
|
77
|
+
limit: int = Field(
|
|
78
|
+
default=10,
|
|
79
|
+
ge=1,
|
|
80
|
+
le=50,
|
|
81
|
+
description="Top-N results to return.",
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@connector(
|
|
86
|
+
output=BDE_SEARCH_OUTPUT,
|
|
87
|
+
tags=["macro", "es", "tool"],
|
|
88
|
+
)
|
|
89
|
+
async def bde_search(params: BdeSearchParams) -> pd.DataFrame:
|
|
90
|
+
"""Semantic-search the Banco de España (BdE) catalog by natural language.
|
|
91
|
+
|
|
92
|
+
Returns the top matching ``serie`` codes from BdE's published
|
|
93
|
+
statistical catalog (~15.5k unique series across 7 chapters: general
|
|
94
|
+
statistics, financial accounts, international economy, bank lending
|
|
95
|
+
survey, financial indicators, exchange rates, interest rates).
|
|
96
|
+
|
|
97
|
+
Pass the returned ``code`` to ``bde_fetch(key=...)`` to retrieve the
|
|
98
|
+
actual time series. The catalog is bilingual — both Spanish and English
|
|
99
|
+
queries route correctly through the embedder.
|
|
100
|
+
"""
|
|
101
|
+
catalog = await _get_catalog()
|
|
102
|
+
matches = await catalog.search(params.query, limit=params.limit)
|
|
103
|
+
return pd.DataFrame(
|
|
104
|
+
[
|
|
105
|
+
{
|
|
106
|
+
"code": m.code,
|
|
107
|
+
"title": m.title,
|
|
108
|
+
"similarity": round(m.similarity, 6),
|
|
109
|
+
}
|
|
110
|
+
for m in matches
|
|
111
|
+
]
|
|
112
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "parsimony-bde"
|
|
3
|
+
version = "0.4.0"
|
|
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>=0.4.0,<0.5",
|
|
25
|
+
"pydantic>=2.11.1,<3",
|
|
26
|
+
"pandas>=2.3.0,<3",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
dev = [
|
|
31
|
+
"pytest>=9.0.3",
|
|
32
|
+
"pytest-asyncio>=1.3.0",
|
|
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.mypy]
|
|
66
|
+
python_version = "3.11"
|
|
67
|
+
warn_return_any = true
|
|
68
|
+
warn_unused_ignores = true
|
|
69
|
+
ignore_missing_imports = true
|
|
70
|
+
|
|
71
|
+
[tool.pytest.ini_options]
|
|
72
|
+
addopts = "--import-mode=importlib -m 'not integration'"
|
|
73
|
+
asyncio_mode = "auto"
|
|
74
|
+
markers = [
|
|
75
|
+
"integration: hits live APIs (may be slow, requires env vars)",
|
|
76
|
+
]
|