话不多先上代码,缺口指的就是连续两天K线中的不相交部分,本代码用于检测那些还没有被补的缺口,这对交易有重要的指导意义:
import os#缓存数据class SecurityData: date = '' #日期 downPrice = 0 #缺口的下半部分 upPrice = 0 #缺口的上半部分#打开日志文件fs = open(r'C:\Py\result.txt','a+')#打开日K线文件fs2 = open(r'C:\Py\SH000001.txt', 'r', True)#索引pos = 0#上日最高价lastHigh = 0#上日最低价lastLow = 0#保存缺口的集合lst = []#最小检测价位priceTick = 2.0#循环遍历每一行while True: #读取该行 line = fs2.readline() #没有行的时候退出 if not line: break #去除前2行和尾行 if pos > 1 and len(line) > 20: #分割字符串 strs = line.split(',') #收盘价 highPrice = float(strs[2]) #开盘价 lowPrice = float(strs[3]) #检测缺口是否被补 for data in lst: #高值+低值 if (highPrice > data.downPrice and highPrice < data.upPrice) and (lowPrice > data.downPrice and lowPrice < data.upPrice): newData1 = SecurityData() newData1.upPrice = data.upPrice newData1.downPrice = highPrice newData1.date = data.date lst.append(newData1) newData2 = SecurityData() newData2.upPrice = lowPrice newData2.downPrice = data.downPrice newData2.date = data.date lst.append(newData2) lst.remove(data) #倒包含 elif (data.downPrice > lowPrice and data.downPrice < highPrice) and (data.upPrice > lowPrice and data.upPrice < highPrice): lst.remove(data) else: #高值 if (highPrice >= data.downPrice and highPrice <= data.upPrice): data.downPrice = highPrice #低值 if (lowPrice >= data.downPrice and lowPrice <= data.upPrice): data.upPrice = lowPrice #判断缺口是否被补 if (data.upPrice - data.downPrice < priceTick): lst.remove(data) #判断是否为缺口 if pos > 2: if lowPrice > lastHigh + priceTick: securityData = SecurityData() securityData.upPrice = lowPrice securityData.downPrice = lastHigh securityData.date = strs[0] lst.append(securityData) elif highPrice < lastLow - priceTick: securityData = SecurityData() securityData.upPrice = lastLow securityData.downPrice = highPrice securityData.date = strs[0] lst.append(securityData) #缓存上日的数据 lastHigh = highPrice lastLow = lowPrice #累加索引 pos = pos + 1#给列表排序from operator import attrgetterlst2 = sorted(lst, key=attrgetter('date'), reverse=False)#输出for val in lst2: print(val.date + ',' + str(val.downPrice) + ',' + str(val.upPrice)) fs.write(val.date + ',' + str(val.downPrice) + ',' + str(val.upPrice) + '\r\n')#关闭文件流fs.close()fs2.close()
新建一个文件,命名为QUE.py,并将上述代码粘贴到你的文件中。
按照教程下载上证指数的前复权数据:
如何免费轻松获得最完整可靠的股票期货等历史数据?
修改Python中的文件和文件夹路径为你的路径,PriceTick修改为最小缺口的值,极其微弱的断裂不能被称为缺口:
如果没有安装Python,就到这个地址下载安装一下:
https://www.python.org/ftp/python/3.9.0/python-3.9.0-amd64.exe
注意第一个界面的Add to Path一定要勾上。
打开命令提示行,输入python C:\PY\QUE.py
输入回车运行脚本,得到如下结果:
result.txt中也输出了结果:
打开图形K线看看几个没补的缺口:
通过跑Python代码发现,上证指数历史上只有寥寥几个缺口没有补,近半年不算的话,只有6124,5178股灾时期有几个头部和底部的缺口没补,还有A股最早期有几个缺口没补,这证明了缺口理论是正确。
结论:
1.计算结果完全正确,而且是完全对应通达信的;
2.可以直接运行,得到结果文件result.txt,怎么用看你的;
3.可以修改代码,例如修改输入结果文件的格式;
4.不止用于A股,什么品种,数据,包括1分钟,5分钟,60分钟线也都可以;
5.可以用来做交易回测。
6.可以把代码嵌入你的Python中,用来做实时监控。