自己做量化交易软件(4)通通量化分析框架构成2

自己做量化交易软件(4)通通量化分析框架构成2

通通股票量化分析框架采用模块化设计,每个模块存放在不同的py文件中。
我们接着上一篇介绍。

五、基础窗口画面框架 HP_view.py
HP_view.py文件中存放了关于窗口构成,绘图的主要模块。
因程序比较长,读者可自己看源代码。
主要模块的功能如下.
class plotFrame3(Frame): # 继承Frame类
这个是构成K线图的模块,数字3表示3指标图形,K线,成交量,自定义指标。

class MainFrame(Frame): # 继承Frame类
是主图类,用于输入选择股票,日期区间,指标类型的功能。
其中st3()是确定按钮,用于切换股票图形画面。

这个文件引入的主要py模块如下:

import HP_zwdata as sd
import HP_lib as mylib
import HP_draw as mydraw

HP_zwdata.py 主要是处理zwDat字王股票历史数据使用的模块。我们基本用不上,就不介绍了,有兴趣去看源代码了。

六、自定义指标绘图模块 HP_draw.py
这个模块主要存放图形最下面的指标绘图函数,我们设计了KDJ,MACD,KDJ,OBV等指标绘图函数,用户可以参考设计自己的新指标。

import HP_zwdata as sd
from HP_global import *
from HP_set import *
import HP_lib as mylib

def draw_OBV(ax1,days,x,y):
        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'
        df=mylib.OBVX(days,x,y)
        ax2 = plt.subplot2grid((7,4), (5,0), sharex=ax1, rowspan=2, colspan=4, axisbg='#07000d')
        fillcolor = '#00ffe8'
        ax2.plot(df.date.values, df.OBV_6.values, color=rsiCol, lw=2)
        ax2.plot(df.date.values, df.OBV_12.values, color=posCol, lw=2)
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        ax2.grid(True, color='r')
        plt.ylabel('OBV', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=6, prune='upper'))
        return

def draw_RSI(ax1,days,x,y,z):
        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'
        df=mylib.RSIX(days,x,'RSI1')
        df=mylib.RSIX(df,y,'RSI2')
        df=mylib.RSIX(df,z,'RSI3')
        ax2 = plt.subplot2grid((7,4), (5,0), sharex=ax1, rowspan=2, colspan=4, axisbg='#07000d')
        fillcolor = '#00ffe8'
        ax2.plot(df.date.values, df.RSI1.values, color=rsiCol, lw=2)
        ax2.plot(df.date.values, df.RSI2.values, color=posCol, lw=2)
        ax2.plot(df.date.values, df.RSI3.values, color=negCol, lw=2)
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        ax2.axhline(80, color=negCol)
        ax2.axhline(20, color=posCol)
        plt.ylabel('RSI', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=6, prune='upper'))
        return

def draw_KDJ(ax1,days,x,y,z):
        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'
        df=mylib.KDJ(days,x,y,z)
        ax2 = plt.subplot2grid((7,4), (5,0), sharex=ax1, rowspan=2, colspan=4, axisbg='#07000d')
        fillcolor = '#00ffe8'
        ax2.plot(df.date.values, df.K.values, color=rsiCol, lw=2)
        ax2.plot(df.date.values, df.D.values, color=posCol, lw=2)
        ax2.plot(df.date.values, df.J.values, color=negCol, lw=2)
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        ax2.axhline(80, color=negCol)
        ax2.axhline(20, color=posCol)
        plt.ylabel('KDJ', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=6, prune='upper'))
        return

def draw_MACD(ax1,days,x,y,z):
        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'
        df=mylib.MACD(days,x,y)
        ax2 = plt.subplot2grid((7,4), (5,0), sharex=ax1, rowspan=2, colspan=4, axisbg='#07000d')
        fillcolor = '#00ffe8'
        ax2.plot(df.date.values, df.MACDsign_12_26.values, color=rsiCol, lw=1)
        ax2.plot(df.date.values, df.MACD_12_26.values, color=negCol, lw=1)
        ax2.fill_between(df.date.values, df.MACDdiff_12_26.values, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        ax2.axhline(0, color=negCol)
        plt.ylabel('MACD', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=3, prune='upper'))
        return     

