Example #1
0
    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
Example #2
0
    def __findBestFloatEncoder(
        self, pct_list: [], originEncoder: FloatEncoder
    ) -> Union[FloatEncoder, Sequence['FloatRange']]:
        SCALE = 5000
        min, max = originEncoder.parseEncode(int(originEncoder.mask() / 2))
        min = int(min * SCALE)
        max = int(max * SCALE)
        step = int((max - min) / 100)

        bestProbal = 0
        bestEncoder = originEncoder
        bestRnageList = None
        for shift in range(min, max, step):
            d = shift / SCALE
            encoder = originEncoder.shift(d)
            flaotRangeList = self.__computeRangeFloatList(pct_list, encoder)
            probal = flaotRangeList[0].probal
            if probal > bestProbal:
                bestProbal = probal
                bestEncoder = encoder
                bestRnageList = flaotRangeList

        return bestEncoder, bestRnageList
Example #3
0
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}")
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