parsimony-treasury 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
+ logs/
35
+ # Recorded HTTP cassettes must never be committed — respx mocks are hand-authored
36
+ # from upstream API documentation. A pre-commit / CI regex scan is the belt; this
37
+ # ignore is the braces. Override per-file via `!` if you need a hand-authored
38
+ # fixture checked in.
39
+ packages/*/tests/fixtures/**
40
+ !packages/*/tests/fixtures/README.md
@@ -0,0 +1,21 @@
1
+ # Changelog — parsimony-treasury
2
+
3
+ All notable changes to `parsimony-treasury` 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,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: parsimony-treasury
3
+ Version: 0.4.0
4
+ Summary: U.S. Treasury connector for the parsimony framework
5
+ Project-URL: Homepage, https://fiscaldata.treasury.gov
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: connectors,data,finance,parsimony,treasury
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
+ Provides-Extra: publish
35
+ Requires-Dist: parsimony-core[standard-onnx]<0.5,>=0.4.0; extra == 'publish'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # parsimony-treasury
39
+
40
+ US Treasury Fiscal Data connector plugin for parsimony — debt, revenue, spending, securities, and other federal fiscal datasets from the Bureau of the Fiscal Service.
41
+
42
+ Part of the [parsimony-connectors](https://github.com/ockham-sh/parsimony-connectors) monorepo. Distributed standalone on PyPI as `parsimony-treasury`.
43
+
44
+ ## Connectors
45
+
46
+ | Name | Kind | Description |
47
+ |---|---|---|
48
+ | `treasury_fetch` | connector | Fetch any Fiscal Data API endpoint as a tidy DataFrame, with optional `filter`, `sort`, and page size. |
49
+ | `enumerate_treasury` | enumerator | Enumerate every Treasury Fiscal Data dataset and endpoint for catalog indexing (drives the `treasury` catalog). |
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ pip install parsimony-treasury
55
+ ```
56
+
57
+ Pulls in `parsimony-core>=0.4,<0.5` automatically. Verify discovery:
58
+
59
+ ```bash
60
+ python -c "from parsimony import discover; print([p.name for p in discover.iter_providers()])"
61
+ ```
62
+
63
+ ## Quick start
64
+
65
+ ```python
66
+ import asyncio
67
+ from parsimony_treasury import CONNECTORS
68
+
69
+ async def main():
70
+ connectors = CONNECTORS.bind_env()
71
+ result = await connectors["treasury_fetch"](
72
+ endpoint="v2/accounting/od/debt_to_penny",
73
+ sort="-record_date",
74
+ page_size=10,
75
+ )
76
+ print(result.data.head())
77
+
78
+ asyncio.run(main())
79
+ ```
80
+
81
+ For multi-plugin composition:
82
+
83
+ ```python
84
+ from parsimony import discover
85
+ connectors = discover.load_all().bind_env()
86
+ ```
87
+
88
+ ## Catalog publishing
89
+
90
+ This plugin publishes a catalog under the `treasury` namespace, backed by `enumerate_treasury` (param-less; walks the Fiscal Data dataset metadata API).
91
+
92
+ ```bash
93
+ parsimony publish --provider treasury --target "hf://<your-org>/parsimony-treasury"
94
+ ```
95
+
96
+ The `{namespace}` placeholder in `--target` is substituted with `treasury` at publish time; targets support `file://`, `hf://`, and `s3://` schemes.
97
+
98
+ ## Provider
99
+
100
+ - Homepage: <https://fiscaldata.treasury.gov>
101
+ - API docs: <https://fiscaldata.treasury.gov/api-documentation/>
102
+
103
+ ## License
104
+
105
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,68 @@
1
+ # parsimony-treasury
2
+
3
+ US Treasury Fiscal Data connector plugin for parsimony — debt, revenue, spending, securities, and other federal fiscal datasets from the Bureau of the Fiscal Service.
4
+
5
+ Part of the [parsimony-connectors](https://github.com/ockham-sh/parsimony-connectors) monorepo. Distributed standalone on PyPI as `parsimony-treasury`.
6
+
7
+ ## Connectors
8
+
9
+ | Name | Kind | Description |
10
+ |---|---|---|
11
+ | `treasury_fetch` | connector | Fetch any Fiscal Data API endpoint as a tidy DataFrame, with optional `filter`, `sort`, and page size. |
12
+ | `enumerate_treasury` | enumerator | Enumerate every Treasury Fiscal Data dataset and endpoint for catalog indexing (drives the `treasury` catalog). |
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install parsimony-treasury
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
+ ## Quick start
27
+
28
+ ```python
29
+ import asyncio
30
+ from parsimony_treasury import CONNECTORS
31
+
32
+ async def main():
33
+ connectors = CONNECTORS.bind_env()
34
+ result = await connectors["treasury_fetch"](
35
+ endpoint="v2/accounting/od/debt_to_penny",
36
+ sort="-record_date",
37
+ page_size=10,
38
+ )
39
+ print(result.data.head())
40
+
41
+ asyncio.run(main())
42
+ ```
43
+
44
+ For multi-plugin composition:
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 a catalog under the `treasury` namespace, backed by `enumerate_treasury` (param-less; walks the Fiscal Data dataset metadata API).
54
+
55
+ ```bash
56
+ parsimony publish --provider treasury --target "hf://<your-org>/parsimony-treasury"
57
+ ```
58
+
59
+ The `{namespace}` placeholder in `--target` is substituted with `treasury` at publish time; targets support `file://`, `hf://`, and `s3://` schemes.
60
+
61
+ ## Provider
62
+
63
+ - Homepage: <https://fiscaldata.treasury.gov>
64
+ - API docs: <https://fiscaldata.treasury.gov/api-documentation/>
65
+
66
+ ## License
67
+
68
+ See [LICENSE](./LICENSE).
@@ -0,0 +1,634 @@
1
+ """US Treasury Fiscal Data: fetch + catalog enumeration.
2
+
3
+ API docs: https://fiscaldata.treasury.gov/api-documentation/
4
+ No authentication required.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import xml.etree.ElementTree as ET
10
+ from datetime import UTC, datetime
11
+ from typing import Annotated, Any, Literal
12
+
13
+ import httpx
14
+ import pandas as pd
15
+ from parsimony.connector import Connectors, connector, enumerator
16
+ from parsimony.errors import EmptyDataError
17
+ from parsimony.result import (
18
+ Column,
19
+ ColumnRole,
20
+ OutputConfig,
21
+ Provenance,
22
+ Result,
23
+ )
24
+ from parsimony.transport import HttpClient, map_http_error
25
+ from pydantic import BaseModel, Field
26
+
27
+ _BASE_URL = "https://api.fiscaldata.treasury.gov/services/api/fiscal_service"
28
+ _METADATA_URL = "https://api.fiscaldata.treasury.gov/services/dtg/metadata/"
29
+ _TREASURY_RATES_BASE_URL = "https://home.treasury.gov/resource-center/data-chart-center/interest-rates/pages/xml"
30
+
31
+ # OData Atom XML namespaces used by the home.treasury.gov rate feeds.
32
+ _ATOM_NS = "{http://www.w3.org/2005/Atom}"
33
+ _ODATA_DATASERVICES_NS = "{http://schemas.microsoft.com/ado/2007/08/dataservices}"
34
+ _ODATA_METADATA_NS = "{http://schemas.microsoft.com/ado/2007/08/dataservices/metadata}"
35
+
36
+ TreasuryRateFeed = Literal[
37
+ "daily_treasury_yield_curve",
38
+ "daily_treasury_real_yield_curve",
39
+ "daily_treasury_bill_rates",
40
+ "daily_treasury_long_term_rate",
41
+ "daily_treasury_real_long_term",
42
+ ]
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Parameter models
47
+ # ---------------------------------------------------------------------------
48
+
49
+
50
+ class TreasuryFetchParams(BaseModel):
51
+ """Parameters for fetching US Treasury fiscal data."""
52
+
53
+ endpoint: Annotated[str, "ns:treasury"] = Field(
54
+ ..., description="API endpoint path (e.g. v2/accounting/od/debt_to_penny)"
55
+ )
56
+ filter: str | None = Field(
57
+ default=None,
58
+ description="Filter expression (e.g. record_date:gte:2024-01-01)",
59
+ )
60
+ sort: str | None = Field(
61
+ default=None,
62
+ description="Sort expression (e.g. -record_date for descending)",
63
+ )
64
+ page_size: int = Field(default=100, ge=1, le=10000, description="Records per page")
65
+
66
+
67
+ class TreasuryEnumerateParams(BaseModel):
68
+ """No parameters needed — enumerates the full Treasury API catalog."""
69
+
70
+ pass
71
+
72
+
73
+ class TreasuryRatesFetchParams(BaseModel):
74
+ """Parameters for fetching a Treasury Office of Debt Management rate feed.
75
+
76
+ The home.treasury.gov rate feeds — Daily Treasury Par Yield Curve,
77
+ Bill Rates, Real Yield Curve, Long-Term Rates, Real Long-Term — are
78
+ paginated by calendar year. ``feed`` is a closed enum so invalid
79
+ values are caught at param-validation time rather than as a 404 from
80
+ Treasury.
81
+ """
82
+
83
+ feed: Annotated[TreasuryRateFeed, "ns:treasury"] = Field(
84
+ ...,
85
+ description=(
86
+ "Treasury OBM rate feed name (one of: daily_treasury_yield_curve, "
87
+ "daily_treasury_real_yield_curve, daily_treasury_bill_rates, "
88
+ "daily_treasury_long_term_rate, daily_treasury_real_long_term)."
89
+ ),
90
+ )
91
+ year: int | None = Field(
92
+ default=None,
93
+ ge=1990,
94
+ le=2100,
95
+ description="Calendar year to retrieve. Defaults to the current UTC year.",
96
+ )
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Output configs
101
+ # ---------------------------------------------------------------------------
102
+
103
+ TREASURY_ENUMERATE_OUTPUT = OutputConfig(
104
+ columns=[
105
+ # Compound code ``{endpoint}#{field}`` so every addressable time-series
106
+ # measure has a unique catalog entry; agents split on ``#`` to recover
107
+ # the fetchable endpoint and the column to read off the row.
108
+ Column(name="code", role=ColumnRole.KEY, namespace="treasury"),
109
+ Column(name="title", role=ColumnRole.TITLE),
110
+ # ``definition`` is the Fiscal Data field's own descriptive text — the
111
+ # most useful semantic signal for retrieval. Routing it through
112
+ # DESCRIPTION (not METADATA) lifts it into ``semantic_text()`` so the
113
+ # embedder indexes it, in addition to BM25.
114
+ Column(name="definition", role=ColumnRole.DESCRIPTION),
115
+ # ``source`` tells the agent which fetch connector to call —
116
+ # ``"fiscal_data"`` → :func:`treasury_fetch`, ``"treasury_rates"`` →
117
+ # :func:`treasury_rates_fetch`. Without this, agents would have to
118
+ # sniff the ``code`` prefix.
119
+ Column(name="source", role=ColumnRole.METADATA),
120
+ Column(name="endpoint", role=ColumnRole.METADATA),
121
+ Column(name="field", role=ColumnRole.METADATA),
122
+ Column(name="data_type", role=ColumnRole.METADATA),
123
+ Column(name="dataset", role=ColumnRole.METADATA),
124
+ Column(name="category", role=ColumnRole.METADATA),
125
+ Column(name="frequency", role=ColumnRole.METADATA),
126
+ Column(name="earliest_date", role=ColumnRole.METADATA),
127
+ Column(name="latest_date", role=ColumnRole.METADATA),
128
+ ]
129
+ )
130
+
131
+ # Treasury field ``data_type`` values that denote a time-series measure (as
132
+ # opposed to dates, identifiers, category labels, or row-scaffolding ints).
133
+ # The prefix match captures precision-suffixed variants (``CURRENCY0``,
134
+ # ``PERCENTAGE_PRECISE``, etc.) that Fiscal Data emits alongside the base
135
+ # types.
136
+ _MEASURE_TYPE_PREFIXES: tuple[str, ...] = (
137
+ "CURRENCY",
138
+ "NUMBER",
139
+ "PERCENTAGE",
140
+ "RATE",
141
+ )
142
+
143
+
144
+ def _is_measure_field(field: dict[str, Any]) -> bool:
145
+ """Whether *field* is an addressable time-series measure.
146
+
147
+ Most measures are typed ``CURRENCY``/``NUMBER``/``PERCENTAGE``/``RATE``
148
+ (or precision-suffixed variants) — caught by prefix match. Treasury's
149
+ Certified Interest Rates (TCIR) tables, however, store rate values as
150
+ ``STRING`` data — Treasury's data dictionary quirk, not real strings.
151
+ Recognise those by name: a STRING column whose name contains ``rate``
152
+ or ``yield`` is a rate value, except for purely descriptive
153
+ ``*_desc`` fields and Y/N-coded indicators.
154
+ """
155
+ data_type = (field.get("data_type") or "").strip()
156
+ if data_type.startswith(_MEASURE_TYPE_PREFIXES):
157
+ return True
158
+ if data_type == "STRING":
159
+ column_name = (field.get("column_name") or "").lower()
160
+ if "rate" not in column_name and "yield" not in column_name:
161
+ return False
162
+ if column_name.endswith("_desc"):
163
+ return False
164
+ definition = (field.get("definition") or "").strip()
165
+ # ``floating_rate`` is a Y/N flag describing the security, not a
166
+ # rate value; same for any other Y/N-prefixed indicator.
167
+ return not definition.startswith("Y/N")
168
+ return False
169
+
170
+
171
+ # ---------------------------------------------------------------------------
172
+ # Treasury Office of Debt Management rate feeds (home.treasury.gov XML)
173
+ #
174
+ # These famous series — Daily Treasury Par Yield Curve, Daily Treasury
175
+ # Bill Rates, etc. — are NOT in Fiscal Data's ``/dtg/metadata/`` endpoint.
176
+ # They live on a separate Treasury subdomain as XML/CSV feeds. Cataloguing
177
+ # them under the same ``treasury`` namespace gives agents one search
178
+ # surface; the ``endpoint`` metadata field carries a ``home/<feed>`` prefix
179
+ # so the fetch path can route by source.
180
+ # ---------------------------------------------------------------------------
181
+
182
+ _TREASURY_RATE_DATASET_CATEGORY = "Office of Debt Management"
183
+
184
+
185
+ def _rate_feed_source_url(feed: str) -> str:
186
+ return (
187
+ "https://home.treasury.gov/resource-center/data-chart-center/"
188
+ f"interest-rates/TextView?type={feed}"
189
+ )
190
+
191
+
192
+ _TREASURY_RATE_FEEDS: tuple[dict[str, Any], ...] = (
193
+ {
194
+ "feed": "daily_treasury_yield_curve",
195
+ "dataset": "Daily Treasury Par Yield Curve Rates",
196
+ "frequency": "Daily",
197
+ "definition_template": (
198
+ "{tenor} constant-maturity Treasury par yield curve rate, published daily by the "
199
+ "U.S. Treasury Office of Debt Management. The par yield curve is derived from "
200
+ "indicative bid-side prices on the most actively traded Treasury securities and is "
201
+ "the canonical risk-free rate benchmark for that maturity."
202
+ ),
203
+ "fields": (
204
+ ("BC_1MONTH", "1 Month"),
205
+ ("BC_1_5MONTH", "1.5 Month"),
206
+ ("BC_2MONTH", "2 Month"),
207
+ ("BC_3MONTH", "3 Month"),
208
+ ("BC_4MONTH", "4 Month"),
209
+ ("BC_6MONTH", "6 Month"),
210
+ ("BC_1YEAR", "1 Year"),
211
+ ("BC_2YEAR", "2 Year"),
212
+ ("BC_3YEAR", "3 Year"),
213
+ ("BC_5YEAR", "5 Year"),
214
+ ("BC_7YEAR", "7 Year"),
215
+ ("BC_10YEAR", "10 Year"),
216
+ ("BC_20YEAR", "20 Year"),
217
+ ("BC_30YEAR", "30 Year"),
218
+ ),
219
+ },
220
+ {
221
+ "feed": "daily_treasury_real_yield_curve",
222
+ "dataset": "Daily Treasury Real Yield Curve Rates",
223
+ "frequency": "Daily",
224
+ "definition_template": (
225
+ "{tenor} real (TIPS-based) Treasury yield curve rate, published daily by the U.S. "
226
+ "Treasury Office of Debt Management. Reflects the inflation-adjusted yield on "
227
+ "Treasury Inflation-Protected Securities at the given constant maturity."
228
+ ),
229
+ "fields": (
230
+ ("TC_5YEAR", "5 Year"),
231
+ ("TC_7YEAR", "7 Year"),
232
+ ("TC_10YEAR", "10 Year"),
233
+ ("TC_20YEAR", "20 Year"),
234
+ ("TC_30YEAR", "30 Year"),
235
+ ),
236
+ },
237
+ {
238
+ "feed": "daily_treasury_bill_rates",
239
+ "dataset": "Daily Treasury Bill Rates",
240
+ "frequency": "Daily",
241
+ "definition_template": "{tenor} {kind}, published daily by the U.S. Treasury Office of Debt Management.",
242
+ "fields": (
243
+ ("ROUND_B1_CLOSE_4WK_2", "4-Week Treasury Bill — Closing Bank Discount Rate"),
244
+ ("ROUND_B1_YIELD_4WK_2", "4-Week Treasury Bill — Coupon Equivalent Yield"),
245
+ ("ROUND_B1_CLOSE_6WK_2", "6-Week Treasury Bill — Closing Bank Discount Rate"),
246
+ ("ROUND_B1_YIELD_6WK_2", "6-Week Treasury Bill — Coupon Equivalent Yield"),
247
+ ("ROUND_B1_CLOSE_8WK_2", "8-Week Treasury Bill — Closing Bank Discount Rate"),
248
+ ("ROUND_B1_YIELD_8WK_2", "8-Week Treasury Bill — Coupon Equivalent Yield"),
249
+ ("ROUND_B1_CLOSE_13WK_2", "13-Week Treasury Bill — Closing Bank Discount Rate"),
250
+ ("ROUND_B1_YIELD_13WK_2", "13-Week Treasury Bill — Coupon Equivalent Yield"),
251
+ ("ROUND_B1_CLOSE_17WK_2", "17-Week Treasury Bill — Closing Bank Discount Rate"),
252
+ ("ROUND_B1_YIELD_17WK_2", "17-Week Treasury Bill — Coupon Equivalent Yield"),
253
+ ("ROUND_B1_CLOSE_26WK_2", "26-Week Treasury Bill — Closing Bank Discount Rate"),
254
+ ("ROUND_B1_YIELD_26WK_2", "26-Week Treasury Bill — Coupon Equivalent Yield"),
255
+ ("ROUND_B1_CLOSE_52WK_2", "52-Week Treasury Bill — Closing Bank Discount Rate"),
256
+ ("ROUND_B1_YIELD_52WK_2", "52-Week Treasury Bill — Coupon Equivalent Yield"),
257
+ ),
258
+ },
259
+ {
260
+ "feed": "daily_treasury_long_term_rate",
261
+ "dataset": "Daily Treasury Long-Term Rates",
262
+ "frequency": "Daily",
263
+ # Long format — the actual rate is in column ``RATE`` parameterised
264
+ # by ``RATE_TYPE``. One catalog row pointing at the feed is the most
265
+ # useful surface; agents fetch and pivot on RATE_TYPE themselves.
266
+ "definition_template": (
267
+ "Daily Treasury long-term composite rates, published by the U.S. Treasury Office of "
268
+ "Debt Management. The feed is in long format: each row carries a ``RATE_TYPE`` "
269
+ "(e.g. LT, LT5, etc.) and a ``RATE`` value. Used to evaluate long-term Treasury "
270
+ "yields when bonds with maturities of 10+ years are not available."
271
+ ),
272
+ "fields": (("RATE", "Long-Term Composite Rate"),),
273
+ },
274
+ {
275
+ "feed": "daily_treasury_real_long_term",
276
+ "dataset": "Daily Treasury Real Long-Term Rate Averages",
277
+ "frequency": "Daily",
278
+ "definition_template": (
279
+ "Daily Treasury real long-term rate averages (TIPS-based), published by the U.S. "
280
+ "Treasury Office of Debt Management."
281
+ ),
282
+ "fields": (("RATE", "Real Long-Term Rate Average"),),
283
+ },
284
+ )
285
+
286
+
287
+ def _build_treasury_rate_rows() -> list[dict[str, str]]:
288
+ """One row per (rate-feed, column) entry from :data:`_TREASURY_RATE_FEEDS`.
289
+
290
+ Pure function — the registry is static so this involves no I/O. The
291
+ code is ``home/{feed}#{column}``; the ``home/`` prefix distinguishes
292
+ these entries from Fiscal Data codes (which are versioned paths like
293
+ ``v2/...``) so a future fetch dispatcher can route by source.
294
+ """
295
+ rows: list[dict[str, str]] = []
296
+ for spec in _TREASURY_RATE_FEEDS:
297
+ feed = spec["feed"]
298
+ endpoint = f"home/{feed}"
299
+ dataset = spec["dataset"]
300
+ frequency = spec["frequency"]
301
+ template: str = spec["definition_template"]
302
+ for column_name, tenor in spec["fields"]:
303
+ kind = "Closing Bank Discount Rate" if "_CLOSE_" in column_name else "Coupon Equivalent Yield"
304
+ definition = template.format(tenor=tenor, kind=kind)
305
+ rows.append(
306
+ {
307
+ "code": f"{endpoint}#{column_name}",
308
+ "title": f"{tenor} — {dataset}",
309
+ "source": "treasury_rates",
310
+ "endpoint": endpoint,
311
+ "field": column_name,
312
+ "definition": definition,
313
+ "data_type": "PERCENTAGE",
314
+ "dataset": dataset,
315
+ "category": _TREASURY_RATE_DATASET_CATEGORY,
316
+ "frequency": frequency,
317
+ "earliest_date": "",
318
+ "latest_date": "",
319
+ }
320
+ )
321
+ return rows
322
+
323
+ # Treasury returns tabular datasets — the output is a DataFrame whose
324
+ # columns depend on the endpoint. We use a minimal schema with just
325
+ # the identity key; actual data columns vary per endpoint.
326
+ TREASURY_FETCH_OUTPUT = OutputConfig(
327
+ columns=[
328
+ Column(name="endpoint", role=ColumnRole.KEY, param_key="endpoint", namespace="treasury"),
329
+ Column(name="title", role=ColumnRole.TITLE),
330
+ Column(name="record_date", dtype="datetime", role=ColumnRole.DATA),
331
+ ]
332
+ )
333
+
334
+ # Rates feeds return one row per business day; rate columns vary per feed
335
+ # (e.g. ``BC_10YEAR`` for the par yield curve, ``ROUND_B1_YIELD_4WK_2`` for
336
+ # bill rates). The schema names only the columns we always materialise; the
337
+ # feed-specific rate columns ride along as additional DATA columns.
338
+ TREASURY_RATES_FETCH_OUTPUT = OutputConfig(
339
+ columns=[
340
+ Column(name="feed", role=ColumnRole.KEY, param_key="feed", namespace="treasury"),
341
+ Column(name="title", role=ColumnRole.TITLE),
342
+ Column(name="record_date", dtype="datetime", role=ColumnRole.DATA),
343
+ ]
344
+ )
345
+
346
+
347
+ # ---------------------------------------------------------------------------
348
+ # Connectors
349
+ # ---------------------------------------------------------------------------
350
+
351
+
352
+ def _make_http() -> HttpClient:
353
+ return HttpClient(_BASE_URL, query_params={"format": "json"})
354
+
355
+
356
+ @connector(output=TREASURY_FETCH_OUTPUT, tags=["macro", "us"])
357
+ async def treasury_fetch(params: TreasuryFetchParams) -> Result:
358
+ """Fetch US Treasury fiscal data by endpoint.
359
+
360
+ Returns the dataset as-is with ``record_date`` parsed and numeric
361
+ columns converted. Each row is one record from the Treasury API.
362
+ """
363
+ http = _make_http()
364
+ req_params: dict[str, Any] = {"page[size]": params.page_size}
365
+ if params.filter:
366
+ req_params["filter"] = params.filter
367
+ if params.sort:
368
+ req_params["sort"] = params.sort
369
+
370
+ response = await http.request("GET", f"/{params.endpoint}", params=req_params)
371
+ try:
372
+ response.raise_for_status()
373
+ except httpx.HTTPStatusError as exc:
374
+ map_http_error(exc, provider="treasury", op_name=params.endpoint)
375
+ body = response.json()
376
+
377
+ data = body.get("data", [])
378
+ if not data:
379
+ raise EmptyDataError(provider="treasury", message=f"No data returned for endpoint: {params.endpoint}")
380
+
381
+ meta = body.get("meta", {})
382
+ labels = meta.get("labels", {})
383
+ data_types = meta.get("dataTypes", {})
384
+
385
+ df = pd.DataFrame(data)
386
+
387
+ # Parse record_date
388
+ if "record_date" in df.columns:
389
+ df["record_date"] = pd.to_datetime(df["record_date"], errors="coerce")
390
+
391
+ # Convert numeric columns identified by API metadata
392
+ numeric_types = {"CURRENCY", "NUMBER", "PERCENTAGE", "RATE"}
393
+ for col, dtype in data_types.items():
394
+ if dtype in numeric_types and col in df.columns:
395
+ df[col] = pd.to_numeric(
396
+ df[col].astype(str).str.replace(",", "", regex=False),
397
+ errors="coerce",
398
+ )
399
+
400
+ # Add identity columns
401
+ table_name = labels.get("record_date", params.endpoint)
402
+ df["endpoint"] = params.endpoint
403
+ df["title"] = table_name
404
+
405
+ return Result.from_dataframe(
406
+ df,
407
+ Provenance(
408
+ source="treasury",
409
+ params={"endpoint": params.endpoint},
410
+ properties={
411
+ "total_records": meta.get("total-count"),
412
+ "source_url": f"https://fiscaldata.treasury.gov/datasets/{params.endpoint}",
413
+ },
414
+ ),
415
+ )
416
+
417
+
418
+ _RATES_DATE_COLUMNS: tuple[str, ...] = ("NEW_DATE", "INDEX_DATE", "QUOTE_DATE")
419
+ _RATES_NUMERIC_TYPES: frozenset[str] = frozenset(
420
+ {"Edm.Double", "Edm.Decimal", "Edm.Single", "Edm.Int32", "Edm.Int64"}
421
+ )
422
+ _RATES_DATETIME_TYPES: frozenset[str] = frozenset({"Edm.DateTime"})
423
+
424
+
425
+ def _parse_treasury_rates_xml(xml_text: str) -> pd.DataFrame:
426
+ """Parse a home.treasury.gov OData Atom rate-feed payload into a DataFrame.
427
+
428
+ Each ``<entry>`` carries an ``m:properties`` block whose ``d:NAME``
429
+ children are the row's columns. ``Edm.DateTime`` values become
430
+ pandas datetimes, ``Edm.Double``/``Edm.Decimal`` become floats, and
431
+ everything else stays as a string. The first ``Edm.DateTime`` column
432
+ encountered (Treasury uses ``NEW_DATE``, ``INDEX_DATE``, or
433
+ ``QUOTE_DATE`` depending on the feed) is duplicated as
434
+ ``record_date`` to give every feed a uniform time axis.
435
+ """
436
+ root = ET.fromstring(xml_text)
437
+ rows: list[dict[str, Any]] = []
438
+ for entry in root.findall(f"{_ATOM_NS}entry"):
439
+ props = entry.find(f"{_ATOM_NS}content/{_ODATA_METADATA_NS}properties")
440
+ if props is None:
441
+ continue
442
+ row: dict[str, Any] = {}
443
+ for prop in props:
444
+ tag = prop.tag.removeprefix(_ODATA_DATASERVICES_NS)
445
+ edm_type = prop.attrib.get(f"{_ODATA_METADATA_NS}type", "Edm.String")
446
+ text = prop.text
447
+ if text is None or text == "":
448
+ row[tag] = None
449
+ continue
450
+ if edm_type in _RATES_DATETIME_TYPES:
451
+ row[tag] = pd.to_datetime(text, errors="coerce")
452
+ elif edm_type in _RATES_NUMERIC_TYPES:
453
+ try:
454
+ row[tag] = float(text)
455
+ except (TypeError, ValueError):
456
+ row[tag] = None
457
+ else:
458
+ row[tag] = text
459
+ if row:
460
+ rows.append(row)
461
+
462
+ df = pd.DataFrame(rows)
463
+ if df.empty:
464
+ return df
465
+ for date_col in _RATES_DATE_COLUMNS:
466
+ if date_col in df.columns:
467
+ df["record_date"] = df[date_col]
468
+ break
469
+ if "record_date" in df.columns:
470
+ df = df.sort_values("record_date").reset_index(drop=True)
471
+ return df
472
+
473
+
474
+ @connector(output=TREASURY_RATES_FETCH_OUTPUT, tags=["macro", "us"])
475
+ async def treasury_rates_fetch(params: TreasuryRatesFetchParams) -> Result:
476
+ """Fetch a Treasury Office of Debt Management rate feed for one calendar year.
477
+
478
+ The home.treasury.gov XML feed is paginated by year via the
479
+ ``field_tdr_date_value`` query parameter. ``year=None`` defaults to
480
+ the current UTC year. Returns a DataFrame whose columns are the
481
+ feed's native rate columns (e.g. ``BC_10YEAR`` for the par yield
482
+ curve) plus a normalised ``record_date``.
483
+ """
484
+ year = params.year if params.year is not None else datetime.now(tz=UTC).year
485
+ op_name = f"rates/{params.feed}/{year}"
486
+ async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
487
+ try:
488
+ response = await client.get(
489
+ _TREASURY_RATES_BASE_URL,
490
+ params={"data": params.feed, "field_tdr_date_value": str(year)},
491
+ )
492
+ response.raise_for_status()
493
+ except httpx.HTTPStatusError as exc:
494
+ map_http_error(exc, provider="treasury", op_name=op_name)
495
+ xml_text = response.text
496
+
497
+ df = _parse_treasury_rates_xml(xml_text)
498
+ if df.empty:
499
+ raise EmptyDataError(
500
+ provider="treasury",
501
+ message=f"No rows returned for rate feed {params.feed!r} year={year}",
502
+ )
503
+
504
+ df["feed"] = params.feed
505
+ df["title"] = params.feed.replace("_", " ").title()
506
+
507
+ return Result.from_dataframe(
508
+ df,
509
+ Provenance(
510
+ source="treasury",
511
+ params={"feed": params.feed, "year": year},
512
+ properties={
513
+ "row_count": len(df),
514
+ "source_url": (
515
+ f"{_TREASURY_RATES_BASE_URL}?data={params.feed}&field_tdr_date_value={year}"
516
+ ),
517
+ },
518
+ ),
519
+ )
520
+
521
+
522
+ @enumerator(
523
+ output=TREASURY_ENUMERATE_OUTPUT,
524
+ tags=["macro", "us"],
525
+ )
526
+ async def enumerate_treasury(params: TreasuryEnumerateParams) -> pd.DataFrame:
527
+ """Enumerate every addressable Treasury time series across two sources.
528
+
529
+ 1. **Fiscal Data API** (``/dtg/metadata/``) — yields one row per
530
+ (endpoint, measure-field) pair. ``data_type`` typed as
531
+ ``CURRENCY``/``NUMBER``/``PERCENTAGE``/``RATE`` (or precision-suffixed
532
+ variants) is a measure; STRING fields whose names contain
533
+ ``rate``/``yield`` are also recognised so the Treasury Certified
534
+ Interest Rates (TCIR) tables — which Treasury stores as STRING — are
535
+ included. Dates, identifiers, and category labels are excluded.
536
+ 2. **Office of Debt Management rate feeds** (home.treasury.gov XML) —
537
+ static registry covering the daily par yield curve, real yield curve,
538
+ bill rates, and long-term composite rates. These are the canonical
539
+ benchmark series and are not in the Fiscal Data metadata.
540
+ """
541
+ async with httpx.AsyncClient(timeout=30.0) as client:
542
+ resp = await client.get(_METADATA_URL)
543
+ try:
544
+ resp.raise_for_status()
545
+ except httpx.HTTPStatusError as exc:
546
+ map_http_error(exc, provider="treasury", op_name="datasets/metadata")
547
+ raw = resp.json()
548
+
549
+ datasets: list[dict] = []
550
+ if isinstance(raw, list):
551
+ datasets = raw
552
+ elif isinstance(raw, dict):
553
+ for key in ("datasets", "data", "result"):
554
+ if key in raw and isinstance(raw[key], list):
555
+ datasets = raw[key]
556
+ break
557
+
558
+ prefix = "/services/api/fiscal_service/"
559
+ rows: list[dict[str, str]] = []
560
+
561
+ for ds in datasets:
562
+ dataset_title = ds.get("title") or ds.get("dataset_name", "")
563
+ category = ds.get("publisher", "")
564
+ ds_frequency = ds.get("update_frequency", "")
565
+ for api in ds.get("apis", []):
566
+ endpoint = api.get("endpoint_txt") or ""
567
+ if endpoint.startswith(prefix):
568
+ endpoint = endpoint[len(prefix) :]
569
+ if not endpoint:
570
+ endpoint = api.get("api_id", "")
571
+ if not endpoint:
572
+ continue
573
+ table_name = api.get("table_name") or dataset_title
574
+ frequency = api.get("update_frequency") or ds_frequency
575
+ earliest_date = api.get("earliest_date", "") or ""
576
+ latest_date = api.get("latest_date", "") or ""
577
+ for field in api.get("fields", []):
578
+ if not _is_measure_field(field):
579
+ continue
580
+ column_name = field.get("column_name", "") or ""
581
+ if not column_name:
582
+ continue
583
+ pretty_name = field.get("pretty_name") or column_name
584
+ definition = field.get("definition", "") or ""
585
+ rows.append(
586
+ {
587
+ "code": f"{endpoint}#{column_name}",
588
+ "title": f"{pretty_name} — {table_name}",
589
+ "source": "fiscal_data",
590
+ "endpoint": endpoint,
591
+ "field": column_name,
592
+ "definition": definition,
593
+ "data_type": field.get("data_type", "") or "",
594
+ "dataset": dataset_title,
595
+ "category": category,
596
+ "frequency": frequency,
597
+ "earliest_date": earliest_date,
598
+ "latest_date": latest_date,
599
+ }
600
+ )
601
+
602
+ rows.extend(_build_treasury_rate_rows())
603
+
604
+ columns = [
605
+ "code",
606
+ "title",
607
+ "source",
608
+ "endpoint",
609
+ "field",
610
+ "definition",
611
+ "data_type",
612
+ "dataset",
613
+ "category",
614
+ "frequency",
615
+ "earliest_date",
616
+ "latest_date",
617
+ ]
618
+ return pd.DataFrame(rows, columns=columns) if rows else pd.DataFrame(columns=columns)
619
+
620
+
621
+ # ---------------------------------------------------------------------------
622
+ # Exports
623
+ # ---------------------------------------------------------------------------
624
+
625
+ from parsimony_treasury.search import ( # noqa: E402, F401 (after public decorators; re-exported)
626
+ PARSIMONY_TREASURY_CATALOG_URL_ENV,
627
+ TREASURY_SEARCH_OUTPUT,
628
+ TreasurySearchParams,
629
+ treasury_search,
630
+ )
631
+
632
+ CATALOGS: list[tuple[str, object]] = [("treasury", enumerate_treasury)]
633
+
634
+ CONNECTORS = Connectors([treasury_fetch, treasury_rates_fetch, enumerate_treasury, treasury_search])
File without changes
@@ -0,0 +1,103 @@
1
+ """Semantic search over the published US Treasury catalog.
2
+
3
+ Wraps the parquet+FAISS catalog at ``hf://parsimony-dev/treasury`` (override
4
+ with ``PARSIMONY_TREASURY_CATALOG_URL`` for local testing) as an MCP tool.
5
+
6
+ Codes returned dispatch to one of two fetch connectors:
7
+
8
+ * ``v<n>/<endpoint>#<field>`` (Fiscal Data) → :func:`treasury_fetch` via
9
+ ``endpoint`` (use the part before ``#``); the field name guides which
10
+ measure to read.
11
+ * ``home/<feed>`` (Treasury rate XML feeds) → :func:`treasury_rates_fetch`
12
+ via ``feed`` (use the part after ``home/``).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import logging
19
+ import os
20
+ from typing import Annotated
21
+
22
+ import pandas as pd
23
+ from parsimony.catalog import Catalog
24
+ from parsimony.connector import connector
25
+ from parsimony.result import Column, ColumnRole, OutputConfig
26
+ from pydantic import BaseModel, Field
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ PARSIMONY_TREASURY_CATALOG_URL_ENV = "PARSIMONY_TREASURY_CATALOG_URL"
31
+ _DEFAULT_CATALOG_URL = "hf://parsimony-dev/treasury"
32
+
33
+ _catalog: Catalog | None = None
34
+ _catalog_lock = asyncio.Lock()
35
+
36
+
37
+ async def _get_catalog() -> Catalog:
38
+ global _catalog
39
+ if _catalog is not None:
40
+ return _catalog
41
+ async with _catalog_lock:
42
+ if _catalog is None:
43
+ url = os.environ.get(PARSIMONY_TREASURY_CATALOG_URL_ENV, _DEFAULT_CATALOG_URL)
44
+ logger.info("loading US Treasury catalog from %s", url)
45
+ _catalog = await Catalog.from_url(url)
46
+ return _catalog
47
+
48
+
49
+ TREASURY_SEARCH_OUTPUT = OutputConfig(
50
+ columns=[
51
+ Column(name="code", role=ColumnRole.KEY, namespace="treasury"),
52
+ Column(name="title", role=ColumnRole.TITLE),
53
+ Column(name="similarity", role=ColumnRole.METADATA),
54
+ ]
55
+ )
56
+
57
+
58
+ class TreasurySearchParams(BaseModel):
59
+ """Parameters for :func:`treasury_search`."""
60
+
61
+ query: Annotated[
62
+ str,
63
+ Field(
64
+ min_length=1,
65
+ max_length=512,
66
+ description=(
67
+ "Natural-language description of the Treasury series you "
68
+ "want (e.g. 'US public debt to the penny', 'daily Treasury "
69
+ "yield curve 10-year', 'monthly Treasury statement receipts')."
70
+ ),
71
+ ),
72
+ ]
73
+ limit: int = Field(default=10, ge=1, le=50, description="Top-N results.")
74
+
75
+
76
+ @connector(
77
+ output=TREASURY_SEARCH_OUTPUT,
78
+ tags=["macro", "us", "tool"],
79
+ )
80
+ async def treasury_search(params: TreasurySearchParams) -> pd.DataFrame:
81
+ """Semantic-search the US Treasury catalog (Fiscal Data + ODM rate feeds).
82
+
83
+ Covers ~884 Fiscal Data measure fields across debt, federal accounts,
84
+ monthly Treasury statements, etc., plus ~35 entries from the 5
85
+ daily Treasury rate feeds (yield curve, real yield curve, bill rates,
86
+ long-term rate, real long-term rate).
87
+
88
+ Dispatch by code prefix: ``home/<feed>`` →
89
+ ``treasury_rates_fetch(feed=...)``; ``v<n>/<endpoint>#<field>`` →
90
+ ``treasury_fetch(endpoint=...)``.
91
+ """
92
+ catalog = await _get_catalog()
93
+ matches = await catalog.search(params.query, limit=params.limit)
94
+ return pd.DataFrame(
95
+ [
96
+ {
97
+ "code": m.code,
98
+ "title": m.title,
99
+ "similarity": round(m.similarity, 6),
100
+ }
101
+ for m in matches
102
+ ]
103
+ )
@@ -0,0 +1,83 @@
1
+ [project]
2
+ name = "parsimony-treasury"
3
+ version = "0.4.0"
4
+ description = "U.S. Treasury 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", "treasury"]
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
+ # Heavy deps for running the HF catalog publisher under scripts/. Kept
31
+ # behind an extra so `pip install parsimony-treasury` stays lean — only
32
+ # catalog maintainers ever need parsimony-core[standard-onnx] (faiss +
33
+ # onnxruntime + sentence-transformers).
34
+ publish = [
35
+ "parsimony-core[standard-onnx]>=0.4.0,<0.5",
36
+ ]
37
+ dev = [
38
+ "pytest>=9.0.3",
39
+ "pytest-asyncio>=1.3.0",
40
+ "pytest-cov>=5.0",
41
+ "respx>=0.22.0",
42
+ "ruff>=0.15.10",
43
+ "mypy>=1.10",
44
+ ]
45
+
46
+ [project.urls]
47
+ Homepage = "https://fiscaldata.treasury.gov"
48
+ Repository = "https://github.com/ockham-sh/parsimony-connectors"
49
+ Issues = "https://github.com/ockham-sh/parsimony-connectors/issues"
50
+
51
+ [project.entry-points."parsimony.providers"]
52
+ treasury = "parsimony_treasury"
53
+
54
+
55
+ [build-system]
56
+ requires = ["hatchling"]
57
+ build-backend = "hatchling.build"
58
+
59
+ [tool.hatch.build.targets.wheel]
60
+ packages = ["parsimony_treasury"]
61
+
62
+ [tool.hatch.build.targets.sdist]
63
+ include = ["parsimony_treasury", "README.md", "LICENSE", "CHANGELOG.md"]
64
+
65
+ [tool.ruff]
66
+ target-version = "py311"
67
+ line-length = 120
68
+
69
+ [tool.ruff.lint]
70
+ select = ["E", "F", "I", "UP", "B", "SIM"]
71
+
72
+ [tool.mypy]
73
+ python_version = "3.11"
74
+ warn_return_any = true
75
+ warn_unused_ignores = true
76
+ ignore_missing_imports = true
77
+
78
+ [tool.pytest.ini_options]
79
+ addopts = "--import-mode=importlib -m 'not integration'"
80
+ asyncio_mode = "auto"
81
+ markers = [
82
+ "integration: hits live APIs (may be slow, requires env vars)",
83
+ ]