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 = 0
        self.maxVal = 0
        self.xdict = xdict
        self.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):
        pass

    def getData(self, code, ktype):
        self.code = code
        self.ktype = ktype
        return 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_data
        except:
            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 = False

    def 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.4
        bPen = 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()

效果:

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

 

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

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

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

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

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

你可能感兴趣的:(金融分析,技术,python3,pyQtGraph,看盘工具,股票K线图)