Metadata-Version: 2.2
Name: gprophet
Version: 0.2.0
Summary: Official Python client for G-Prophet, an auditable quantitative market research platform that turns market data and model outputs into reviewable research records
License: MIT
Project-URL: Homepage, https://www.gprophet.com
Project-URL: Documentation, https://www.gprophet.com/api-docs
Project-URL: Repository, https://github.com/g-prophet/gprophet-python
Project-URL: Bug Tracker, https://github.com/g-prophet/gprophet-python/issues
Keywords: stock,model-projection,ai,finance,research,gprophet
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Provides-Extra: mcp
Requires-Dist: mcp<2.0.0,>=1.26.0; extra == "mcp"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-httpx>=0.21; extra == "dev"
Requires-Dist: mcp<2.0.0,>=1.26.0; extra == "dev"

# G-Prophet Python SDK

Official Python client for [G-Prophet](https://www.gprophet.com), an auditable quantitative market research platform that turns market data and model outputs into reviewable research records.

G-Prophet produces research material. Its output is not personalised investment advice, a trading recommendation, or an instruction to buy, sell, or hold any instrument. The platform is built for research, model observation, and retrospective evaluation; historical results do not guarantee future performance.

## Scope and data semantics

`predict()` and `compare()` return a **model reference path**: one reference price per market-local trading date, with uncertainty bounds tied to that same date. The path is not actual future OHLCV, and it is not a price forecast.

`predicted_price` is a field name kept for compatibility with existing API clients. It carries the same value as the last point's `model_reference_price` inside `model_reference_path` — a model reference value, not a predicted market price. `direction` and `change_percent` describe the shape of that reference path relative to the latest quote; neither is a trading signal. Use `history()` for observed historical OHLCV.

## Installation

```bash
pip install gprophet
```

To also use the MCP Server (for AI agents like Claude, Kiro, etc.):

```bash
pip install "gprophet[mcp]"
```

The core HTTP SDK supports Python 3.8+. The MCP extra requires Python 3.10+.

## Quick Start

```python
from gprophet import GProphet, InsufficientPointsError

client = GProphet(api_key="gp_sk_your_key_here")

# Free planning check: reads live pricing from /info and the current balance.
# It does not reserve points, so the paid call can still return HTTP 402 later.
plan = client.preflight("quote", market="US")
print(plan)  # ready plus point, scope, and daily/monthly quota checks

# Get a stock quote
if plan["ready"]:
    try:
        quote = client.quote("AAPL", market="US")
        print(f"AAPL: ${quote['price']}")
    except InsufficientPointsError as exc:
        # Another concurrent call may have spent points after the preflight.
        print(exc.to_dict())

# Daily model reference path: one reference price per market trading day
pred = client.predict("AAPL", market="US", days=7)
print(f"Model reference: ${pred['predicted_price']} ({pred['direction']})")
for point in pred["model_reference_path"]["points"]:
    print(point["date"], point["model_reference_price"])

# CN/A-share model reference path can use G-Prophet2026V2, with V1 as fallback.
cn_pred = client.predict("600519", market="CN", days=7, algorithm="gprophet2026v2")
print(f"600519: ¥{cn_pred['predicted_price']} ({cn_pred['direction']})")

# Technical analysis
tech = client.technical("AAPL", market="US")
print(f"Indicator observation: {tech['overall_signal']}")

# Batch quotes
quotes = client.batch_quote(["AAPL", "GOOGL", "MSFT"], market="US")
for q in quotes["results"]:
    if q["success"]:
        print(f"{q['symbol']}: ${q['price']}")

# AI-assisted research report (async with auto-polling)
analysis = client.analyze_stock("AAPL", market="US", wait=True)
print(analysis["analysis"]["summary"])

# International markets: search first, then use the returned canonical symbol
results = client.search("HSBA", market="UK")
symbol = results["results"][0]["symbol"]  # e.g. HSBA.LON
uk_pred = client.predict(symbol, market="UK", days=7)

# Japan and Korea examples
jp_pred = client.predict("7203.T", market="JP", days=7)
kr_pred = client.predict("005930.KS", market="KR", days=7)
```

Only public metadata is needed? `GProphet().health()` and `GProphet().info()` work without a key. Paid, account, and authenticated health methods still require one.

## MCP Server (for AI Agents)

After installing with `pip install gprophet[mcp]`, a `gprophet-mcp` command is available.
The MCP server may start without `GPROPHET_API_KEY` for the public
`gprophet_health` and `gprophet_info` tools. Protected tools then return a
structured `MISSING_API_KEY` error instead of preventing server startup.

See [MCP Server documentation](https://github.com/g-prophet/gprophet-python/tree/main/mcp-server) for setup details.

## API Reference

### System
- `client.health()` — Public origin-reachability check (`GET /health`)
- `client.auth_health()` — Validate the API key/account and report quota counters and points for free
- `client.prediction_health(market)` — Check prediction scope, market, and one-run point affordability for free
- `client.info()` — API metadata, pricing, supported markets, currency, timezone, and market_details

Supported markets are `US`, `CN`, `HK`, `JP`, `KR`, `CRYPTO`, `UK`, `CA`, `DE`, and `IN`. Prefer `client.info()` as the source of truth instead of hard-coding this list.

The health methods do not run a model or deduct points.

Symbol notes:
- HK accepts bare digits, zero-padded codes, or `.HK` suffix. `700`, `0700`, and `700.HK` resolve to the same Hong Kong listing.
- JP accepts bare or `.T` symbols such as `7203` and `7203.T`; KR accepts 6-digit symbols with optional `.KS` / `.KQ` suffixes such as `005930.KS` and `035420.KQ`.
- UK is the official market code for UK stocks. Do not use `GB` or `LSE` as the `market`; use symbols such as `HSBA.LON`.
- For AI agents and automation, call `client.search(...)` first when the ticker is uncertain, then call `predict(...)` with the returned canonical `symbol`.

### Account
- `client.balance()` — Points balance and quota info
- `client.usage(days=7)` — Usage statistics
- `client.estimate_cost(operation, market, count)` — Estimate cost from the `/info` pricing table (cached for up to five minutes by default)
- `client.preflight(operation, market, count)` — Refresh pricing and evaluate known point, scope, and quota gates without spending or reserving points
- `client.check_points(required)` — Check a known point requirement against the current balance
- `client.ensure_points(required)` — Raise a structured `InsufficientPointsError` if the balance is too low

Preflight is intentionally explicit rather than automatic on every paid method. This avoids an extra network round trip when the caller does not need it. It refreshes `/info` pricing by default; pass `refresh_pricing=False` only when pricing cached for up to five minutes is acceptable. For `compare`, omitting `count` uses the SDK's default model count (CN 5, other markets 4); for `batch_quote`, pass the exact symbol count. Treat the result as planning information, not a reservation of points or a rate-limit slot; always handle a later HTTP 402/429 from the paid call.

### Model reference path
- `client.predict(symbol, market, days, algorithm)` — Daily model reference path plus summary fields
- `client.compare(symbol, market, days, algorithms)` — Multi-algorithm summary comparison with currency/timezone; no per-algorithm path

`predict()` returns `currency`, IANA `timezone`, and `model_reference_path.points` with date-aligned uncertainty bounds. `predicted_price` is the path's final `model_reference_price` under the field name existing clients already read; treat it as a model reference value, not a predicted market price or price target. `uncertainty.confidence_level` is a model-reported score, not nominal coverage; do not interpret it as a calibrated “95% confidence interval.” The path is not actual future OHLCV. Use `history()` for observed historical OHLCV. Every paid prediction response also repeats this framing in a top-level `research_disclaimer` field.

Supported model algorithms include `auto`, `gprophet2026v1`, `gprophet2026v2` (CN/A-shares only), `lstm`, `transformer`, `random_forest`, and `ensemble`.
For `client.compare(...)`, the default CN algorithm list includes `gprophet2026v2`; other markets do not expose V2.

### Market Data
- `client.quote(symbol, market)` — Latest available quote with currency/timezone
- `client.batch_quote(symbols, market)` — Batch quotes with currency/timezone
- `client.history(symbol, market, period)` — Observed historical OHLCV with currency/timezone
- `client.search(keyword, market, limit)` — Search symbols with market currency/timezone

### Technical Analysis
- `client.technical(symbol, market, indicators)` — Technical indicators and observations; defaults to RSI, MACD, Bollinger, KDJ, SMA, and EMA

### Sentiment
- `client.fear_greed(days)` — Crypto Fear & Greed Index
- `client.market_overview(market)` — Market overview

### Analysis
- `client.analyze_stock(symbol, market, locale, callback_url, wait)` — AI-assisted research report (58 pts)
- `client.analyze_comprehensive(symbol, market, locale, callback_url, wait)` — Multi-agent, multi-factor research review (150 pts)
- `client.task_status(task_id)` — Check async task status

Both analysis methods accept an optional `callback_url`. It must be a public
HTTPS URL without user information and must not use localhost or a
private/reserved IP literal. It is limited to 2048 characters and cannot
contain backslashes, control characters, or an explicit port 0. The SDK
rejects invalid callbacks before sending the paid request. The API may
additionally return `VALIDATION_ERROR` (HTTP 422) after server-side safety
checks; correct the URL rather than retrying it unchanged. When `wait=True`,
`poll_interval` and `max_wait` must
both be positive finite numbers.

After an analysis task has been created, polling failures never make the paid
analysis call itself retryable. The raised error includes `task_id`,
`poll_retryable`, and an `agent_action` directing callers to continue only with
`client.task_status(task_id)`; do not resubmit the analysis automatically.

## Error Handling

```python
from gprophet import (
    GProphet,
    GProphetError,
    InsufficientPointsError,
    RateLimitError,
)

client = GProphet(api_key="gp_sk_...")

try:
    result = client.predict("AAPL", market="US")
except RateLimitError as e:
    print(f"Rate limited, retry after {e.retry_after}s")
except InsufficientPointsError as e:
    print(f"Need {e.required} points, have {e.available}, shortage {e.shortage}")
    # retryable is False: add points before retrying the paid call.
except GProphetError as e:
    print(e.to_dict())
```

The SDK automatically retries only transient `RATE_LIMITED` responses. It does not retry `INSUFFICIENT_POINTS` or `QUOTA_EXCEEDED`. A timeout or malformed gateway response from a paid endpoint is also marked non-retryable because the server may already have consumed points; check usage, balance, or task state before deciding what to do. Downstream agents should follow the structured `retryable` and `agent_action` fields.

## Configuration

```python
client = GProphet(
    api_key="gp_sk_...",
    base_url="https://www.gprophet.com/api/external/v1",  # Custom base URL
    timeout=120,      # Request timeout (seconds); recommended for DE/IN and other slower international markets
    max_retries=3,    # Auto-retry only transient RATE_LIMITED responses
)
```

## License

MIT
