接到一个朋友的需要,做一个简单的指标监控,就是当多个周期的均线和ķ线满足某种情况的时候发出信号。其实这种预警很多图表操盘软件也可以做,但是问题是多个品种监控的时候效率非常低,还容易死机,同时监控信息的发出手段不灵活,例如不方便发到QQ或者微信群里面于是想到可以通过蟒蛇来做这个事情。
主程序如下:
Mon = Monitor()
Mon.addRule(RuleResonanceUp())
with open("flist.txt",'r') as f:
flist = f.readlines()
for line in flist:
print("Processing "+line)
bd = BarData(line.strip('\n'))
Mon.Run(bd)
初始化一个监控器监控器,并给这个监控器里面放入所需要监控的规则类RuleResonanceUp
所有品种的代码放在一个flist.txt文件中,读出来以后由BarData这个类进行初始化,获得多周期的交易数据,作为监控器要处理的数据上下文。
然后运行监控器,监控器会逐一将规则套入上下文数据中进行判断,满足条件的就发出消息通知。
其他的代码:
from jqdatasdk import *
import talib #用来做指标计算,算是最流行的库了吧
import matplotlib.pyplot as plt #用来做图示,这个是调试用的,调好后基本就不用了
from matplotlib.pylab import date2num #用来做图示的,调试用,调好后就基本不用了
import mpl_finance as mpf #用来图示的。
import matplotlib.ticker as ticker #用来改图示的横坐标
import pandas as pd
import pandas.io.excel #用来输出文件用的
import datetime
import numpy as np
class BarData(object): #用来获取品种的实际数据
def __init__(self, stockCode, enddate=None):
self.stockCode = stockCode
self.endDate = enddate
self.get_560Bars()
self.apply_indicators()
def get_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)
def apply_indicators(self): #这个系统用到20 60 和经典参数的macd
def apply_ma60(df):
df["MA60"] = talib.MA(df["close"], timeperiod=60)
def apply_ma20(df):
df["MA20"] = talib.MA(df["close"], timeperiod=20)
def apply_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)
def apply_hist_signals(df):
"""
:type df: Dataframe
"""
#在原来的dataframe里面加入所有历史的信号,每个信号加一列
#需要支持的值是: c-ma60, ma60Slope, c-ma20, macdGold, macdDead, macdGoldsoon, macdDeadsoon, DEASlope
df['c_minus_ma60'] = df['close'] - df["MA60"] #用来判断是否在ma60之上
df['ma60Slope'] = None
for i in range(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"] = False
for i in range(len(df)):
if (df["DIFF"][i] - df["DEA"][i]) > 0 :
df.loc[i,"macdGold"] = True
if (df["DIFF"][i] - df["DEA"][i]) < 0 :
df.loc[i,"macdDead"] = True
df["macdGoldsoon"] = None # macd 将要金叉死叉
df["macdDeadsoon"] = None
for i in range(len(df)-2) :
if df["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"] = True
if df["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"] = True
df['DEASlope'] = None
for i in range(1, len(df)):
df.loc[i, 'DEASlope'] = df["DEA"][i] - df["DEA"][i - 1]
df["KDir"] = 0
for i in range(1,len(df)): # K线方向判断,如果高点抬高 低点抬高就多,高点低点降低就空,内包外包就保持
if (df["high"][i] > df["high"][i-1]) and (df["low"][i] > df["low"][i-1]):
df.loc[i,"KDir"] = 1
elif df["high"][i] < df["high"][i-1] and df["low"][i] < df["low"][i-1]:
df.loc[i,"KDir"] = -1
else :
df.loc[i,"KDir"] = df["KDir"][i-1]
for dft in [self.df5m, self.df60m, self.df1d, self.df1w]:
apply_ma60(dft)
apply_ma20(dft)
apply_macd(dft)
apply_hist_signals(dft)
class Rule(object): #预警规则的基类
def __init__(self):
self.name = "RuleBase"
def ApplyRule(self, bd):
pass
def Msg(self): #当规则发生的时候,要发出来的消息
return "Non Rule Implemented."
class RuleResonanceUp(Rule): #多头共振的规则,所有的周期都是多的时候提醒
def __init__(self):
self.name = "RuleResonaceUp"
def ApplyRule(self, bd):
if bd.df1w["KDir"].tolist()[-1] > 0 and bd.df1d.KDir.tolist()[-1] > 0 and bd.df1d.DEASlope.tolist()[-1] > 0 and bd.df60m.KDir.tolist()[-1] > 0 \
and bd.df60m.DEASlope.tolist()[-1] > 0 and bd.df5m.ma60Slope.tolist()[-1] > 0 and bd.df5m.DEASlope.tolist()[-1] > 0 \
and bd.df5m.KDir.tolist()[-1] >0:
return True
else:
return False
def Msg(self):
return "周K,日K,日DEA,日K,小时DEA,小时K,5mDEA、5mMA60、5mK,多方共振。"
class Monitor(object):
def __init__(self):
self.Rules = []
def addRule(self,r):
self.Rules += [r]
def Run(self,bd): #执行规则,满足规则的时候打印提醒信息,在这里,可以换成ichat或者pyqq啥的,就可以实现微信和qq的通知了。
for r in self.Rules:
if r.ApplyRule(bd):
print(datetime.datetime.now()," "+get_security_info(bd.stockCode).display_name+': '+r.Msg())
pass
以上就是一个简单的利用jqdata进行多品种均线情况监控的规则框架。
原文链接:https://www.joinquant.com/view/community/detail/16682
原文作者:聚宽/fwoods