吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2815|回复: 34
收起左侧

[Python 原创] 上班查看股票走势图,纯娱乐

  [复制链接]
jiatengxian 发表于 2026-1-16 16:07
本帖最后由 jiatengxian 于 2026-1-16 16:19 编辑

背景:
1、本人上班族,工位不太方便看股票的客户端
2、由于股票的客户端红红绿绿的很明显,领导,同事一眼就能发现
3、本人又想看看股票的走势

下附源码,以开盘价为0轴线,开盘上涨即+%,开盘下跌后即-%
直接双击运行后,在弹框中输入对应代码
由于是周五收盘后所写,实时更新走势图未经验证,下周要有时间会在原贴继续优化

临时所写  我自己将就看 下跌百分比可能有点问题  总比没有强

没有py环境的下述网盘提供了可直接运行的exe
通过网盘分享的文件:bbb.exe
链接: https://pan.baidu.com/s/1EnBkIgbG60vk_3NJEdqDBA?pwd=jmah 提取码: jmah

下附源码:感兴趣的可以自己优化下
[Python] 纯文本查看 复制代码
import requests
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import time

# 请求头
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "Referer": "https://quote.eastmoney.com/"
}

# 股票市场前缀
def get_market(code):
    if code.startswith("6"):
        return "1." + code   # 上证
    elif code.startswith("0") or code.startswith("3"):
        return "0." + code   # 深证
    else:
        raise ValueError("股票代码格式错误,应如 600519 / 002044")

# 获取分时数据和昨日收盘价
def get_minute_data(code):
    secid = get_market(code)
    url = "https://push2his.eastmoney.com/api/qt/stock/trends2/get"
    params = {
        "secid": secid,
        "fields1": "f1,f2,f3,f4,f5",
        "fields2": "f51,f52,f53,f54,f55",
        "ut": "fa5fd1943c7b386f172d6893dbfba10b",
        "iscr": "0",
        "ndays": "1"
    }

    r = requests.get(url, params=params, headers=HEADERS, timeout=10, proxies={"http": None, "https": None})
    r.raise_for_status()
    j = r.json()
    data = j.get("data", {})
    trends = data.get("trends", [])

    if not trends:
        raise ValueError("接口未返回有效分时数据")

    prices = []
    for item in trends:
        parts = item.split(",")
        try:
            price = float(parts[1])
            prices.append(price)
        except:
            continue

    if len(prices) < 2:
        raise ValueError("分时数据不足")

    yesterday_close = float(data.get("preclose", prices[0]))
    return prices, yesterday_close

# 绘制初始图
def draw_chart(prices, yesterday_close, code):
    percents = [(p - yesterday_close) / yesterday_close * 100 for p in prices]

    plt.ion()  # 开启交互模式
    fig, ax = plt.subplots(figsize=(10, 5))
    line, = ax.plot(percents, linestyle="--", color="black", linewidth=1.6)
    ax.axhline(0, color="black")  # 0轴对应昨日收盘

    # 自定义Y轴刻度带符号
    def y_format(x, pos):
        if x > 0:
            return f"+{x:.2f}"
        elif x < 0:
            return f"{x:.2f}"
        else:
            return "0"
    ax.yaxis.set_major_formatter(mticker.FuncFormatter(y_format))

    plt.title(f"{code} 实时分时走势(涨跌幅 %)")
    plt.xlabel("时间(分钟)")
    plt.ylabel("涨跌幅 %")
    plt.grid(False)
    plt.show(block=False)

    return fig, ax, line

# 更新曲线
def update_chart(fig, ax, line, prices, yesterday_close):
    percents = [(p - yesterday_close) / yesterday_close * 100 for p in prices]

    line.set_ydata(percents)
    line.set_xdata(range(len(percents)))
    ax.relim()
    ax.autoscale_view()
    fig.canvas.draw()
    fig.canvas.flush_events()

# 主程序
def main():
    code = input("请输入股票代码(如 600519 / 002044):").strip()

    try:
        prices, yesterday_close = get_minute_data(code)
        print(f"获取到 {len(prices)} 个分时点,开始绘图…")
        fig, ax, line = draw_chart(prices, yesterday_close, code)

        while True:
            try:
                prices, _ = get_minute_data(code)
                update_chart(fig, ax, line, prices, yesterday_close)
                time.sleep(5)  # 每 5 秒刷新一次
            except Exception as e:
                print("更新失败:", e)
                time.sleep(5)

    except Exception as e:
        print("获取数据失败:", e)

if __name__ == "__main__":
    main()






下附运行截图



运行图一

运行图一

运行图二

运行图二

免费评分

参与人数 3吾爱币 +9 热心值 +3 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
zhaoyf18 + 1 + 1 用心讨论,共获提升!
wanfon + 1 + 1 热心回复!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

tomato798 发表于 2026-2-5 16:32
本帖最后由 tomato798 于 2026-2-5 16:33 编辑
ketidea 发表于 2026-1-29 09:37
拖动反应很慢,有优化之后的嘛?

