系列:Python实时盯盘与预警 · 第 01 篇 · 适合初学 · 5 分钟读完即可跑通
痛点开场
中午吃饭回来打开同花顺,30 只自选股一通翻:先看平安银行,再看宁德,再点比亚迪——回过神来 5 分钟过去了,异动早过去了。
真正的问题不是"我有没有数据",而是一屏看不见 30 只的当前价 + 涨跌幅。本文就用一份麦蕊/必盈/魔码/智兔任一品牌的 API 证书(免费版就够),把 30 只自选股的实时报价聚到一屏,按涨跌幅排序,一眼看出谁动了。
本文你将得到什么
环境准备(5 分钟)
- 安装 mairui 1.0.0:pip install mairui(建议安装在专用 conda 环境 fastApiEnv,不要污染系统 Python)
- 准备一份证书(作为占位符在脚本里以 MAIRUI_LICENCE 环境变量传入)
- 执行前 set MAIRUI_LICENCE=<你的麦蕊证书>
完整可运行脚本
自验环境:fastApiEnv / Python 3.9 / mairui 1.0.0;30 只自选股已 PASS 跑通。
"""【Python实时盯盘与预警 #01】自选股实时报价+涨跌幅一屏看完"""
from __future__ import annotations
import os
import sys
from datetime import datetime
# 复用内容龙虾 _common/mairui_helper.py 的证书加载器(只读不打印)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "_common"))
from mairui_helper import load_licence # noqa: E402
from mairui import Client # noqa: E402
# 30 只自选股(股票代码 = 6 位数字;也可改用 stock_list() 过滤行业/板块)
DEFAULT_WATCHLIST = [
"000001", "000002", "000333", "000858", "002594",
"300750", "600000", "600028", "600030", "600276",
"600519", "600887", "601012", "601318", "601398",
"601857", "601988", "688981", "002475", "300059",
"600036", "601166", "600900", "601288", "601628",
"600585", "000063", "000725", "002415", "300760",
]
def fetch_quotes(api: Client, codes: list[str]) –> list[dict]:
quotes = []
for code in codes:
try:
q = api.stock_real_time(code)
except Exception as e:
print(f"[warn] {code} 取数失败:{e}", file=sys.stderr)
continue
if not isinstance(q, dict):
continue
quotes.append({
"code": code, "price": q.get("p"), "prev_close": q.get("yc"),
"change_pct": q.get("zf"), "turnover": q.get("hs"),
"amount": q.get("cje"), "amplitude": q.get("tr"), "time": q.get("t"),
})
return quotes
def render(quotes: list[dict]) –> str:
quotes.sort(key=lambda x: –(x["change_pct"] or 0))
lines = [
f"【自选股 实时盯盘快照】时间 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 共 {len(quotes)} 只",
f"{'排名':>3} {'代码':<7} {'现价':>7} {'涨跌幅%':>9} {'成交额(亿)':>10} {'换手率%':>9} {'振幅%':>8} {'时间':<20}",
]
for i, q in enumerate(quotes, 1):
pct = q["change_pct"] if q["change_pct"] is not None else 0.0
marker = "▲" if pct > 0 else ("▼" if pct < 0 else "·")
amount_yi = (q["amount"] or 0) / 1e8
lines.append(
f"{i:>3} {q['code']:<7} {q['price']:>7.2f} {marker}{pct:>7.2f}% "
f"{amount_yi:>9.2f} {(q['turnover'] or 0):>8.2f}% {(q['amplitude'] or 0):>7.2f}% {str(q['time'] or ''):<20}"
)
return "\\n".join(lines)
def main() –> int:
lic = load_licence()
print(f"[info] licence present: True (value hidden, len={len(lic)})")
with Client(licence=lic) as api:
quotes = fetch_quotes(api, DEFAULT_WATCHLIST)
print(render(quotes))
print(f"\\n[统计] 上涨 {sum(1 for q in quotes if (q['change_pct'] or 0) > 0)} / "
f"下跌 {sum(1 for q in quotes if (q['change_pct'] or 0) < 0)} / "
f"平 {sum(1 for q in quotes if (q['change_pct'] or 0) == 0)}")
return 0
if __name__ == "__main__":
sys.exit(main())
真实运行输出(截取)
【自选股 实时盯盘快照】时间 2026-08-02 09:55:16 共 30 只
排名 代码 现价 涨跌幅% 成交额(亿) 换手率% 振幅% 时间
1 688981 123.99 ▲ 9.19% 100.61 0.00% 3.87% 2026-07-31 15:00:04
2 002415 37.65 ▲ 6.85% 63.30 0.00% 1.90% 2026-07-31 15:00:00
3 002475 57.48 ▲ 6.55% 106.93 0.00% 2.48% 2026-07-31 15:00:00
…
30 300760 158.88 ▲ 1.38% 17.85 0.00% 0.93% 2026-07-31 15:00:00
[统计] 上涨 30 / 下跌 0 / 平 0
表中数据来源:内部验证环境 fastApiEnv + 本地 licence 调用 /hsrl/stock_real_time 接口返回,未带具体证书(占位符 MAIRUI_LICENCE)。
💡 真实盘中到 09:30 / 10:00 / 14:00 等关键时点,下一次刷新时间戳就会落到当天的盘中时间;本文示例运行时间 09:55,刚好开盘前的尾盘数据,所以时间戳是 2026-07-31 15:00。盘中做实时盯盘,刷新间隔建议 3 秒。
代码要点拆解
接入盘中实时(30 秒接入)
把 main() 改成下面这版即可,每 3 秒拉一次,对应 Time 列连续闪烁:
import time
def loop():
while True:
with Client(licence=load_licence()) as api:
quotes = fetch_quotes(api, DEFAULT_WATCHLIST)
# 终端清屏仅 Windows 示例;macOS/Linux 用 'clear'
os.system("cls" if os.name == "nt" else "clear")
print(render(quotes))
time.sleep(3)
常见坑
小结 + 下篇预告
本文给出了单文件、零外部依赖、30 只自选股的盘中盯盘骨架——可在 5 分钟内搭起来跑。下篇 #02 我们加"涨跌幅阈值"——到 ±3% 自动本地提示(或桌面通知),把"看完才知道"变成"到了立刻知道"。
合规与引导
数据/接口演示仅作技术示意,不构成投资建议。本系列代码仅用于自验与教学,请勿用于非法牟利
提示:脚本中所有"证书"出现处都用 MAIRUI_LICENCE 环境变量或 <你的麦蕊证书> 占位;任何含真实证书 UUID 的版本都不应被发布。