七、股票数据处理函数库 HP_lib.py
这个文件中存放了一些常用数据函数,用户可以自己根据例子来扩充自己的函数库。
下面是部分程序代码,完整代码请阅读源程序。

###################基本函数库##############################
使用说明
df 指标序列
tp 指标字段,例如close
n  周期数
al 字段别名,可以省略
----------------------------------------------------
import hplibx as mylib
平均移动线函数
def MA(df,tp, n)        #移动平均,Moving Average  
使用 df=(df,'close',5)

def EMA(df,tp, n)   #指数移动平均.Exponential Moving Average      

上穿函数
def CROSS(df,tp1,tp2)

#取前n周期数值函数    
def REF(df,tp,n)    

#取后n周期数值函数
def REFX(df,tp, n)

#Standard Deviation#标准偏差  
def STDDEV(df,tp,n):  

#取前n周期数值的最高价
def HHV(df,tp, n,al=''):     

#取前n周期数值的最低价
def LLV(df,tp, n,al=''):  

#取前n周期数值大于0的次数
def COUNT(df,tp, n,al=''):  

#求前n周期数值和
def SUM(df,tp, n,al=''):  

 #Winner当前价格获利率
def WINNER(df,price, tp1,al=''):  

#求动态移动平均。
#DMA(X,A),求X的A日动态移动平均。
def DMA(df,tp1,tp2,al=''):     

#大于等于函数
def EGT(df,tp1,tp2,al=''): 

#小于等于函数
def ELT(df,tp1,tp2,al=''):  

#等于函数
def EQUAL(df,tp1,tp2,al=''): 

#大于函数
def GT(df,tp1,tp2,al=''):  

#小于函数
def LT(df,tp1,tp2,al=''):  

#并且函数
def AND(df,tp1,tp2,al=''): 

#或者函数
def OR(df,tp1,tp2,al=''):     
###################指标库########################    
def ACCDIST(df, n):             #积累/分配,Accumulation/Distribution  
def ADX(df, n, n_ADX):      #定向运动平均指数,Average Directional Movement Index  
def ATR(df, n):                     #平均真实范围.Average True Range
def BBANDS(df, n):              #布林带.Bollinger Bands  
def CCI(df, n):                     #商品通道指数,Commodity Channel Index  
def COPP(df, n):                #COPPOCK曲线,Coppock Curve 
def Chaikin(df):                    #蔡金振荡器,Chaikin Oscillator  
def DONCH(df, n):               #奇安通道,Donchian Channel  
def EOM(df, n):                     #缓解运动,Ease of Movement
def FORCE(df, n):                   #力指数,Force Index 
def KELCH(df, n):               #Keltner通道,Keltner Channel
def KST(df, r1, r2, r3, r4, n1, n2, n3, n4):  # KST振荡器,KST Oscillator 
def MACD(df, n_fast, n_slow): 
    #MACD指标信号和MACD的区别, MACD Signal and MACD difference   

def MFI(df, n):                     #资金流量指标和比率,Money Flow Index and Ratio
def MOM(df, n):                     #动量.Momentum  
def MassI(df):                      #质量指数,Mass Index    
def OBV(df, n):                     #平衡量,On-balance volume
def PPSR(df):                       #支点,支撑和阻力.Pivot Points, Supports and Resistances  
def ROC(df, n):                     #变化率.Rate of Change 
def RSI(df, n):                     #相对强弱指标,Relative Strength Index
def STDDEV(df, n):              #标准偏差,#Standard Deviation
def STO(df, n):                     #随机指标D,Stochastic oscillator %D  
def STOK(df):                       #随机指标K,Stochastic oscillator %K  
def TRIX(df, n):                #矩阵,#Trix  
def TSI(df, r, s):              #真实强度指数,True Strength Index
def ULTOSC(df):                     #最终振荡器,Ultimate Oscillator 
def Vortex(df, n):              #涡指标,#Vortex Indicator     

