python3绘制股票K线图的那些坑【三】pyQtgraph绘制精美股票K线图--对数系正确实现集成Tushare数据源

本文主要是介绍python3绘制股票K线图的那些坑【三】pyQtgraph绘制精美股票K线图--对数系正确实现集成Tushare数据源,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

上一篇文章,使用K线工具做了简单的尝试,经过反复的试验。修正x轴日期显示问题,对数化呈现Y轴数据与股价不一致问题解决。

废话不说,直接上代码,看效果。

import sys
import pyqtgraph as pg
from qtpy.QtGui import *
from pyqtgraph import QtCore, QtGui
import numpy as np
import datetime as dt
import pandas as pd
import tushare as ts# 增加窗口视图,支持选择性缩放,不然x轴的日期,Y轴的股价都不会根据缩放变化
########################################################################
class CustomViewBox(pg.ViewBox):# ----------------------------------------------------------------------def __init__(self, *args, **kwds):pg.ViewBox.__init__(self, *args, **kwds)# 拖动放大模式self.setMouseMode(self.RectMode)## 右键自适应# ----------------------------------------------------------------------def mouseClickEvent(self, ev):if ev.button() == QtCore.Qt.RightButton:self.autoRange()# X轴日期坐标显示
########################################################################
class MyStringAxis(pg.AxisItem):"""时间序列横坐标支持"""# 初始化# ----------------------------------------------------------------------def __init__(self, xdict, *args, **kwargs):pg.AxisItem.__init__(self, *args, **kwargs)self.minVal = 0self.maxVal = 0self.xdict = xdictself.x_values = np.asarray(xdict.keys())self.x_strings = xdict.values()self.setPen(color=(255, 255, 255, 255), width=0.8)self.setStyle(tickFont=QFont("Roman times", 10, QFont.Bold), autoExpandTextSpace=True)# 更新坐标映射表# ----------------------------------------------------------------------def update_xdict(self, xdict):self.xdict.update(xdict)self.x_values = np.array(list(self.xdict.keys()))self.x_strings = np.array(list(self.xdict.values()))# 将原始横坐标转换为时间字符串# ----------------------------------------------------------------------def tickStrings(self, values, scale, spacing):strings = []for v in values:vs = int(v * scale)if vs in self.x_values:vstr = self.x_strings[vs]vstr = vstr.strftime('%Y-%m-%d %H:%M:%S')else:vstr = ""strings.append(vstr)return strings#集成Tushare取数据
class GetData():def __init__(self, *arg):passdef getData(self, code, ktype):self.code = codeself.ktype = ktypereturn self.getData_Tushare(self.code, self.ktype)def getData_Tushare(self, code, ktype='30', start=str(dt.date.today() - dt.timedelta(days=1000)),end=str(dt.date.today() + dt.timedelta(days=1))):try:self.k_data = ts.get_k_data(code, ktype=ktype)#print(self.k_data)self.k_data.rename(columns={'date': 'datetime'}, inplace=True)self.k_data.drop(columns={'code'}, inplace=True)self.k_data.index = pd.to_datetime(self.k_data['datetime'])self.k_data.dropna(axis=0, inplace=True)#print(self.k_data)return self.k_dataexcept:print('getData_Tushare except')return#日本蜡烛图自定义对象,画出K线关键就靠它了
class CandlestickItem(pg.GraphicsObject):data2 = []def __init__(self, data):pg.GraphicsObject.__init__(self)self.data = data  ## data must have fields: time, open, close, min, max# self.data['open'] = np.log(self.data['open'])# self.data['close'] = np.log(self.data['close'])# self.data['low'] = np.log(self.data['low'])# self.data['high'] = np.log(self.data['high'])self.generatePicture()self.logMode = Falsedef setLogMode(self, x=None, y=None):self.logMode = (x, y)#当上层选择log对数模式时,这个方法会被调用,要把原始数据对数化处理,不然图形不会变if y == True:self.data['open'] = np.log10(self.data['open'])self.data['close'] = np.log10(self.data['close'])self.data['low'] = np.log10(self.data['low'])self.data['high'] = np.log10(self.data['high'])self.update()def update(self):self.generatePicture()def generatePicture(self):self.picture = QtGui.QPicture()p = QtGui.QPainter(self.picture)w = 0.4bPen = pg.mkPen(color=(0, 240, 240, 255), width=w * 2)bBrush = pg.mkBrush((0, 240, 240, 255))rPen = pg.mkPen(color=(255, 60, 60, 255), width=w * 2)rBrush = pg.mkBrush((255, 60, 60, 255))rBrush.setStyle(QtCore.Qt.NoBrush) #阳线红色,空心for (t, open, close, low, high) in self.data:# 下跌蓝色(实心), 上涨红色(空心)pen, brush, pmin, pmax = (bPen, bBrush, close, open) \if open > close else (rPen, rBrush, open, close)p.setPen(pen)p.setBrush(brush)# 画K线方块和上下影线if open == close:p.drawLine(QtCore.QPointF(t - w, open), QtCore.QPointF(t + w, close))else:p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))if pmin > low:p.drawLine(QtCore.QPointF(t, low), QtCore.QPointF(t, pmin))if high > pmax:p.drawLine(QtCore.QPointF(t, pmax), QtCore.QPointF(t, high))p.end()def paint(self, p, *args):p.drawPicture(0, 0, self.picture)def boundingRect(self):return QtCore.QRectF(self.picture.boundingRect())def floatrange(start,stop,steps):return [start + float(i) * (stop - start) / (float(steps) - 1) for i in range(steps)]## Start 
if __name__ == '__main__':app = QtGui.QApplication(sys.argv)#从Tushare取数据data = []dataTool = GetData()datas = dataTool.getData('600519', '30')datas['time_int'] = np.array(range(len(datas.index)))data = datas[['time_int', 'open', 'close', 'low', 'high']].to_records(False)#处理x轴日期映射字典xdict = {}axisTime = MyStringAxis(xdict, orientation='bottom')xdict = dict(enumerate(datas.index.tolist()))print(xdict)axisTime.update_xdict(xdict)vlogMax=np.max(np.log10(data['high']))vlogMin=np.min(np.log10(data['low']))item = CandlestickItem(data)vb = CustomViewBox()plt = pg.PlotWidget(viewBox=vb, axisItems={'bottom': axisTime})plt.addItem(item)plt.setLogMode(y=True)plt.hideAxis('left')plt.showAxis('right')yaxis=plt.getAxis('right')vb.setRange(yRange=(vlogMin, vlogMax))plt.show()plt.setWindowTitle('pyqtgraph example: customGraphicsItem')app.exec()

效果:

 

可以看到,依然有些小问题。y轴的坐标范围太大,导致全视图时空区太大。另外Y轴的股票价格是用科学计数法显示的。

另外需要注意的是,数据处理的部分,取对数时要取以10为底的对数,才能正常对应到PyQtGraph的log对数体系。如果用e为底的自然对数,则Y轴值会显示大3倍多。

使用Python3+PyQtGraph呈现K线图,已经有了不少的进展。

后续还会进一步增强,增加百分比Y轴坐标,增加鼠标十字,增加多图联动,主图指标等关键功能。敬请期待吧!

这篇关于python3绘制股票K线图的那些坑【三】pyQtgraph绘制精美股票K线图--对数系正确实现集成Tushare数据源的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/379849

相关文章

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri