实时股价展示工具(Python,efinance)

该代码示例展示了如何利用Python的efinance库和matplotlib库,根据用户输入的股票代码和刷新时间间隔,从数据中读取并绘制股票价格图表。程序会不断更新最新的股票行情,并在退出时关闭所有图形窗口。
摘要由CSDN通过智能技术生成

一. 问题描述

设计一个实时股价展示工具, 要求用户可以根据输入的股票代码,和输入的freq(刷新时间间隔)参数绘制出股票股价图.

二. 结果展示

以下是2023/03/21日的贵州茅台600519当日的股价情况

和网站结果显示完全相同

 三. 程序源码

# 作者:顺手牵羊
# 链接:https: // www.zhihu.com / question / 438404653 / answer / 1794419766
# 来源:知乎
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

# 导入 efinance 如果没有安装则需要通过执行命令: pip install efinance 来安装
import csv
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
import efinance as ef
import time
from datetime import datetime


def read_csv(filepath, name):
    date_list = []
    shares_list = []
    with open(filepath, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        header_row = next(reader)
        for row in reader:
            date = row[3]
            date_list.append(date)
            shares = float(row[5])
            shares_list.append(shares)

        pass

    fig = plt.figure(figsize=(20, 8), dpi=80)
    plt.plot(date_list, shares_list)

    x_major_locator = MultipleLocator(5)
    # 把x轴的刻度间隔设置为1,并存在变量里2
    y_major_locator = MultipleLocator(5)
    # 把y轴的刻度间隔设置为10,并存在变量里
    ax = plt.gca()
    # ax为两条坐标轴的实例
    ax.xaxis.set_major_locator(x_major_locator)
    # 把x轴的主刻度设置为1的倍数
    ax.yaxis.set_major_locator(y_major_locator)

    plt.xticks(rotation=90)
    # plt.legend(loc='lower right')
    plt.ion()
    plt.pause(50)
    plt.close('all')
    pass


def main():
    # 股票代码
    stock_code = '600519'
    # 数据间隔时间为 1 分钟
    freq = 1
    status = {stock_code: 0}
    while 1:
        # 获取最新一个交易日的分钟级别股票行情数据
        df = ef.stock.get_quote_history(
            stock_code, klt=freq)
        # 现在的时间
        now = str(datetime.today()).split('.')[0]
        # 将数据存储到 csv 文件中
        df.to_csv(f'{stock_code}.csv', encoding='utf-8-sig')
        print(f'已在 {now}, 将股票: {stock_code} 的行情数据存储到文件: {stock_code}.csv 中!')
        read_csv(str(stock_code + '.csv'), str(stock_code))
        if len(df) >= status[stock_code]:
            print(f'{stock_code} 已收盘')
            break
        status[stock_code] = len(df)
        print('暂停 60 秒')
        time.sleep(60)
        print('-' * 10)

    # print('全部股票已收盘')


if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值