一. 问题描述
设计一个实时股价展示工具, 要求用户可以根据输入的股票代码,和输入的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()