Metadata-Version: 2.5
Name: nlalpha_tushare
Version: 0.3.3
Summary: Tushare data provider plugin for NLAlpha
Project-URL: Homepage, https://github.com/ruimarj/nlalpha-tushare
Project-URL: Repository, https://github.com/ruimarj/nlalpha-tushare
Project-URL: Issues, https://github.com/ruimarj/nlalpha-tushare/issues
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
Requires-Python: <3.13,>=3.12
Requires-Dist: nlalpha-core>=0.7.0
Requires-Dist: nlalpha-data>=0.4.0
Requires-Dist: six>=1.16
Requires-Dist: tushare>=1.4
Description-Content-Type: text/markdown

# nlalpha-tushare 0.3.3

Tushare data source plugin: it provides nlalpha-data with daily bars for A-share stocks, indices, futures, ETFs/funds, convertible bonds, and options, plus minute-bar access for A-share stocks and futures. It is discovered at runtime through the `nlalpha.data` entry point and installed into the data image.

## Positioning

nlalpha-tushare is a **data provider plugin** in the nlalpha ecosystem and does not run on its own. It is discovered by `nlalpha-data` (an MCP server) through the `nlalpha.data` group of `importlib.metadata.entry_points`:

- The plugin class `TusharePlugin` (`__init__.py`) declares metadata and availability; `get_provider()` returns the data provider instance.
- The provider class `TushareDataProvider` (`provider.py`) implements the `DataProvider` contract, pulls bars from the Tushare Pro API, and converts them into internal `Bar` structures.
- Caching is managed by `nlalpha-data`'s `DataLoader` / Parquet store; this package only handles API fetching.

## Provider manifest

`get_manifest()` returns an `nlalpha.provider_manifest.v1` document validated by the provider SDK. It declares the machine-readable `capabilities` block (asset classes, intervals, adjustment support, reference/realism data, calendar exchanges), the six China-specific `tools` with input/output JSON Schemas, and the `guidance_sections` that `confess` reads from `knowledge/provider.md`; `nlalpha-data` surfaces it through `about` and `confess`. The six China-specific tools are provider-declared and are not separate MCP tools: call them through the data service gateway as `data.invoke_provider_tool("tushare", "<tool>", {...})`, which validates arguments against the declared input schema and bounds the response. The provider base contains no vendor branches.

## Reference and realism data

Besides bars, the provider exposes reference and realism data to `nlalpha-data`:

| Capability | Provider method | Tushare endpoint |
|---|---|---|
| Instrument master | `list_instruments` | `stock_basic`/`index_basic`/`fund_basic`/`fut_basic`/`cb_basic`/`opt_basic` |
| Trading calendar | `get_trading_calendar` | `trade_cal` (no GFEX) |
| Daily indicators | `get_daily_basic` | `daily_basic` |
| Price limits | `get_price_limits` | `stk_limit` |
| Suspensions and resumptions | `get_suspensions` | `suspend_d` |
| Index weights | `get_index_weights` | `index_weight` |

Instrument, calendar, and realism requests use yearly chunks where applicable, enforce endpoint row caps, return JSON-safe rows, and treat an empty response as a valid empty list. Futures and options require an explicit `market`; `status` is only accepted for stock and fund. Endpoint mappings, units, and normalization rules are documented in [`provider.md`](src/nlalpha_tushare/knowledge/provider.md).

## Availability semantics

Whether the data source is available is decided by `is_available()`, which is the source of truth for provider registration and status display (`discover_data_providers` filters plugins by it, and `list_data_providers` shows status by it):

- `TusharePlugin.is_available()`: the `tushare` library is installed (`find_spec` probe, without triggering an actual import) **and** the `TUSHARE_TOKEN` environment variable is configured.
- `TushareDataProvider.is_available()`: the token passed to the constructor is non-empty **and** the `tushare` library is importable.

If either condition is unmet, the data source is not registered, and queries return an explicit "no available data source" error instead of registering and failing only on the first call.

## Dependencies

| Package | Relationship |
|----|------|
| `nlalpha-core` | market/time contracts, errors, and shared telemetry library |
| `nlalpha-data` | `DataProvider` base class and `Bar` contract |
| `tushare>=1.4` | Third-party data API client. |

## Runtime configuration

| Environment variable | Description |
|----------|------|
| `TUSHARE_TOKEN` | Tushare Pro API token, required. Provide it through the deployment's secret mechanism. |

## Network contract

The tushare 1.4.x client requests `http://api.waditu.com:80` by default (a deprecated endpoint). Deployments commonly allow only public HTTPS outbound traffic, so `_get_pro()` forces the endpoint to `https://api.tushare.pro/dataapi` (verified working inside the provider). Do not bypass an outbound policy at the deployment layer.

## Independent package boundary

This package is an independent Python package. Its package boundary and entry-point declaration must not be merged into another package.

## Time interpretation

This provider targets domestic CN stock, index, futures (including continuous series), ETF/fund, convertible bond, and option symbols; its handling is not a claim about every Tushare feed. Daily stock/index/ETF-fund/convertible-bond `trade_date` values are session labels mapped to real exchange-calendar bounds (XSHG/XBSE), not local midnight or a 24-hour bar. Daily futures, continuous futures, and commodity options require an explicit per-symbol `session_calendars` constructor mapping; equity options use XSHG. No stock calendar or China-market default is substituted for an unknown futures or commodity option contract calendar.