"""
import platform
import pandas as pd  
import numpy  
import math as m
#from HP_global import *
import HP_global


#版本号
def VER():
    return 1.00

#版本号
def Ver():
    return 1.00

#聚宽股票代码转换
def jqsn(s):
    if (len(s)<6 and len(s)>0):
        s=s.zfill(6)+'.XSHE'
    if len(s)==6:
        if s[0:1]=='0':
            s=s+'.XSHE'
        else:
            s=s+'.XSHG'
    return s

##############内部函数库########################
def ema(c_list,n=12):
    y_list=[]
    _n = 1    
    for c in c_list: 
        if c == c_list[0]:
            y = c
        elif _n<n:
            y= c*2/(_n+1) + (1- 2/(_n+1))*y_list[-1] 
        else:
            y=c*2/(n+1)+(1-2/(n+1))*y_list[-1]
        y_list.append(y)
        _n = _n+1        
    return y_list

##############基本函数库#########################
def G_MA(Series,n):
    G_pyver=int(platform.python_version()[0:1])
    G_ma=None
    if G_pyver==2:
        G_MAstr='pd.rolling_mean(Series,n)'
        G_ma=eval(G_MAstr)
    else :
        G_MAstr='Series.rolling(window=n,center=False).mean()'
        G_ma=eval(G_MAstr)
    return G_ma

#通用STD计算        
def G_STD(Series,n):
    G_pyver=int(platform.python_version()[0:1])
    G_ma=None
    if G_pyver==2:
        G_MAstr='pd.rolling_std(Series,n)'
        G_ma=eval(G_MAstr)
    else :
        G_MAstr='Series.rolling(window=n,center=False).std()'
        G_ma=eval(G_MAstr)
    return G_ma

八、构建主窗口的程序包 HP_MainPage.py
在介绍HP_Login.py登录窗口代码时,我们看到了引入这个文件包。
from HP_MainPage import *
当用户密码通过验证时,就会执行主画面构建模块MainPage(self.root) 。
HP_MainPage.py部分源代码如下,完整程序请读者阅读源代码。

from PIL import Image, ImageTk
import webbrowser
import os
from HP_view import * #菜单栏对应的各个子页面 
from HP_global import *
from HP_set import *


class MainPage(object):  
    def __init__(self, master=None):  
        HP_init()
        self.root = master #定义内部变量root  
        G_root=self.root
        self.w = G_winW
        self.h = G_winH
        self.root.title(G_title)  
        self.staIco = '.\jk.ico'
        self.root.geometry('%dx%d' % (self.w, self.h)) #设置窗口大小  
        #plotCreat(self.root)
        self.createUI()
        self.center()
        self.loop()


    # 生成界面
    def createUI(self):
        self.createICO()
        self.createMenu()
        self.createToolbar()
        self.createPage()  


    def loop(self):
        self.root.resizable(True, True)   #禁止修改窗口大小
        self.center()                       #窗口居中
        self.root.mainloop()

    def _quit(self):
        #结束事件主循环,并销毁应用程序窗口
        self.root.quit()
        self.root.destroy()     

    def center(self):
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = int( (ws/2) - (self.w/2) )
        y = int( (hs/2) - (self.h/2) )
        self.root.geometry('{}x{}+{}+{}'.format(self.w, self.h, x, y))
        self.root.iconbitmap(self.staIco)

主窗口显示画面如下:
主窗口显示画面

这2篇文章大概介绍了通通量化软件总构成。我们后面根据自己程序的完善,逐步介绍给大家,怎么扩种软件功能,来实现自己所要求的功能。

猜你喜欢

转载自blog.csdn.net/hepu8/article/details/82718592