跳转至

Python

tokease 是灵鲸算力指数平台的官方 Python 客户端。它做两件事:

  • 不发请求,查看五个数据集的参数和字段。
  • 携带 API Key,调用 POST /api/v1/query,把结果整理成 pandas.DataFrame。

协议、权限和字段以 接口总览 为准。本页只说明怎么用这个包。

安装

需要 Python 3.10 或更高版本。pandas 是必装依赖,没有可选安装方式。

pip install tokease
1
2
3
import tokease

tokease.__version__  # 与平台 package.json 的 version 相同

服务地址与 API Key

安装后的请求地址固定为 https://whale.tokease.cn,来自包内的 Homepage,调用时不能改。

Key 按下面的顺序取值,用到第一个非空值:

  1. Client(api_key=...)
  2. 环境变量 TOKEASE_API_KEY
  3. 环境变量 WHALEINDEX_API_KEY

五个查询方法都必须有 Key。没有 Key 时在本地抛出 TokeaseError,不会发请求。

1
2
3
4
5
import os
import tokease

os.environ["TOKEASE_API_KEY"] = "tokease_xxxxxxxxxxxx_xxxxxxxx"
client = tokease.Client(timeout=30, max_retries=5)

timeout 是单次 HTTP 超时秒数,默认 30。max_retries 是遇到分钟限流(HTTP 429 且业务码 42901)时的额外重试次数,默认 5。退避时间是 2^次数 秒再加 0 到 1 秒的随机抖动。每日额度用尽(42902)不会自动重试。

先看参数,再发请求

这些函数只读本地目录,不访问服务端。

函数 返回
list_datasets() 五个数据集名称。list_datasets("query") 相同;其他 kind 抛出 TokeaseError
dataset_params(name) 该数据集的输入参数
dataset_fields(name) 该数据集的输出字段
describe(name) 一个数据集的完整说明;省略 name 时返回全部
get_dataset(name) APISpec 对象
builtin_indices() 内置 8 个指数的代码、名称、visibility、默认排序
hardware_base_codes() 参与 Hardware_Index 的六个基础指数,不含租赁指数
import tokease

tokease.list_datasets()
# ['index_basic', 'index_daily', 'index_latest', 'index_quote', 'trade_calendar']

for item in tokease.dataset_params("index_daily"):
    print(item.name, item.description)

for item in tokease.dataset_fields("index_quote"):
    print(item.name, item.type)

spec = tokease.describe("index_latest")
print(spec["scope"], spec["sort"], spec["default_fields"])

for series in tokease.builtin_indices():
    print(series.sort_no, series.index_code, series.visibility, series.quotes, series.derived)

线上的名称、排序和公开级别以后台为准。builtin_indices() 只反映内置默认值,展示顺序请用 index_basic 返回的 sort_no。

五个查询方法

全部返回 pandas.DataFrame。参数名与服务端白名单一致,未知参数、未知字段、以及 trade_date 和日期区间同时出现,都会在本地拒绝。

方法 数据集 scope 主要参数
index_basic index_basic index:read index_code
index_daily index_daily index:read index_code、trade_date 或 start_date/end_date
index_latest index_latest index:read index_code
index_quote index_quote quote:read 同上,另加 specification
trade_calendar trade_calendar calendar:read trade_date 或 start_date/end_date

每个方法还可以传:

参数 默认 说明
fields 该数据集的全部字段 列名列表,顺序即 DataFrame 的列顺序
limit 1000 单页行数,1 到 5000
offset 0 起始偏移
paginate True 为真时按 has_more 自动取完

日期可以写 YYYYMMDD、YYYY-MM-DD,也可以传 datetime.date。发给服务端时统一成 YYYYMMDD。start_date 不能晚于 end_date。

basic = client.index_basic()
latest = client.index_latest()
daily = client.index_daily(
    index_code="Server_Index",
    start_date="20260801",
    end_date="20260831",
    fields=["trade_date", "index_code", "index_value", "change_rate"],
)
quotes = client.index_quote(
    index_code="Server_Index",
    specification="B300",
    start_date="2026-08-01",
    end_date="2026-08-31",
)
calendar = client.trade_calendar(start_date="20260801", end_date="20260831")

也可以走通用入口,效果与上面的方法相同:

1
2
3
4
5
6
7
daily = client.query(
    "index_daily",
    params={"index_code": "Server_Index", "trade_date": "20260820"},
    fields=["trade_date", "index_value"],
    limit=100,
    paginate=False,
)

省略 index_code 时,服务端只返回该 Key 有权查看的指数。一次调用里的 index_code 只能是一个代码。

DataFrame

列 DataFrame 类型
trade_date、base_date datetime64
calculated_at 带 UTC 时区的 datetime64
点位、价格、权重、涨跌、base_value float64
sort_no 可空整数 Int64
enabled、is_workday 可空布尔

空的价格或点位变成 NaN,不会变成 0。change_rate 仍是比例:0.0123 表示上涨 1.23%。

1
2
3
daily.attrs["dataset"]      # "index_daily"
daily.attrs["request_id"]   # 最后一页的 request_id,报错反馈时提供它
daily.dtypes

自动翻页会把多页拼成一张表。只要某一页时传 paginate=False,再用返回行数自己递增 offset。

能看到什么

SDK 始终走 API Key,不走网站的公开裁剪。Key 具备对应 scope 时,index_only 指数也会返回 weighted_price 和规格报价。网站上这些指数只公开点位。

仍受这些限制:

  • scope 不足、指数不在 Key 的允许范围、来源 IP 不在白名单:TokeaseAPIError,业务码 40301 或 40302。
  • visibility = member 的指数(当前是 Hardware_Index)需要有效会员。免费 Key 指定该代码会失败;省略代码时结果里不包含它。
  • 免费账户默认只能看到延迟 7 个交易日及更早的 index_daily、index_latest、index_quote。index_basic 和 trade_calendar 不受这道日期限制。
  • 新创建的 Key 默认同时具备 index:read、quote:read、calendar:read。升级前的旧 Key 可能只有其中一部分。

Hardware_Index 没有规格报价,index_quote 查不到它的明细。hardware_base_codes() 给出参与计算的六个基础指数。

错误

异常 何时出现
TokeaseError 本地问题:缺少 Key、未知数据集、非法参数或字段、日期写反、limit 超出 1–5000
TokeaseAPIError 服务端拒绝或 HTTP 失败。属性有 code、status、request_id
1
2
3
4
5
6
7
8
from tokease import TokeaseAPIError, TokeaseError

try:
    frame = client.index_daily(index_code="Hardware_Index", trade_date="20260820")
except TokeaseError as exc:
    print(exc)
except TokeaseAPIError as exc:
    print(exc.code, exc.status, exc.request_id, exc)

Key 无效是 40102,过期是 40103。带了无效 Key 不会改用登录会话。

一次取齐最新行情

1
2
3
4
5
6
7
8
9
import tokease

client = tokease.Client()
latest = client.index_latest(
    fields=["index_code", "trade_date", "index_value", "change_rate", "weighted_price"],
)
latest = latest.sort_values("index_code")
print(latest.to_string(index=False))
print("request_id", latest.attrs["request_id"])