[Python] 纯文本查看 复制代码
# -*- encoding:utf-8 -*-
# auth: tomato

import requests
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import time


# ================== 中文字体(去报错) ==================
matplotlib.rcParams["font.sans-serif"] = ["SimHei"]
matplotlib.rcParams["axes.unicode_minus"] = False


# ================== 请求头 ==================
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "Referer": "https://quote.eastmoney.com/"
}


# ================== 股票市场前缀 ==================
def get_market(code):
    if code.startswith("6"):
        return "1." + code
    elif code.startswith("0") or code.startswith("3"):
        return "0." + code
    else:
        raise ValueError("股票代码格式错误,应如 600519 / 002044")


# ================== 获取分时数据 ==================
def get_minute_data(code):

    secid = get_market(code)

    url = "https://push2his.eastmoney.com/api/qt/stock/trends2/get"

    params = {
        "secid": secid,
        "fields1": "f1,f2,f3,f4,f5",
        "fields2": "f51,f52,f53,f54,f55",
        "ut": "fa5fd1943c7b386f172d6893dbfba10b",
        "iscr": "0",
        "ndays": "1"
    }

    r = requests.get(
        url,
        params=params,
        headers=HEADERS,
        timeout=10,
        proxies={"http": None, "https": None}
    )

    r.raise_for_status()

    j = r.json()

    data = j.get("data", {})

    trends = data.get("trends", [])

    if not trends:
        raise ValueError("接口未返回有效分时数据")

    prices = []

    for item in trends:

        parts = item.split(",")

        try:
            prices.append(float(parts[1]))
        except:
            continue

    if len(prices) < 2:
        raise ValueError("分时数据不足")

    yesterday_close = float(
        data.get("preclose", prices[0])
    )

    return prices, yesterday_close


# ================== 绘图 ==================
def draw_chart(prices, yesterday_close, code):

    percents = [
        (p - yesterday_close) / yesterday_close * 100
        for p in prices
    ]

    plt.ion()

    fig, ax = plt.subplots(figsize=(10, 5))

    line, = ax.plot(
        percents,
        linestyle="--",
        color="black",
        linewidth=1.6
    )

    ax.axhline(0, color="black")


    def y_format(x, pos):

        if x > 0:
            return f"+{x:.2f}"
        elif x < 0:
            return f"{x:.2f}"
        else:
            return "0"


    ax.yaxis.set_major_formatter(
        mticker.FuncFormatter(y_format)
    )

    plt.title(f"{code} 实时分时走势(涨跌幅 %)")

    plt.xlabel("时间(分钟)")

    plt.ylabel("涨跌幅 %")

    plt.grid(False)

    plt.show(block=False)

    return fig, ax, line


# ================== 更新 ==================
def update_chart(fig, ax, line, prices, yesterday_close):

    percents = [
        (p - yesterday_close) / yesterday_close * 100
        for p in prices
    ]

    line.set_ydata(percents)

    line.set_xdata(range(len(percents)))

    ax.relim()

    ax.autoscale_view()

    # &#11088;关键:不用同步 draw
    fig.canvas.draw_idle()

    fig.canvas.flush_events()


# ================== 主程序 ==================
def main():

    code = input("请输入股票代码(如 600519 / 002044):").strip()

    try:

        prices, yesterday_close = get_minute_data(code)

        print(f"获取到 {len(prices)} 个分时点,开始绘图…")

        fig, ax, line = draw_chart(
            prices,
            yesterday_close,
            code
        )


        while True:

            try:

                prices, _ = get_minute_data(code)

                update_chart(
                    fig,
                    ax,
                    line,
                    prices,
                    yesterday_close
                )

                # &#11088;给GUI时间响应
                plt.pause(5)

            except Exception as e:

                print("更新失败:", e)

    except Exception as e:

        print("获取数据失败:", e)


# ================== 入口 ==================
if __name__ == "__main__":

    main()
小鸟会飞 发表于 2026-1-16 16:11
 楼主| jiatengxian 发表于 2026-1-16 16:14

不会  你开一天  身边同事都不知道你这是这个什么线
jiukou 发表于 2026-1-16 16:18
你真有办法,佩服!
hainanyu 发表于 2026-1-16 16:18
谢谢分享,近期正在学习这方面知识
Kls673M 发表于 2026-1-16 16:20
论坛有好几个伪装的, 都被你们玩坏了
FBIdajie 发表于 2026-1-16 16:21
谢谢楼主,祝楼主发财
cn2jp 发表于 2026-1-16 16:22
你等着,我这就告诉你老板去
 楼主| jiatengxian 发表于 2026-1-16 16:24
cn2jp 发表于 2026-1-16 16:22
你等着,我这就告诉你老板去

我这是方便大家
happin1982 发表于 2026-1-16 16:35
再加上数据分析功能上去
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-4-20 11:55

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表