python-bcb 0.3.4__tar.gz → 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.
- python_bcb-0.4.0/.claude/plans/dynamic-bubbling-glade.md +430 -0
- python_bcb-0.4.0/.claude/plans/phase2-review.md +357 -0
- python_bcb-0.4.0/.claude/plans/phase4-review.md +487 -0
- python_bcb-0.4.0/.claude/plans/recursive-sniffing-snowflake.md +59 -0
- python_bcb-0.4.0/.claude/plans/text-output.md +149 -0
- python_bcb-0.4.0/.claude/settings.json +3 -0
- python_bcb-0.4.0/.claude/settings.local.json +54 -0
- python_bcb-0.4.0/.github/workflows/dependency-audit.yml +31 -0
- python_bcb-0.4.0/.github/workflows/integration.yml +29 -0
- python_bcb-0.4.0/.github/workflows/lint.yml +28 -0
- python_bcb-0.4.0/.github/workflows/sphinx.yml +41 -0
- python_bcb-0.4.0/.github/workflows/test.yml +30 -0
- python_bcb-0.4.0/.gitignore +21 -0
- python_bcb-0.4.0/.python-version +1 -0
- python_bcb-0.4.0/CHANGELOG.md +127 -0
- python_bcb-0.4.0/CLAUDE.md +91 -0
- python_bcb-0.4.0/PKG-INFO +225 -0
- python_bcb-0.4.0/QUESTIONS.md +989 -0
- python_bcb-0.4.0/README.md +213 -0
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/__init__.py +4 -2
- python_bcb-0.4.0/bcb/currency.py +1087 -0
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/exceptions.py +22 -1
- python_bcb-0.4.0/bcb/http.py +184 -0
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/odata/__init__.py +3 -1
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/odata/api.py +284 -33
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/odata/framework.py +359 -71
- python_bcb-0.4.0/bcb/sgs/__init__.py +609 -0
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/sgs/regional_economy.py +70 -44
- {python_bcb-0.3.4 → python_bcb-0.4.0}/bcb/utils.py +2 -0
- python_bcb-0.4.0/docs/.claude/settings.local.json +10 -0
- python_bcb-0.4.0/docs/Makefile +20 -0
- python_bcb-0.4.0/docs/_static/images/ipca12m-acumulado.png +0 -0
- python_bcb-0.4.0/docs/_static/images/savefig/currency1.png +0 -0
- python_bcb-0.4.0/docs/_static/images/savefig/sgs1.png +0 -0
- python_bcb-0.4.0/docs/_static/images/savefig/taxajuros1.png +0 -0
- python_bcb-0.4.0/docs/_static/images/selic.png +0 -0
- python_bcb-0.4.0/docs/api.rst +27 -0
- python_bcb-0.4.0/docs/async.rst +275 -0
- python_bcb-0.4.0/docs/conf.py +96 -0
- python_bcb-0.4.0/docs/currency.rst +142 -0
- python_bcb-0.4.0/docs/expectativas.rst +104 -0
- python_bcb-0.4.0/docs/index.rst +120 -0
- python_bcb-0.4.0/docs/make.bat +35 -0
- python_bcb-0.4.0/docs/odata.rst +481 -0
- python_bcb-0.4.0/docs/project-health-hardening.md +134 -0
- python_bcb-0.4.0/docs/sgs.rst +128 -0
- python_bcb-0.4.0/docs/taxajuros.rst +48 -0
- python_bcb-0.4.0/examples/async_usage.py +92 -0
- python_bcb-0.4.0/examples/currency_exchange.py +70 -0
- python_bcb-0.4.0/examples/odata_query.py +86 -0
- python_bcb-0.4.0/examples/sgs_time_series.py +41 -0
- python_bcb-0.4.0/notebooks/SGS Economia Regional - Inadimpl/303/252ncia.ipynb" +771 -0
- python_bcb-0.4.0/notebooks/bcb_Expectativas_da_SELIC_(nova_API).ipynb +442 -0
- python_bcb-0.4.0/notebooks/currency PTAX.ipynb +657 -0
- python_bcb-0.4.0/notebooks/currency get EUR parity.ipynb +213 -0
- python_bcb-0.4.0/notebooks/currency get strong currencies.ipynb +242 -0
- python_bcb-0.4.0/notebooks/currency get with side.ipynb +386 -0
- python_bcb-0.4.0/notebooks/currency get.ipynb +596 -0
- python_bcb-0.4.0/notebooks/dinheiro em circula/303/247/303/243o.ipynb" +649 -0
- python_bcb-0.4.0/notebooks/expectativas IPCA anual.ipynb +224 -0
- python_bcb-0.4.0/notebooks/odata ODataAPI.ipynb +667 -0
- python_bcb-0.4.0/notebooks/odata examples.ipynb +3205 -0
- python_bcb-0.4.0/notebooks/odata taxas de juros cheque especial.ipynb +2937 -0
- python_bcb-0.4.0/notebooks/pix.odata +1 -0
- python_bcb-0.4.0/notebooks/sgs get series with join.ipynb +181 -0
- python_bcb-0.4.0/notebooks/sgs get series with period index.ipynb +135 -0
- python_bcb-0.4.0/notebooks/sgs get series.ipynb +1618 -0
- python_bcb-0.4.0/notebooks/workspace.ipynb +2662 -0
- python_bcb-0.4.0/pyproject.toml +73 -0
- python_bcb-0.4.0/tests/__init__.py +0 -0
- python_bcb-0.4.0/tests/conftest.py +275 -0
- python_bcb-0.4.0/tests/integration/__init__.py +0 -0
- python_bcb-0.4.0/tests/integration/test_currency.py +40 -0
- python_bcb-0.4.0/tests/integration/test_expectativas.py +33 -0
- python_bcb-0.4.0/tests/integration/test_sgs.py +54 -0
- python_bcb-0.4.0/tests/sgs/__init__.py +0 -0
- python_bcb-0.4.0/tests/sgs/test_regional_economy.py +91 -0
- python_bcb-0.4.0/tests/sgs/test_series.py +254 -0
- python_bcb-0.4.0/tests/test_async.py +461 -0
- python_bcb-0.4.0/tests/test_currency.py +332 -0
- python_bcb-0.4.0/tests/test_currency_negative.py +402 -0
- python_bcb-0.4.0/tests/test_exceptions.py +77 -0
- python_bcb-0.4.0/tests/test_expectativas.py +1 -0
- python_bcb-0.4.0/tests/test_http.py +198 -0
- python_bcb-0.4.0/tests/test_odata.py +926 -0
- python_bcb-0.4.0/tests/test_request_timeout.py +192 -0
- python_bcb-0.4.0/tests/test_sgs_negative.py +284 -0
- python_bcb-0.4.0/tests/test_utils.py +18 -0
- python_bcb-0.4.0/uv.lock +3402 -0
- python_bcb-0.3.4/PKG-INFO +0 -81
- python_bcb-0.3.4/README.md +0 -61
- python_bcb-0.3.4/bcb/currency.py +0 -225
- python_bcb-0.3.4/bcb/sgs/__init__.py +0 -203
- python_bcb-0.3.4/pyproject.toml +0 -58
- {python_bcb-0.3.4 → python_bcb-0.4.0}/LICENSE +0 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
# Plan: python-bcb Improvements (QUESTIONS.md)
|
|
2
|
+
|
|
3
|
+
## Context
|
|
4
|
+
50 architectural/design questions were raised in a code review of python-bcb (Brazilian Central Bank API client). The user reviewed and answered all questions. This plan organizes the actionable decisions into 8 independent implementation phases, ordered by dependency.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Architecture Decisions (Finalized)
|
|
9
|
+
|
|
10
|
+
| # | Decision |
|
|
11
|
+
|---|----------|
|
|
12
|
+
| A1 | **Shared global `httpx.Client`** in `bcb/http.py`, imported by all modules |
|
|
13
|
+
| A2 | **Fail-fast everywhere**: `_fetch_symbol_response` raises immediately; `get(["USD", "BOGUS"])` raises `CurrencyNotFoundError` on first invalid symbol |
|
|
14
|
+
| A3 | **True async via `httpx.AsyncClient`**: add `async_get()` functions in each module |
|
|
15
|
+
| A4 | **Format detection**: assert expected response structure, raise descriptive `BCBAPIError` if BCB API format changes |
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Phase 1: Shared HTTP Infrastructure
|
|
20
|
+
**Dependencies:** None — must be done first (all other phases depend on it)
|
|
21
|
+
|
|
22
|
+
**Files to create/modify:**
|
|
23
|
+
- `bcb/http.py` (NEW) — shared client module
|
|
24
|
+
- `bcb/currency.py`
|
|
25
|
+
- `bcb/sgs/__init__.py`
|
|
26
|
+
- `bcb/odata/framework.py`
|
|
27
|
+
- `pyproject.toml` — add `tenacity` dependency
|
|
28
|
+
|
|
29
|
+
**Changes:**
|
|
30
|
+
- Create `bcb/http.py` with:
|
|
31
|
+
- `_CLIENT = httpx.Client(timeout=30.0, follow_redirects=True)` (sync)
|
|
32
|
+
- `_ASYNC_CLIENT = httpx.AsyncClient(timeout=30.0, follow_redirects=True)` (async)
|
|
33
|
+
- `DEFAULT_TIMEOUT = 30.0` constant
|
|
34
|
+
- Replace all bare `httpx.get()` calls across modules with `_CLIENT.get()`
|
|
35
|
+
- Standardize timeout: all calls use `DEFAULT_TIMEOUT`, allow per-call override via `timeout=` kwarg
|
|
36
|
+
- Add `tenacity`-based `@retry` decorator for transient network errors (max 3 retries, fixed wait)
|
|
37
|
+
- Fix `_get_valid_currency_list` recursive date-rollback: add `max_rollback=30` depth guard to prevent `RecursionError`
|
|
38
|
+
- Fix `http://` URL in `_get_valid_currency_list` → `https://`
|
|
39
|
+
|
|
40
|
+
**No async API yet** — `_ASYNC_CLIENT` just defined, used in Phase 6.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Phase 2: Exception Hierarchy & Error Handling
|
|
45
|
+
**Dependencies:** Phase 1 (HTTP client standardized)
|
|
46
|
+
|
|
47
|
+
**Files:**
|
|
48
|
+
- `bcb/exceptions.py`
|
|
49
|
+
- `bcb/currency.py`
|
|
50
|
+
- `bcb/sgs/__init__.py`
|
|
51
|
+
|
|
52
|
+
**Changes:**
|
|
53
|
+
- In `bcb/exceptions.py`:
|
|
54
|
+
- Make `BCBAPIError.status_code` required (remove `Optional`)
|
|
55
|
+
- Add `BCBAPINotFoundError(BCBAPIError)` — for 404 responses
|
|
56
|
+
- Add `BCBRateLimitError(BCBAPIError)` — for 429 responses
|
|
57
|
+
- In `bcb/currency.py`:
|
|
58
|
+
- Remove `warnings.warn()` at L141 → raise `BCBAPIError` with status code
|
|
59
|
+
- Change `_fetch_symbol_response` to raise (never return `None`) — per A2 decision
|
|
60
|
+
- Remove `Optional` return type from `_fetch_symbol_response`, `_get_symbol`, `_get_symbol_text`
|
|
61
|
+
- Detect 429 → raise `BCBRateLimitError`
|
|
62
|
+
- Detect 404 → raise `BCBAPINotFoundError`
|
|
63
|
+
- In `bcb/sgs/__init__.py`:
|
|
64
|
+
- Replace bare `except Exception` (L253) with `except json.JSONDecodeError`
|
|
65
|
+
- Detect 429 → raise `BCBRateLimitError`
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## Phase 3: Cache Refactor
|
|
70
|
+
**Dependencies:** None (independent)
|
|
71
|
+
|
|
72
|
+
**Files:**
|
|
73
|
+
- `bcb/currency.py`
|
|
74
|
+
- `bcb/odata/framework.py`
|
|
75
|
+
|
|
76
|
+
**Changes:**
|
|
77
|
+
- In `bcb/currency.py`:
|
|
78
|
+
- Replace `_CACHE: dict[str, pd.DataFrame]` with a thread-safe wrapper class:
|
|
79
|
+
```python
|
|
80
|
+
class _Cache:
|
|
81
|
+
def __init__(self) -> None:
|
|
82
|
+
self._lock = threading.Lock()
|
|
83
|
+
self._data: dict[CacheKey, pd.DataFrame] = {}
|
|
84
|
+
def get(self, key): ...
|
|
85
|
+
def set(self, key, value): ...
|
|
86
|
+
def clear(self): ...
|
|
87
|
+
```
|
|
88
|
+
- Replace string keys `"TEMP_CURRENCY_ID_LIST"` / `"TEMP_FILE_CURRENCY_LIST"` with a `CacheKey` namedtuple (or `@dataclass(frozen=True)`)
|
|
89
|
+
- Make cache injectable: `get(..., cache: _Cache = _DEFAULT_CACHE)` — module-level default, but testable
|
|
90
|
+
- Update `clear_cache()` to delegate to `_DEFAULT_CACHE.clear()`
|
|
91
|
+
- In `bcb/odata/framework.py`:
|
|
92
|
+
- Add module-level `_METADATA_CACHE: dict[str, ODataMetadata] = {}` (keyed by URL)
|
|
93
|
+
- In `ODataService.__init__`: check cache before fetching `$metadata`
|
|
94
|
+
- Cache is in-memory, no TTL, lives with process
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Phase 4: Data Validation & Type Safety
|
|
99
|
+
**Dependencies:** Phases 1 and 2 (exception classes must exist)
|
|
100
|
+
|
|
101
|
+
**Files:**
|
|
102
|
+
- `bcb/currency.py`
|
|
103
|
+
- `bcb/sgs/__init__.py`
|
|
104
|
+
- `bcb/odata/api.py`
|
|
105
|
+
- `bcb/odata/framework.py`
|
|
106
|
+
- `bcb/utils.py`
|
|
107
|
+
|
|
108
|
+
**Changes:**
|
|
109
|
+
- **CSV validation** (`bcb/currency.py`):
|
|
110
|
+
- Assert CSV has exactly 8 columns after parsing; raise `BCBAPIError` if not
|
|
111
|
+
- Add explicit `errors='raise'` to `.astype()` calls for type conversion failures
|
|
112
|
+
- **Date validation** (`bcb/currency.py`, `bcb/sgs/__init__.py`):
|
|
113
|
+
- Wrap `pd.to_datetime(..., format=...)` in try/except `ValueError` → raise `BCBAPIError` with descriptive message
|
|
114
|
+
- **Type conversion validation** (`bcb/currency.py`):
|
|
115
|
+
- Wrap `.astype("int32")` and `.astype(np.float64)` conversions in try/except → raise `BCBAPIError`
|
|
116
|
+
- **SGSCode → dataclass** (`bcb/sgs/__init__.py`):
|
|
117
|
+
- Convert `SGSCode` to `@dataclass`:
|
|
118
|
+
```python
|
|
119
|
+
@dataclass(frozen=True)
|
|
120
|
+
class SGSCode:
|
|
121
|
+
value: int
|
|
122
|
+
name: str
|
|
123
|
+
|
|
124
|
+
@classmethod
|
|
125
|
+
def from_code(cls, code: int | str) -> SGSCode: ...
|
|
126
|
+
|
|
127
|
+
@classmethod
|
|
128
|
+
def from_named(cls, code: int | str, name: str) -> SGSCode: ...
|
|
129
|
+
|
|
130
|
+
def __repr__(self) -> str: ...
|
|
131
|
+
```
|
|
132
|
+
- Remove the always-true nested `if isinstance(code, int | str)` check
|
|
133
|
+
- **SGS input validation** (`bcb/sgs/__init__.py`):
|
|
134
|
+
- In `_codes()`: validate that int codes are positive; raise `ValueError` if not
|
|
135
|
+
- **TypedDict for dict returns** (`bcb/currency.py`, `bcb/sgs/__init__.py`):
|
|
136
|
+
- Define `CurrencyTextResult = TypedDict("CurrencyTextResult", {"symbol": str, ...})`
|
|
137
|
+
- Update overload declarations to use `TypedDict`
|
|
138
|
+
- **Absolute imports + annotations** (all `bcb/` files):
|
|
139
|
+
- Add `from __future__ import annotations` to every file
|
|
140
|
+
- Convert all relative imports to absolute imports (e.g., `from .exceptions` → `from bcb.exceptions`)
|
|
141
|
+
- **Format detection** (`bcb/currency.py`, `bcb/sgs/__init__.py`, `bcb/odata/framework.py`):
|
|
142
|
+
- Add `_validate_*_response()` helpers that assert expected response structure
|
|
143
|
+
- Called immediately after HTTP response parsing
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## Phase 5: API Consistency
|
|
148
|
+
**Dependencies:** Phases 1–4
|
|
149
|
+
|
|
150
|
+
**Files:**
|
|
151
|
+
- `bcb/currency.py`
|
|
152
|
+
- `bcb/sgs/__init__.py`
|
|
153
|
+
- `bcb/odata/api.py`
|
|
154
|
+
- `bcb/odata/framework.py`
|
|
155
|
+
|
|
156
|
+
**Files to change:**
|
|
157
|
+
- `bcb/currency.py` — URL construction fix only
|
|
158
|
+
- `bcb/odata/api.py` — Endpoint.get() explicit kwargs
|
|
159
|
+
- `bcb/sgs/__init__.py` — no URL changes needed (payload dict already passed via `params=` to httpx)
|
|
160
|
+
|
|
161
|
+
**Changes:**
|
|
162
|
+
|
|
163
|
+
**5A: `bcb/currency.py` — `_currency_url()` uses urlencode**
|
|
164
|
+
|
|
165
|
+
Add `from urllib.parse import urlencode` and replace inline f-string query params:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
def _currency_url(currency_id: int, start_date: DateInput, end_date: DateInput) -> str:
|
|
169
|
+
start_date = Date(start_date)
|
|
170
|
+
end_date = Date(end_date)
|
|
171
|
+
params = urlencode({
|
|
172
|
+
"method": "gerarCSVFechamentoMoedaNoPeriodo",
|
|
173
|
+
"ChkMoeda": currency_id,
|
|
174
|
+
"DATAINI": start_date.date.strftime("%d/%m/%Y"),
|
|
175
|
+
"DATAFIM": end_date.date.strftime("%d/%m/%Y"),
|
|
176
|
+
})
|
|
177
|
+
return f"https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?{params}"
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
**5B: `bcb/odata/api.py` — explicit kwargs on `Endpoint.get()`**
|
|
181
|
+
|
|
182
|
+
Add typed explicit kwargs while keeping `*args` for backwards compatibility:
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
def get(
|
|
186
|
+
self,
|
|
187
|
+
*args: Any,
|
|
188
|
+
filter: Optional[ODataPropertyFilter] = None,
|
|
189
|
+
orderby: Optional[ODataPropertyOrderBy] = None,
|
|
190
|
+
select: Optional[ODataProperty] = None,
|
|
191
|
+
limit: Optional[int] = None,
|
|
192
|
+
skip: Optional[int] = None,
|
|
193
|
+
output: str = "dataframe",
|
|
194
|
+
**kwargs: Any,
|
|
195
|
+
) -> Union[pd.DataFrame, str]:
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Apply explicit kwargs first, then process `*args` positional dispatch.
|
|
199
|
+
`filter` shadows the built-in intentionally (common pattern in Python ORMs).
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## Phase 6: Async API
|
|
204
|
+
**Dependencies:** Phase 1 (`_ASYNC_CLIENT` defined), Phases 2–5 (stable sync API)
|
|
205
|
+
|
|
206
|
+
**Files to change:**
|
|
207
|
+
- `bcb/sgs/__init__.py` — `async_get_json()` + `async_get()` with `asyncio.gather()`
|
|
208
|
+
- `bcb/currency.py` — full async internal chain + `async_get()`
|
|
209
|
+
- `bcb/odata/framework.py` — `ODataQuery.async_text()` + `ODataQuery.async_collect()`
|
|
210
|
+
- `bcb/odata/api.py` — `EndpointQuery.async_collect()` + `Endpoint.async_get()` + `Endpoint.async_query()`
|
|
211
|
+
|
|
212
|
+
`bcb/http.py` needs no changes — `_ASYNC_CLIENT` already defined.
|
|
213
|
+
|
|
214
|
+
---
|
|
215
|
+
|
|
216
|
+
### 6A: `bcb/sgs/__init__.py`
|
|
217
|
+
|
|
218
|
+
Add `import asyncio` and `from bcb.http import _ASYNC_CLIENT` to imports.
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
async def async_get_json(code, start=None, end=None, last=0) -> str:
|
|
222
|
+
url, payload = _get_url_and_payload(code, start, end, last)
|
|
223
|
+
res = await _ASYNC_CLIENT.get(url, params=payload)
|
|
224
|
+
if res.status_code == 429:
|
|
225
|
+
raise BCBRateLimitError(...)
|
|
226
|
+
if res.status_code != 200:
|
|
227
|
+
try:
|
|
228
|
+
res_json = json.loads(res.text)
|
|
229
|
+
except json.JSONDecodeError:
|
|
230
|
+
res_json = {}
|
|
231
|
+
if "error" in res_json:
|
|
232
|
+
raise SGSError(f"BCB error: {res_json['error']}")
|
|
233
|
+
elif "erro" in res_json:
|
|
234
|
+
raise SGSError(f"BCB error: {res_json['erro']['detail']}")
|
|
235
|
+
raise SGSError(f"Download error: code = {code}")
|
|
236
|
+
return str(res.text)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
async def async_get(codes, start=None, end=None, last=0, multi=True, freq=None, output="dataframe"):
|
|
240
|
+
code_list = list(_codes(codes))
|
|
241
|
+
# Concurrent HTTP requests via asyncio.gather()
|
|
242
|
+
texts = await asyncio.gather(
|
|
243
|
+
*[async_get_json(c.value, start, end, last) for c in code_list]
|
|
244
|
+
)
|
|
245
|
+
if output == "text":
|
|
246
|
+
results = {c.value: t for c, t in zip(code_list, texts)}
|
|
247
|
+
if len(results) == 1:
|
|
248
|
+
return next(iter(results.values()))
|
|
249
|
+
return results
|
|
250
|
+
dfs = [_format_df(pd.read_json(StringIO(t)), c, freq) for c, t in zip(code_list, texts)]
|
|
251
|
+
if len(dfs) == 1:
|
|
252
|
+
return dfs[0]
|
|
253
|
+
return pd.concat(dfs, axis=1) if multi else dfs
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
---
|
|
257
|
+
|
|
258
|
+
### 6B: `bcb/currency.py`
|
|
259
|
+
|
|
260
|
+
Add `import asyncio` and `from bcb.http import _ASYNC_CLIENT` to imports.
|
|
261
|
+
|
|
262
|
+
Write async versions of the internal chain — all sharing the same `_DEFAULT_CACHE`
|
|
263
|
+
(the `threading.RLock()` is safe to acquire briefly from async code since cache
|
|
264
|
+
operations are O(1) dict lookups):
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
async def _async_currency_id_list(cache=None) -> pd.DataFrame:
|
|
268
|
+
# Check cache; fetch HTML via _ASYNC_CLIENT if miss; same parse logic as sync
|
|
269
|
+
|
|
270
|
+
async def _async_get_valid_currency_list(_date, n=0, max_rollback=30):
|
|
271
|
+
# Same date rollback loop as sync, but with await _ASYNC_CLIENT.get()
|
|
272
|
+
|
|
273
|
+
async def _async_get_currency_list(cache=None) -> pd.DataFrame:
|
|
274
|
+
# Check cache; call _async_get_valid_currency_list() if miss; same parse
|
|
275
|
+
|
|
276
|
+
async def _async_get_currency_id(symbol) -> int:
|
|
277
|
+
# Concurrent: asyncio.gather(_async_currency_id_list(), _async_get_currency_list())
|
|
278
|
+
# Then same merge/lookup logic as _get_currency_id()
|
|
279
|
+
|
|
280
|
+
async def _async_fetch_symbol_response(symbol, start_date, end_date):
|
|
281
|
+
# cid = await _async_get_currency_id(symbol)
|
|
282
|
+
# res = await _ASYNC_CLIENT.get(_currency_url(cid, start_date, end_date))
|
|
283
|
+
# Same HTML error page check + HTTP status checks as sync version
|
|
284
|
+
|
|
285
|
+
async def _async_get_symbol(symbol, start_date, end_date) -> pd.DataFrame:
|
|
286
|
+
# res = await _async_fetch_symbol_response(...)
|
|
287
|
+
# Then same _validate_currency_csv / _parse_currency_dates / _parse_currency_types pipeline
|
|
288
|
+
|
|
289
|
+
async def _async_get_symbol_text(symbol, start_date, end_date) -> str:
|
|
290
|
+
# res = await _async_fetch_symbol_response(...)
|
|
291
|
+
# return res.text
|
|
292
|
+
|
|
293
|
+
async def async_get(symbols, start, end, side="ask", groupby="symbol", output="dataframe"):
|
|
294
|
+
# Concurrent requests: asyncio.gather(*[_async_get_symbol(s,...) for s in symbols])
|
|
295
|
+
# Same side/groupby post-processing as sync get()
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
---
|
|
299
|
+
|
|
300
|
+
### 6C: `bcb/odata/framework.py`
|
|
301
|
+
|
|
302
|
+
Add `from bcb.http import _ASYNC_CLIENT` to imports.
|
|
303
|
+
Add two methods to `ODataQuery`:
|
|
304
|
+
|
|
305
|
+
```python
|
|
306
|
+
async def async_text(self) -> str:
|
|
307
|
+
# Identical query-string building to text() (reuse _build_parameters())
|
|
308
|
+
# Only difference: await _ASYNC_CLIENT.get(...) instead of _CLIENT.get(...)
|
|
309
|
+
|
|
310
|
+
async def async_collect(self) -> Any:
|
|
311
|
+
return json.loads(await self.async_text())
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
316
|
+
### 6D: `bcb/odata/api.py`
|
|
317
|
+
|
|
318
|
+
Add `import asyncio` to imports.
|
|
319
|
+
|
|
320
|
+
`EndpointQuery`:
|
|
321
|
+
```python
|
|
322
|
+
async def async_collect(self, output="dataframe") -> Union[pd.DataFrame, str]:
|
|
323
|
+
if output == "text":
|
|
324
|
+
return await self.async_text()
|
|
325
|
+
raw_data = await super().async_collect()
|
|
326
|
+
data = pd.DataFrame(raw_data["value"])
|
|
327
|
+
# Same date-column logic as sync collect()
|
|
328
|
+
return data
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
`Endpoint`:
|
|
332
|
+
```python
|
|
333
|
+
def async_query(self) -> EndpointQuery:
|
|
334
|
+
return EndpointQuery(self._entity, self._url, self._date_columns)
|
|
335
|
+
|
|
336
|
+
async def async_get(self, *args, filter=None, orderby=None, select=None,
|
|
337
|
+
limit=None, skip=None, output="dataframe", verbose=False, **kwargs):
|
|
338
|
+
# Same query setup as sync get(), but final call uses:
|
|
339
|
+
# await _query.async_collect(output="text") or await _query.async_collect()
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
---
|
|
343
|
+
|
|
344
|
+
### Lifecycle note
|
|
345
|
+
|
|
346
|
+
Document in `bcb/http.py` docstring and `close_async_client()` that the
|
|
347
|
+
`_ASYNC_CLIENT` module-level singleton should be closed in long-running apps:
|
|
348
|
+
|
|
349
|
+
```python
|
|
350
|
+
await bcb.http.close_async_client() # or via asyncio context manager
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
---
|
|
354
|
+
|
|
355
|
+
## Phase 7: Testing Overhaul
|
|
356
|
+
**Dependencies:** Phases 1–5 complete (stable API)
|
|
357
|
+
|
|
358
|
+
**Files:**
|
|
359
|
+
- `tests/conftest.py`
|
|
360
|
+
- `tests/test_currency.py`
|
|
361
|
+
- `tests/test_sgs.py`
|
|
362
|
+
- `tests/test_odata.py` (new)
|
|
363
|
+
- `tests/integration/` (existing)
|
|
364
|
+
|
|
365
|
+
**Changes:**
|
|
366
|
+
- Replace hardcoded mock data constants in `conftest.py` with factory functions
|
|
367
|
+
- e.g., `make_currency_csv(symbols=["USD"], dates=1)` generates minimal valid CSV
|
|
368
|
+
- e.g., `make_sgs_response(code=1, n=1)` generates minimal valid JSON
|
|
369
|
+
- Add comprehensive negative test cases:
|
|
370
|
+
- Malformed input: bad dates, invalid symbols, non-integer SGS codes, empty symbol list
|
|
371
|
+
- API failures: 404, 429, 500 responses
|
|
372
|
+
- Network failures: connection timeout, malformed JSON, malformed CSV, wrong column count
|
|
373
|
+
- Use `pytest-httpx` to mock all HTTP calls in unit tests (eliminate all flakiness)
|
|
374
|
+
- Move all tests using live HTTP to `tests/integration/`
|
|
375
|
+
- Remove `@mark.flaky` from any test where HTTP is now properly mocked
|
|
376
|
+
- Add tests for thread-safety of cache (concurrent reads/writes)
|
|
377
|
+
- Add tests for async API (use `pytest-anyio` or `anyio`)
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
## Phase 8: Logging & Documentation
|
|
382
|
+
**Dependencies:** All previous phases (API surface is stable)
|
|
383
|
+
|
|
384
|
+
**Files:**
|
|
385
|
+
- All `bcb/` modules
|
|
386
|
+
- `README.md`
|
|
387
|
+
- `docs/` (existing Sphinx docs)
|
|
388
|
+
- `examples/` (NEW directory)
|
|
389
|
+
|
|
390
|
+
**Changes:**
|
|
391
|
+
- **Logging** (`bcb/currency.py`, `bcb/sgs/__init__.py`, `bcb/odata/framework.py`):
|
|
392
|
+
- Add `logger = logging.getLogger(__name__)` to each module
|
|
393
|
+
- `logger.debug()` before each HTTP request: URL and params (no secrets)
|
|
394
|
+
- `logger.debug()` after each response: status code and content length
|
|
395
|
+
- `logger.warning()` for retry attempts
|
|
396
|
+
- **Docstrings** (all public functions):
|
|
397
|
+
- Full docstrings: summary, Parameters, Returns, Raises sections
|
|
398
|
+
- Minimal one-line docstrings for private helpers
|
|
399
|
+
- Add `pydocstyle` to ruff config (or `ruff` rule `D` subset)
|
|
400
|
+
- **Examples** (`examples/`):
|
|
401
|
+
- `examples/sgs_time_series.py` — basic SGS usage
|
|
402
|
+
- `examples/currency_exchange.py` — currency rate fetching
|
|
403
|
+
- `examples/odata_query.py` — OData filter/orderby usage
|
|
404
|
+
- `examples/async_usage.py` — async API example
|
|
405
|
+
- **README** (`README.md`):
|
|
406
|
+
- Add "Which module to use?" decision table
|
|
407
|
+
- Add FAQ section for common use cases
|
|
408
|
+
|
|
409
|
+
---
|
|
410
|
+
|
|
411
|
+
## Summary
|
|
412
|
+
|
|
413
|
+
| Phase | Area | Key Files | Scope |
|
|
414
|
+
|-------|------|-----------|-------|
|
|
415
|
+
| 1 | Shared HTTP client | `bcb/http.py` (new), 3 existing | Foundation |
|
|
416
|
+
| 2 | Exception hierarchy | `bcb/exceptions.py`, `bcb/currency.py`, `bcb/sgs/__init__.py` | Errors |
|
|
417
|
+
| 3 | Cache refactor | `bcb/currency.py`, `bcb/odata/framework.py` | State mgmt |
|
|
418
|
+
| 4 | Data validation & types | 5 files | Type safety |
|
|
419
|
+
| 5 | API consistency | 4 files | API polish |
|
|
420
|
+
| 6 | Async API | 5 files | New feature |
|
|
421
|
+
| 7 | Testing overhaul | `tests/` | Quality |
|
|
422
|
+
| 8 | Logging & docs | All + new `examples/` | DX |
|
|
423
|
+
|
|
424
|
+
## Verification (Run After Each Phase)
|
|
425
|
+
```bash
|
|
426
|
+
uv run pytest -m "not integration"
|
|
427
|
+
uv run ruff check bcb/ tests/
|
|
428
|
+
uv run ruff format --check bcb/ tests/
|
|
429
|
+
uv run mypy bcb/
|
|
430
|
+
```
|