parsimony-boc 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.
@@ -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-boc
2
+
3
+ All notable changes to `parsimony-boc` 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,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: parsimony-boc
3
+ Version: 0.4.0
4
+ Summary: Bank of Canada connector for the parsimony framework
5
+ Project-URL: Homepage, https://www.bankofcanada.ca
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: boc,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-boc
37
+
38
+ Bank of Canada connector — Canadian exchange rates, interest rates, and macroeconomic time series via the Valet API.
39
+
40
+ Part of the [parsimony-connectors](https://github.com/ockham-sh/parsimony-connectors) monorepo. Distributed standalone on PyPI as `parsimony-boc`.
41
+
42
+ ## Connectors
43
+
44
+ | Name | Kind | Description |
45
+ |---|---|---|
46
+ | `boc_fetch` | fetch | Fetch one or more BoC time series by name (e.g. `FXUSDCAD,FXEURCAD`) or by group (e.g. `group:FX_RATES_DAILY`). |
47
+ | `enumerate_boc` | enumerator | Enumerate all BoC series (15,000+) via `/lists/series/json`. |
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install parsimony-boc
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 Bank of Canada Valet API is open and unauthenticated.
64
+
65
+ ## Quick start
66
+
67
+ ```python
68
+ import asyncio
69
+ from parsimony_boc import CONNECTORS
70
+
71
+ async def main():
72
+ connectors = CONNECTORS.bind_env()
73
+ result = await connectors["boc_fetch"](series_name="FXUSDCAD")
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 `boc` namespace. Build and push:
89
+
90
+ ```bash
91
+ parsimony publish --provider boc --target "hf://<your-org>/parsimony-boc"
92
+ ```
93
+
94
+ ## Provider
95
+
96
+ - Homepage: https://www.bankofcanada.ca
97
+ - API docs: https://www.bankofcanada.ca/valet/docs
98
+
99
+ ## License
100
+
101
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,66 @@
1
+ # parsimony-boc
2
+
3
+ Bank of Canada connector — Canadian exchange rates, interest rates, and macroeconomic time series via the Valet API.
4
+
5
+ Part of the [parsimony-connectors](https://github.com/ockham-sh/parsimony-connectors) monorepo. Distributed standalone on PyPI as `parsimony-boc`.
6
+
7
+ ## Connectors
8
+
9
+ | Name | Kind | Description |
10
+ |---|---|---|
11
+ | `boc_fetch` | fetch | Fetch one or more BoC time series by name (e.g. `FXUSDCAD,FXEURCAD`) or by group (e.g. `group:FX_RATES_DAILY`). |
12
+ | `enumerate_boc` | enumerator | Enumerate all BoC series (15,000+) via `/lists/series/json`. |
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install parsimony-boc
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 Bank of Canada Valet API is open and unauthenticated.
29
+
30
+ ## Quick start
31
+
32
+ ```python
33
+ import asyncio
34
+ from parsimony_boc import CONNECTORS
35
+
36
+ async def main():
37
+ connectors = CONNECTORS.bind_env()
38
+ result = await connectors["boc_fetch"](series_name="FXUSDCAD")
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 `boc` namespace. Build and push:
54
+
55
+ ```bash
56
+ parsimony publish --provider boc --target "hf://<your-org>/parsimony-boc"
57
+ ```
58
+
59
+ ## Provider
60
+
61
+ - Homepage: https://www.bankofcanada.ca
62
+ - API docs: https://www.bankofcanada.ca/valet/docs
63
+
64
+ ## License
65
+
66
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,408 @@
1
+ """Bank of Canada (BoC): fetch + catalog enumeration.
2
+
3
+ API docs: https://www.bankofcanada.ca/valet/docs
4
+ No authentication required.
5
+
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ from typing import Annotated, Any
13
+
14
+ import httpx
15
+ import pandas as pd
16
+ from parsimony.connector import Connectors, connector, enumerator
17
+ from parsimony.errors import EmptyDataError
18
+ from parsimony.result import (
19
+ Column,
20
+ ColumnRole,
21
+ OutputConfig,
22
+ Provenance,
23
+ Result,
24
+ )
25
+ from parsimony.transport import map_http_error
26
+ from pydantic import BaseModel, Field, field_validator
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ _BASE_URL = "https://www.bankofcanada.ca/valet"
32
+
33
+ #: Concurrency cap for the per-group fan-out used to build the
34
+ #: series→group map. BoC's Valet endpoint is unauthenticated and
35
+ #: tolerates moderate concurrency; 16 keeps total enumeration time at
36
+ #: ~1 minute for the ~2,350 groups while staying well under any sensible
37
+ #: rate limit.
38
+ _GROUP_FETCH_CONCURRENCY = 16
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Parameter models
43
+ # ---------------------------------------------------------------------------
44
+
45
+
46
+ class BocFetchParams(BaseModel):
47
+ """Parameters for fetching Bank of Canada time series."""
48
+
49
+ series_name: Annotated[str, "ns:boc"] = Field(
50
+ ...,
51
+ description=(
52
+ "Comma-separated BoC series names (e.g. FXUSDCAD,FXEURCAD) "
53
+ "or a group name prefixed with 'group:' (e.g. group:FX_RATES_DAILY)"
54
+ ),
55
+ )
56
+ start_date: str | None = Field(default=None, description="Start date (YYYY-MM-DD)")
57
+ end_date: str | None = Field(default=None, description="End date (YYYY-MM-DD)")
58
+
59
+ @field_validator("series_name")
60
+ @classmethod
61
+ def _non_empty(cls, v: str) -> str:
62
+ v = v.strip()
63
+ if not v:
64
+ raise ValueError("series_name must be non-empty")
65
+ return v
66
+
67
+
68
+ class BocEnumerateParams(BaseModel):
69
+ """No parameters needed — enumerates all BoC series."""
70
+
71
+ pass
72
+
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # Output configs
76
+ # ---------------------------------------------------------------------------
77
+
78
+ BOC_ENUMERATE_OUTPUT = OutputConfig(
79
+ columns=[
80
+ # The KEY is either a series name (e.g. ``FXUSDCAD``) or a group
81
+ # entry prefixed with ``group:`` (e.g. ``group:FX_RATES_DAILY``).
82
+ # Groups are first-class addressable entities — ``boc_fetch``
83
+ # accepts ``series_name="group:NAME"`` and BoC's
84
+ # ``/observations/group/{name}/json`` returns the full panel — so
85
+ # they get their own catalog rows for discovery, in addition to
86
+ # the per-series rows. The ``group:`` prefix matches the syntax
87
+ # ``boc_fetch`` already expects.
88
+ Column(name="series_name", role=ColumnRole.KEY, namespace="boc"),
89
+ Column(name="title", role=ColumnRole.TITLE),
90
+ # ``description`` is the upstream Valet ``description`` text — the
91
+ # most useful semantic signal for retrieval. Routed via DESCRIPTION
92
+ # (not METADATA) so it lifts into ``semantic_text()`` for the
93
+ # embedder, mirroring how Treasury surfaces ``definition``. For
94
+ # group rows this carries the group's ``description`` text from
95
+ # ``/lists/groups/json`` (e.g. units and frequency hints like
96
+ # "Month-end, Millions of dollars").
97
+ Column(name="description", role=ColumnRole.DESCRIPTION),
98
+ # ``source`` tells the agent which fetch connector to call. BOC has
99
+ # a single Valet source today; the column is future-proofing for a
100
+ # parallel source so dispatch is already wired (matches Treasury's
101
+ # ``fiscal_data``/``treasury_rates`` split).
102
+ Column(name="source", role=ColumnRole.METADATA),
103
+ # ``entity_type`` is ``"series"`` for individual series rows and
104
+ # ``"group"`` for group rows — lets agents filter or weight by
105
+ # entity granularity.
106
+ Column(name="entity_type", role=ColumnRole.METADATA),
107
+ # ``group`` carries the upstream group ID (e.g. ``FX_RATES_DAILY``)
108
+ # the series belongs to — populated from /lists/groups/json plus
109
+ # per-group membership. Multi-group membership is rare; when it
110
+ # occurs we keep the first encountered group ID. Empty string when
111
+ # a series isn't a member of any catalogued group. For group rows
112
+ # this is the group's own ID.
113
+ Column(name="group", role=ColumnRole.METADATA),
114
+ Column(name="group_label", role=ColumnRole.METADATA),
115
+ ]
116
+ )
117
+
118
+ BOC_FETCH_OUTPUT = OutputConfig(
119
+ columns=[
120
+ Column(name="series_name", role=ColumnRole.KEY, param_key="series_name", namespace="boc"),
121
+ Column(name="title", role=ColumnRole.TITLE),
122
+ Column(name="date", dtype="datetime", role=ColumnRole.DATA),
123
+ Column(name="value", dtype="numeric", role=ColumnRole.DATA),
124
+ ]
125
+ )
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # Helpers
130
+ # ---------------------------------------------------------------------------
131
+
132
+
133
+ def _parse_observations(
134
+ json_data: dict[str, Any],
135
+ series_details: dict[str, Any] | None = None,
136
+ ) -> pd.DataFrame:
137
+ """Parse BoC Valet API observations response into long-format DataFrame.
138
+
139
+ The observations array has entries like:
140
+ {"d": "2024-01-15", "FXUSDCAD": {"v": "1.3456"}, "FXEURCAD": {"v": "1.4678"}}
141
+ """
142
+ observations = json_data.get("observations", [])
143
+ if not observations:
144
+ return pd.DataFrame(columns=["series_name", "title", "date", "value"])
145
+
146
+ # Discover series columns (everything except "d")
147
+ sample = observations[0]
148
+ series_cols = [k for k in sample if k != "d"]
149
+
150
+ rows: list[dict[str, Any]] = []
151
+ for obs in observations:
152
+ date = obs.get("d", "")
153
+ for col in series_cols:
154
+ raw = obs.get(col)
155
+ if raw is None:
156
+ continue
157
+ raw_value = raw.get("v") if isinstance(raw, dict) else raw
158
+ try:
159
+ value = float(raw_value) if raw_value is not None and raw_value not in ("", "NaN") else None
160
+ except (ValueError, TypeError):
161
+ value = None
162
+
163
+ # Resolve title from seriesDetail if available
164
+ title = col
165
+ if series_details and col in series_details:
166
+ detail = series_details[col]
167
+ title = detail.get("label", detail.get("description", col))
168
+
169
+ rows.append(
170
+ {
171
+ "series_name": col,
172
+ "title": title,
173
+ "date": date,
174
+ "value": value,
175
+ }
176
+ )
177
+
178
+ return pd.DataFrame(rows) if rows else pd.DataFrame(columns=["series_name", "title", "date", "value"])
179
+
180
+
181
+ async def _fetch_group_membership(
182
+ client: httpx.AsyncClient,
183
+ group_name: str,
184
+ semaphore: asyncio.Semaphore,
185
+ ) -> tuple[str, list[str]]:
186
+ """Fetch a single group's series-membership list.
187
+
188
+ Returns ``(group_name, list_of_series_names)``. On any HTTP error the
189
+ group is treated as empty — enumeration continues. We don't surface
190
+ individual group failures because cataloguing is a best-effort sweep
191
+ and BoC does occasionally retire group endpoints while leaving them
192
+ in the index.
193
+ """
194
+ async with semaphore:
195
+ try:
196
+ resp = await client.get(f"/groups/{group_name}/json")
197
+ resp.raise_for_status()
198
+ except httpx.HTTPError as exc:
199
+ logger.warning("BoC group fetch failed for %r: %s", group_name, exc)
200
+ return group_name, []
201
+ body = resp.json()
202
+
203
+ details = body.get("groupDetails") or {}
204
+ members = details.get("groupSeries") or {}
205
+ if not isinstance(members, dict):
206
+ return group_name, []
207
+ return group_name, [s for s in members if s]
208
+
209
+
210
+ async def _build_series_to_group_map(
211
+ client: httpx.AsyncClient,
212
+ groups_index: dict[str, dict[str, Any]],
213
+ ) -> dict[str, tuple[str, str]]:
214
+ """For each series, resolve ``(group_id, group_label)``.
215
+
216
+ Multi-group membership is rare in BoC's catalog (groups partition
217
+ series by economic theme); when it occurs the first encountered
218
+ group wins. Iteration order is the order BoC returns groups in
219
+ ``/lists/groups/json``, which is stable across requests.
220
+ """
221
+ semaphore = asyncio.Semaphore(_GROUP_FETCH_CONCURRENCY)
222
+ tasks = [
223
+ _fetch_group_membership(client, group_name, semaphore)
224
+ for group_name in groups_index
225
+ ]
226
+ results = await asyncio.gather(*tasks)
227
+
228
+ series_to_group: dict[str, tuple[str, str]] = {}
229
+ for group_name, members in results:
230
+ info = groups_index.get(group_name) or {}
231
+ label = info.get("label") if isinstance(info, dict) else ""
232
+ label = label or ""
233
+ for series_name in members:
234
+ if series_name not in series_to_group:
235
+ series_to_group[series_name] = (group_name, label)
236
+ return series_to_group
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Connectors
241
+ # ---------------------------------------------------------------------------
242
+
243
+
244
+ @connector(output=BOC_FETCH_OUTPUT, tags=["macro", "ca"])
245
+ async def boc_fetch(params: BocFetchParams) -> Result:
246
+ """Fetch Bank of Canada time series by series name(s) or group name.
247
+
248
+ Use 'group:GROUP_NAME' syntax for group queries (e.g. group:FX_RATES_DAILY).
249
+ Otherwise, pass comma-separated series names (e.g. FXUSDCAD,FXEURCAD).
250
+ """
251
+ async with httpx.AsyncClient(base_url=_BASE_URL, timeout=60.0) as client:
252
+ req_params: dict[str, str] = {}
253
+ if params.start_date:
254
+ req_params["start_date"] = params.start_date
255
+ if params.end_date:
256
+ req_params["end_date"] = params.end_date
257
+
258
+ if params.series_name.startswith("group:"):
259
+ group_name = params.series_name[6:].strip()
260
+ url = f"/observations/group/{group_name}/json"
261
+ else:
262
+ url = f"/observations/{params.series_name}/json"
263
+
264
+ response = await client.get(url, params=req_params)
265
+ try:
266
+ response.raise_for_status()
267
+ except httpx.HTTPStatusError as exc:
268
+ map_http_error(exc, provider="boc", op_name="observations")
269
+ json_data = response.json()
270
+
271
+ series_details = json_data.get("seriesDetail")
272
+ df = _parse_observations(json_data, series_details)
273
+ if df.empty:
274
+ raise EmptyDataError(provider="boc", message=f"No observations returned for: {params.series_name}")
275
+
276
+ return Result.from_dataframe(
277
+ df,
278
+ Provenance(
279
+ source="boc",
280
+ params={"series_name": params.series_name},
281
+ properties={"source_url": "https://www.bankofcanada.ca/valet/docs"},
282
+ ),
283
+ )
284
+
285
+
286
+ @enumerator(
287
+ output=BOC_ENUMERATE_OUTPUT,
288
+ tags=["macro", "ca"],
289
+ )
290
+ async def enumerate_boc(params: BocEnumerateParams) -> pd.DataFrame:
291
+ """Enumerate every Bank of Canada series via Valet's three list endpoints.
292
+
293
+ Granularity is one row per series — Valet addresses observations per
294
+ series, so series-level keys are the right unit (~15k rows).
295
+
296
+ Pipeline:
297
+
298
+ 1. ``/lists/series/json`` — single call returning all ~15k series with
299
+ upstream ``label`` and ``description``. ``description`` lands in a
300
+ ColumnRole.DESCRIPTION column so the embedder indexes it.
301
+ 2. ``/lists/groups/json`` — single call returning all ~2.3k groups
302
+ with their labels.
303
+ 3. ``/groups/{name}/json`` — fanned out concurrently for every group
304
+ to discover series membership; a series→group map is built and
305
+ attached to every row. Groups exist purely for discovery; missing
306
+ membership leaves the ``group`` field empty.
307
+ """
308
+ async with httpx.AsyncClient(base_url=_BASE_URL, timeout=60.0) as client:
309
+ series_resp = await client.get("/lists/series/json")
310
+ try:
311
+ series_resp.raise_for_status()
312
+ except httpx.HTTPStatusError as exc:
313
+ map_http_error(exc, provider="boc", op_name="series/list")
314
+ series_payload = series_resp.json()
315
+
316
+ groups_resp = await client.get("/lists/groups/json")
317
+ try:
318
+ groups_resp.raise_for_status()
319
+ except httpx.HTTPStatusError as exc:
320
+ map_http_error(exc, provider="boc", op_name="groups/list")
321
+ groups_payload = groups_resp.json()
322
+
323
+ groups_index = groups_payload.get("groups") or {}
324
+ if not isinstance(groups_index, dict):
325
+ groups_index = {}
326
+ series_to_group = await _build_series_to_group_map(client, groups_index)
327
+
328
+ series = series_payload.get("series") or {}
329
+ rows: list[dict[str, str]] = []
330
+ for series_name, info in series.items():
331
+ if not series_name:
332
+ continue
333
+ if isinstance(info, dict):
334
+ label = info.get("label") or series_name
335
+ desc = info.get("description") or ""
336
+ else:
337
+ label = str(info)
338
+ desc = ""
339
+
340
+ group_id, group_label = series_to_group.get(series_name, ("", ""))
341
+
342
+ rows.append(
343
+ {
344
+ "series_name": series_name,
345
+ "title": label,
346
+ "description": desc,
347
+ "source": "valet",
348
+ "entity_type": "series",
349
+ "group": group_id,
350
+ "group_label": group_label,
351
+ }
352
+ )
353
+
354
+ # Emit one row per group as a discoverable catalog entity. Groups are
355
+ # addressable via ``boc_fetch(series_name="group:NAME")`` (BoC's
356
+ # ``/observations/group/{name}/json``), so cataloguing them lets
357
+ # agents search by group description (e.g. "Month-end, Millions of
358
+ # dollars" — uniquely a group-level signal) and fetch a whole panel
359
+ # in one shot. ~2.3k groups; 2.2k carry non-empty descriptions in
360
+ # practice. Group rows use the ``group:`` prefix in their KEY,
361
+ # matching the syntax ``boc_fetch`` already accepts.
362
+ for group_name, group_info in groups_index.items():
363
+ if not group_name:
364
+ continue
365
+ if isinstance(group_info, dict):
366
+ g_label = group_info.get("label") or group_name
367
+ g_desc = group_info.get("description") or ""
368
+ else:
369
+ g_label = str(group_info)
370
+ g_desc = ""
371
+ rows.append(
372
+ {
373
+ "series_name": f"group:{group_name}",
374
+ "title": g_label,
375
+ "description": g_desc,
376
+ "source": "valet",
377
+ "entity_type": "group",
378
+ "group": group_name,
379
+ "group_label": g_label,
380
+ }
381
+ )
382
+
383
+ columns = [
384
+ "series_name",
385
+ "title",
386
+ "description",
387
+ "source",
388
+ "entity_type",
389
+ "group",
390
+ "group_label",
391
+ ]
392
+ return pd.DataFrame(rows, columns=columns) if rows else pd.DataFrame(columns=columns)
393
+
394
+
395
+ # ---------------------------------------------------------------------------
396
+ # Exports
397
+ # ---------------------------------------------------------------------------
398
+
399
+ from parsimony_boc.search import ( # noqa: E402, F401 (after public decorators; re-exported)
400
+ BOC_SEARCH_OUTPUT,
401
+ PARSIMONY_BOC_CATALOG_URL_ENV,
402
+ BocSearchParams,
403
+ boc_search,
404
+ )
405
+
406
+ CATALOGS: list[tuple[str, object]] = [("boc", enumerate_boc)]
407
+
408
+ CONNECTORS = Connectors([boc_fetch, enumerate_boc, boc_search])
File without changes
@@ -0,0 +1,99 @@
1
+ """Semantic search over the published Bank of Canada (BoC) catalog.
2
+
3
+ Wraps the parquet+FAISS catalog at ``hf://parsimony-dev/boc`` (override with
4
+ ``PARSIMONY_BOC_CATALOG_URL`` for local testing) as an MCP tool.
5
+
6
+ Codes returned by this tool are series names (e.g. ``FXUSDCAD``) or group
7
+ identifiers prefixed with ``group:`` (e.g. ``group:FX_RATES_DAILY``). Pass
8
+ the returned ``code`` to :func:`boc_fetch` via its ``series_name`` parameter.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import logging
15
+ import os
16
+ from typing import Annotated
17
+
18
+ import pandas as pd
19
+ from parsimony.catalog import Catalog
20
+ from parsimony.connector import connector
21
+ from parsimony.result import Column, ColumnRole, OutputConfig
22
+ from pydantic import BaseModel, Field
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ PARSIMONY_BOC_CATALOG_URL_ENV = "PARSIMONY_BOC_CATALOG_URL"
27
+ _DEFAULT_CATALOG_URL = "hf://parsimony-dev/boc"
28
+
29
+ _catalog: Catalog | None = None
30
+ _catalog_lock = asyncio.Lock()
31
+
32
+
33
+ async def _get_catalog() -> Catalog:
34
+ global _catalog
35
+ if _catalog is not None:
36
+ return _catalog
37
+ async with _catalog_lock:
38
+ if _catalog is None:
39
+ url = os.environ.get(PARSIMONY_BOC_CATALOG_URL_ENV, _DEFAULT_CATALOG_URL)
40
+ logger.info("loading BoC catalog from %s", url)
41
+ _catalog = await Catalog.from_url(url)
42
+ return _catalog
43
+
44
+
45
+ BOC_SEARCH_OUTPUT = OutputConfig(
46
+ columns=[
47
+ Column(name="code", role=ColumnRole.KEY, namespace="boc"),
48
+ Column(name="title", role=ColumnRole.TITLE),
49
+ Column(name="similarity", role=ColumnRole.METADATA),
50
+ ]
51
+ )
52
+
53
+
54
+ class BocSearchParams(BaseModel):
55
+ """Parameters for :func:`boc_search`."""
56
+
57
+ query: Annotated[
58
+ str,
59
+ Field(
60
+ min_length=1,
61
+ max_length=512,
62
+ description=(
63
+ "Natural-language description of the BoC series or group "
64
+ "you want (e.g. 'CAD USD daily exchange rate', 'Canadian "
65
+ "10-year bond yield', 'overnight rate'). Bilingual EN/FR "
66
+ "queries both work."
67
+ ),
68
+ ),
69
+ ]
70
+ limit: int = Field(default=10, ge=1, le=50, description="Top-N results.")
71
+
72
+
73
+ @connector(
74
+ output=BOC_SEARCH_OUTPUT,
75
+ tags=["macro", "ca", "tool"],
76
+ )
77
+ async def boc_search(params: BocSearchParams) -> pd.DataFrame:
78
+ """Semantic-search the Bank of Canada (BoC) Valet catalog.
79
+
80
+ Returns the top matching series/group codes from BoC's Valet API
81
+ (~15.4k series + 2.4k groups across exchange rates, interest rates,
82
+ monetary aggregates, balance sheets, FMI surveys, and more).
83
+
84
+ Pass the returned ``code`` to ``boc_fetch(series_name=...)``. Codes
85
+ prefixed ``group:`` resolve to the full group panel; bare codes
86
+ resolve to a single series.
87
+ """
88
+ catalog = await _get_catalog()
89
+ matches = await catalog.search(params.query, limit=params.limit)
90
+ return pd.DataFrame(
91
+ [
92
+ {
93
+ "code": m.code,
94
+ "title": m.title,
95
+ "similarity": round(m.similarity, 6),
96
+ }
97
+ for m in matches
98
+ ]
99
+ )
@@ -0,0 +1,76 @@
1
+ [project]
2
+ name = "parsimony-boc"
3
+ version = "0.4.0"
4
+ description = "Bank of Canada 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", "boc"]
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.bankofcanada.ca"
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
+ boc = "parsimony_boc"
46
+
47
+
48
+ [build-system]
49
+ requires = ["hatchling"]
50
+ build-backend = "hatchling.build"
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["parsimony_boc"]
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = ["parsimony_boc", "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
+ ]