使用PyQtGraph绘制精美的股票行情K线图的示例代码


Posted in Python onMarch 14, 2019

pyqtgraph是Python平台上一种功能强大的2D/3D绘图库,相对于matplotlib库,由于其在内部实现方式上,使用了高速计算的numpy信号处理库以及Qt的GraphicsView框架,因此它在大数据量的处理及快速显示方面有着天然的优势,非常适合于需要快速绘图更新、视频或实时交互性的操作场合,在数学、科学和工程领域都有着广泛的应用。

K线图介绍

对于股票交易者来讲,K线图是弄清股票一段时间走势的一种最基本的图形工具,K线分为阳线和阴线,阳线和阴线都包含了开盘价、收盘价、最高价和最低价,一般K线如下图所示:

当收盘价大于开盘价时,称为阳线,在图形上一般用红色表示,反之,当收盘价低于开盘价时,称为阴线,在图形上一般用绿色表示。由于其形状颇似一根根蜡烛,K线图有时也叫做蜡烛图。

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'QWidget_plot.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from PyQt4 import QtCore, QtGui
import datetime
import pyqtgraph as pg
import tushare as ts

try:
  _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
  def _fromUtf8(s):
    return s

try:
  _encoding = QtGui.QApplication.UnicodeUTF8
  def _translate(context, text, disambig):
    return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
  def _translate(context, text, disambig):
    return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
  def setupUi(self, MainWindow):
    MainWindow.setObjectName(_fromUtf8("MainWindow"))
    MainWindow.resize(800, 600)
    self.centralwidget = QtGui.QWidget(MainWindow)
    self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
    self.verticalLayout_2 = QtGui.QVBoxLayout(self.centralwidget)
    self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout"))
    self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
    self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtGui.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 31))
    self.menubar.setObjectName(_fromUtf8("menubar"))
    MainWindow.setMenuBar(self.menubar)

    self.drawChart = DrawChart(ktype='D')
    self.verticalLayout_2.addWidget(self.drawChart.pyqtgraphDrawChart())

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

  def retranslateUi(self, MainWindow):
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

class DrawChart():
  def __init__(self, code='sz50', start=str(datetime.date.today() - datetime.timedelta(days=200)), end=str(datetime.date.today() + datetime.timedelta(days=1)), ktype='D'):
    self.code = code
    self.start = start
    self.end = end
    self.ktype = ktype
    self.data_list, self.t = self.getData()

  def pyqtgraphDrawChart(self):
    try:
      self.item = CandlestickItem(self.data_list)
      self.xdict = {0: str(self.hist_data.index[0]).replace('-', '/'), int((self.t + 1) / 2) - 1: str(self.hist_data.index[int((self.t + 1) / 2)]).replace('-', '/'), self.t - 1: str(self.hist_data.index[-1]).replace('-', '/')}
      self.stringaxis = pg.AxisItem(orientation='bottom')
      self.stringaxis.setTicks([self.xdict.items()])
      self.plt = pg.PlotWidget(axisItems={'bottom': self.stringaxis}, enableMenu=False)

      self.plt.addItem(self.item)
      # self.plt.showGrid(x=True, y=True)

      return self.plt
    except:
      return pg.PlotWidget()

  def getData(self):
    self.start = str(datetime.date.today() - datetime.timedelta(days=150))
    self.end = str(datetime.date.today() + datetime.timedelta(days=1))
    self.hist_data = ts.get_hist_data(self.code, self.start, self.end, self.ktype).sort_index()[-300:-1]
    data_list = []
    t = 0
    for dates, row in self.hist_data.iterrows():
      open, high, close, low, volume, price_change, p_change, ma5, ma10, ma20 = row[:10]
      datas = (t, open, close, low, high, volume, price_change, p_change, ma5, ma10, ma20)
      data_list.append(datas)
      t += 1
    return data_list, t

class CandlestickItem(pg.GraphicsObject):
  def __init__(self, data):
    pg.GraphicsObject.__init__(self)
    self.data = data
    self.generatePicture()

  def generatePicture(self):
    self.picture = QtGui.QPicture()
    p = QtGui.QPainter(self.picture)
    p.setPen(pg.mkPen('w'))
    w = (self.data[1][0] - self.data[0][0]) / 3.
    prema5 = 0
    prema10 = 0
    prema20 = 0
    for (t, open, close, min, max, volume, price_change, p_change, ma5, ma10, ma20) in self.data:
      if open > close:
        p.setPen(pg.mkPen('g'))
        p.setBrush(pg.mkBrush('g'))
      else:
        p.setPen(pg.mkPen('r'))
        p.setBrush(pg.mkBrush('r'))
      p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
      p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
      if prema5 != 0:
        p.setPen(pg.mkPen('w'))
        p.setBrush(pg.mkBrush('w'))
        p.drawLine(QtCore.QPointF(t-1, prema5), QtCore.QPointF(t, ma5))
      prema5 = ma5
      if prema10 != 0:
        p.setPen(pg.mkPen('c'))
        p.setBrush(pg.mkBrush('c'))
        p.drawLine(QtCore.QPointF(t-1, prema10), QtCore.QPointF(t, ma10))
      prema10 = ma10
      if prema20 != 0:
        p.setPen(pg.mkPen('m'))
        p.setBrush(pg.mkBrush('m'))
        p.drawLine(QtCore.QPointF(t-1, prema20), QtCore.QPointF(t, ma20))
      prema20 = ma20
    p.end()

  def paint(self, p, *args):
    p.drawPicture(0, 0, self.picture)

  def boundingRect(self):
    return QtCore.QRectF(self.picture.boundingRect())

