# SAGAX Python SDK

SAGAX 量化交易平台 Python SDK，通过 HMAC-SHA256 签名认证调用全部 API。支持 **A股** + **期货** 双市场。

**SAGAX Python SDK** — access the SAGAX Quantitative Trading Platform API with HMAC-SHA256 authentication. Supports **A-shares** + **Futures** markets.

## Installation

```bash
pip install sagax-sdk
```

## Quick Start

```python
from sagax import SagaxClient

client = SagaxClient(
    api_key="sagax_ak_...",
    secret_key="sagax_sk_...",
    # base_url="https://api.sagax.cn",      # A-shares backend (default)
    # futures_url="https://api.sagax.cn:5001",  # Futures backend
)
```

## A-shares API (A股)

### Market Data (Basic Tier)

```python
overview = client.market.overview()          # 市场概览
indices  = client.market.indices()           # 主要指数
sectors  = client.market.sectors()           # 板块表现
gainers  = client.market.gainers(limit=10)   # 涨幅榜
losers   = client.market.losers(limit=10)    # 跌幅榜
```

### Stock Data (Basic / Standard Tier)

```python
# Basic tier
stocks = client.stock.list(page=1, per_page=50)
results = client.stock.search(q="平安银行")
info   = client.stock.basic("000001.SZ")
daily  = client.stock.daily("000001.SZ", start="2026-01-01")
price  = client.stock.price("000001.SZ")

# Structured financial data (Basic tier)
trades     = client.stock.block_trades("000001.SZ")       # 大宗交易
express    = client.stock.express("000001.SZ")             # 业绩快报
floats     = client.stock.share_float("000001.SZ")         # 限售解禁
holders    = client.stock.holdertrade("000001.SZ")         # 股东增减持

# Standard tier
indicators = client.stock.indicators("000001.SZ", days=60)
factors    = client.stock.factors("000001.SZ")
```

### Factor System (Standard Tier)

```python
all_factors = client.factors.list()                       # 因子列表
categories  = client.factors.categories()                 # 因子分类
ep_data     = client.factors.data("ep", date="2026-03-11")# 因子截面数据
detail      = client.factors.detail("ep")                 # 因子详情
bt          = client.factors.backtest("ep")               # 单因子回测
ranking     = client.factors.top_bottom("ep", top_n=20)   # 因子排行
```

### AI Analysis (Standard Tier)

```python
search = client.ai.search(q="新能源")

# 深度思考模式 (thinking) 可能耗时 1-5 分钟
valuation     = client.ai.valuation("000001.SZ", mode="thinking")
comprehensive = client.ai.comprehensive("000001.SZ")
trend         = client.ai.trend("000001.SZ")
batch         = client.ai.batch(["000001.SZ", "600000.SH"])
report        = client.ai.report("valuation", "000001.SZ")
```

### Backtesting (Advanced Tier)

```python
result = client.backtest.run(
    factors=[{"name": "ep", "weight": 0.5}, {"name": "momentum_20d", "weight": 0.5}],
    start_date="2025-01-01",
    end_date="2026-01-01",
    top_n=30,
)
saved = client.backtest.result(result["run_id"])
```

### Multi-Agent Strategy (Advanced Tier)

```python
spec   = client.agent.strategy_spec()         # 默认策略配置
result = client.agent.run()                    # 运行策略
llm    = client.agent.llm_decision()           # LLM 多智能体决策
regime = client.agent.regime()                 # 市场状态检测
```

### Factor Lab (Advanced Tier)

```python
factor  = client.factorlab.generate(prompt="高ROE低波动因子")
reviews = client.factorlab.reviews()
client.factorlab.approve("factor_xxx.py")
```

### AI Chat (Advanced Tier)

```python
# Streaming
for event in client.chat.stream("分析平安银行走势"):
    if event["type"] == "token":
        print(event["content"], end="", flush=True)

# Convenience (returns full text)
text = client.chat.send("分析平安银行走势")

# Session management
sessions = client.chat.sessions()
client.chat.delete_session("sess_xxx")
```

### News Intelligence (Advanced Tier)

```python
news      = client.news.articles(category="macro", limit=50)
signals   = client.news.signals(ts_code="000001.SZ")
dashboard = client.news.dashboard()
```

## Futures API (期货)

Futures data routes to a separate backend. Configure `futures_url` or it defaults to `base_url` (same host, different port).

```python
client = SagaxClient(
    api_key="...",
    secret_key="...",
    futures_url="http://localhost:5001",  # Futures backend
)
```

### Market Data

```python
overview = client.futures.overview()          # 市场概览
indices  = client.futures.indices()           # 主力合约行情
sectors  = client.futures.sectors()           # 按交易所分组
gainers  = client.futures.gainers(limit=10)   # 涨幅榜
losers   = client.futures.losers(limit=10)    # 跌幅榜
scan     = client.futures.market_scan()       # 异动扫描 (量能突增/持仓变动)
```

### Contract Data

```python
# Contract list & search
contracts = client.futures.contracts(exchange="SHFE", main_only=True)
results   = client.futures.search("螺纹钢")

# Single contract
info      = client.futures.basic("rb2510")
price     = client.futures.price("rb2510")
daily     = client.futures.daily("rb2510", days=60)
inds      = client.futures.indicators("rb2510")       # MA5/10/20/60
latest    = client.futures.indicators_latest("rb2510") # Latest bar

# Minute K-lines (5min / 15min)
kline     = client.futures.kline("rb2510", period="5min", limit=500)
```

## Permission Tiers

| Tier | Rate Limit | Modules |
|------|-----------|---------|
| **basic** | 60/min | market, stock (basic), futures |
| **standard** | 120/min | + factors, ai, stock (indicators/factors) |
| **advanced** | 300/min | + backtest, agent, factorlab, chat, news |

API Key permission tier is assigned by SAGAX admin.

## Error Handling

```python
from sagax import SagaxClient, AuthError, RateLimitError, NotFoundError

client = SagaxClient(api_key="...", secret_key="...")

try:
    data = client.stock.daily("000001.SZ")
except AuthError as e:
    print(f"Auth failed: {e}")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except NotFoundError:
    print("Stock not found")
```

## Configuration

```python
client = SagaxClient(
    api_key="...",
    secret_key="...",
    base_url="https://api.sagax.cn",       # A-shares API endpoint
    futures_url="https://api.sagax.cn:5001",  # Futures API endpoint
    timeout=30,                             # Default timeout (seconds)
    max_retries=3,                          # Retries on 429
)
```

## License

MIT