Minute requests route to `stk_mins` or `ft_mins` rather than falling back to daily endpoints. Since endpoint meaning is not inferred, configure `minute_timestamp_semantics="open"` or `"close"` on `TushareDataProvider`, or set `TUSHARE_MINUTE_TIMESTAMP_SEMANTICS`. The current domestic feed handling interprets `trade_time` in Asia/Shanghai; this is not a universal Tushare timezone guarantee. Returned Bars carry UTC bounds and original source timezone, timestamp semantics, UTC offset, session label (when supplied), and calendar ID. The interval is an aggregation label; explicit session bounds represent actual endpoints and need not span the nominal fixed interval.

## Historical Tushare 0.2.0 focused verification

Tushare 0.2.0 private stub checks covered daily session labels, injected futures night-session bounds, minute endpoint routing, composite-provider time-contract propagation, and MCP Drawer artifact metadata matching. No live Tushare request or full suite was run.

## Volume-unit contract

Tushare returns Bar values whose volume has already been normalized according to the source contract. Explicit `volume_unit` and `bar_contract` metadata are returned by `nlalpha_data.load_bars` and included in Parquet exports. Daily `vol` is converted from lots to instrument quantity: ×100 for stock/index/ETF-fund (shares or units), ×10 for convertible bonds, and ×1 for options. Stock minute volume is already shares; futures volume remains in contract units, including adjusted continuous futures. Callers must not convert it again or branch on provider identity. Missing source fields and upstream errors remain visible errors. Unknown calendars remain rejected; this plugin does not claim a general China futures calendar.

## Price adjustment: stock, fund, and continuous futures

Stock daily uses `daily` plus `adj_factor`; ETF/fund daily uses `fund_daily` plus `fund_adj`. For both, `forward` (qfq) computes `raw * factor / anchor` with the anchor taken from the latest trading day in the request window, while `backward` (hfq) computes `raw * factor`. Only OHLC is adjusted, values are not rounded, and missing factor rows fail with the affected dates. Daily rows are split into calendar-year chunks; adjustment factors are fetched once for the full request range, fall back to yearly chunks only when the row cap is reached, and are cached for six hours. Account-level rate limits (for example 1/min or 1/hour on `adj_factor`) surface as retryable `rate_limited` errors. Stock caps both endpoints at 6000 rows, fund caps `fund_daily` at 5000 and `fund_adj` at 2000, and reaching a cap fails explicitly. Fund evidence: [fund adjustment](https://tushare.pro/document/2?doc_id=199).

Continuous futures are recognized on futures venues when the code is letters plus at most two digits (`^[A-Z]+\d{0,2}$`, e.g. `IF.CFX`, `IFL1.CFX`); four-digit YYMM contracts such as `IF2501.CFX` are not continuous. They support only daily `forward`/`backward`; `unadjusted`, omitted adjustment, and minute requests fail, and a symbol-specific `session_calendars` entry is required. `backward` uses `fut_daily_adj` directly because it is already back-adjusted. `forward` additionally fetches `fut_adjfactor`, merges on `trade_date`, and divides OHLC by the latest-window factor using `Decimal`; volume and open interest are unchanged. `fut_daily_adj` uses calendar-year chunks capped at 3000 rows; `fut_adjfactor` is fetched once for the full range with the same cap fallback and cache. Evidence: [fut_daily_adj](https://tushare.pro/document/2?doc_id=492), [fut_adjfactor](https://tushare.pro/document/2?doc_id=499).

Official references: [stock daily](https://tushare.pro/document/2?doc_id=27), [index daily](https://tushare.pro/document/2?doc_id=95), [fund daily](https://tushare.pro/document/2?doc_id=127), [fund adjustment](https://tushare.pro/document/2?doc_id=199), [convertible bond daily](https://tushare.pro/document/2?doc_id=187), [option daily](https://tushare.pro/document/2?doc_id=159), [futures daily](https://tushare.pro/document/2?doc_id=138), [fut_daily_adj](https://tushare.pro/document/2?doc_id=492), [fut_adjfactor](https://tushare.pro/document/2?doc_id=499), [stock minute](https://tushare.pro/document/2?doc_id=370).

## Canonical route and evidence guide

The provider-specific symbol routing, interval aliases, adjustment evidence, minute timestamp requirement, daily futures calendar requirement, and availability limits are documented in [`provider.md`](src/nlalpha_tushare/knowledge/provider.md). Stock and ETF/fund daily support `unadjusted`, `forward`, and `backward`; forward/backward OHLC is computed locally from their daily and factor endpoints with a request-end qfq anchor, without `pro_bar` or two-decimal rounding. Continuous futures support only `forward` and `backward`, using `fut_daily_adj` and `fut_adjfactor`. The plugin reads `TUSHARE_MINUTE_TIMESTAMP_SEMANTICS` when constructing its provider; direct construction uses the `minute_timestamp_semantics` argument. The data service's `confess(provider_id="tushare")` reads this guide from the provider package. Neither a configured token nor provider availability proves that a specific endpoint is covered or permitted for the account; runtime guide integration remains pending.

## License

Community distribution under AGPL-3.0-or-later. The license covers this NLAlpha package and its own distribution; Tushare and other third-party dependencies retain their own licenses.