if __name__ == "__main__":
  import sys
  app = QtGui.QApplication(sys.argv)
  MainWindow = QtGui.QMainWindow()
  ui = Ui_MainWindow()
  ui.setupUi(MainWindow)
  MainWindow.show()
  sys.exit(app.exec_())

使用PyQtGraph绘制精美的股票行情K线图的示例代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
浅谈Python中的数据类型
May 05 Python
解析Python中的生成器及其与迭代器的差异
Jun 20 Python
Python全局变量用法实例分析
Jul 19 Python
Python利用Beautiful Soup模块修改内容方法示例
Mar 27 Python
Python实现统计代码行的方法分析
Jul 12 Python
python实现对求解最长回文子串的动态规划算法
Jun 02 Python
python中的字符串内部换行方法
Jul 19 Python
通过python实现随机交换礼物程序详解
Jul 10 Python
matlab中二维插值函数interp2的使用详解
Apr 22 Python
Python爬虫之Selenium多窗口切换的实现
Dec 04 Python
python 利用panda 实现列联表(交叉表)
Feb 06 Python
python内置模块之上下文管理contextlib
Jun 14 Python
详解Django+uwsgi+Nginx上线最佳实战
Mar 14 #Python
TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片
Mar 14 #Python
Python通过TensorFlow卷积神经网络实现猫狗识别
Mar 14 #Python
python3实现钉钉消息推送的方法示例
Mar 14 #Python
详解Python做一个名片管理系统
Mar 14 #Python
在Python中使用Neo4j的方法
Mar 14 #Python
浅谈Python中eval的强大与危害
Mar 13 #Python
You might like
PHP5中MVC结构学习
2006/10/09 PHP
PHP 反射机制实现动态代理的代码
2008/10/22 PHP
PHP程序员学习使用Swoole的理由
2018/06/24 PHP
Thinkphp 框架扩展之标签库驱动原理与用法分析
2020/04/23 PHP
JQuery 常用操作代码
2010/03/14 Javascript
纯Javascript实现Windows 8 Metro风格实现
2013/10/15 Javascript
jQuery中DOM树操作之复制元素的方法
2015/01/23 Javascript
基于JS+Canves实现点击按钮水波纹效果
2016/09/15 Javascript
详解jQuery中ajax.load()方法
2017/01/25 Javascript
javascript简写常用的12个技巧(可以大大减少你的js代码量)
2020/03/28 Javascript
基于jquery实现左右上下移动效果
2018/05/02 jQuery
基于AngularJs select绑定数字类型的问题
2018/10/08 Javascript
微信小程序网络请求实现过程解析
2019/11/06 Javascript
[02:07]DOTA2超级联赛专访BBC:难忘网吧超神经历
2013/06/09 DOTA
详解Python的Twisted框架中reactor事件管理器的用法
2016/05/25 Python
Django使用详解:ORM 的反向查找(related_name)
2018/05/30 Python
pandas使用之宽表变窄表的实现
2020/04/12 Python
Pycharm的Available Packages为空的解决方法
2020/09/18 Python
windows系统Tensorflow2.x简单安装记录(图文)
2021/01/18 Python
全球速卖通:AliExpress(国际版淘宝)
2017/09/20 全球购物
法国在线宠物店:zooplus.fr
2018/02/23 全球购物
跑步、骑行和铁人三项的高性能眼镜和服装:ROKA
2018/07/06 全球购物
英国发展最快的在线超市之一:Click Marketplace
2021/02/15 全球购物
什么叫应用程序域?什么是托管代码?什么是强类型系统?什么是装箱和拆箱?什么是重载?CTS、CLS和CLR分别作何解释?
2012/05/23 面试题
毕业自我鉴定范文
2013/11/06 职场文书
志愿者宣传口号
2014/06/17 职场文书
乡镇群众路线教育实践活动整改措施
2014/10/04 职场文书
工伤死亡理赔协议书
2014/10/20 职场文书
工厂清洁工岗位职责
2015/02/14 职场文书
社区扶贫帮困工作总结
2015/05/20 职场文书
地道战观后感
2015/06/04 职场文书
导游词之西江千户苗寨
2019/12/24 职场文书
python实现进度条的多种实现
2021/04/29 Python
HTML通过表单实现酒店筛选功能
2021/05/18 HTML / CSS
Golang实现AES对称加密的过程详解
2021/05/20 Golang
NASA 机智号火星直升机拍到了毅力号设备碎片
2022/04/29 数码科技