def __computeRangeFloatList(self, pct_list: [], encoder: FloatEncoder, sort=True) -> Sequence['FloatRange']: rangeCount = {} totalCount = len(pct_list) for i in range(0, encoder.mask()): rangeCount[i] = 0 for pct in pct_list: encode = encoder.encode(pct) rangeCount[encode] += 1 rangeList = [] for encode, count in rangeCount.items(): probal = 0.0 if totalCount > 0: probal = count / totalCount floatRange = FloatRange(encode=encode, probal=probal) rangeList.append(floatRange) if sort: return FloatRange.sort(rangeList) return rangeList
class More_detail_KPattern_skip1_predit2(Find_KPattern_skip1_predit2): def __init__(self, limit_close_pct=1, kPatters: [] = None): Find_KPattern_skip1_predit2.__init__(self, limit_close_pct=limit_close_pct) self.kPatters = kPatters self.pct_split = [-7, -5, -3, -1.0, 0, 1, 3, 5, 7] self.pctEncoder = FloatEncoder(self.pct_split) self.kPattersMap = {} self.allTradyDayCount = 0 self.allTradeDay = 0 self.occurDayMap = {} for value in kPatters: self.kPattersMap[value] = True pass def onCreate(self): super().onCreate() self.occurDayMap.clear() self.allTradyDayCount = 0 self.allTradeDay = 0 def onStart(self, code: str) -> bool: self.allTradyDayCount = 0 return Find_KPattern_skip1_predit2.onStart(self, code) def onEnd(self, code: str): Find_KPattern_skip1_predit2.onEnd(self, code) self.allTradeDay = max(self.allTradeDay, self.allTradyDayCount) def collect(self, bar: BarData) -> TraceData: traceData = Find_KPattern_skip1_predit2.collect(self, bar) self.allTradyDayCount += 1 if not traceData is None: kPatternValue = traceData.kPatternValue if self.kPattersMap.get(kPatternValue) is None: ##过滤 return None return traceData def newCountData(self) -> CountData: data = Find_KPattern_skip1_predit2.newCountData(self) data.sell_disbute = np.zeros(self.pctEncoder.mask()) ##卖方力量分布情况 data.buy_disbute = np.zeros(self.pctEncoder.mask()) # 买方力量分布情况 return data def doWantedTraceData(self, traceData: Skip1_Predict2_TraceData, countData: CountData): Find_KPattern_skip1_predit2.doWantedTraceData(self, traceData, countData) sell_pct = traceData.sell_pct buy_pct = traceData.buy_pct ##统计买卖双方的分布情况 countData.buy_disbute[self.pctEncoder.encode(buy_pct)] += 1 countData.sell_disbute[self.pctEncoder.encode(sell_pct)] += 1 occurBar = traceData.occurBar dayKey = occurBar.datetime.year * 13 * 35 + occurBar.datetime.month * 13 + occurBar.datetime.day self.occurDayMap[dayKey] = True pass def onDestroy(self): Find_KPattern_skip1_predit2.onDestroy(self) if not self.print_on_destroy: return print(f"所有交易日中,有意义的k线形态出现占比:%.2f%%,allTradeDay = { self.allTradeDay}" % (100 * len(self.occurDayMap) / self.allTradeDay)) for kValue, dataItem in self.dataSet.items(): total_count1 = 0 total_count2 = 0 for cnt in dataItem.sell_disbute: total_count1 += cnt for cnt in dataItem.buy_disbute: total_count2 += cnt assert total_count1 == total_count2 assert total_count1 > 0 print(f"k线形态值:%6d, " % (kValue)) print(f" 卖方价格分布:") info = "" for encode in range(0, len(dataItem.sell_disbute)): occurtRate = 100 * dataItem.sell_disbute[encode] / total_count1 info += f"{self.pctEncoder.descriptEncdoe(encode)}:%.2f%%," % ( occurtRate) print(f" {info}") print(f" 买方价格分布:") info = "" for encode in range(0, len(dataItem.buy_disbute)): occurtRate = 100 * dataItem.buy_disbute[encode] / total_count1 info += f"{self.pctEncoder.descriptEncdoe(encode)}:%.2f%%," % ( occurtRate) print(f" {info}")
def printKPatterMoreDetail(kPatters=[ 535, 359, 1239, 1415, 1072, 712, 1412, 1240, 1413, 888, 2823, 706, 1414, 1064 ]): from vnpy.trader.constant import Exchange from vnpy.trader.constant import Interval sw = SWImpl() lists = sw.getSW2List() start = datetime(2014, 5, 1) end = datetime(2020, 8, 17) pct_split = [-7, -5, -3, -1.5, -0.5, 0.5, 1.5, 3, 5, 7] #pct_split = [-7, -5, -3, -1.0, 0, 1, 3, 5, 7] pct_split = [2] pctEncoder = FloatEncoder(pct_split) kPattersMap = {} for value in kPatters: kPattersMap[value] = True class InnerData(object): kValue: int ## sell_disbute = np.zeros(pctEncoder.mask()) ##卖方力量分布情况 buy_disbute = np.zeros(pctEncoder.mask()) #买方力量分布情况 pass dataSet = {} occurDayMap = {} allTrayDay = 1 for code in lists: # for code in lists: barList = sw.getSW2Daily(code, start, end) indicator = Indicator(40) traceItems: ['TraceIn3DayItem'] = [] allTrayDay = max(allTrayDay, len(barList)) for bar in barList: ###跟踪数据 toDeleteList = [] for traceItem in traceItems: traceItem.onTraceBar(bar) if traceItem.isFinished(): toDeleteList.append(traceItem) if traceItem.isWanted(): occurBar = traceItem.firstBar dayKey = occurBar.datetime.year * 13 * 35 + occurBar.datetime.month * 13 + occurBar.datetime.day occurDayMap[dayKey] = True ###归纳到统计里面 innerData: InnerData = dataSet.get(traceItem.kPattern) if innerData is None: innerData = InnerData() innerData.kValue = traceItem.kPattern dataSet[traceItem.kPattern] = innerData sell_pct = traceItem.current_sell_pct buy_pct = traceItem.current_buy_pct innerData.buy_disbute[pctEncoder.encode(buy_pct)] += 1 innerData.sell_disbute[pctEncoder.encode( sell_pct)] += 1 pass for traceItem in toDeleteList: traceItems.remove(traceItem) indicator.update_bar(bar) kEncodeValue = KPattern.encode2KAgo1(indicator) if kEncodeValue is None or kPattersMap.get(kEncodeValue) is None: continue traceItem = TraceIn3DayItem(kEncodeValue, bar) traceItems.append(traceItem) print(f"所有交易日中,有意义的k线形态出现占比:%.2f%%" % (100 * len(occurDayMap) / allTrayDay)) for kValue, dataItem in dataSet.items(): total_count1 = 0 total_count2 = 0 for cnt in dataItem.sell_disbute: total_count1 += cnt for cnt in dataItem.buy_disbute: total_count2 += cnt assert total_count1 == total_count2 assert total_count1 > 0 print(f"\n\nk:%6d, " % (kValue)) print(f" 卖方价格分布:") for encode in range(0, len(dataItem.sell_disbute)): occurtRate = 100 * dataItem.sell_disbute[encode] / total_count1 print(f" {pctEncoder.descriptEncdoe(encode)}:%.2f%%" % (occurtRate)) print(f" 买方价格分布:") for encode in range(0, len(dataItem.buy_disbute)): occurtRate = 100 * dataItem.buy_disbute[encode] / total_count1 print(f" {pctEncoder.descriptEncdoe(encode)}:%.2f%%" % (occurtRate)) pass
class EngineModel2KAlgo2(CoreEngineModel): def __init__(self): self.lasted3Bar = np.array([None, None, None]) self.lasted3BarKdj = np.array([None, None, None]) self.kdjEncoder = FloatEncoder([15, 30, 45, 60, 75, 90]) self.sw = SWImpl() def onCollectStart(self, code: str) -> bool: from earnmi.chart.Indicator import Indicator self.indicator = Indicator(40) self.code = code return True def onCollectTrace(self, bar: BarData) -> CollectData: self.indicator.update_bar(bar) self.lasted3Bar[:-1] = self.lasted3Bar[1:] self.lasted3BarKdj[:-1] = self.lasted3BarKdj[1:] k, d, j = self.indicator.kdj(fast_period=9, slow_period=3) self.lasted3Bar[-1] = bar self.lasted3BarKdj[-1] = [k, d, j] if self.indicator.count >= 20: from earnmi.chart.KPattern import KPattern kPatternValue = KPattern.encode2KAgo1(self.indicator) if not kPatternValue is None: _kdj_mask = self.kdjEncoder.mask() kPatternValue = kPatternValue * _kdj_mask * _kdj_mask + self.kdjEncoder.encode( k) * _kdj_mask + self.kdjEncoder.encode(d) dimen = Dimension(type=TYPE_2KAGO1, value=kPatternValue) collectData = CollectData(dimen=dimen) collectData.occurBars.append(self.lasted3Bar[-2]) collectData.occurBars.append(self.lasted3Bar[-1]) collectData.occurKdj.append(self.lasted3BarKdj[-2]) collectData.occurKdj.append(self.lasted3BarKdj[-1]) return collectData return None def onCollect(self, data: CollectData, newBar: BarData) -> bool: if len(data.occurBars) < 3: data.occurBars.append(self.lasted3Bar[-1]) data.occurKdj.append(self.lasted3BarKdj[-1]) else: data.predictBars.append(newBar) size = len(data.predictBars) return size >= 2 @abstractmethod def getYLabelPrice(self, cData: CollectData) -> [float, float, float]: bars: ['BarData'] = cData.predictBars if len(bars) > 0: sell_price = -9999999999 buy_price = -sell_price for bar in bars: sell_price = max((bar.high_price + bar.close_price) / 2, sell_price) buy_price = min((bar.low_price + bar.close_price) / 2, buy_price) return sell_price, buy_price return None, None def getYBasePrice(self, cData: CollectData) -> float: return cData.occurBars[-2].close_price def generateXFeature(self, cData: CollectData) -> []: #保证len小于三,要不然就不能作为生成特征值。 if (len(cData.occurBars) < 3): return None occurBar = cData.occurBars[-2] skipBar = cData.occurBars[-1] kdj = cData.occurKdj[-1] sell_pct = 100 * ((skipBar.high_price + skipBar.close_price) / 2 - occurBar.close_price) / occurBar.close_price buy_pct = 100 * ((skipBar.low_price + skipBar.close_price) / 2 - occurBar.close_price) / occurBar.close_price def set_0_between_100(x): if x > 100: return 100 if x < 0: return 0 return x def percent_to_one(x): return int(x * 100) / 1000.0 data = [] data.append(percent_to_one(buy_pct)) data.append(percent_to_one(sell_pct)) data.append(set_0_between_100(kdj[0]) / 100) data.append(set_0_between_100(kdj[2]) / 100) return data
def printKPatterMoreDetail(kPatters=[ 6, 3, 17, 81, 7, 5, 4, 82, 159, 16, 28, 83, 15, 84, 18, 27, 93, 104, 158, 92, 160, 236, 157, 94, 85, 80, 14, 8, 161, 9, 29, 170, 26, 19, 38, 2, 79 ]): from earnmi.data.SWImpl import SWImpl from vnpy.trader.constant import Exchange from vnpy.trader.constant import Interval sw = SWImpl() lists = sw.getSW2List() start = datetime(2014, 5, 1) end = datetime(2020, 8, 17) pct_split = [-7, -5, -3, -1.5, -0.5, 0.5, 1.5, 3, 5, 7] pct_split = [-7, -5, -3, -1.0, 0, 1, 3, 5, 7] pct_split = [-0.5, 0.5] pctEncoder = FloatEncoder(pct_split) kPattersMap = {} for value in kPatters: kPattersMap[value] = True class InnerData(object): kValue: int ## sell_disbute = np.zeros(pctEncoder.mask()) ##卖方力量分布情况 buy_disbute = np.zeros(pctEncoder.mask()) #买方力量分布情况 pass dataSet = {} occurDayMap = {} allTrayDay = 1 for code in lists: # for code in lists: barList = sw.getSW2Daily(code, start, end) indicator = Indicator(40) preBar = None previousIsMatch = False previousPatternVaule = None allTrayDay = max(allTrayDay, len(barList)) for i in range(0, len(barList)): bar = barList[i] indicator.update_bar(bar) patternValue = KPattern.encode1KAgo1(indicator) todayIsMatch = False if not patternValue is None: todayIsMatch = kPattersMap.__contains__(patternValue) if todayIsMatch: dayKey = bar.datetime.year * 13 * 35 + bar.datetime.month * 13 + bar.datetime.day occurDayMap[dayKey] = True pass if previousIsMatch: innerData: InnerData = dataSet.get(previousIsMatch) if innerData is None: innerData = InnerData() innerData.kValue = previousIsMatch dataSet[previousPatternVaule] = innerData sell_pct = 100 * ((bar.high_price + bar.close_price) / 2 - preBar.close_price) / preBar.close_price buy_pct = 100 * ((bar.low_price + bar.close_price) / 2 - preBar.close_price) / preBar.close_price innerData.buy_disbute[pctEncoder.encode(buy_pct)] += 1 innerData.sell_disbute[pctEncoder.encode(sell_pct)] += 1 pass preBar = bar previousIsMatch = todayIsMatch previousPatternVaule = patternValue print(f"所有交易日中,有意义的k线形态出现占比:%.2f%%" % (100 * len(occurDayMap) / allTrayDay)) for kValue, dataItem in dataSet.items(): total_count1 = 0 total_count2 = 0 for cnt in dataItem.sell_disbute: total_count1 += cnt for cnt in dataItem.buy_disbute: total_count2 += cnt assert total_count1 == total_count2 assert total_count1 > 0 print(f"\n\nk:%6d, " % (kValue)) print(f" 卖方价格分布:") for encode in range(0, len(dataItem.sell_disbute)): occurtRate = 100 * dataItem.sell_disbute[encode] / total_count1 print(f" {pctEncoder.descriptEncdoe(encode)}:%.2f%%" % (occurtRate)) print(f" 买方价格分布:") for encode in range(0, len(dataItem.buy_disbute)): occurtRate = 100 * dataItem.buy_disbute[encode] / total_count1 print(f" {pctEncoder.descriptEncdoe(encode)}:%.2f%%" % (occurtRate)) pass