接到一个朋友的需要,做一个简单的指标监控,就是当多个周期的均线和K线满足某种情况的时候发出信号。其实这种预警很多图表操盘软件也可以做,但是问题是多个品种监控的时候效率非常低,还容易死机,同时监控信息的发出手段不灵活,例如不方便发到QQ或者微信群里面。于是想到可以通过python来做这个事情。
主程序如下:
Mon = Monitor()Mon.addRule(RuleResonanceUp())withopen("flist.txt",'r')asf: flist = f.readlines()forlineinflist: print("Processing "+line) bd = BarData(line.strip('\n')) Mon.Run(bd)
初始化一个Monitor监控器,并给这个监控器里面放入所需要监控的规则类RuleResonanceUp
所有品种的代码放在一个flist.txt文件中,读出来以后由BarData这个类进行初始化,获得多周期的交易数据,作为监控器要处理的数据上下文。
然后运行监控器,监控器会逐一将规则套入上下文数据中进行判断,满足条件的就发出消息通知。
其他的代码:
fromjqdatasdkimport*importtalib#用来做指标计算,算是最流行的库了吧importmatplotlib.pyplotasplt#用来做图示,这个是调试用的,调好后基本就不用了frommatplotlib.pylabimportdate2num#用来做图示的,调试用,调好后就基本不用了importmpl_financeasmpf#用来图示的。importmatplotlib.tickerasticker#用来改图示的横坐标importpandasaspdimportpandas.io.excel#用来输出文件用的importdatetimeimportnumpyasnpclassBarData(object):#用来获取品种的实际数据def__init__(self, stockCode, enddate=None):self.stockCode = stockCode self.endDate = enddate self.get_560Bars() self.apply_indicators()defget_560Bars(self):#这个系统用到周线日线小时和5分钟self.df1w = get_bars(self.stockCode,100, unit='1w', fields=['date','open','high','low','close'], include_now=True, end_dt = self.endDate) self.df1d = get_bars(self.stockCode,100, unit='1d', fields=['date','open','high','low','close'], include_now=True, end_dt = self.endDate) self.df60m = get_bars(self.stockCode,100, unit='60m', fields=['date','open','high','low','close'], include_now=True, end_dt=self.endDate) self.df5m = get_bars(self.stockCode,100, unit='5m', fields=['date','open','high','low','close'], include_now=True, end_dt=self.endDate)defapply_indicators(self):#这个系统用到20 60 和经典参数的macddefapply_ma60(df):df["MA60"] = talib.MA(df["close"], timeperiod=60)defapply_ma20(df):df["MA20"] = talib.MA(df["close"], timeperiod=20)defapply_macd(df):#close = [float(x) for x in df['close']]df["DIFF"], df['DEA'], df['MACDhist'] = talib.MACD(df['close'], fastperiod=12, slowperiod=26, signalperiod=9)defapply_hist_signals(df):"""
:type df: Dataframe
"""#在原来的dataframe里面加入所有历史的信号,每个信号加一列#需要支持的值是: c-ma60, ma60Slope, c-ma20, macdGold, macdDead, macdGoldsoon, macdDeadsoon, DEASlopedf['c_minus_ma60'] = df['close'] - df["MA60"]#用来判断是否在ma60之上df['ma60Slope'] =Noneforiinrange(1,len(df)): df.loc[i,'ma60Slope'] = df["MA60"][i] - df["MA60"][i-1]#用来判断ma60的斜率df['c_minus_ma20'] = df['close'] - df["MA20"]#用来判断是否在ma20之上df["macdGold"] =False# macd 金叉死叉df["macdDead"] =Falseforiinrange(len(df)):if(df["DIFF"][i] - df["DEA"][i]) >0: df.loc[i,"macdGold"] =Trueif(df["DIFF"][i] - df["DEA"][i]) <0: df.loc[i,"macdDead"] =Truedf["macdGoldsoon"] =None# macd 将要金叉死叉df["macdDeadsoon"] =Noneforiinrange(len(df)-2) :ifdf["DEA"][i+1] > df["DIFF"][i+1]:if(df["DEA"][i+1] - df["DIFF"][i+1])-((df["DEA"][i]-df["DIFF"][i]) - (df["DEA"][i+1]-df["DIFF"][i+1])) <0: df.loc[i+2,"macdGoldsoon"] =Trueifdf["DIFF"][i +1] > df["DEA"][i +1]:if(df["DIFF"][i +1] - df["DEA"][i +1]) - ( (df["DIFF"][i] - df["DEA"][i]) - (df["DIFF"][i +1] - df["DEA"][i +1])) <0: df.loc[i+2,"macdDeadsoon"] =Truedf['DEASlope'] =Noneforiinrange(1, len(df)): df.loc[i,'DEASlope'] = df["DEA"][i] - df["DEA"][i -1] df["KDir"] =0foriinrange(1,len(df)):# K线方向判断,如果高点抬高 低点抬高就多,高点低点降低就空,内包外包就保持if(df["high"][i] > df["high"][i-1])and(df["low"][i] > df["low"][i-1]): df.loc[i,"KDir"] =1elifdf["high"][i] < df["high"][i-1]anddf["low"][i] < df["low"][i-1]: df.loc[i,"KDir"] =-1else: df.loc[i,"KDir"] = df["KDir"][i-1]fordftin[self.df5m, self.df60m, self.df1d, self.df1w]: apply_ma60(dft) apply_ma20(dft) apply_macd(dft) apply_hist_signals(dft)classRule(object):#预警规则的基类def__init__(self):self.name ="RuleBase"defApplyRule(self, bd):passdefMsg(self):#当规则发生的时候,要发出来的消息return"Non Rule Implemented."classRuleResonanceUp(Rule):#多头共振的规则,所有的周期都是多的时候提醒def__init__(self):self.name ="RuleResonaceUp"defApplyRule(self, bd):ifbd.df1w["KDir"].tolist()[-1] >0andbd.df1d.KDir.tolist()[-1] >0andbd.df1d.DEASlope.tolist()[-1] >0andbd.df60m.KDir.tolist()[-1] >0\andbd.df60m.DEASlope.tolist()[-1] >0andbd.df5m.ma60Slope.tolist()[-1] >0andbd.df5m.DEASlope.tolist()[-1] >0\andbd.df5m.KDir.tolist()[-1] >0:returnTrueelse:returnFalsedefMsg(self):return"周K,日K,日DEA,日K,小时DEA,小时K,5mDEA、5mMA60、5mK,多方共振。"classMonitor(object):def__init__(self):self.Rules = []defaddRule(self,r):self.Rules += [r]defRun(self,bd):#执行规则,满足规则的时候打印提醒信息,在这里,可以换成ichat或者pyqq啥的,就可以实现微信和qq的通知了。forrinself.Rules:ifr.ApplyRule(bd): print(datetime.datetime.now()," "+get_security_info(bd.stockCode).display_name+': '+r.Msg())pass