话不多说先上代码,此代码经过反复验证,确认计算结果与通达信完全一致,这里周期取30日:
#请使用前复权的日K线数据import os#缓存数据class SecurityData: code = '' #股票代码 name = '' #股票名称 value = 0 #数值#定义列表lst = []#打开日志文件fs = open(r'C:\Py\result.txt','a+')#循环遍历所有的日K线文件for root, dirs, files in os.walk(r'C:\Py\day'): for file in files: #写日志 print('正在计算' + file) #打开日K线文件 fs2 = open(os.path.join(root,file), 'r', True) #索引 pos = 0 #数据索引 dataPos = 0 #股票名称 sName = '' #符合条件的数量 duoCount = 0 #上次均值 lastClose = 0 #OBV obv = 0 #周期 m = 30 #保存数据的集合 lstObv = [] #上次均值 lastObvMa = 0 #循环遍历每一行 while True: #读取该行 line = fs2.readline() #没有行的时候退出 if not line: break #去除前2行和尾行 if pos > 1 and len(line) > 20: #重置数量 duoCount = 0 #分割字符串 strs = line.split(',') #成交量 volume = float(strs[5]) #收盘价 closePrice = float(strs[4]) if dataPos == 0: lastClose = closePrice if closePrice > lastClose: obv = obv + volume elif closePrice < lastClose: obv = obv - volume lstObv.append(obv) #真实计算周期 realN = m if dataPos < m: realN = dataPos + 1 #数值的和 startIndex = dataPos - m + 1 if startIndex < 0: startIndex = 0 sum = 0 if dataPos > m: #高性能求和 sum = lastObvMa * m + obv - lstObv[startIndex - 1] else: #计算和 thisLst = lstObv[startIndex:dataPos + 1] for cVal in thisLst: sum = sum + cVal #计算MA obvMa = sum / realN if (dataPos > 0) and (obv > obvMa) and (lstObv[dataPos - 1] < lastObvMa): duoCount = duoCount + 1 lastObvMa = obvMa lastClose = closePrice #累加索引 dataPos = dataPos + 1 elif pos == 0: sName = line[line.find(' ') + 1 : line.find(' 日线')] #累加索引 pos = pos + 1 #保存到列表中 securityData = SecurityData() securityData.code = file[0 : 8] securityData.value = duoCount securityData.name = sName lst.append(securityData) #关闭文件流 fs2.close()#给列表排序from operator import attrgetterlst2 = sorted(lst, key=attrgetter('value'), reverse=True)#输出结果count = 0for val in lst2: if val.value >= 1: print(str(count + 1) + ',' + val.name + ',' + val.code + ',OBV金叉') fs.write(str(count + 1) + ',' + val.name+ ',' + val.code + ',OBV金叉\r\n') count = count + 1#关闭文件流fs.close()
新建一个文件,命名为OBV.py,并将上述代码粘贴到你的文件中。
按照教程下载所有A股的前复权数据,并放到一个文件夹中:
如何免费轻松获得最完整可靠的股票期货等历史数据?
修改Python中的文件和文件夹路径为你的路径:
如果没有安装Python,就到这个地址下载安装一下:
https://www.python.org/ftp/python/3.9.0/python-3.9.0-amd64.exe
注意第一个界面的Add to Path一定要勾上。
打开命令提示行,输入python C:\PY\OBV.py
输入回车运行脚本,得到如下结果:
result.txt中也输出了结果:
打开图形K线验证结果:
第一个,皖通高速,SH600012,的确是超卖
第二个,四川路桥,SH600039,的确是超卖
第三个,国机汽车,SH600335,的确是超卖
结论:
1.计算结果完全正确,而且是完全对应通达信的;
2.可以直接运行,得到结果文件result.txt,怎么用看你的;
3.可以修改代码,例如修改输入结果文件的格式;
4.不止用于A股,什么品种,数据,包括1分钟,5分钟,60分钟线也都可以;
5.可以用来做交易回测,超卖和超买只是把if (dataPos > 0) and (obv > obvMa) and (lstObv[dataPos - 1] < lastObvMa):改成if (dataPos > 0) and (obv < obvMa) and (lstObv[dataPos - 1] > lastObvMa):。
6.可以把代码嵌入你的Python中,用来做实时监控。