polefinance 0.1.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,48 @@
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ .output
14
+ .vinxi
15
+ .tanstack/**
16
+ .nitro
17
+ *.local
18
+
19
+ # Wrangler / Cloudflare
20
+ .wrangler/
21
+ .dev.vars
22
+
23
+ # Editor directories and files
24
+ .vscode/*
25
+ !.vscode/extensions.json
26
+ .idea
27
+ .DS_Store
28
+ *.suo
29
+ *.ntvs*
30
+ *.njsproj
31
+ *.sln
32
+ *.sw?
33
+ .env
34
+
35
+ # Supabase CLI local state (project ref, cached versions) — machine-local, not shared config
36
+ supabase/.temp/
37
+
38
+ # Local R2/S3 emulator data (bun run r2:local)
39
+ .s3rver-data/
40
+
41
+ # Python bytecode from the quant reference implementation. The fixtures it generates ARE
42
+ # committed — they are the contract the TS suite is tested against — but the cache is not.
43
+ __pycache__/
44
+ *.py[cod]
45
+ *.egg-info/
46
+
47
+ # Python virtualenvs (python-sdk, mcp-server) — created locally with `uv venv`, never committed.
48
+ .venv/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PoleFinance
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.5
2
+ Name: polefinance
3
+ Version: 0.1.0
4
+ Summary: Official Python client for the Pôle Finance API
5
+ Project-URL: Documentation, https://polefinance-invest.com/developers/docs
6
+ Author: PoleFinance
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: httpx<1,>=0.25
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'test'
15
+ Requires-Dist: pytest>=7; extra == 'test'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # polefinance — Python SDK for the Pôle Finance API
19
+
20
+ Typed client (sync and async) for `https://polefinance-invest.com/api/v1`.
21
+
22
+ > Status: 0.1.0, not yet published on PyPI (publication pending approval).
23
+
24
+ ## Install (from this repository)
25
+
26
+ ```bash
27
+ pip install ./python-sdk
28
+ ```
29
+
30
+ ## Quick start
31
+
32
+ 1. Create a project and an API key at https://polefinance-invest.com/developers/dashboard.
33
+ 2. `export POLEFINANCE_API_KEY="pf_live_…"` — never put the key in code.
34
+
35
+ ```python
36
+ from polefinance import PoleFinance
37
+
38
+ with PoleFinance() as client: # reads POLEFINANCE_API_KEY
39
+ page = client.instruments.list(exchange="BRVM", limit=20)
40
+ for inst in page.data:
41
+ print(inst.id, inst.name)
42
+ sonatel = client.instruments.get("BRVM:SNTS")
43
+ for inst in client.instruments.iterate(q="bank"): # follows pagination
44
+ ...
45
+ ```
46
+
47
+ Compute on your own series (nothing stored, scope `analytics:compute`):
48
+
49
+ ```python
50
+ closes = [100, 101.2, 99.8, 102.4, 103.1, 104.0]
51
+ client.technical.indicators(close=closes, indicators=[{"name": "sma", "period": 3}])
52
+ client.risk.metrics(prices=closes, periods_per_year=252, risk_free_rate=0.03)
53
+ client.optimization.portfolio({"BRVM:SNTS": snts_returns, "BRVM:ORAC": orac_returns},
54
+ method="min_variance") # max_sharpe, risk_parity, equal_weight
55
+ client.backtests.run(dates=dates, assets=[{"id": "A", "closes": closes_a}],
56
+ strategy="buy_hold", rebalance="monthly", fees=0.01)
57
+ ```
58
+
59
+ Async: `AsyncPoleFinance` has the same methods (`await`, `async for` on `iterate`).
60
+
61
+ ## Errors
62
+
63
+ `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404),
64
+ `RateLimitError` (429, `.retry_after`), `APIError` (others), `APIConnectionError` (network).
65
+ Each carries `.code`, `.message`, `.request_id`.
66
+
67
+ ## Behaviour
68
+
69
+ - Timeout 15 s (`timeout=`), up to 2 retries (`max_retries=`) on network errors, 502/503/504 and
70
+ 429 with `Retry-After`. A daily-quota 429 is not retried. v1 calls are GETs or pure computations, so retries are safe.
71
+ - `market_data.quotes()` currently raises `PermissionDeniedError(code="market_data_not_available")`.
72
+
73
+ ## Develop
74
+
75
+ ```bash
76
+ pip install -e ".[test]" && pytest
77
+ ```
@@ -0,0 +1,60 @@
1
+ # polefinance — Python SDK for the Pôle Finance API
2
+
3
+ Typed client (sync and async) for `https://polefinance-invest.com/api/v1`.
4
+
5
+ > Status: 0.1.0, not yet published on PyPI (publication pending approval).
6
+
7
+ ## Install (from this repository)
8
+
9
+ ```bash
10
+ pip install ./python-sdk
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ 1. Create a project and an API key at https://polefinance-invest.com/developers/dashboard.
16
+ 2. `export POLEFINANCE_API_KEY="pf_live_…"` — never put the key in code.
17
+
18
+ ```python
19
+ from polefinance import PoleFinance
20
+
21
+ with PoleFinance() as client: # reads POLEFINANCE_API_KEY
22
+ page = client.instruments.list(exchange="BRVM", limit=20)
23
+ for inst in page.data:
24
+ print(inst.id, inst.name)
25
+ sonatel = client.instruments.get("BRVM:SNTS")
26
+ for inst in client.instruments.iterate(q="bank"): # follows pagination
27
+ ...
28
+ ```
29
+
30
+ Compute on your own series (nothing stored, scope `analytics:compute`):
31
+
32
+ ```python
33
+ closes = [100, 101.2, 99.8, 102.4, 103.1, 104.0]
34
+ client.technical.indicators(close=closes, indicators=[{"name": "sma", "period": 3}])
35
+ client.risk.metrics(prices=closes, periods_per_year=252, risk_free_rate=0.03)
36
+ client.optimization.portfolio({"BRVM:SNTS": snts_returns, "BRVM:ORAC": orac_returns},
37
+ method="min_variance") # max_sharpe, risk_parity, equal_weight
38
+ client.backtests.run(dates=dates, assets=[{"id": "A", "closes": closes_a}],
39
+ strategy="buy_hold", rebalance="monthly", fees=0.01)
40
+ ```
41
+
42
+ Async: `AsyncPoleFinance` has the same methods (`await`, `async for` on `iterate`).
43
+
44
+ ## Errors
45
+
46
+ `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404),
47
+ `RateLimitError` (429, `.retry_after`), `APIError` (others), `APIConnectionError` (network).
48
+ Each carries `.code`, `.message`, `.request_id`.
49
+
50
+ ## Behaviour
51
+
52
+ - Timeout 15 s (`timeout=`), up to 2 retries (`max_retries=`) on network errors, 502/503/504 and
53
+ 429 with `Retry-After`. A daily-quota 429 is not retried. v1 calls are GETs or pure computations, so retries are safe.
54
+ - `market_data.quotes()` currently raises `PermissionDeniedError(code="market_data_not_available")`.
55
+
56
+ ## Develop
57
+
58
+ ```bash
59
+ pip install -e ".[test]" && pytest
60
+ ```
@@ -0,0 +1,16 @@
1
+ """Quick start — run with: POLEFINANCE_API_KEY=pf_live_… python examples/quickstart.py"""
2
+ from polefinance import PoleFinance, PermissionDeniedError
3
+
4
+ with PoleFinance() as client:
5
+ for ex in client.exchanges.list():
6
+ print(f"{ex.id:<9} {ex.instrument_count:>6} instruments ({ex.name})")
7
+
8
+ page = client.instruments.list(exchange="BRVM", limit=10)
9
+ print(f"\nBRVM — {page.total} instruments, first {len(page.data)}:")
10
+ for inst in page.data:
11
+ print(f" {inst.id:<12} {inst.name} [{inst.currency}]")
12
+
13
+ try:
14
+ client.market_data.quotes(["BRVM:SNTS"])
15
+ except PermissionDeniedError as e:
16
+ print(f"\nQuotes: {e.code}")
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "polefinance"
7
+ version = "0.1.0"
8
+ description = "Official Python client for the Pôle Finance API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "PoleFinance" }]
13
+ dependencies = ["httpx>=0.25,<1"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed"]
15
+
16
+ [project.optional-dependencies]
17
+ test = ["pytest>=7", "pytest-asyncio>=0.21"]
18
+
19
+ [project.urls]
20
+ Documentation = "https://polefinance-invest.com/developers/docs"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/polefinance"]
24
+
25
+ [tool.pytest.ini_options]
26
+ asyncio_mode = "auto"
27
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,30 @@
1
+ """Official Python client for the Pôle Finance API."""
2
+
3
+ from ._client import AsyncPoleFinance, PoleFinance
4
+ from .errors import (
5
+ APIConnectionError,
6
+ APIError,
7
+ AuthenticationError,
8
+ NotFoundError,
9
+ PermissionDeniedError,
10
+ PoleFinanceError,
11
+ RateLimitError,
12
+ )
13
+ from .models import Exchange, Instrument, Page, Quote
14
+
15
+ __version__ = "0.1.0"
16
+ __all__ = [
17
+ "PoleFinance",
18
+ "AsyncPoleFinance",
19
+ "Instrument",
20
+ "Exchange",
21
+ "Quote",
22
+ "Page",
23
+ "PoleFinanceError",
24
+ "APIError",
25
+ "APIConnectionError",
26
+ "AuthenticationError",
27
+ "PermissionDeniedError",
28
+ "NotFoundError",
29
+ "RateLimitError",
30
+ ]
@@ -0,0 +1,323 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ import random
6
+ import time
7
+ from typing import Any, AsyncIterator, Dict, Iterable, Iterator, List, Optional
8
+
9
+ import httpx
10
+
11
+ from .errors import APIConnectionError, PoleFinanceError, RateLimitError, error_for
12
+ from .models import Exchange, Instrument, Page, Quote
13
+
14
+ DEFAULT_BASE_URL = "https://polefinance-invest.com/api/v1"
15
+ __version__ = "0.1.0"
16
+
17
+ # Only these are retried: the request never reached the handler (connection error) or the API
18
+ # asked us to come back (429 with Retry-After) or failed transiently (502/503/504). v1 calls are
19
+ # GETs or pure computations (POST, nothing stored), so a retry can never double an action.
20
+ RETRY_STATUSES = {429, 502, 503, 504}
21
+
22
+
23
+ def _resolve_key(api_key: Optional[str]) -> str:
24
+ key = api_key or os.environ.get("POLEFINANCE_API_KEY")
25
+ if not key:
26
+ raise PoleFinanceError("No API key: pass api_key= or set POLEFINANCE_API_KEY.")
27
+ return key
28
+
29
+
30
+ def _params(**kw: Any) -> Dict[str, Any]:
31
+ return {k: v for k, v in kw.items() if v is not None}
32
+
33
+
34
+ def _backoff(attempt: int, retry_after: Optional[float]) -> float:
35
+ if retry_after is not None:
36
+ return min(retry_after, 60.0)
37
+ return min(0.5 * 2**attempt, 8.0) * (0.5 + random.random() / 2)
38
+
39
+
40
+ def _parse(resp: httpx.Response) -> Any:
41
+ try:
42
+ body = resp.json()
43
+ except ValueError:
44
+ body = None
45
+ if resp.status_code >= 400:
46
+ ra = resp.headers.get("retry-after")
47
+ raise error_for(resp.status_code, body, resp.headers.get("x-request-id"), float(ra) if ra else None)
48
+ return body
49
+
50
+
51
+ def _page(body: dict, model) -> Page:
52
+ meta = body.get("meta", {})
53
+ return Page(
54
+ data=[model.from_json(d) for d in body.get("data", [])],
55
+ total=meta.get("total", 0),
56
+ next_cursor=meta.get("next_cursor"),
57
+ request_id=meta.get("request_id"),
58
+ )
59
+
60
+
61
+ class _Base:
62
+ def __init__(self, api_key: Optional[str], base_url: Optional[str], timeout: float, max_retries: int):
63
+ self._key = _resolve_key(api_key)
64
+ self.base_url = (base_url or os.environ.get("POLEFINANCE_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
65
+ self.timeout = timeout
66
+ self.max_retries = max_retries
67
+
68
+ @property
69
+ def _headers(self) -> Dict[str, str]:
70
+ return {"Authorization": f"Bearer {self._key}", "User-Agent": f"polefinance-python/{__version__}"}
71
+
72
+ def __repr__(self) -> str: # never print the key
73
+ return f"{type(self).__name__}(base_url={self.base_url!r})"
74
+
75
+
76
+ class PoleFinance(_Base):
77
+ """Synchronous client.
78
+
79
+ >>> client = PoleFinance() # reads POLEFINANCE_API_KEY
80
+ >>> client.instruments.get("BRVM:SNTS").name
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ api_key: Optional[str] = None,
86
+ *,
87
+ base_url: Optional[str] = None,
88
+ timeout: float = 15.0,
89
+ max_retries: int = 2,
90
+ http_client: Optional[httpx.Client] = None,
91
+ ):
92
+ super().__init__(api_key, base_url, timeout, max_retries)
93
+ self._http = http_client or httpx.Client(timeout=timeout)
94
+ self.instruments = _Instruments(self)
95
+ self.exchanges = _Exchanges(self)
96
+ self.market_data = _MarketData(self)
97
+ self.technical = _Compute(self, "/technical/indicators")
98
+ self.risk = _Compute(self, "/risk/metrics")
99
+ self.optimization = _Optimization(self)
100
+ self.backtests = _Compute(self, "/backtests/run")
101
+
102
+ def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
103
+ return self._request("GET", path, params=params)
104
+
105
+ def _post(self, path: str, body: Dict[str, Any]) -> Any:
106
+ return self._request("POST", path, json=body)
107
+
108
+ def _request(self, method: str, path: str, **kw: Any) -> Any:
109
+ for attempt in range(self.max_retries + 1):
110
+ try:
111
+ resp = self._http.request(method, self.base_url + path, headers=self._headers, **kw)
112
+ except httpx.HTTPError as e:
113
+ if attempt == self.max_retries:
114
+ raise APIConnectionError(str(e)) from e
115
+ time.sleep(_backoff(attempt, None))
116
+ continue
117
+ if resp.status_code in RETRY_STATUSES and attempt < self.max_retries:
118
+ ra = resp.headers.get("retry-after")
119
+ if resp.status_code == 429 and not ra:
120
+ return _parse(resp) # daily quota: retrying won't help
121
+ time.sleep(_backoff(attempt, float(ra) if ra else None))
122
+ continue
123
+ return _parse(resp)
124
+ raise PoleFinanceError("unreachable") # pragma: no cover
125
+
126
+ def close(self) -> None:
127
+ self._http.close()
128
+
129
+ def __enter__(self) -> "PoleFinance":
130
+ return self
131
+
132
+ def __exit__(self, *exc: object) -> None:
133
+ self.close()
134
+
135
+
136
+ class AsyncPoleFinance(_Base):
137
+ """Asynchronous client — same methods as PoleFinance, awaited."""
138
+
139
+ def __init__(
140
+ self,
141
+ api_key: Optional[str] = None,
142
+ *,
143
+ base_url: Optional[str] = None,
144
+ timeout: float = 15.0,
145
+ max_retries: int = 2,
146
+ http_client: Optional[httpx.AsyncClient] = None,
147
+ ):
148
+ super().__init__(api_key, base_url, timeout, max_retries)
149
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
150
+ self.instruments = _AsyncInstruments(self)
151
+ self.exchanges = _AsyncExchanges(self)
152
+ self.market_data = _AsyncMarketData(self)
153
+ self.technical = _AsyncCompute(self, "/technical/indicators")
154
+ self.risk = _AsyncCompute(self, "/risk/metrics")
155
+ self.optimization = _AsyncOptimization(self)
156
+ self.backtests = _AsyncCompute(self, "/backtests/run")
157
+
158
+ async def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
159
+ return await self._request("GET", path, params=params)
160
+
161
+ async def _post(self, path: str, body: Dict[str, Any]) -> Any:
162
+ return await self._request("POST", path, json=body)
163
+
164
+ async def _request(self, method: str, path: str, **kw: Any) -> Any:
165
+ for attempt in range(self.max_retries + 1):
166
+ try:
167
+ resp = await self._http.request(method, self.base_url + path, headers=self._headers, **kw)
168
+ except httpx.HTTPError as e:
169
+ if attempt == self.max_retries:
170
+ raise APIConnectionError(str(e)) from e
171
+ await asyncio.sleep(_backoff(attempt, None))
172
+ continue
173
+ if resp.status_code in RETRY_STATUSES and attempt < self.max_retries:
174
+ ra = resp.headers.get("retry-after")
175
+ if resp.status_code == 429 and not ra:
176
+ return _parse(resp)
177
+ await asyncio.sleep(_backoff(attempt, float(ra) if ra else None))
178
+ continue
179
+ return _parse(resp)
180
+ raise PoleFinanceError("unreachable") # pragma: no cover
181
+
182
+ async def aclose(self) -> None:
183
+ await self._http.aclose()
184
+
185
+ async def __aenter__(self) -> "AsyncPoleFinance":
186
+ return self
187
+
188
+ async def __aexit__(self, *exc: object) -> None:
189
+ await self.aclose()
190
+
191
+
192
+ class _Instruments:
193
+ def __init__(self, c: PoleFinance):
194
+ self._c = c
195
+
196
+ def list(self, *, exchange: Optional[str] = None, q: Optional[str] = None, limit: int = 50, cursor: Optional[str] = None) -> Page[Instrument]:
197
+ return _page(self._c._get("/instruments", _params(exchange=exchange, q=q, limit=limit, cursor=cursor)), Instrument)
198
+
199
+ def search(self, q: str, *, exchange: Optional[str] = None, limit: int = 20) -> List[Instrument]:
200
+ return self.list(q=q, exchange=exchange, limit=limit).data
201
+
202
+ def iterate(self, *, exchange: Optional[str] = None, q: Optional[str] = None, page_size: int = 100) -> Iterator[Instrument]:
203
+ """Every matching instrument, following next_cursor."""
204
+ cursor = None
205
+ while True:
206
+ page = self.list(exchange=exchange, q=q, limit=page_size, cursor=cursor)
207
+ yield from page.data
208
+ if not page.next_cursor:
209
+ return
210
+ cursor = page.next_cursor
211
+
212
+ def get(self, instrument_id: str) -> Instrument:
213
+ return Instrument.from_json(self._c._get(f"/instruments/{instrument_id}")["data"])
214
+
215
+
216
+ class _Exchanges:
217
+ def __init__(self, c: PoleFinance):
218
+ self._c = c
219
+
220
+ def list(self) -> List[Exchange]:
221
+ return [Exchange.from_json(d) for d in self._c._get("/exchanges")["data"]]
222
+
223
+
224
+ class _MarketData:
225
+ def __init__(self, c: PoleFinance):
226
+ self._c = c
227
+
228
+ def quotes(self, instrument_ids: Iterable[str]) -> List[Quote]:
229
+ """Delayed quotes. Raises PermissionDeniedError(code="market_data_not_available") while disabled."""
230
+ ids = ",".join(instrument_ids)
231
+ return [Quote.from_json(d) for d in self._c._get("/market-data/quotes", {"instruments": ids})["data"]]
232
+
233
+
234
+ class _AsyncInstruments:
235
+ def __init__(self, c: AsyncPoleFinance):
236
+ self._c = c
237
+
238
+ async def list(self, *, exchange: Optional[str] = None, q: Optional[str] = None, limit: int = 50, cursor: Optional[str] = None) -> Page[Instrument]:
239
+ return _page(await self._c._get("/instruments", _params(exchange=exchange, q=q, limit=limit, cursor=cursor)), Instrument)
240
+
241
+ async def search(self, q: str, *, exchange: Optional[str] = None, limit: int = 20) -> List[Instrument]:
242
+ return (await self.list(q=q, exchange=exchange, limit=limit)).data
243
+
244
+ async def iterate(self, *, exchange: Optional[str] = None, q: Optional[str] = None, page_size: int = 100) -> AsyncIterator[Instrument]:
245
+ cursor = None
246
+ while True:
247
+ page = await self.list(exchange=exchange, q=q, limit=page_size, cursor=cursor)
248
+ for item in page.data:
249
+ yield item
250
+ if not page.next_cursor:
251
+ return
252
+ cursor = page.next_cursor
253
+
254
+ async def get(self, instrument_id: str) -> Instrument:
255
+ return Instrument.from_json((await self._c._get(f"/instruments/{instrument_id}"))["data"])
256
+
257
+
258
+ class _AsyncExchanges:
259
+ def __init__(self, c: AsyncPoleFinance):
260
+ self._c = c
261
+
262
+ async def list(self) -> List[Exchange]:
263
+ return [Exchange.from_json(d) for d in (await self._c._get("/exchanges"))["data"]]
264
+
265
+
266
+ class _AsyncMarketData:
267
+ def __init__(self, c: AsyncPoleFinance):
268
+ self._c = c
269
+
270
+ async def quotes(self, instrument_ids: Iterable[str]) -> List[Quote]:
271
+ ids = ",".join(instrument_ids)
272
+ return [Quote.from_json(d) for d in (await self._c._get("/market-data/quotes", {"instruments": ids}))["data"]]
273
+
274
+
275
+ def _assets(returns_by_id: Dict[str, List[float]]) -> List[Dict[str, Any]]:
276
+ return [{"id": k, "returns": list(v)} for k, v in returns_by_id.items()]
277
+
278
+
279
+ class _Compute:
280
+ """client.technical.indicators(...) / client.risk.metrics(...) — returns the `data` dict."""
281
+
282
+ def __init__(self, c: PoleFinance, path: str):
283
+ self._c, self._path = c, path
284
+
285
+ def __call__(self, **body: Any) -> Dict[str, Any]:
286
+ return self._c._post(self._path, _params(**body))["data"]
287
+
288
+ indicators = __call__
289
+ metrics = __call__
290
+ run = __call__
291
+
292
+
293
+ class _Optimization:
294
+ def __init__(self, c: PoleFinance):
295
+ self._c = c
296
+
297
+ def portfolio(self, returns_by_id: Dict[str, List[float]], *, method: str = "min_variance", periods_per_year: Optional[int] = None, risk_free_rate: Optional[float] = None) -> Dict[str, Any]:
298
+ body = _params(method=method, assets=_assets(returns_by_id), periods_per_year=periods_per_year, risk_free_rate=risk_free_rate)
299
+ return self._c._post("/optimization/portfolio", body)["data"]
300
+
301
+
302
+ class _AsyncCompute:
303
+ def __init__(self, c: AsyncPoleFinance, path: str):
304
+ self._c, self._path = c, path
305
+
306
+ async def __call__(self, **body: Any) -> Dict[str, Any]:
307
+ return (await self._c._post(self._path, _params(**body)))["data"]
308
+
309
+ indicators = __call__
310
+ metrics = __call__
311
+ run = __call__
312
+
313
+
314
+ class _AsyncOptimization:
315
+ def __init__(self, c: AsyncPoleFinance):
316
+ self._c = c
317
+
318
+ async def portfolio(self, returns_by_id: Dict[str, List[float]], *, method: str = "min_variance", periods_per_year: Optional[int] = None, risk_free_rate: Optional[float] = None) -> Dict[str, Any]:
319
+ body = _params(method=method, assets=_assets(returns_by_id), periods_per_year=periods_per_year, risk_free_rate=risk_free_rate)
320
+ return (await self._c._post("/optimization/portfolio", body))["data"]
321
+
322
+
323
+ __all__ = ["PoleFinance", "AsyncPoleFinance", "RateLimitError"]
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class PoleFinanceError(Exception):
7
+ """Base class for every error raised by this package."""
8
+
9
+
10
+ class APIConnectionError(PoleFinanceError):
11
+ """The API could not be reached (network error or timeout)."""
12
+
13
+
14
+ class APIError(PoleFinanceError):
15
+ """The API answered with an error status."""
16
+
17
+ def __init__(self, status: int, code: str, message: str, request_id: Optional[str] = None):
18
+ super().__init__(f"{status} {code}: {message}" + (f" (request_id={request_id})" if request_id else ""))
19
+ self.status = status
20
+ self.code = code
21
+ self.message = message
22
+ self.request_id = request_id
23
+
24
+
25
+ class AuthenticationError(APIError):
26
+ """401 — missing, invalid, revoked or expired key."""
27
+
28
+
29
+ class PermissionDeniedError(APIError):
30
+ """403 — the key lacks a scope, its project is archived, or the service is not available."""
31
+
32
+
33
+ class NotFoundError(APIError):
34
+ """404 — unknown instrument or endpoint."""
35
+
36
+
37
+ class RateLimitError(APIError):
38
+ """429 — per-minute limit or daily quota reached."""
39
+
40
+ def __init__(self, *args, retry_after: Optional[float] = None, **kwargs):
41
+ super().__init__(*args, **kwargs)
42
+ self.retry_after = retry_after
43
+
44
+
45
+ def error_for(status: int, body: object, request_id: Optional[str], retry_after: Optional[float]) -> APIError:
46
+ err = body.get("error", {}) if isinstance(body, dict) else {}
47
+ code = str(err.get("code", "http_error"))
48
+ message = str(err.get("message", f"HTTP {status}"))
49
+ rid = err.get("request_id") or request_id
50
+ if status == 401:
51
+ return AuthenticationError(status, code, message, rid)
52
+ if status == 403:
53
+ return PermissionDeniedError(status, code, message, rid)
54
+ if status == 404:
55
+ return NotFoundError(status, code, message, rid)
56
+ if status == 429:
57
+ return RateLimitError(status, code, message, rid, retry_after=retry_after)
58
+ return APIError(status, code, message, rid)
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Generic, List, Optional, TypeVar
5
+
6
+ T = TypeVar("T")
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Instrument:
11
+ id: str
12
+ symbol: str
13
+ name: str
14
+ exchange: str
15
+ currency: str
16
+ instrument_type: str
17
+ country: Optional[str] = None
18
+ sector: Optional[str] = None
19
+ listing_status: str = "active"
20
+
21
+ @classmethod
22
+ def from_json(cls, d: dict) -> "Instrument":
23
+ return cls(**{k: d.get(k) for k in cls.__dataclass_fields__ if k in d})
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Exchange:
28
+ id: str
29
+ name: str
30
+ country: Optional[str]
31
+ currency: str
32
+ instrument_count: int
33
+
34
+ @classmethod
35
+ def from_json(cls, d: dict) -> "Exchange":
36
+ return cls(**{k: d.get(k) for k in cls.__dataclass_fields__})
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Quote:
41
+ instrument_id: str
42
+ price: Optional[float]
43
+ change_24h_pct: Optional[float]
44
+ volume: Optional[float]
45
+ provider: str
46
+ as_of: str
47
+ data_type: str # always "delayed" — never real-time
48
+
49
+ @classmethod
50
+ def from_json(cls, d: dict) -> "Quote":
51
+ return cls(**{k: d.get(k) for k in cls.__dataclass_fields__})
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Page(Generic[T]):
56
+ data: List[T]
57
+ total: int
58
+ next_cursor: Optional[str]
59
+ request_id: Optional[str] = None
File without changes
@@ -0,0 +1,130 @@
1
+ import httpx
2
+ import pytest
3
+
4
+ from polefinance import (
5
+ AsyncPoleFinance,
6
+ AuthenticationError,
7
+ NotFoundError,
8
+ PermissionDeniedError,
9
+ PoleFinance,
10
+ PoleFinanceError,
11
+ RateLimitError,
12
+ )
13
+
14
+ KEY = "pf_live_ABCDEFGH_" + "x" * 40
15
+ ROWS = [
16
+ {"id": f"BRVM:S{i}", "symbol": f"S{i}", "name": f"Stock {i}", "exchange": "BRVM", "currency": "XOF",
17
+ "instrument_type": "stock", "country": "CI", "sector": None, "listing_status": "active"}
18
+ for i in range(5)
19
+ ]
20
+
21
+
22
+ def api(request: httpx.Request) -> httpx.Response:
23
+ assert request.headers["authorization"] == f"Bearer {KEY}"
24
+ p = request.url.path
25
+ if p.endswith("/instruments"):
26
+ off = int(request.url.params.get("cursor") or 0)
27
+ lim = int(request.url.params.get("limit", 50))
28
+ nxt = str(off + lim) if off + lim < len(ROWS) else None
29
+ return httpx.Response(200, json={"data": ROWS[off:off + lim], "meta": {"total": len(ROWS), "next_cursor": nxt, "request_id": "req_1"}})
30
+ if p.endswith("/instruments/BRVM:S1"):
31
+ return httpx.Response(200, json={"data": ROWS[1], "meta": {}})
32
+ if p.endswith("/exchanges"):
33
+ return httpx.Response(200, json={"data": [{"id": "BRVM", "name": "BRVM", "country": "UEMOA", "currency": "XOF", "instrument_count": 5}]})
34
+ if p.endswith("/market-data/quotes"):
35
+ return httpx.Response(403, json={"error": {"code": "market_data_not_available", "message": "pending", "request_id": "req_q"}})
36
+ return httpx.Response(404, json={"error": {"code": "not_found", "message": "no", "request_id": "req_404"}})
37
+
38
+
39
+ def client(handler=api, **kw):
40
+ return PoleFinance(KEY, base_url="https://x.test/api/v1", http_client=httpx.Client(transport=httpx.MockTransport(handler)), **kw)
41
+
42
+
43
+ def test_list_get_and_paginate():
44
+ c = client()
45
+ page = c.instruments.list(exchange="BRVM", limit=2)
46
+ assert [i.id for i in page.data] == ["BRVM:S0", "BRVM:S1"]
47
+ assert page.total == 5 and page.next_cursor == "2"
48
+ assert [i.symbol for i in c.instruments.iterate(page_size=2)] == [f"S{i}" for i in range(5)]
49
+ assert c.instruments.get("BRVM:S1").name == "Stock 1"
50
+ assert c.exchanges.list()[0].instrument_count == 5
51
+
52
+
53
+ def test_errors_are_typed():
54
+ c = client()
55
+ with pytest.raises(NotFoundError) as e:
56
+ c.instruments.get("BRVM:NOPE")
57
+ assert e.value.request_id == "req_404"
58
+ with pytest.raises(PermissionDeniedError) as e:
59
+ c.market_data.quotes(["BRVM:S1"])
60
+ assert e.value.code == "market_data_not_available"
61
+ bad = client(lambda r: httpx.Response(401, json={"error": {"code": "invalid_api_key", "message": "x"}}))
62
+ with pytest.raises(AuthenticationError):
63
+ bad.exchanges.list()
64
+
65
+
66
+ def test_retries_429_with_retry_after_then_succeeds(monkeypatch):
67
+ monkeypatch.setattr("time.sleep", lambda s: None)
68
+ calls = {"n": 0}
69
+
70
+ def flaky(r):
71
+ calls["n"] += 1
72
+ if calls["n"] == 1:
73
+ return httpx.Response(429, headers={"retry-after": "1"}, json={"error": {"code": "rate_limited", "message": "slow"}})
74
+ return api(r)
75
+
76
+ assert len(client(flaky).exchanges.list()) == 1
77
+ assert calls["n"] == 2
78
+
79
+
80
+ def test_daily_quota_is_not_retried():
81
+ calls = {"n": 0}
82
+
83
+ def quota(r):
84
+ calls["n"] += 1
85
+ return httpx.Response(429, json={"error": {"code": "quota_exceeded", "message": "done"}})
86
+
87
+ with pytest.raises(RateLimitError):
88
+ client(quota).exchanges.list()
89
+ assert calls["n"] == 1
90
+
91
+
92
+ def test_key_from_env_and_never_in_repr(monkeypatch):
93
+ monkeypatch.delenv("POLEFINANCE_API_KEY", raising=False)
94
+ with pytest.raises(PoleFinanceError):
95
+ PoleFinance()
96
+ monkeypatch.setenv("POLEFINANCE_API_KEY", KEY)
97
+ c = PoleFinance()
98
+ assert KEY not in repr(c)
99
+
100
+
101
+ async def test_async_client():
102
+ c = AsyncPoleFinance(KEY, base_url="https://x.test/api/v1", http_client=httpx.AsyncClient(transport=httpx.MockTransport(api)))
103
+ async with c:
104
+ assert (await c.instruments.get("BRVM:S1")).symbol == "S1"
105
+ ids = [i.id async for i in c.instruments.iterate(page_size=3)]
106
+ assert len(ids) == 5
107
+
108
+
109
+ def test_compute_endpoints_post_json():
110
+ import json as _json
111
+
112
+ seen = []
113
+
114
+ def h(r):
115
+ seen.append((r.method, r.url.path, _json.loads(r.content)))
116
+ return httpx.Response(200, json={"data": {"ok": True}})
117
+
118
+ c = client(h)
119
+ assert c.technical.indicators(close=[1, 2, 3], indicators=[{"name": "sma", "period": 2}]) == {"ok": True}
120
+ c.risk.metrics(prices=[100, 101, 102], risk_free_rate=0.03)
121
+ c.optimization.portfolio({"BRVM:SNTS": [0.01, 0.02], "BRVM:ORAC": [0.0, 0.01]}, method="risk_parity")
122
+ c.backtests.run(dates=["2025-01-02"], assets=[{"id": "A", "closes": [1.0]}], strategy="buy_hold")
123
+ assert seen.pop()[:2] == ("POST", "/api/v1/backtests/run")
124
+ assert [s[:2] for s in seen] == [
125
+ ("POST", "/api/v1/technical/indicators"),
126
+ ("POST", "/api/v1/risk/metrics"),
127
+ ("POST", "/api/v1/optimization/portfolio"),
128
+ ]
129
+ assert seen[1][2] == {"prices": [100, 101, 102], "risk_free_rate": 0.03}
130
+ assert seen[2][2]["assets"][0] == {"id": "BRVM:SNTS", "returns": [0.01, 0.02]}