gprophet 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.
gprophet-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 G-Prophet
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,139 @@
1
+ Metadata-Version: 2.2
2
+ Name: gprophet
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the G-Prophet AI Stock Prediction API
5
+ License: MIT
6
+ Project-URL: Homepage, https://gprophet.com
7
+ Project-URL: Documentation, https://gprophet.com/docs/api
8
+ Project-URL: Repository, https://github.com/g-prophet/gprophet-python
9
+ Project-URL: Bug Tracker, https://github.com/g-prophet/gprophet-python/issues
10
+ Keywords: stock,prediction,ai,finance,trading,gprophet
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Office/Business :: Financial :: Investment
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: httpx>=0.24.0
27
+ Provides-Extra: mcp
28
+ Requires-Dist: mcp>=1.0.0; extra == "mcp"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0; extra == "dev"
31
+ Requires-Dist: pytest-httpx>=0.21; extra == "dev"
32
+
33
+ # G-Prophet Python SDK
34
+
35
+ Official Python client for the [G-Prophet](https://gprophet.com) AI Stock Prediction API.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install gprophet
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```python
46
+ from gprophet import GProphet
47
+
48
+ client = GProphet(api_key="gp_sk_your_key_here")
49
+
50
+ # Check balance
51
+ print(client.balance())
52
+
53
+ # Get a stock quote
54
+ quote = client.quote("AAPL", market="US")
55
+ print(f"AAPL: ${quote['price']}")
56
+
57
+ # AI prediction
58
+ pred = client.predict("AAPL", market="US", days=7)
59
+ print(f"Predicted: ${pred['predicted_price']} ({pred['direction']})")
60
+
61
+ # Technical analysis
62
+ tech = client.technical("AAPL", market="US")
63
+ print(f"Signal: {tech['overall_signal']}")
64
+
65
+ # Batch quotes
66
+ quotes = client.batch_quote(["AAPL", "GOOGL", "MSFT"], market="US")
67
+ for q in quotes["results"]:
68
+ if q["success"]:
69
+ print(f"{q['symbol']}: ${q['price']}")
70
+
71
+ # AI stock analysis (async with auto-polling)
72
+ analysis = client.analyze_stock("AAPL", market="US", wait=True)
73
+ print(analysis["analysis"]["summary"])
74
+ ```
75
+
76
+ ## API Reference
77
+
78
+ ### System
79
+ - `client.health()` — Health check
80
+ - `client.info()` — API metadata, pricing, supported markets
81
+
82
+ ### Account
83
+ - `client.balance()` — Points balance and quota info
84
+ - `client.usage(days=7)` — Usage statistics
85
+
86
+ ### Predictions
87
+ - `client.predict(symbol, market, days, algorithm)` — AI price prediction
88
+ - `client.compare(symbol, market, days, algorithms)` — Multi-algorithm comparison
89
+
90
+ ### Market Data
91
+ - `client.quote(symbol, market)` — Real-time quote
92
+ - `client.batch_quote(symbols, market)` — Batch quotes
93
+ - `client.history(symbol, market, period)` — Historical OHLCV
94
+ - `client.search(keyword, market, limit)` — Search symbols
95
+
96
+ ### Technical Analysis
97
+ - `client.technical(symbol, market, indicators)` — Technical indicators & signals
98
+
99
+ ### Sentiment
100
+ - `client.fear_greed(days)` — Crypto Fear & Greed Index
101
+ - `client.market_overview(market)` — Market overview
102
+
103
+ ### Analysis
104
+ - `client.analyze_stock(symbol, market, locale, wait)` — AI stock analysis (58 pts)
105
+ - `client.analyze_comprehensive(symbol, market, locale, wait)` — Multi-agent analysis (150 pts)
106
+ - `client.task_status(task_id)` — Check async task status
107
+
108
+ ## Error Handling
109
+
110
+ ```python
111
+ from gprophet import GProphet
112
+ from gprophet.client import GProphetError, RateLimitError, InsufficientPointsError
113
+
114
+ client = GProphet(api_key="gp_sk_...")
115
+
116
+ try:
117
+ result = client.predict("AAPL", market="US")
118
+ except RateLimitError as e:
119
+ print(f"Rate limited, retry after {e.retry_after}s")
120
+ except InsufficientPointsError as e:
121
+ print(f"Need {e.required} points, have {e.available}")
122
+ except GProphetError as e:
123
+ print(f"API error [{e.code}]: {e.message}")
124
+ ```
125
+
126
+ ## Configuration
127
+
128
+ ```python
129
+ client = GProphet(
130
+ api_key="gp_sk_...",
131
+ base_url="https://gprophet.com/api/external/v1", # Custom base URL
132
+ timeout=60, # Request timeout (seconds)
133
+ max_retries=3, # Auto-retry on rate limit
134
+ )
135
+ ```
136
+
137
+ ## License
138
+
139
+ MIT
@@ -0,0 +1,107 @@
1
+ # G-Prophet Python SDK
2
+
3
+ Official Python client for the [G-Prophet](https://gprophet.com) AI Stock Prediction API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install gprophet
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```python
14
+ from gprophet import GProphet
15
+
16
+ client = GProphet(api_key="gp_sk_your_key_here")
17
+
18
+ # Check balance
19
+ print(client.balance())
20
+
21
+ # Get a stock quote
22
+ quote = client.quote("AAPL", market="US")
23
+ print(f"AAPL: ${quote['price']}")
24
+
25
+ # AI prediction
26
+ pred = client.predict("AAPL", market="US", days=7)
27
+ print(f"Predicted: ${pred['predicted_price']} ({pred['direction']})")
28
+
29
+ # Technical analysis
30
+ tech = client.technical("AAPL", market="US")
31
+ print(f"Signal: {tech['overall_signal']}")
32
+
33
+ # Batch quotes
34
+ quotes = client.batch_quote(["AAPL", "GOOGL", "MSFT"], market="US")
35
+ for q in quotes["results"]:
36
+ if q["success"]:
37
+ print(f"{q['symbol']}: ${q['price']}")
38
+
39
+ # AI stock analysis (async with auto-polling)
40
+ analysis = client.analyze_stock("AAPL", market="US", wait=True)
41
+ print(analysis["analysis"]["summary"])
42
+ ```
43
+
44
+ ## API Reference
45
+
46
+ ### System
47
+ - `client.health()` — Health check
48
+ - `client.info()` — API metadata, pricing, supported markets
49
+
50
+ ### Account
51
+ - `client.balance()` — Points balance and quota info
52
+ - `client.usage(days=7)` — Usage statistics
53
+
54
+ ### Predictions
55
+ - `client.predict(symbol, market, days, algorithm)` — AI price prediction
56
+ - `client.compare(symbol, market, days, algorithms)` — Multi-algorithm comparison
57
+
58
+ ### Market Data
59
+ - `client.quote(symbol, market)` — Real-time quote
60
+ - `client.batch_quote(symbols, market)` — Batch quotes
61
+ - `client.history(symbol, market, period)` — Historical OHLCV
62
+ - `client.search(keyword, market, limit)` — Search symbols
63
+
64
+ ### Technical Analysis
65
+ - `client.technical(symbol, market, indicators)` — Technical indicators & signals
66
+
67
+ ### Sentiment
68
+ - `client.fear_greed(days)` — Crypto Fear & Greed Index
69
+ - `client.market_overview(market)` — Market overview
70
+
71
+ ### Analysis
72
+ - `client.analyze_stock(symbol, market, locale, wait)` — AI stock analysis (58 pts)
73
+ - `client.analyze_comprehensive(symbol, market, locale, wait)` — Multi-agent analysis (150 pts)
74
+ - `client.task_status(task_id)` — Check async task status
75
+
76
+ ## Error Handling
77
+
78
+ ```python
79
+ from gprophet import GProphet
80
+ from gprophet.client import GProphetError, RateLimitError, InsufficientPointsError
81
+
82
+ client = GProphet(api_key="gp_sk_...")
83
+
84
+ try:
85
+ result = client.predict("AAPL", market="US")
86
+ except RateLimitError as e:
87
+ print(f"Rate limited, retry after {e.retry_after}s")
88
+ except InsufficientPointsError as e:
89
+ print(f"Need {e.required} points, have {e.available}")
90
+ except GProphetError as e:
91
+ print(f"API error [{e.code}]: {e.message}")
92
+ ```
93
+
94
+ ## Configuration
95
+
96
+ ```python
97
+ client = GProphet(
98
+ api_key="gp_sk_...",
99
+ base_url="https://gprophet.com/api/external/v1", # Custom base URL
100
+ timeout=60, # Request timeout (seconds)
101
+ max_retries=3, # Auto-retry on rate limit
102
+ )
103
+ ```
104
+
105
+ ## License
106
+
107
+ MIT
@@ -0,0 +1,16 @@
1
+ """
2
+ G-Prophet Python SDK
3
+ Official Python client for the G-Prophet External API.
4
+
5
+ Usage:
6
+ from gprophet import GProphet
7
+
8
+ client = GProphet(api_key="gp_sk_...")
9
+ result = client.predict("AAPL", market="US", days=7)
10
+ print(result)
11
+ """
12
+
13
+ from gprophet.client import GProphet
14
+
15
+ __version__ = "0.1.0"
16
+ __all__ = ["GProphet", "__version__"]
@@ -0,0 +1,353 @@
1
+ """
2
+ G-Prophet API Client
3
+ """
4
+
5
+ import time
6
+ import logging
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ import httpx
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class GProphetError(Exception):
15
+ """Base exception for G-Prophet API errors."""
16
+
17
+ def __init__(self, code: str, message: str, details: Any = None, status_code: int = 0):
18
+ self.code = code
19
+ self.message = message
20
+ self.details = details
21
+ self.status_code = status_code
22
+ super().__init__(f"[{code}] {message}")
23
+
24
+
25
+ class RateLimitError(GProphetError):
26
+ """Raised when rate limit is exceeded."""
27
+
28
+ def __init__(self, message: str, retry_after: int = 60):
29
+ self.retry_after = retry_after
30
+ super().__init__("RATE_LIMITED", message, status_code=429)
31
+
32
+
33
+ class InsufficientPointsError(GProphetError):
34
+ """Raised when points are insufficient."""
35
+
36
+ def __init__(self, message: str, required: int = 0, available: int = 0):
37
+ self.required = required
38
+ self.available = available
39
+ super().__init__("INSUFFICIENT_POINTS", message, status_code=402)
40
+
41
+
42
+ class GProphet:
43
+ """
44
+ G-Prophet API Client.
45
+
46
+ Args:
47
+ api_key: Your API key (starts with 'gp_sk_')
48
+ base_url: API base URL (default: https://gprophet.com/api/external/v1)
49
+ timeout: Request timeout in seconds (default: 60)
50
+ max_retries: Max retries on rate limit (default: 3)
51
+ """
52
+
53
+ DEFAULT_BASE_URL = "https://gprophet.com/api/external/v1"
54
+
55
+ def __init__(
56
+ self,
57
+ api_key: str,
58
+ base_url: str = None,
59
+ timeout: int = 60,
60
+ max_retries: int = 3,
61
+ ):
62
+ if not api_key or not api_key.startswith("gp_sk_"):
63
+ raise ValueError("API key must start with 'gp_sk_'")
64
+
65
+ self.api_key = api_key
66
+ self.base_url = (base_url or self.DEFAULT_BASE_URL).rstrip("/")
67
+ self.timeout = timeout
68
+ self.max_retries = max_retries
69
+ self._client = httpx.Client(
70
+ base_url=self.base_url,
71
+ headers={"X-API-Key": self.api_key},
72
+ timeout=timeout,
73
+ )
74
+
75
+ def close(self):
76
+ """Close the HTTP client."""
77
+ self._client.close()
78
+
79
+ def __enter__(self):
80
+ return self
81
+
82
+ def __exit__(self, *args):
83
+ self.close()
84
+
85
+ # ==================== Internal ====================
86
+
87
+ def _request(self, method: str, path: str, **kwargs) -> Dict:
88
+ """Make an API request with automatic retry on rate limit."""
89
+ for attempt in range(self.max_retries + 1):
90
+ resp = self._client.request(method, path, **kwargs)
91
+
92
+ if resp.status_code == 429 and attempt < self.max_retries:
93
+ retry_after = int(resp.headers.get("Retry-After", "5"))
94
+ logger.warning(f"Rate limited, retrying in {retry_after}s (attempt {attempt + 1})")
95
+ time.sleep(retry_after)
96
+ continue
97
+
98
+ data = resp.json()
99
+
100
+ if resp.status_code == 429:
101
+ details = data.get("error", {}).get("details", {})
102
+ raise RateLimitError(
103
+ data.get("error", {}).get("message", "Rate limited"),
104
+ retry_after=details.get("retry_after_seconds", 60)
105
+ )
106
+
107
+ if resp.status_code == 402:
108
+ details = data.get("error", {}).get("details", {})
109
+ raise InsufficientPointsError(
110
+ data.get("error", {}).get("message", "Insufficient points"),
111
+ required=details.get("required", 0),
112
+ available=details.get("available", 0)
113
+ )
114
+
115
+ if not data.get("success", False):
116
+ err = data.get("error", {})
117
+ raise GProphetError(
118
+ code=err.get("code", "UNKNOWN"),
119
+ message=err.get("message", "Unknown error"),
120
+ details=err.get("details"),
121
+ status_code=resp.status_code
122
+ )
123
+
124
+ return data.get("data")
125
+
126
+ # Should not reach here
127
+ raise GProphetError("MAX_RETRIES", "Max retries exceeded")
128
+
129
+ def _get(self, path: str, params: Dict = None) -> Dict:
130
+ return self._request("GET", path, params=params)
131
+
132
+ def _post(self, path: str, json: Dict = None) -> Dict:
133
+ return self._request("POST", path, json=json)
134
+
135
+ # ==================== System ====================
136
+
137
+ def health(self) -> Dict:
138
+ """Check API health status."""
139
+ resp = self._client.get("/health")
140
+ return resp.json()
141
+
142
+ def info(self) -> Dict:
143
+ """Get API metadata: supported markets, algorithms, pricing."""
144
+ return self._get("/info")
145
+
146
+ # ==================== Account ====================
147
+
148
+ def balance(self) -> Dict:
149
+ """Get current points balance and quota info."""
150
+ return self._get("/account/balance")
151
+
152
+ def usage(self, days: int = 7) -> Dict:
153
+ """Get API usage statistics."""
154
+ return self._get("/account/usage", params={"days": days})
155
+
156
+ # ==================== Predictions ====================
157
+
158
+ def predict(
159
+ self,
160
+ symbol: str,
161
+ market: str = "US",
162
+ days: int = 7,
163
+ algorithm: str = "auto",
164
+ ) -> Dict:
165
+ """
166
+ Predict stock/crypto price movement.
167
+
168
+ Args:
169
+ symbol: Stock/crypto symbol (e.g., 'AAPL', '600519', 'BTCUSDT')
170
+ market: Market code ('US', 'CN', 'HK', 'CRYPTO')
171
+ days: Prediction horizon (1-30)
172
+ algorithm: Algorithm ('auto', 'gprophet2026v1', 'lstm', 'transformer', 'random_forest', 'ensemble')
173
+
174
+ Returns:
175
+ Prediction result with predicted_price, direction, confidence, etc.
176
+ """
177
+ return self._post("/predictions/predict", json={
178
+ "symbol": symbol, "market": market, "days": days, "algorithm": algorithm
179
+ })
180
+
181
+ def compare(
182
+ self,
183
+ symbol: str,
184
+ market: str = "US",
185
+ days: int = 5,
186
+ algorithms: List[str] = None,
187
+ ) -> Dict:
188
+ """
189
+ Compare predictions from multiple algorithms.
190
+
191
+ Args:
192
+ symbol: Stock/crypto symbol
193
+ market: Market code
194
+ days: Prediction horizon (1-30)
195
+ algorithms: List of algorithms to compare
196
+ """
197
+ return self._post("/predictions/compare", json={
198
+ "symbol": symbol, "market": market, "days": days,
199
+ "algorithms": algorithms or ["gprophet2026v1", "lstm", "transformer", "ensemble"]
200
+ })
201
+
202
+ # ==================== Market Data ====================
203
+
204
+ def quote(self, symbol: str, market: str = "US") -> Dict:
205
+ """Get real-time quote for a symbol."""
206
+ return self._get("/market-data/quote", params={"symbol": symbol, "market": market})
207
+
208
+ def batch_quote(self, symbols: List[str], market: str = "US") -> Dict:
209
+ """Get quotes for multiple symbols at once."""
210
+ return self._post("/market-data/batch-quote", json={"symbols": symbols, "market": market})
211
+
212
+ def history(self, symbol: str, market: str = "US", period: str = "3m") -> Dict:
213
+ """
214
+ Get historical OHLCV data.
215
+
216
+ Args:
217
+ symbol: Stock/crypto symbol
218
+ market: Market code
219
+ period: Time range ('1w', '1m', '3m', '6m', '1y', '2y')
220
+ """
221
+ return self._get("/market-data/history", params={
222
+ "symbol": symbol, "market": market, "period": period
223
+ })
224
+
225
+ def search(self, keyword: str, market: str = "US", limit: int = 10) -> Dict:
226
+ """Search for stocks/crypto by keyword."""
227
+ return self._get("/market-data/search", params={
228
+ "keyword": keyword, "market": market, "limit": limit
229
+ })
230
+
231
+ # ==================== Technical Analysis ====================
232
+
233
+ def technical(
234
+ self,
235
+ symbol: str,
236
+ market: str = "US",
237
+ indicators: List[str] = None,
238
+ ) -> Dict:
239
+ """
240
+ Calculate technical indicators and generate trading signals.
241
+
242
+ Args:
243
+ symbol: Stock/crypto symbol
244
+ market: Market code
245
+ indicators: List of indicators ('rsi', 'macd', 'bollinger', 'kdj', 'sma', 'ema')
246
+ """
247
+ return self._post("/technical/analyze", json={
248
+ "symbol": symbol, "market": market,
249
+ "indicators": indicators or ["rsi", "macd", "bollinger", "kdj"]
250
+ })
251
+
252
+ # ==================== Sentiment ====================
253
+
254
+ def fear_greed(self, days: int = 1) -> Dict:
255
+ """Get crypto Fear & Greed Index."""
256
+ return self._get("/sentiment/fear-greed", params={"days": days})
257
+
258
+ def market_overview(self, market: str = "CN") -> Dict:
259
+ """Get market overview (breadth, hot concepts, major indices)."""
260
+ return self._get("/sentiment/market-overview", params={"market": market})
261
+
262
+ # ==================== Analysis ====================
263
+
264
+ def analyze_stock(
265
+ self,
266
+ symbol: str,
267
+ market: str = "US",
268
+ locale: str = "zh-CN",
269
+ callback_url: str = None,
270
+ wait: bool = False,
271
+ poll_interval: int = 5,
272
+ max_wait: int = 300,
273
+ ) -> Dict:
274
+ """
275
+ Run AI stock analysis (58 points).
276
+
277
+ Args:
278
+ symbol: Stock/crypto symbol
279
+ market: Market code ('US', 'CN', 'CRYPTO')
280
+ locale: Language ('zh-CN', 'en-US')
281
+ callback_url: Optional webhook URL for result delivery
282
+ wait: If True, poll until completion (blocking)
283
+ poll_interval: Seconds between polls (default 5)
284
+ max_wait: Max seconds to wait (default 300)
285
+
286
+ Returns:
287
+ If wait=False: task info with task_id
288
+ If wait=True: completed analysis result
289
+ """
290
+ result = self._post("/analysis/stock", json={
291
+ "symbol": symbol, "market": market, "locale": locale,
292
+ "callback_url": callback_url
293
+ })
294
+
295
+ if wait:
296
+ return self._poll_task(result["task_id"], poll_interval, max_wait)
297
+ return result
298
+
299
+ def analyze_comprehensive(
300
+ self,
301
+ symbol: str,
302
+ market: str = "US",
303
+ locale: str = "zh-CN",
304
+ callback_url: str = None,
305
+ wait: bool = False,
306
+ poll_interval: int = 5,
307
+ max_wait: int = 300,
308
+ ) -> Dict:
309
+ """
310
+ Run multi-agent comprehensive analysis (150 points).
311
+
312
+ Args:
313
+ symbol: Stock/crypto symbol
314
+ market: Market code ('US', 'CN', 'HK', 'CRYPTO')
315
+ locale: Language ('zh-CN', 'en-US')
316
+ callback_url: Optional webhook URL for result delivery
317
+ wait: If True, poll until completion (blocking)
318
+ poll_interval: Seconds between polls (default 5)
319
+ max_wait: Max seconds to wait (default 300)
320
+
321
+ Returns:
322
+ If wait=False: task info with task_id
323
+ If wait=True: completed analysis result
324
+ """
325
+ result = self._post("/analysis/comprehensive", json={
326
+ "symbol": symbol, "market": market, "locale": locale,
327
+ "callback_url": callback_url
328
+ })
329
+
330
+ if wait:
331
+ return self._poll_task(result["task_id"], poll_interval, max_wait)
332
+ return result
333
+
334
+ def task_status(self, task_id: str) -> Dict:
335
+ """Check the status of an async analysis task."""
336
+ return self._get(f"/analysis/task/{task_id}")
337
+
338
+ def _poll_task(self, task_id: str, interval: int = 5, max_wait: int = 300) -> Dict:
339
+ """Poll a task until completion."""
340
+ elapsed = 0
341
+ while elapsed < max_wait:
342
+ status = self.task_status(task_id)
343
+ if status["status"] == "completed":
344
+ return status.get("result", status)
345
+ if status["status"] == "failed":
346
+ raise GProphetError(
347
+ code="TASK_FAILED",
348
+ message=status.get("error", "Task failed")
349
+ )
350
+ time.sleep(interval)
351
+ elapsed += interval
352
+
353
+ raise GProphetError(code="TIMEOUT", message=f"Task {task_id} did not complete within {max_wait}s")
@@ -0,0 +1,324 @@
1
+ """
2
+ G-Prophet MCP Server
3
+ Exposes G-Prophet External API as MCP tools for AI agents.
4
+
5
+ Usage as CLI (after pip install gprophet[mcp]):
6
+ export GPROPHET_API_KEY=gp_sk_...
7
+ gprophet-mcp
8
+
9
+ Or add to mcp.json:
10
+ {
11
+ "mcpServers": {
12
+ "gprophet": {
13
+ "command": "gprophet-mcp",
14
+ "env": { "GPROPHET_API_KEY": "gp_sk_..." }
15
+ }
16
+ }
17
+ }
18
+ """
19
+
20
+ import os
21
+ import sys
22
+ import json
23
+ import logging
24
+ import asyncio
25
+
26
+ import httpx
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ API_KEY = ""
31
+ BASE_URL = ""
32
+
33
+
34
+ def _api_request(method: str, path: str, params: dict = None, json_body: dict = None) -> dict:
35
+ """Make an API request to G-Prophet."""
36
+ with httpx.Client(
37
+ base_url=BASE_URL,
38
+ headers={"X-API-Key": API_KEY},
39
+ timeout=120,
40
+ ) as client:
41
+ resp = client.request(method, path, params=params, json=json_body)
42
+ return resp.json()
43
+
44
+
45
+ def _format_result(data: dict) -> str:
46
+ """Format API response for MCP output."""
47
+ return json.dumps(data, indent=2, ensure_ascii=False)
48
+
49
+
50
+ def _build_tools():
51
+ """Build tool definitions. Import mcp here to keep it lazy."""
52
+ from mcp.types import Tool
53
+
54
+ return [
55
+ Tool(
56
+ name="gprophet_predict",
57
+ description="Predict stock/crypto price using AI. Markets: US, CN, HK, CRYPTO. Algorithms: auto, gprophet2026v1, lstm, transformer, random_forest, ensemble.",
58
+ inputSchema={
59
+ "type": "object",
60
+ "properties": {
61
+ "symbol": {"type": "string", "description": "Stock/crypto symbol (e.g., AAPL, 600519, BTCUSDT)"},
62
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
63
+ "days": {"type": "integer", "minimum": 1, "maximum": 30, "default": 7},
64
+ "algorithm": {"type": "string", "default": "auto"},
65
+ },
66
+ "required": ["symbol"],
67
+ },
68
+ ),
69
+ Tool(
70
+ name="gprophet_quote",
71
+ description="Get real-time stock/crypto quote.",
72
+ inputSchema={
73
+ "type": "object",
74
+ "properties": {
75
+ "symbol": {"type": "string", "description": "Stock/crypto symbol"},
76
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
77
+ },
78
+ "required": ["symbol"],
79
+ },
80
+ ),
81
+ Tool(
82
+ name="gprophet_batch_quote",
83
+ description="Get quotes for multiple symbols at once (max 20).",
84
+ inputSchema={
85
+ "type": "object",
86
+ "properties": {
87
+ "symbols": {"type": "array", "items": {"type": "string"}, "description": "List of symbols"},
88
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
89
+ },
90
+ "required": ["symbols"],
91
+ },
92
+ ),
93
+ Tool(
94
+ name="gprophet_history",
95
+ description="Get historical OHLCV price data.",
96
+ inputSchema={
97
+ "type": "object",
98
+ "properties": {
99
+ "symbol": {"type": "string"},
100
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
101
+ "period": {"type": "string", "enum": ["1w", "1m", "3m", "6m", "1y", "2y"], "default": "3m"},
102
+ },
103
+ "required": ["symbol"],
104
+ },
105
+ ),
106
+ Tool(
107
+ name="gprophet_search",
108
+ description="Search for stocks/crypto by keyword.",
109
+ inputSchema={
110
+ "type": "object",
111
+ "properties": {
112
+ "keyword": {"type": "string"},
113
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
114
+ "limit": {"type": "integer", "minimum": 1, "maximum": 50, "default": 10},
115
+ },
116
+ "required": ["keyword"],
117
+ },
118
+ ),
119
+ Tool(
120
+ name="gprophet_technical",
121
+ description="Calculate technical indicators (RSI, MACD, Bollinger, KDJ, SMA, EMA) and generate trading signals.",
122
+ inputSchema={
123
+ "type": "object",
124
+ "properties": {
125
+ "symbol": {"type": "string"},
126
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
127
+ "indicators": {
128
+ "type": "array",
129
+ "items": {"type": "string", "enum": ["rsi", "macd", "bollinger", "kdj", "sma", "ema"]},
130
+ "default": ["rsi", "macd", "bollinger", "kdj"],
131
+ },
132
+ },
133
+ "required": ["symbol"],
134
+ },
135
+ ),
136
+ Tool(
137
+ name="gprophet_fear_greed",
138
+ description="Get crypto market Fear & Greed Index.",
139
+ inputSchema={
140
+ "type": "object",
141
+ "properties": {
142
+ "days": {"type": "integer", "minimum": 1, "maximum": 365, "default": 1},
143
+ },
144
+ },
145
+ ),
146
+ Tool(
147
+ name="gprophet_market_overview",
148
+ description="Get market overview: breadth, hot concepts, major indices.",
149
+ inputSchema={
150
+ "type": "object",
151
+ "properties": {
152
+ "market": {"type": "string", "enum": ["CN", "US"], "default": "CN"},
153
+ },
154
+ },
155
+ ),
156
+ Tool(
157
+ name="gprophet_analyze_stock",
158
+ description="Run AI stock analysis report (58 points). Returns task_id for async polling.",
159
+ inputSchema={
160
+ "type": "object",
161
+ "properties": {
162
+ "symbol": {"type": "string"},
163
+ "market": {"type": "string", "enum": ["US", "CN", "CRYPTO"], "default": "US"},
164
+ "locale": {"type": "string", "enum": ["zh-CN", "en-US"], "default": "en-US"},
165
+ },
166
+ "required": ["symbol"],
167
+ },
168
+ ),
169
+ Tool(
170
+ name="gprophet_analyze_comprehensive",
171
+ description="Run multi-agent comprehensive analysis (150 points). Returns task_id for async polling.",
172
+ inputSchema={
173
+ "type": "object",
174
+ "properties": {
175
+ "symbol": {"type": "string"},
176
+ "market": {"type": "string", "enum": ["US", "CN", "HK", "CRYPTO"], "default": "US"},
177
+ "locale": {"type": "string", "enum": ["zh-CN", "en-US"], "default": "en-US"},
178
+ },
179
+ "required": ["symbol"],
180
+ },
181
+ ),
182
+ Tool(
183
+ name="gprophet_task_status",
184
+ description="Check the status of an async analysis task.",
185
+ inputSchema={
186
+ "type": "object",
187
+ "properties": {
188
+ "task_id": {"type": "string", "description": "Task ID returned by analysis endpoints"},
189
+ },
190
+ "required": ["task_id"],
191
+ },
192
+ ),
193
+ Tool(
194
+ name="gprophet_balance",
195
+ description="Check current points balance and API quota.",
196
+ inputSchema={"type": "object", "properties": {}},
197
+ ),
198
+ Tool(
199
+ name="gprophet_info",
200
+ description="Get API metadata: supported markets, algorithms, pricing.",
201
+ inputSchema={"type": "object", "properties": {}},
202
+ ),
203
+ ]
204
+
205
+
206
+ def _dispatch(name: str, args: dict) -> dict:
207
+ """Route tool calls to API endpoints."""
208
+
209
+ if name == "gprophet_predict":
210
+ return _api_request("POST", "/predictions/predict", json_body={
211
+ "symbol": args["symbol"],
212
+ "market": args.get("market", "US"),
213
+ "days": args.get("days", 7),
214
+ "algorithm": args.get("algorithm", "auto"),
215
+ })
216
+
217
+ if name == "gprophet_quote":
218
+ return _api_request("GET", "/market-data/quote", params={
219
+ "symbol": args["symbol"], "market": args.get("market", "US")
220
+ })
221
+
222
+ if name == "gprophet_batch_quote":
223
+ return _api_request("POST", "/market-data/batch-quote", json_body={
224
+ "symbols": args["symbols"], "market": args.get("market", "US")
225
+ })
226
+
227
+ if name == "gprophet_history":
228
+ return _api_request("GET", "/market-data/history", params={
229
+ "symbol": args["symbol"], "market": args.get("market", "US"),
230
+ "period": args.get("period", "3m")
231
+ })
232
+
233
+ if name == "gprophet_search":
234
+ return _api_request("GET", "/market-data/search", params={
235
+ "keyword": args["keyword"], "market": args.get("market", "US"),
236
+ "limit": args.get("limit", 10)
237
+ })
238
+
239
+ if name == "gprophet_technical":
240
+ return _api_request("POST", "/technical/analyze", json_body={
241
+ "symbol": args["symbol"], "market": args.get("market", "US"),
242
+ "indicators": args.get("indicators", ["rsi", "macd", "bollinger", "kdj"])
243
+ })
244
+
245
+ if name == "gprophet_fear_greed":
246
+ return _api_request("GET", "/sentiment/fear-greed", params={
247
+ "days": args.get("days", 1)
248
+ })
249
+
250
+ if name == "gprophet_market_overview":
251
+ return _api_request("GET", "/sentiment/market-overview", params={
252
+ "market": args.get("market", "CN")
253
+ })
254
+
255
+ if name == "gprophet_analyze_stock":
256
+ return _api_request("POST", "/analysis/stock", json_body={
257
+ "symbol": args["symbol"], "market": args.get("market", "US"),
258
+ "locale": args.get("locale", "en-US")
259
+ })
260
+
261
+ if name == "gprophet_analyze_comprehensive":
262
+ return _api_request("POST", "/analysis/comprehensive", json_body={
263
+ "symbol": args["symbol"], "market": args.get("market", "US"),
264
+ "locale": args.get("locale", "en-US")
265
+ })
266
+
267
+ if name == "gprophet_task_status":
268
+ return _api_request("GET", f"/analysis/task/{args['task_id']}")
269
+
270
+ if name == "gprophet_balance":
271
+ return _api_request("GET", "/account/balance")
272
+
273
+ if name == "gprophet_info":
274
+ return _api_request("GET", "/info")
275
+
276
+ return {"error": f"Unknown tool: {name}"}
277
+
278
+
279
+ def main():
280
+ """Entry point for the gprophet-mcp CLI command."""
281
+ try:
282
+ from mcp.server import Server
283
+ from mcp.server.stdio import stdio_server
284
+ from mcp.types import TextContent
285
+ except ImportError:
286
+ print(
287
+ "Error: MCP dependencies not installed.\n"
288
+ "Install with: pip install gprophet[mcp]",
289
+ file=sys.stderr,
290
+ )
291
+ sys.exit(1)
292
+
293
+ global API_KEY, BASE_URL
294
+ API_KEY = os.environ.get("GPROPHET_API_KEY", "")
295
+ BASE_URL = os.environ.get("GPROPHET_BASE_URL", "https://gprophet.com/api/external/v1")
296
+
297
+ if not API_KEY:
298
+ print("Error: GPROPHET_API_KEY environment variable is required", file=sys.stderr)
299
+ sys.exit(1)
300
+
301
+ server = Server("gprophet")
302
+ tools = _build_tools()
303
+
304
+ @server.list_tools()
305
+ async def list_tools():
306
+ return tools
307
+
308
+ @server.call_tool()
309
+ async def call_tool(name: str, arguments: dict):
310
+ try:
311
+ result = _dispatch(name, arguments)
312
+ return [TextContent(type="text", text=_format_result(result))]
313
+ except Exception as e:
314
+ return [TextContent(type="text", text=f"Error: {e}")]
315
+
316
+ async def _run():
317
+ async with stdio_server() as (read_stream, write_stream):
318
+ await server.run(read_stream, write_stream, server.create_initialization_options())
319
+
320
+ asyncio.run(_run())
321
+
322
+
323
+ if __name__ == "__main__":
324
+ main()
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.2
2
+ Name: gprophet
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the G-Prophet AI Stock Prediction API
5
+ License: MIT
6
+ Project-URL: Homepage, https://gprophet.com
7
+ Project-URL: Documentation, https://gprophet.com/docs/api
8
+ Project-URL: Repository, https://github.com/g-prophet/gprophet-python
9
+ Project-URL: Bug Tracker, https://github.com/g-prophet/gprophet-python/issues
10
+ Keywords: stock,prediction,ai,finance,trading,gprophet
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Office/Business :: Financial :: Investment
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: httpx>=0.24.0
27
+ Provides-Extra: mcp
28
+ Requires-Dist: mcp>=1.0.0; extra == "mcp"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0; extra == "dev"
31
+ Requires-Dist: pytest-httpx>=0.21; extra == "dev"
32
+
33
+ # G-Prophet Python SDK
34
+
35
+ Official Python client for the [G-Prophet](https://gprophet.com) AI Stock Prediction API.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install gprophet
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```python
46
+ from gprophet import GProphet
47
+
48
+ client = GProphet(api_key="gp_sk_your_key_here")
49
+
50
+ # Check balance
51
+ print(client.balance())
52
+
53
+ # Get a stock quote
54
+ quote = client.quote("AAPL", market="US")
55
+ print(f"AAPL: ${quote['price']}")
56
+
57
+ # AI prediction
58
+ pred = client.predict("AAPL", market="US", days=7)
59
+ print(f"Predicted: ${pred['predicted_price']} ({pred['direction']})")
60
+
61
+ # Technical analysis
62
+ tech = client.technical("AAPL", market="US")
63
+ print(f"Signal: {tech['overall_signal']}")
64
+
65
+ # Batch quotes
66
+ quotes = client.batch_quote(["AAPL", "GOOGL", "MSFT"], market="US")
67
+ for q in quotes["results"]:
68
+ if q["success"]:
69
+ print(f"{q['symbol']}: ${q['price']}")
70
+
71
+ # AI stock analysis (async with auto-polling)
72
+ analysis = client.analyze_stock("AAPL", market="US", wait=True)
73
+ print(analysis["analysis"]["summary"])
74
+ ```
75
+
76
+ ## API Reference
77
+
78
+ ### System
79
+ - `client.health()` — Health check
80
+ - `client.info()` — API metadata, pricing, supported markets
81
+
82
+ ### Account
83
+ - `client.balance()` — Points balance and quota info
84
+ - `client.usage(days=7)` — Usage statistics
85
+
86
+ ### Predictions
87
+ - `client.predict(symbol, market, days, algorithm)` — AI price prediction
88
+ - `client.compare(symbol, market, days, algorithms)` — Multi-algorithm comparison
89
+
90
+ ### Market Data
91
+ - `client.quote(symbol, market)` — Real-time quote
92
+ - `client.batch_quote(symbols, market)` — Batch quotes
93
+ - `client.history(symbol, market, period)` — Historical OHLCV
94
+ - `client.search(keyword, market, limit)` — Search symbols
95
+
96
+ ### Technical Analysis
97
+ - `client.technical(symbol, market, indicators)` — Technical indicators & signals
98
+
99
+ ### Sentiment
100
+ - `client.fear_greed(days)` — Crypto Fear & Greed Index
101
+ - `client.market_overview(market)` — Market overview
102
+
103
+ ### Analysis
104
+ - `client.analyze_stock(symbol, market, locale, wait)` — AI stock analysis (58 pts)
105
+ - `client.analyze_comprehensive(symbol, market, locale, wait)` — Multi-agent analysis (150 pts)
106
+ - `client.task_status(task_id)` — Check async task status
107
+
108
+ ## Error Handling
109
+
110
+ ```python
111
+ from gprophet import GProphet
112
+ from gprophet.client import GProphetError, RateLimitError, InsufficientPointsError
113
+
114
+ client = GProphet(api_key="gp_sk_...")
115
+
116
+ try:
117
+ result = client.predict("AAPL", market="US")
118
+ except RateLimitError as e:
119
+ print(f"Rate limited, retry after {e.retry_after}s")
120
+ except InsufficientPointsError as e:
121
+ print(f"Need {e.required} points, have {e.available}")
122
+ except GProphetError as e:
123
+ print(f"API error [{e.code}]: {e.message}")
124
+ ```
125
+
126
+ ## Configuration
127
+
128
+ ```python
129
+ client = GProphet(
130
+ api_key="gp_sk_...",
131
+ base_url="https://gprophet.com/api/external/v1", # Custom base URL
132
+ timeout=60, # Request timeout (seconds)
133
+ max_retries=3, # Auto-retry on rate limit
134
+ )
135
+ ```
136
+
137
+ ## License
138
+
139
+ MIT
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ gprophet/__init__.py
5
+ gprophet/client.py
6
+ gprophet/mcp_server.py
7
+ gprophet/py.typed
8
+ gprophet.egg-info/PKG-INFO
9
+ gprophet.egg-info/SOURCES.txt
10
+ gprophet.egg-info/dependency_links.txt
11
+ gprophet.egg-info/entry_points.txt
12
+ gprophet.egg-info/requires.txt
13
+ gprophet.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ gprophet-mcp = gprophet.mcp_server:main
@@ -0,0 +1,8 @@
1
+ httpx>=0.24.0
2
+
3
+ [dev]
4
+ pytest>=7.0
5
+ pytest-httpx>=0.21
6
+
7
+ [mcp]
8
+ mcp>=1.0.0
@@ -0,0 +1 @@
1
+ gprophet
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0,<77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gprophet"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for the G-Prophet AI Stock Prediction API"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.8"
12
+ keywords = ["stock", "prediction", "ai", "finance", "trading", "gprophet"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "Intended Audience :: Financial and Insurance Industry",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.8",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Office/Business :: Financial :: Investment",
25
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
26
+ ]
27
+ dependencies = [
28
+ "httpx>=0.24.0",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ mcp = [
33
+ "mcp>=1.0.0",
34
+ ]
35
+ dev = [
36
+ "pytest>=7.0",
37
+ "pytest-httpx>=0.21",
38
+ ]
39
+
40
+ [project.scripts]
41
+ gprophet-mcp = "gprophet.mcp_server:main"
42
+
43
+ [project.urls]
44
+ Homepage = "https://gprophet.com"
45
+ Documentation = "https://gprophet.com/docs/api"
46
+ Repository = "https://github.com/g-prophet/gprophet-python"
47
+ "Bug Tracker" = "https://github.com/g-prophet/gprophet-python/issues"
48
+
49
+ [tool.setuptools.packages.find]
50
+ include = ["gprophet*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+