darwin-symbols 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 darwinalpha
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,184 @@
1
+ Metadata-Version: 2.3
2
+ Name: darwin-symbols
3
+ Version: 0.1.0
4
+ Summary: cache-backed symbol directory for CN, US and HK markets
5
+ Keywords: darwin,symbols,stocks,etf,index,cache
6
+ Author: darwinalpha
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 darwinalpha
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ Classifier: Development Status :: 3 - Alpha
29
+ Classifier: Intended Audience :: Developers
30
+ Classifier: License :: OSI Approved :: MIT License
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: Programming Language :: Python :: 3.12
33
+ Classifier: Programming Language :: Python :: 3.13
34
+ Classifier: Topic :: Office/Business :: Financial :: Investment
35
+ Requires-Dist: pandas>=2.0
36
+ Requires-Dist: pyarrow>=14
37
+ Requires-Dist: platformdirs>=4
38
+ Requires-Dist: tickflow>=0.1.24
39
+ Requires-Dist: ohlcvault[pandas]>=0.3
40
+ Requires-Dist: pytest>=8 ; extra == 'test'
41
+ Requires-Dist: pytest-cov>=5 ; extra == 'test'
42
+ Requires-Python: >=3.12
43
+ Project-URL: Homepage, https://github.com/darwinalpha/darwin-symbols
44
+ Project-URL: Documentation, https://github.com/darwinalpha/darwin-symbols/blob/main/README.md
45
+ Project-URL: Chinese Documentation, https://github.com/darwinalpha/darwin-symbols/blob/main/README.cn.md
46
+ Provides-Extra: test
47
+ Description-Content-Type: text/markdown
48
+
49
+ # darwin-symbols
50
+
51
+ [简体中文](https://github.com/darwinalpha/darwin-symbols/blob/main/README.cn.md)
52
+
53
+ > **Data notice — read before use.** This package ships **no market data**.
54
+ > On first use it downloads symbol tables from third-party providers into a
55
+ > local cache and refreshes them automatically after 7 days. The package does
56
+ > not bundle, resell, or redistribute any provider data. All data rights remain
57
+ > with the respective providers; you are responsible for complying with their
58
+ > terms of service. See [Data sources and legal notice](#5-data-sources-and-legal-notice).
59
+
60
+ A lightweight, cache-backed symbol directory for the Darwin data tools.
61
+ One flat table covers stocks, ETFs, indexes and commodities across CN, US and
62
+ HK markets — designed for `loop`-style iteration with zero per-call setup.
63
+
64
+ - **One schema, four types.** `type` distinguishes `stock` / `etf` / `index` /
65
+ `commodity`. `000300.SH` (index) and `600000.SH` (stock) share the same code
66
+ format and the same table.
67
+ - **Local cache, self-healing.** Missing or stale cache (>7 days) triggers an
68
+ automatic, cross-process-locked refresh on first call. Failed refresh falls
69
+ back to the previous cache. No key is required for the default source.
70
+ - **Static constants bundled.** A small set of stable reference codes
71
+ (domestic/international indexes, gold spots) is compiled into the library —
72
+ these are project-owned constants, not provider data.
73
+ - **No no-op setup.** No "fetch the code table first" step; callers go straight
74
+ to `get_symbols()`.
75
+
76
+ ```bash
77
+ pip install darwin-symbols
78
+ ```
79
+
80
+ Python >= 3.12.
81
+
82
+ ---
83
+
84
+ ## 1. Quick start
85
+
86
+ ```python
87
+ from darwin_symbols import get_symbols
88
+
89
+ # First call: downloads and caches if missing/stale. Later calls: cache hit.
90
+ df = get_symbols(region="cn", type="stock")
91
+ for symbol in df["symbol"]:
92
+ ... # feed directly into a fetch loop
93
+
94
+ indexes = get_symbols(type="index") # domestic + international
95
+ gold = get_symbols(type="commodity") # Au99.95, Au99.99, ...
96
+ ```
97
+
98
+ ```bash
99
+ darwin-symbols update # force refresh now
100
+ darwin-symbols status # show as_of, sources, row counts
101
+ ```
102
+
103
+ ---
104
+
105
+ ## 2. Schema
106
+
107
+ One flat `symbols` table; one row per instrument.
108
+
109
+ | Field | Meaning | Example |
110
+ | --- | --- | --- |
111
+ | `symbol` | Primary key, provider-native code | `600000.SH`, `AAPL.US`, `100.DJIA` |
112
+ | `region` | `cn` / `us` / `hk` (or provider-specific for global indexes) | `cn` |
113
+ | `exchange` | Exchange label; null when not applicable | `SSE` |
114
+ | `code` | Bare code without suffix | `600000` |
115
+ | `type` | `stock` / `etf` / `index` / `commodity` | `stock` |
116
+ | `name` | Display name | `浦发银行` |
117
+ | `currency` | `CNY` / `USD` / `HKD` | `CNY` |
118
+ | `list_date` | Reference only, nullable | `19991110` |
119
+ | `delist_date` | Reference only, nullable | null |
120
+ | `source` | `tickflow` / `ohlcvault` / `static` | `tickflow` |
121
+
122
+ `list_date` and `delist_date` are best-effort hints. `get_symbols()` does **not**
123
+ filter by them by default — silent filtering would introduce survivorship bias.
124
+ Callers decide explicitly.
125
+
126
+ ---
127
+
128
+ ## 3. Public API
129
+
130
+ | Function | Returns |
131
+ | --- | --- |
132
+ | `get_symbols(region=None, exchange=None, type=None, symbol=None)` | `DataFrame` from cache (refresh-on-miss / refresh-on-stale) |
133
+ | `lookup(raw, source=None)` | `symbol` or `None`; normalizes provider codes |
134
+ | `snapshot_info()` | `{as_of, sources, counts, cache_path}` |
135
+ | `update(force=False)` | Refresh cache; `force=True` ignores TTL |
136
+ | `get_static_codes(type=None)` | Bundled constants only, zero network |
137
+
138
+ ---
139
+
140
+ ## 4. Cache lifecycle
141
+
142
+ 1. `get_symbols()` reads `platformdirs.user_cache_dir("darwin-symbols")`.
143
+ 2. Cache missing or `as_of` older than 7 days → acquire a cross-process file
144
+ lock → re-check (avoid duplicate downloads) → download → normalize → merge
145
+ → **validate schema** → atomic write (`parquet` + `manifest.json`) → release.
146
+ 3. Fetch failure or **upstream schema change** → **no cache write**; serve stale
147
+ data with a warning (no cache → raise). The manifest's `as_of` never advances
148
+ unless the data file was actually replaced.
149
+ 4. `source` on each row makes the origin auditable.
150
+
151
+ See [design document](docs/design.md) for the full contract and test plan.
152
+
153
+ ---
154
+
155
+ ## 5. Data sources and legal notice
156
+
157
+ | Source | Role | License / terms |
158
+ | --- | --- | --- |
159
+ | [tickflow](https://github.com/tickflow-org/tickflow) | Base rows: CN/US/HK stocks and ETFs (`CN_Equity_A`, `CN_ETF`, `HK_Equity`, `US_Equity`) | SDK is MIT; free tier requires no registration. **The MIT license covers the SDK code, not API-returned data.** Data rights belong to the provider. |
160
+ | [ohlcvault](https://pypi.org/project/ohlcvault/) | Row fill (delisted instruments) and column fill (`list_date` / `delist_date`) | Subject to its own service terms. |
161
+ | Project-owned constants | Domestic/international indexes, gold spots | Static codes from the maintainer's own configuration; no third-party data involved. |
162
+
163
+ This library is a **technical client**, not a data licensor. It neither bundles
164
+ nor redistributes provider data, and makes no warranty about data accuracy,
165
+ completeness, or fitness for any purpose. You must review and comply with each
166
+ provider's current terms; terms may change, and this document will be updated
167
+ accordingly. If a provider's terms prohibit the use described here, stop using
168
+ the affected source.
169
+
170
+ ---
171
+
172
+ ## 6. Conventions
173
+
174
+ - UTF-8 + LF; source files checked by contract tests.
175
+ - Bilingual documentation and docstrings; public APIs documented.
176
+ - Fast, offline unit tests with fakes; live-source tests are opt-in and marked.
177
+ - Typed exceptions with context; secrets never enter source or docs.
178
+
179
+ ---
180
+
181
+ ## 7. License
182
+
183
+ MIT. See [LICENSE](LICENSE). The MIT license applies to this library's code only
184
+ and does not grant any rights to third-party data.
@@ -0,0 +1,136 @@
1
+ # darwin-symbols
2
+
3
+ [简体中文](https://github.com/darwinalpha/darwin-symbols/blob/main/README.cn.md)
4
+
5
+ > **Data notice — read before use.** This package ships **no market data**.
6
+ > On first use it downloads symbol tables from third-party providers into a
7
+ > local cache and refreshes them automatically after 7 days. The package does
8
+ > not bundle, resell, or redistribute any provider data. All data rights remain
9
+ > with the respective providers; you are responsible for complying with their
10
+ > terms of service. See [Data sources and legal notice](#5-data-sources-and-legal-notice).
11
+
12
+ A lightweight, cache-backed symbol directory for the Darwin data tools.
13
+ One flat table covers stocks, ETFs, indexes and commodities across CN, US and
14
+ HK markets — designed for `loop`-style iteration with zero per-call setup.
15
+
16
+ - **One schema, four types.** `type` distinguishes `stock` / `etf` / `index` /
17
+ `commodity`. `000300.SH` (index) and `600000.SH` (stock) share the same code
18
+ format and the same table.
19
+ - **Local cache, self-healing.** Missing or stale cache (>7 days) triggers an
20
+ automatic, cross-process-locked refresh on first call. Failed refresh falls
21
+ back to the previous cache. No key is required for the default source.
22
+ - **Static constants bundled.** A small set of stable reference codes
23
+ (domestic/international indexes, gold spots) is compiled into the library —
24
+ these are project-owned constants, not provider data.
25
+ - **No no-op setup.** No "fetch the code table first" step; callers go straight
26
+ to `get_symbols()`.
27
+
28
+ ```bash
29
+ pip install darwin-symbols
30
+ ```
31
+
32
+ Python >= 3.12.
33
+
34
+ ---
35
+
36
+ ## 1. Quick start
37
+
38
+ ```python
39
+ from darwin_symbols import get_symbols
40
+
41
+ # First call: downloads and caches if missing/stale. Later calls: cache hit.
42
+ df = get_symbols(region="cn", type="stock")
43
+ for symbol in df["symbol"]:
44
+ ... # feed directly into a fetch loop
45
+
46
+ indexes = get_symbols(type="index") # domestic + international
47
+ gold = get_symbols(type="commodity") # Au99.95, Au99.99, ...
48
+ ```
49
+
50
+ ```bash
51
+ darwin-symbols update # force refresh now
52
+ darwin-symbols status # show as_of, sources, row counts
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 2. Schema
58
+
59
+ One flat `symbols` table; one row per instrument.
60
+
61
+ | Field | Meaning | Example |
62
+ | --- | --- | --- |
63
+ | `symbol` | Primary key, provider-native code | `600000.SH`, `AAPL.US`, `100.DJIA` |
64
+ | `region` | `cn` / `us` / `hk` (or provider-specific for global indexes) | `cn` |
65
+ | `exchange` | Exchange label; null when not applicable | `SSE` |
66
+ | `code` | Bare code without suffix | `600000` |
67
+ | `type` | `stock` / `etf` / `index` / `commodity` | `stock` |
68
+ | `name` | Display name | `浦发银行` |
69
+ | `currency` | `CNY` / `USD` / `HKD` | `CNY` |
70
+ | `list_date` | Reference only, nullable | `19991110` |
71
+ | `delist_date` | Reference only, nullable | null |
72
+ | `source` | `tickflow` / `ohlcvault` / `static` | `tickflow` |
73
+
74
+ `list_date` and `delist_date` are best-effort hints. `get_symbols()` does **not**
75
+ filter by them by default — silent filtering would introduce survivorship bias.
76
+ Callers decide explicitly.
77
+
78
+ ---
79
+
80
+ ## 3. Public API
81
+
82
+ | Function | Returns |
83
+ | --- | --- |
84
+ | `get_symbols(region=None, exchange=None, type=None, symbol=None)` | `DataFrame` from cache (refresh-on-miss / refresh-on-stale) |
85
+ | `lookup(raw, source=None)` | `symbol` or `None`; normalizes provider codes |
86
+ | `snapshot_info()` | `{as_of, sources, counts, cache_path}` |
87
+ | `update(force=False)` | Refresh cache; `force=True` ignores TTL |
88
+ | `get_static_codes(type=None)` | Bundled constants only, zero network |
89
+
90
+ ---
91
+
92
+ ## 4. Cache lifecycle
93
+
94
+ 1. `get_symbols()` reads `platformdirs.user_cache_dir("darwin-symbols")`.
95
+ 2. Cache missing or `as_of` older than 7 days → acquire a cross-process file
96
+ lock → re-check (avoid duplicate downloads) → download → normalize → merge
97
+ → **validate schema** → atomic write (`parquet` + `manifest.json`) → release.
98
+ 3. Fetch failure or **upstream schema change** → **no cache write**; serve stale
99
+ data with a warning (no cache → raise). The manifest's `as_of` never advances
100
+ unless the data file was actually replaced.
101
+ 4. `source` on each row makes the origin auditable.
102
+
103
+ See [design document](docs/design.md) for the full contract and test plan.
104
+
105
+ ---
106
+
107
+ ## 5. Data sources and legal notice
108
+
109
+ | Source | Role | License / terms |
110
+ | --- | --- | --- |
111
+ | [tickflow](https://github.com/tickflow-org/tickflow) | Base rows: CN/US/HK stocks and ETFs (`CN_Equity_A`, `CN_ETF`, `HK_Equity`, `US_Equity`) | SDK is MIT; free tier requires no registration. **The MIT license covers the SDK code, not API-returned data.** Data rights belong to the provider. |
112
+ | [ohlcvault](https://pypi.org/project/ohlcvault/) | Row fill (delisted instruments) and column fill (`list_date` / `delist_date`) | Subject to its own service terms. |
113
+ | Project-owned constants | Domestic/international indexes, gold spots | Static codes from the maintainer's own configuration; no third-party data involved. |
114
+
115
+ This library is a **technical client**, not a data licensor. It neither bundles
116
+ nor redistributes provider data, and makes no warranty about data accuracy,
117
+ completeness, or fitness for any purpose. You must review and comply with each
118
+ provider's current terms; terms may change, and this document will be updated
119
+ accordingly. If a provider's terms prohibit the use described here, stop using
120
+ the affected source.
121
+
122
+ ---
123
+
124
+ ## 6. Conventions
125
+
126
+ - UTF-8 + LF; source files checked by contract tests.
127
+ - Bilingual documentation and docstrings; public APIs documented.
128
+ - Fast, offline unit tests with fakes; live-source tests are opt-in and marked.
129
+ - Typed exceptions with context; secrets never enter source or docs.
130
+
131
+ ---
132
+
133
+ ## 7. License
134
+
135
+ MIT. See [LICENSE](LICENSE). The MIT license applies to this library's code only
136
+ and does not grant any rights to third-party data.
@@ -0,0 +1,68 @@
1
+ [project]
2
+ name = "darwin-symbols"
3
+ version = "0.1.0"
4
+ description = "cache-backed symbol directory for CN, US and HK markets"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ keywords = [
8
+ "darwin",
9
+ "symbols",
10
+ "stocks",
11
+ "etf",
12
+ "index",
13
+ "cache",
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Office/Business :: Financial :: Investment",
23
+ ]
24
+ dependencies = [
25
+ "pandas>=2.0",
26
+ "pyarrow>=14",
27
+ "platformdirs>=4",
28
+ "tickflow>=0.1.24",
29
+ "ohlcvault[pandas]>=0.3",
30
+ ]
31
+
32
+ [project.license]
33
+ file = "LICENSE"
34
+
35
+ [[project.authors]]
36
+ name = "darwinalpha"
37
+
38
+ [project.optional-dependencies]
39
+ test = [
40
+ "pytest>=8",
41
+ "pytest-cov>=5",
42
+ ]
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/darwinalpha/darwin-symbols"
46
+ Documentation = "https://github.com/darwinalpha/darwin-symbols/blob/main/README.md"
47
+ "Chinese Documentation" = "https://github.com/darwinalpha/darwin-symbols/blob/main/README.cn.md"
48
+
49
+ [project.scripts]
50
+ darwin-symbols = "darwin_symbols.cli:main"
51
+
52
+ [build-system]
53
+ requires = ["uv_build>=0.13.10,<0.14.0"]
54
+ build-backend = "uv_build"
55
+
56
+ [tool.uv.build-backend]
57
+ module-name = "darwin_symbols"
58
+ module-root = "src"
59
+
60
+ [tool.pytest.ini_options]
61
+ pythonpath = [
62
+ "src",
63
+ ".",
64
+ ]
65
+ testpaths = ["tests"]
66
+ python_files = "test_*.py"
67
+ addopts = "-v"
68
+ markers = ["live: tests that perform a real network collection"]
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "darwin-symbols"
3
+ version = "0.1.0"
4
+ description = "cache-backed symbol directory for CN, US and HK markets"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = { file = "LICENSE" }
8
+ authors = [{ name = "darwinalpha" }]
9
+ keywords = ["darwin", "symbols", "stocks", "etf", "index", "cache"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Topic :: Office/Business :: Financial :: Investment",
18
+ ]
19
+ dependencies = [
20
+ "pandas>=2.0",
21
+ "pyarrow>=14",
22
+ "platformdirs>=4",
23
+ "tickflow>=0.1.24",
24
+ "ohlcvault[pandas]>=0.3",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest>=8", "pytest-cov>=5"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/darwinalpha/darwin-symbols"
32
+ Documentation = "https://github.com/darwinalpha/darwin-symbols/blob/main/README.md"
33
+ "Chinese Documentation" = "https://github.com/darwinalpha/darwin-symbols/blob/main/README.cn.md"
34
+
35
+ [project.scripts]
36
+ darwin-symbols = "darwin_symbols.cli:main"
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.13.10,<0.14.0"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.uv.build-backend]
43
+ module-name = "darwin_symbols"
44
+ module-root = "src"
45
+
46
+ [tool.pytest.ini_options]
47
+ pythonpath = ["src", "."]
48
+ testpaths = ["tests"]
49
+ python_files = "test_*.py"
50
+ addopts = "-v"
51
+ markers = [
52
+ "live: tests that perform a real network collection",
53
+ ]
@@ -0,0 +1,36 @@
1
+ """darwin-symbols — cache-backed symbol directory for CN, US and HK markets.
2
+
3
+ This library ships no provider data. On first use it downloads symbol tables
4
+ into a local cache; see README for the data notice and legal terms.
5
+ """
6
+
7
+ from .api import (
8
+ get_static_codes,
9
+ get_symbols,
10
+ lookup,
11
+ snapshot_info,
12
+ update,
13
+ )
14
+ from .exceptions import (
15
+ DarwinSymbolsError,
16
+ SymbolsCacheError,
17
+ SymbolsLockError,
18
+ SymbolsSchemaError,
19
+ SymbolsSourceError,
20
+ )
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = [
25
+ "get_symbols",
26
+ "lookup",
27
+ "snapshot_info",
28
+ "update",
29
+ "get_static_codes",
30
+ "DarwinSymbolsError",
31
+ "SymbolsCacheError",
32
+ "SymbolsLockError",
33
+ "SymbolsSourceError",
34
+ "SymbolsSchemaError",
35
+ "__version__",
36
+ ]
@@ -0,0 +1,127 @@
1
+ """Public API for darwin-symbols."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+
9
+ from .cache import RefreshResult, refresh, read_manifest, read_symbols
10
+ from .constants import build_static_frame
11
+ from .schema import SYMBOL_COLUMNS, validate_symbols_frame
12
+
13
+ __all__ = [
14
+ "get_symbols",
15
+ "lookup",
16
+ "snapshot_info",
17
+ "update",
18
+ "get_static_codes",
19
+ ]
20
+
21
+
22
+ def _ensure_data(*, force: bool = False, **kwargs: Any) -> RefreshResult | None:
23
+ """Return cached data, refreshing on miss/stale; None only when unusable."""
24
+ from .cache import is_stale
25
+
26
+ manifest = read_manifest()
27
+ if not force and not is_stale(manifest):
28
+ frame = read_symbols()
29
+ if frame is not None:
30
+ return RefreshResult(frame, manifest or {})
31
+
32
+ # De-duplicate static rows if a stale cache was read but refresh failed.
33
+ return refresh(force=force, **kwargs)
34
+
35
+
36
+ def _filter(
37
+ frame: pd.DataFrame,
38
+ *,
39
+ region: str | None,
40
+ exchange: str | None,
41
+ type: str | None,
42
+ symbol: str | None,
43
+ ) -> pd.DataFrame:
44
+ mask = pd.Series(True, index=frame.index)
45
+ if region is not None:
46
+ mask &= frame["region"] == region
47
+ if exchange is not None:
48
+ mask &= frame["exchange"] == exchange
49
+ if type is not None:
50
+ mask &= frame["type"] == type
51
+ if symbol is not None:
52
+ mask &= frame["symbol"] == symbol
53
+ return frame[mask][list(SYMBOL_COLUMNS)].reset_index(drop=True).copy()
54
+
55
+
56
+ def get_symbols(
57
+ region: str | None = None,
58
+ exchange: str | None = None,
59
+ type: str | None = None,
60
+ symbol: str | None = None,
61
+ *,
62
+ _tickflow_client: Any | None = None,
63
+ _ohlcvault_client: Any | None = None,
64
+ _skip_ohlcvault: bool = False,
65
+ ) -> pd.DataFrame:
66
+ """Return symbols matching filters, refreshing cache when missing or stale.
67
+
68
+ Filters are conjunctive. The returned frame is a copy; mutating it never
69
+ affects the cache.
70
+ """
71
+ kwargs: dict[str, Any] = {}
72
+ if _tickflow_client is not None:
73
+ kwargs["tickflow_client"] = _tickflow_client
74
+ if _ohlcvault_client is not None:
75
+ kwargs["ohlcvault_client"] = _ohlcvault_client
76
+ if _skip_ohlcvault:
77
+ kwargs["skip_ohlcvault"] = True
78
+
79
+ result = _ensure_data(**kwargs)
80
+ if result is None:
81
+ from .exceptions import SymbolsCacheError
82
+
83
+ raise SymbolsCacheError("no symbol data available")
84
+ return _filter(result.frame, region=region, exchange=exchange, type=type, symbol=symbol)
85
+
86
+
87
+ def lookup(raw: str, source: str | None = None) -> str | None:
88
+ """Normalise a provider code to the unified ``symbol``.
89
+
90
+ ``source`` is reserved for future multi-code mappings; currently the raw
91
+ code is matched directly against the symbol column.
92
+ """
93
+ result = _ensure_data()
94
+ if result is None:
95
+ return None
96
+ matches = result.frame[result.frame["symbol"] == raw]
97
+ if matches.empty:
98
+ return None
99
+ return str(matches.iloc[0]["symbol"])
100
+
101
+
102
+ def snapshot_info() -> dict[str, Any]:
103
+ """Report cache metadata without triggering a refresh."""
104
+ manifest = read_manifest() or {}
105
+ from .cache import CACHE_DIR
106
+
107
+ return {
108
+ "as_of": manifest.get("as_of"),
109
+ "sources": manifest.get("sources", []),
110
+ "counts": manifest.get("counts", {}),
111
+ "cache_path": str(CACHE_DIR),
112
+ }
113
+
114
+
115
+ def update(force: bool = False, **kwargs: Any) -> dict[str, Any]:
116
+ """Force or conditionally refresh the cache; return the new manifest."""
117
+ result = refresh(force=True, **kwargs) if force else refresh(**kwargs)
118
+ return result.manifest
119
+
120
+
121
+ def get_static_codes(type: str | None = None) -> pd.DataFrame:
122
+ """Return compiled-in constants only — zero network, zero cache."""
123
+ frame = build_static_frame()
124
+ if type is not None:
125
+ frame = frame[frame["type"] == type].reset_index(drop=True)
126
+ validate_symbols_frame(frame)
127
+ return frame.copy()