--- title: Sina Real Time API emoji: 📈 colorFrom: blue colorTo: green sdk: docker app_port: 7860 pinned: false --- # Sina Real Time API 把原来的新浪财经 WebSocket 实时行情采集器改成了一个可部署到 Hugging Face Spaces 的 Docker API 服务。 服务启动后会: 1. 连接 `wss://hq.sinajs.cn/wskt` 实时推送接口; 2. 按 `--chunk-size` 拆分为多个并行 WebSocket 连接; 3. 将最新行情保存在内存中,供 HTTP API 查询; 4. 同时继续将原始记录写入每日 CSV:`data/data_YYYY-MM-DD.csv`。 ## API ### `GET /health` 服务状态。 ```bash curl https://.hf.space/health ``` 返回示例: ```json { "ok": true, "started_at": "2026-04-25T08:00:00.000", "watched_codes": 100, "cached_quotes": 100 } ``` ### `GET /codes` 返回当前监听的股票代码列表。 ```bash curl https://.hf.space/codes ``` ### `GET /latest?limit=100` 返回最新缓存行情列表,默认最多 100 条。 ```bash curl "https://.hf.space/latest?limit=20" ``` ### `GET /latest/{code}` 查询单只股票最新行情。 ```bash curl https://.hf.space/latest/sh600519 ``` 也可以用 query 参数: ```bash curl "https://.hf.space/latest?code=sh600519" ``` ### `GET /batch?codes=...` 查询多只股票最新行情。 ```bash curl "https://.hf.space/batch?codes=sh600519,sz000001" ``` ## 返回字段 `/latest` 返回的每条行情大致包含: ```json { "received_at": "2026-04-25T09:30:00.123", "code": "sh600519", "name": "贵州茅台", "previous_close": "...", "open": "...", "price": "...", "high": "...", "low": "...", "bid1": "...", "ask1": "...", "volume": "...", "amount": "...", "trade_date": "...", "trade_time": "...", "status": "...", "raw_fields": "新浪原始字段字符串", "fields": ["新浪原始字段数组"] } ``` ## 部署到 Hugging Face Spaces ### 方法一:网页上传 1. 在 Hugging Face 创建一个新的 Space。 2. SDK 选择 **Docker**。 3. 把本仓库所有文件上传到 Space。 4. 等待自动 build 完成。 5. 打开 `https://.hf.space/health` 测试。 ### 方法二:Git 推送 ```bash git lfs install huggingface-cli login # 新建 Space 后,把下面的地址替换成你的 Space 仓库地址 git remote add space https://huggingface.co/spaces// git add . git commit -m "Deploy Sina real-time API" git push space main ``` ## 切换股票池 默认 Docker 启动命令使用 `stocks_100.txt`,适合先部署验证。你可以在 `Dockerfile` 末尾修改: ```dockerfile CMD ["sina-realtime-api", "--stocks", "stocks_1000.txt", "--output", "data", "--chunk-size", "500"] ``` 或者全量: ```dockerfile CMD ["sina-realtime-api", "--stocks", "stocks_all.txt", "--output", "data", "--chunk-size", "500"] ``` 全量沪深 A 股会建立更多 WebSocket 连接,不建议一开始就在 Hugging Face 免费资源上直接跑全量。 ## 本地 Docker 测试 ```bash docker build -t sina-real-time-api . docker run --rm -p 7860:7860 sina-real-time-api curl http://localhost:7860/health ``` ## 命令行参数 ```text Options: -s, --stocks 股票列表文件 [default: stocks_100.txt] -o, --output 输出目录 [default: data] --chunk-size 每个连接的股票数 [default: 500] --buffer 通道缓冲容量 [default: 131072] --api-host API host [default: 0.0.0.0] --api-port API port;未设置时读取 PORT 环境变量,否则 7860 -h, --help -V, --version ``` ## 注意事项 - 非 A 股交易时段,新浪上游可能不推送新数据;这时 `/health` 可能正常,但 `/latest/{code}` 可能暂时返回 `quote_not_ready`。 - Hugging Face Spaces 的文件系统不适合作为长期数据库,CSV 更适合调试或短期缓存;生产环境建议接入数据库或对象存储。 - 如果 Space 休眠,重启后内存缓存会清空,需要等待上游重新推送行情。