stockscreen-mcp 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 @@
1
+ dist/
@@ -0,0 +1,203 @@
1
+ Copyright 2026 xang1234
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2026 xang1234
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.5
2
+ Name: stockscreen-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for daily stock screens (Minervini, CANSLIM, VCP and more), RS ratings, market breadth and IBD-style group rankings across 12 markets. No API keys or setup.
5
+ Project-URL: Homepage, https://github.com/xang1234/stock-screener/tree/main/stockscreen-mcp
6
+ Project-URL: Repository, https://github.com/xang1234/stock-screener
7
+ Project-URL: Issues, https://github.com/xang1234/stock-screener/issues
8
+ Project-URL: Live demo, https://xang1234.github.io/stock-screener/
9
+ Author: David Ten
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: canslim,market-breadth,mcp,minervini,relative-strength,stock-screener,trading
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Office/Business :: Financial :: Investment
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: mcp<3,>=2.3
19
+ Description-Content-Type: text/markdown
20
+
21
+ # stockscreen-mcp
22
+
23
+ <!-- mcp-name: io.github.xang1234/stockscreen-mcp -->
24
+
25
+ Daily stock screens, relative-strength ratings, market breadth and industry group rankings for **12 markets**, available to Claude, Cursor, VS Code or any other [MCP](https://modelcontextprotocol.io/) client.
26
+
27
+ - No API keys and no server to run.
28
+ - It reads the snapshot that the open-source [stock-screener](https://github.com/xang1234/stock-screener) project publishes after every market close.
29
+ - That's the same data as the [live demo](https://xang1234.github.io/stock-screener/).
30
+
31
+ ```bash
32
+ uvx stockscreen-mcp
33
+ ```
34
+
35
+ **Markets:** United States, Canada, Germany, Hong Kong, mainland China, Japan, Korea, Taiwan, India, Singapore, Malaysia and Australia.
36
+
37
+ ## What you can ask
38
+
39
+ - "Which stocks pass the Minervini trend template in the US today, and which of them are in top-20 industry groups?"
40
+ - "Run the CANSLIM screen for Japan and show the five strongest by 3-month RS."
41
+ - "How healthy is the US market right now? Exposure, distribution days, breadth."
42
+ - "What are the leading industry groups this week, and which groups moved up the most?"
43
+ - "Tell me everything the scan knows about NVDA, and which screens it passes."
44
+ - "Find Hong Kong stocks with RS above 90, in stage 2, with quarterly EPS growth over 25%."
45
+
46
+ ## Tools
47
+
48
+ All tools are read-only.
49
+
50
+ | Tool | What it returns |
51
+ |---|---|
52
+ | `list_markets` | Markets in the current publish, with each one's data date, status and features |
53
+ | `list_screens` | The 28 preset screens and their exact rules: Minervini, CANSLIM, VCP, cup with handle, high tight flag, momentum, IPOs and more |
54
+ | `run_screen` | A preset and/or your own filters over every stock in a market's scan, sorted, with the match count. A preset returns exactly the stocks the website shows for it |
55
+ | `get_stock` | One stock: RS ratings (overall, 1M, 3M, 12M), stage, screener scores, growth, group rank, setup and pattern fields, and the screens it passes |
56
+ | `market_overview` | Exposure score and stance, distribution days, follow-through day, StockBee-style breadth (4% movers, 5/10-day ratios, T2108, 52-week highs/lows), key index moves, top groups |
57
+ | `group_rankings` | IBD-style industry groups ranked by relative strength, with 1W/1M/3M/6M rank changes and weekly movers. Pass a group for its rank history and strongest stocks |
58
+
59
+ ### Reading the data
60
+
61
+ - **RS ratings** (`rs_rating`, `rs_rating_1m/3m/12m`) are percentiles from 1 to 99 *within the stock's own market*, where 99 is the strongest.
62
+ - **Group rank 1** is the strongest group.
63
+ - **Every result has an `as_of_date`:** the last completed session the publish covers. This is end-of-day data with nothing intraday, and it is never fetched live from price providers.
64
+
65
+ ## Setup
66
+
67
+ The server needs [uv](https://docs.astral.sh/uv/getting-started/installation/), which provides `uvx`.
68
+
69
+ **Claude Code**
70
+
71
+ ```bash
72
+ claude mcp add stockscreen -- uvx stockscreen-mcp
73
+ ```
74
+
75
+ **Claude Desktop**: add to `claude_desktop_config.json`.
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "stockscreen": { "command": "uvx", "args": ["stockscreen-mcp"] }
81
+ }
82
+ }
83
+ ```
84
+
85
+ **Cursor**: add the same `mcpServers` entry to `~/.cursor/mcp.json`.
86
+
87
+ **VS Code**: add to `.vscode/mcp.json`.
88
+
89
+ ```json
90
+ {
91
+ "servers": {
92
+ "stockscreen": { "type": "stdio", "command": "uvx", "args": ["stockscreen-mcp"] }
93
+ }
94
+ }
95
+ ```
96
+
97
+ **Codex CLI**: add to `~/.codex/config.toml`.
98
+
99
+ ```toml
100
+ [mcp_servers.stockscreen]
101
+ command = "uvx"
102
+ args = ["stockscreen-mcp"]
103
+ ```
104
+
105
+ To run the newest version from `main` rather than the latest release, replace `stockscreen-mcp` in `args` with `--from`, `git+https://github.com/xang1234/stock-screener#subdirectory=stockscreen-mcp`, `stockscreen-mcp`.
106
+
107
+ ## How it works
108
+
109
+ - **Data source:** the server reads the JSON that the static site publishes to GitHub Pages. The root `manifest.json` points at the current publish.
110
+ - **Download and caching:** each market's scan is downloaded once, on first use (US is about 7 MB compressed), and kept in memory. The two most recently used markets stay cached, and the cache refreshes when a new publish appears.
111
+ - **Data URL:** set `STOCKSCREEN_DATA_URL` to read from another publish, such as a fork's GitHub Pages site.
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ cd stockscreen-mcp
117
+ uv run pytest # unit tests, no network
118
+ STOCKSCREEN_LIVE=1 uv run pytest -m live # against the real publish
119
+ ```
120
+
121
+ ## License and disclaimer
122
+
123
+ Apache-2.0. This is screening data for education and research, **not investment advice**.
@@ -0,0 +1,103 @@
1
+ # stockscreen-mcp
2
+
3
+ <!-- mcp-name: io.github.xang1234/stockscreen-mcp -->
4
+
5
+ Daily stock screens, relative-strength ratings, market breadth and industry group rankings for **12 markets**, available to Claude, Cursor, VS Code or any other [MCP](https://modelcontextprotocol.io/) client.
6
+
7
+ - No API keys and no server to run.
8
+ - It reads the snapshot that the open-source [stock-screener](https://github.com/xang1234/stock-screener) project publishes after every market close.
9
+ - That's the same data as the [live demo](https://xang1234.github.io/stock-screener/).
10
+
11
+ ```bash
12
+ uvx stockscreen-mcp
13
+ ```
14
+
15
+ **Markets:** United States, Canada, Germany, Hong Kong, mainland China, Japan, Korea, Taiwan, India, Singapore, Malaysia and Australia.
16
+
17
+ ## What you can ask
18
+
19
+ - "Which stocks pass the Minervini trend template in the US today, and which of them are in top-20 industry groups?"
20
+ - "Run the CANSLIM screen for Japan and show the five strongest by 3-month RS."
21
+ - "How healthy is the US market right now? Exposure, distribution days, breadth."
22
+ - "What are the leading industry groups this week, and which groups moved up the most?"
23
+ - "Tell me everything the scan knows about NVDA, and which screens it passes."
24
+ - "Find Hong Kong stocks with RS above 90, in stage 2, with quarterly EPS growth over 25%."
25
+
26
+ ## Tools
27
+
28
+ All tools are read-only.
29
+
30
+ | Tool | What it returns |
31
+ |---|---|
32
+ | `list_markets` | Markets in the current publish, with each one's data date, status and features |
33
+ | `list_screens` | The 28 preset screens and their exact rules: Minervini, CANSLIM, VCP, cup with handle, high tight flag, momentum, IPOs and more |
34
+ | `run_screen` | A preset and/or your own filters over every stock in a market's scan, sorted, with the match count. A preset returns exactly the stocks the website shows for it |
35
+ | `get_stock` | One stock: RS ratings (overall, 1M, 3M, 12M), stage, screener scores, growth, group rank, setup and pattern fields, and the screens it passes |
36
+ | `market_overview` | Exposure score and stance, distribution days, follow-through day, StockBee-style breadth (4% movers, 5/10-day ratios, T2108, 52-week highs/lows), key index moves, top groups |
37
+ | `group_rankings` | IBD-style industry groups ranked by relative strength, with 1W/1M/3M/6M rank changes and weekly movers. Pass a group for its rank history and strongest stocks |
38
+
39
+ ### Reading the data
40
+
41
+ - **RS ratings** (`rs_rating`, `rs_rating_1m/3m/12m`) are percentiles from 1 to 99 *within the stock's own market*, where 99 is the strongest.
42
+ - **Group rank 1** is the strongest group.
43
+ - **Every result has an `as_of_date`:** the last completed session the publish covers. This is end-of-day data with nothing intraday, and it is never fetched live from price providers.
44
+
45
+ ## Setup
46
+
47
+ The server needs [uv](https://docs.astral.sh/uv/getting-started/installation/), which provides `uvx`.
48
+
49
+ **Claude Code**
50
+
51
+ ```bash
52
+ claude mcp add stockscreen -- uvx stockscreen-mcp
53
+ ```
54
+
55
+ **Claude Desktop**: add to `claude_desktop_config.json`.
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "stockscreen": { "command": "uvx", "args": ["stockscreen-mcp"] }
61
+ }
62
+ }
63
+ ```
64
+
65
+ **Cursor**: add the same `mcpServers` entry to `~/.cursor/mcp.json`.
66
+
67
+ **VS Code**: add to `.vscode/mcp.json`.
68
+
69
+ ```json
70
+ {
71
+ "servers": {
72
+ "stockscreen": { "type": "stdio", "command": "uvx", "args": ["stockscreen-mcp"] }
73
+ }
74
+ }
75
+ ```
76
+
77
+ **Codex CLI**: add to `~/.codex/config.toml`.
78
+
79
+ ```toml
80
+ [mcp_servers.stockscreen]
81
+ command = "uvx"
82
+ args = ["stockscreen-mcp"]
83
+ ```
84
+
85
+ To run the newest version from `main` rather than the latest release, replace `stockscreen-mcp` in `args` with `--from`, `git+https://github.com/xang1234/stock-screener#subdirectory=stockscreen-mcp`, `stockscreen-mcp`.
86
+
87
+ ## How it works
88
+
89
+ - **Data source:** the server reads the JSON that the static site publishes to GitHub Pages. The root `manifest.json` points at the current publish.
90
+ - **Download and caching:** each market's scan is downloaded once, on first use (US is about 7 MB compressed), and kept in memory. The two most recently used markets stay cached, and the cache refreshes when a new publish appears.
91
+ - **Data URL:** set `STOCKSCREEN_DATA_URL` to read from another publish, such as a fork's GitHub Pages site.
92
+
93
+ ## Development
94
+
95
+ ```bash
96
+ cd stockscreen-mcp
97
+ uv run pytest # unit tests, no network
98
+ STOCKSCREEN_LIVE=1 uv run pytest -m live # against the real publish
99
+ ```
100
+
101
+ ## License and disclaimer
102
+
103
+ Apache-2.0. This is screening data for education and research, **not investment advice**.
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "stockscreen-mcp"
3
+ dynamic = ["version"]
4
+ description = "MCP server for daily stock screens (Minervini, CANSLIM, VCP and more), RS ratings, market breadth and IBD-style group rankings across 12 markets. No API keys or setup."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.10"
8
+ authors = [{ name = "David Ten" }]
9
+ keywords = ["mcp", "stock-screener", "minervini", "canslim", "relative-strength", "market-breadth", "trading"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Financial and Insurance Industry",
13
+ "Programming Language :: Python :: 3",
14
+ "Topic :: Office/Business :: Financial :: Investment",
15
+ ]
16
+ dependencies = ["mcp>=2.3,<3"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/xang1234/stock-screener/tree/main/stockscreen-mcp"
20
+ Repository = "https://github.com/xang1234/stock-screener"
21
+ Issues = "https://github.com/xang1234/stock-screener/issues"
22
+ "Live demo" = "https://xang1234.github.io/stock-screener/"
23
+
24
+ [project.scripts]
25
+ stockscreen-mcp = "stockscreen_mcp.server:main"
26
+
27
+ [build-system]
28
+ requires = ["hatchling>=1.27"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.version]
32
+ path = "src/stockscreen_mcp/__init__.py"
33
+
34
+ [dependency-groups]
35
+ dev = ["pytest>=8", "anyio>=4"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ markers = ["live: hits the published data on GitHub Pages (run with STOCKSCREEN_LIVE=1)"]
@@ -0,0 +1,3 @@
1
+ """MCP server over the stock-screener project's published daily data."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,182 @@
1
+ """Read-only access to the static site's published JSON, cached per publish."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import http.client
7
+ import json
8
+ import os
9
+ import threading
10
+ import time
11
+ import urllib.error
12
+ import urllib.request
13
+ import zlib
14
+ from collections import OrderedDict
15
+ from collections.abc import Callable
16
+ from typing import Any
17
+
18
+ from mcp.server.mcpserver.exceptions import ToolError
19
+
20
+ from . import __version__
21
+
22
+ DEFAULT_BASE_URL = "https://xang1234.github.io/stock-screener/static-data/"
23
+ # GitHub Pages serves the data with Cache-Control: max-age=600.
24
+ MANIFEST_TTL_SECONDS = 600
25
+ # Chart series and per-field availability notes: large and unused by any tool.
26
+ HEAVY_FIELDS = frozenset({"price_sparkline_data", "rs_sparkline_data", "field_availability"})
27
+ # ponytail: pruned US rows are ~100 MB as Python objects (more while a chunk is parsed),
28
+ # so keep only the most recently used markets' files; raise it or switch to columnar rows.
29
+ MAX_CACHED_MARKETS = 2
30
+
31
+
32
+ def fetch_json(url: str) -> Any:
33
+ request = urllib.request.Request(
34
+ url, headers={"Accept-Encoding": "gzip", "User-Agent": f"stockscreen-mcp/{__version__}"}
35
+ )
36
+ with urllib.request.urlopen(request, timeout=60) as response:
37
+ body = response.read()
38
+ if response.headers.get("Content-Encoding") == "gzip":
39
+ body = gzip.decompress(body)
40
+ return json.loads(body)
41
+
42
+
43
+ def prune(value: Any) -> Any:
44
+ """Drop HEAVY_FIELDS at any depth (group files nest stock rows)."""
45
+ if isinstance(value, dict):
46
+ return {k: prune(v) for k, v in value.items() if k not in HEAVY_FIELDS}
47
+ if isinstance(value, list):
48
+ return [prune(v) for v in value]
49
+ return value
50
+
51
+
52
+ class _GenerationReplaced(Exception):
53
+ """The publish this load started from was replaced mid-load."""
54
+
55
+
56
+ class StaticData:
57
+ def __init__(
58
+ self,
59
+ base_url: str | None = None,
60
+ fetch: Callable[[str], Any] = fetch_json,
61
+ clock: Callable[[], float] = time.monotonic,
62
+ ) -> None:
63
+ base = base_url or os.environ.get("STOCKSCREEN_DATA_URL") or DEFAULT_BASE_URL
64
+ self.base_url = base.rstrip("/") + "/"
65
+ self._fetch = fetch
66
+ self._clock = clock
67
+ # ponytail: one lock for every load; per-file locks if concurrent calls ever matter.
68
+ self._lock = threading.RLock()
69
+ self._manifest: dict[str, Any] | None = None
70
+ self._manifest_at = 0.0
71
+ self._cache: dict[tuple[str, str], Any] = {}
72
+ self._recent_markets: OrderedDict[str, None] = OrderedDict()
73
+
74
+ def _get(self, path: str) -> Any:
75
+ url = self.base_url + path
76
+ try:
77
+ return self._fetch(url)
78
+ except urllib.error.HTTPError:
79
+ raise
80
+ # OSError covers URLError and timeouts; ValueError bad JSON; the rest truncated bodies.
81
+ except (OSError, ValueError, EOFError, zlib.error, http.client.HTTPException) as exc:
82
+ raise ToolError(f"Could not reach the published data at {url}: {exc!r}") from exc
83
+
84
+ def manifest(self, *, refresh: bool = False) -> dict[str, Any]:
85
+ with self._lock:
86
+ stale = self._clock() - self._manifest_at > MANIFEST_TTL_SECONDS
87
+ if refresh or self._manifest is None or stale:
88
+ try:
89
+ manifest = self._get("manifest.json")
90
+ except urllib.error.HTTPError as exc:
91
+ raise ToolError(f"The published data manifest is unavailable ({exc.code}).") from exc
92
+ self._manifest, self._manifest_at = manifest, self._clock()
93
+ root = manifest["data_root"]
94
+ self._cache = {k: v for k, v in self._cache.items() if k[0] == root}
95
+ return self._manifest
96
+
97
+ def market(self, code: str) -> dict[str, Any]:
98
+ code = code.strip().upper()
99
+ manifest = self.manifest()
100
+ entry = manifest["markets"].get(code)
101
+ if entry is not None:
102
+ return entry
103
+ if code in manifest.get("unavailable_markets", []):
104
+ raise ToolError(f"{code} is not available in the current publish; try again after the next one.")
105
+ known = ", ".join(sorted(manifest["markets"]))
106
+ raise ToolError(f"Unknown market {code!r}. Available markets: {known}.")
107
+
108
+ def _touch_market(self, path: str) -> None:
109
+ """Mark a market's files as recently used, evicting the least recent beyond the cap."""
110
+ parts = path.split("/")
111
+ if len(parts) < 2 or parts[0] != "markets":
112
+ return
113
+ self._recent_markets.pop(parts[1], None)
114
+ self._recent_markets[parts[1]] = None
115
+ while len(self._recent_markets) > MAX_CACHED_MARKETS:
116
+ evicted, _ = self._recent_markets.popitem(last=False)
117
+ prefix = f"markets/{evicted}/"
118
+ self._cache = {k: v for k, v in self._cache.items() if not k[1].startswith(prefix)}
119
+
120
+ def _store(self, root: str, key: tuple[str, str], value: Any) -> None:
121
+ # A publish replaced mid-load is still read consistently, but never cached.
122
+ if root == self.manifest()["data_root"]:
123
+ self._cache[key] = value
124
+
125
+ def _load(self, path: str, root: str, *, cache: bool = True) -> Any:
126
+ """One file of the publish under `root` (pinned for the whole load)."""
127
+ key = (root, path)
128
+ self._touch_market(path)
129
+ if key in self._cache:
130
+ return self._cache[key]
131
+ try:
132
+ value = prune(self._get(root + path))
133
+ except urllib.error.HTTPError as exc:
134
+ if exc.code == 404 and self.manifest(refresh=True)["data_root"] != root:
135
+ raise _GenerationReplaced from exc
136
+ raise ToolError(f"Published file {root}{path} is unavailable ({exc.code}).") from exc
137
+ if cache:
138
+ self._store(root, key, value)
139
+ return value
140
+
141
+ def _retrying(self, load: Callable[[str], Any]) -> Any:
142
+ """Run a load against one publish; only the newest is deployed, so restart on a new one."""
143
+ with self._lock:
144
+ for _ in range(2):
145
+ try:
146
+ return load(self.manifest()["data_root"])
147
+ except _GenerationReplaced:
148
+ continue
149
+ raise ToolError("The published data changed while loading; try again in a minute.")
150
+
151
+ def load(self, path: str) -> Any:
152
+ return self._retrying(lambda root: self._load(path, root))
153
+
154
+ def page(self, code: str, page: str) -> Any | None:
155
+ """A market page (home, breadth, groups, scan), or None if not published for it."""
156
+ entry = self.page_entry(code, page)
157
+ return None if entry is None else self.load(entry["path"])
158
+
159
+ def page_entry(self, code: str, page: str) -> dict[str, Any] | None:
160
+ return self.market(code).get("pages", {}).get(page)
161
+
162
+ def scan(self, code: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
163
+ """The scan manifest and every row, initial rows and chunks merged by symbol."""
164
+ if self.page_entry(code, "scan") is None:
165
+ raise ToolError(f"Scan results are not published for {code.upper()}.")
166
+
167
+ def load_all(root: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
168
+ scan_path = self.page_entry(code, "scan")["path"]
169
+ scan = self._load(scan_path, root)
170
+ # Lives under the market's prefix so eviction drops it with the market's files.
171
+ key = (root, scan_path.rsplit("/", 1)[0] + "/rows")
172
+ if key in self._cache:
173
+ return scan, self._cache[key]
174
+ merged = {row["symbol"]: row for row in scan.get("initial_rows", [])}
175
+ for chunk in scan.get("chunks", []):
176
+ for row in self._load(chunk["path"], root, cache=False)["rows"]:
177
+ merged[row["symbol"]] = row
178
+ rows = list(merged.values())
179
+ self._store(root, key, rows)
180
+ return scan, rows
181
+
182
+ return self._retrying(load_all)