使用PyQtGraph繪制精美的股票行情K線圖的示例代碼
pyqtgraph是Python平臺上一種功能強大的2D/3D繪圖庫,相對于matplotlib庫,由于其在內(nèi)部實現(xiàn)方式上,使用了高速計算的numpy信號處理庫以及Qt的GraphicsView框架,因此它在大數(shù)據(jù)量的處理及快速顯示方面有著天然的優(yōu)勢,非常適合于需要快速繪圖更新、視頻或?qū)崟r交互性的操作場合,在數(shù)學、科學和工程領(lǐng)域都有著廣泛的應(yīng)用。
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_())
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python神經(jīng)網(wǎng)絡(luò)Xception模型復現(xiàn)詳解
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Xception模型復現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05pytest?fixtures函數(shù)及測試函數(shù)的參數(shù)化解讀
這篇文章主要介紹了pytest?fixtures函數(shù)及測試函數(shù)的參數(shù)化解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05Python工廠模式實現(xiàn)封裝Webhook群聊機器人詳解
企業(yè)存在給 特定群組 自動推送消息的需求,你可以在群聊中添加一個自定義機器人,通過服務(wù)端調(diào)用 webhook 地址,即可將外部系統(tǒng)的通知消息即時推送到群聊中。本文就來和大家聊聊具體實現(xiàn)方法2023-02-02Python實現(xiàn)加密的RAR文件解壓的方法(密碼已知)
這篇文章主要介紹了Python實現(xiàn)加密的RAR文件解壓,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09Python利用QQ郵箱發(fā)送郵件的實現(xiàn)方法(分享)
下面小編就為大家?guī)硪黄狿ython利用QQ郵箱發(fā)送郵件的實現(xiàn)方法(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06Python實現(xiàn)解壓當天創(chuàng)建的ZIP文件到指定文件夾中
這篇文章主要為大家詳細介紹了Python如何實現(xiàn)解壓當天創(chuàng)建的ZIP文件到指定文件夾中,文中的示例代碼講解詳細,需要的小伙伴可以參考下2024-03-03