示例#1
0
    class QuantStrategy(CoreEngineStrategy):
        def __init__(self):
            self.sw = SWImpl()

        def generatePredictOrder(self, engine: CoreEngine, predict: PredictData,debugPrams:{}=None) -> PredictOrder:

            if debugPrams is None:
                debugPrams = {}
            quantData = engine.queryQuantData(predict.dimen)
            code = predict.collectData.occurBars[-1].symbol
            name = self.sw.getSw2Name(code)
            order = PredictOrder(dimen=predict.dimen, code=code, name=name)
            start_price = engine.getEngineModel().getYBasePrice(predict.collectData)

            _min, _max = quantData.getSellFloatEncoder().parseEncode(quantData.sellRange[0].encode)
            order.suggestSellPrice = start_price * (1 + (_min +  _max) / 2 / 100)
            _min, _max = quantData.getBuyFloatEncoder().parseEncode(quantData.buyRange[0].encode)
            order.suggestBuyPrice = start_price * (1 + (_min +  _max) / 2 / 100)

            order.power_rate = quantData.getPowerRate();

            ##for backTest
            self.checkIfBuyPrice(order,predict.collectData.occurBars[-1].close_price,debugPrams)
            return order

        def checkIfBuyPrice(self,order: PredictOrder,targetPrice:float,debugPrams:{}=None):
            if order.status != PredictOrderStatus.TRACE:
                return
            quantData = engine.queryQuantData(order.dimen)

            if quantData.getPowerRate() > 0.9 and order.suggestBuyPrice >= targetPrice:
                order.status = PredictOrderStatus.HOLD
                order.buyPrice = targetPrice

        def updatePredictOrder(self, order: PredictOrder, bar: BarData, isTodayLastBar: bool,debugPrams:{}):
            if (order.status == PredictOrderStatus.HOLD):
                if bar.high_price >= order.suggestSellPrice:
                    order.sellPrice = order.suggestSellPrice
                    order.status = PredictOrderStatus.CROSS
                    return
                if order.holdDay >= 1:
                    order.sellPrice = bar.close_price
                    order.status = PredictOrderStatus.CROSS
                    return
            order.holdDay += 1
            self.checkIfBuyPrice(order,bar.low_price,debugPrams)
示例#2
0
class Generate_Feature_KPattern_skip1_predit2(
        More_detail_KPattern_skip1_predit2):
    def __init__(self, limit_close_pct=1, kPatters: [] = None):
        super().__init__(limit_close_pct, kPatters)
        self.traceDatas = []
        self.sw = SWImpl()
        self.predictTraceDatas: ['Skip1_Predict2_TraceData'] = []
        #pct_split = [-7, -5, -3, -1.5, -0.5, 0.5, 1.5, 3, 5, 7]
        #self.pctEncoder = FloatEncoder(pct_split)

    def onCreate(self):
        super().onCreate()
        self.traceDatas.clear()

    def doWantedTraceData(self, traceData: Skip1_Predict2_TraceData,
                          countData: CountData):
        super().doWantedTraceData(traceData, countData)
        self.traceDatas.append(traceData)
        pass

    def onTraceStop(self, traceData: Skip1_Predict2_TraceData):
        super().onTraceStop(traceData)
        if (not traceData.skipBar is None):
            self.predictTraceDatas.append(traceData)

    def generateData(
            self,
            traceDatas: Sequence["Skip1_Predict2_TraceData"]) -> pd.DataFrame:
        trainDataSet = []
        for traceData in traceDatas:
            occurBar = traceData.occurBar
            skipBar = traceData.skipBar
            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
            data = []
            data.append(self.code)
            data.append(self.sw.getSw2Name(self.code))
            data.append(traceData.kPatternValue)
            data.append(buy_pct)
            data.append(sell_pct)
            data.append(traceData.indicator_k)
            data.append(traceData.indicator_j)

            data.append(traceData.sell_pct)
            data.append(traceData.buy_pct)
            trainDataSet.append(data)
        cloumns = [
            "code", "name", "kPattern", "buy_price", "sell_price", "k", "j",
            "label_sell_price", "label_buy_price"
        ]
        return pd.DataFrame(trainDataSet, columns=cloumns)

    def getPandasData(self) -> pd.DataFrame:
        return self.generateData(self.traceDatas)

    def writeToXml(self) -> bool:
        size = len(self.traceDatas)
        if size < 1:
            print("no need to write")
            return False
        wxl = self.getPandasData()
        writer = pd.ExcelWriter('files/sw_train_data_sample.xlsx')
        wxl.to_excel(writer, sheet_name="sample", index=False)
        writer.save()
        writer.close()
        print(f"write dataSize = {size}")
        return True

    def onDestroy(self):
        super().onDestroy()
示例#3
0
class MyStrategy(CoreEngineStrategy):
    def __init__(self):
        self.sw = SWImpl()
        self.mDateHoldCountMap = {}  ##统计产生收集个数的次数

    def generatePredictOrder(self,
                             engine: CoreEngine,
                             predict: PredictData,
                             debugPrams: {} = None) -> PredictOrder:

        if debugPrams is None:
            debugPrams = {}

        code = predict.collectData.occurBars[-1].symbol
        name = self.sw.getSw2Name(code)
        order = PredictOrder(dimen=predict.dimen, code=code, name=name)
        predict_sell_pct = predict.getPredictSellPct(engine.getEngineModel())
        predict_buy_pct = predict.getPredictBuyPct(engine.getEngineModel())
        start_price = engine.getEngineModel().getYBasePrice(
            predict.collectData)
        order.suggestSellPrice = start_price * (1 + predict_sell_pct / 100)
        order.suggestBuyPrice = start_price * (1 + predict_buy_pct / 100)
        order.power_rate = engine.queryQuantData(predict.dimen).getPowerRate()

        timeKey = utils.to_start_date(
            predict.collectData.occurBars[-1].datetime)
        if self.mDateHoldCountMap.get(timeKey) is None:
            self.mDateHoldCountMap[timeKey] = 0

        ##for backTest
        occurBar: BarData = predict.collectData.occurBars[-2]
        skipBar: BarData = predict.collectData.occurBars[-1]
        buy_price = skipBar.close_price
        predict_sell_pct = 100 * (order.suggestSellPrice -
                                  start_price) / start_price
        predict_buy_pct = 100 * (order.suggestBuyPrice -
                                 start_price) / start_price
        buy_point_pct = 100 * (
            buy_price - occurBar.close_price) / occurBar.close_price  ##买入的价格

        abilityData = engine.queryPredictAbilityData(predict.dimen)
        quantData = engine.queryQuantData(predict.dimen)
        delta = abs(quantData.sellCenterPct) - abs(quantData.buyCenterPct)
        if abs(delta) < 0.05:
            # 多空力量差不多
            power = 0
        if delta > 0:
            # 适合做多
            power = (quantData.sellCenterPct +
                     quantData.buyCenterPct) / quantData.sellCenterPct
        else:
            power = -(quantData.sellCenterPct +
                      quantData.buyCenterPct) / quantData.buyCenterPct

        extraCondition = True
        quant_power = debugPrams.get("quant_power")
        if not quant_power is None:
            extraCondition = extraCondition and predict.quantData.getPowerRate(
            ) >= quant_power

        predict_buy_pct_param = debugPrams.get("predict_buy_pct")
        if not predict_buy_pct_param is None:
            extraCondition = extraCondition and predict_buy_pct >= predict_buy_pct_param

        if extraCondition and predict_sell_pct - buy_point_pct > 1 \
                and abilityData.trainData.biasSellLoss < 10:
            order.status = PredictOrderStatus.HOLD
            order.buyPrice = buy_price

            timeKey = utils.to_start_date(
                predict.collectData.occurBars[-1].datetime)
            self.mDateHoldCountMap[timeKey] += 1

        else:
            order.status = PredictOrderStatus.STOP
        return order

    def updatePredictOrder(self,
                           order: PredictOrder,
                           bar: BarData,
                           isTodayLastBar: bool,
                           debugParams: {} = None):
        if (order.status == PredictOrderStatus.HOLD):
            if bar.high_price >= order.suggestSellPrice:
                order.sellPrice = order.suggestSellPrice
                order.status = PredictOrderStatus.CROSS
                return
            order.holdDay += 1
            if order.holdDay >= 2:
                order.sellPrice = bar.close_price
                order.status = PredictOrderStatus.CROSS
                return
示例#4
0
    class MyPattherCollector(KPatternCollector):
        # 收集指定的k线
        collectKPatternOnly = True
        KPattern: [] = [712]
        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)

        def __init__(self):
            self.kPattersMap = {}
            self.sw = SWImpl()
            self.dataSet = []
            for value in self.KPattern:
                self.kPattersMap[value] = True

        def onStart(self, code: str) -> bool:
            self.indicator = Indicator(40)
            self.traceCode = code
            self.traceName = self.sw.getSw2Name(code)
            return True

        """
        检查是否追踪某个k线形态,是的话,创建一个最终值对象。
        """

        def checkIfTrace(self, newBar: BarData) -> TraceIn3DayItem:
            self.indicator.update_bar(newBar)
            kEncodeValue = KPattern.encode2KAgo1(self.indicator)
            if kEncodeValue is None:
                return None
            if self.collectKPatternOnly and self.kPattersMap.get(
                    kEncodeValue) is None:
                return None
            return TraceIn3DayItem(kEncodeValue, newBar)

        def onTraceFinish(self, traceItem: TraceIn3DayItem):
            if traceItem.isWanted():
                ##收集数据。
                data = []
                data.append(self.traceCode)
                data.append(self.traceName)
                data.append(traceItem.kPattern)
                data.append(traceItem.first_buy_pct)
                data.append(traceItem.fisrt_sell_pct)
                data.append(traceItem.current_sell_pct)
                data.append(traceItem.current_buy_pct)
                self.dataSet.append(data)

        def onDestroy(self):
            import pandas as pd
            cloumns = [
                "code", "name", "kPattern", "buy_price", "sell_price",
                "label_sell_price", "label_buy_price"
            ]
            wxl = pd.DataFrame(self.dataSet, columns=cloumns)
            writer = pd.ExcelWriter('files/sw_train_data_sample.xlsx')
            wxl.to_excel(writer, sheet_name="sample", index=False)
            writer.save()
            writer.close()
            print(f"dataSize = {len(self.dataSet)}")
示例#5
0
def generateSWTrainData(kPatterns: [], start: datetime,
                        end: datetime) -> pd.DataFrame:
    sw = SWImpl()
    lists = sw.getSW2List()
    cloumns = [
        "code", "name", "kPattern", "k", "d", "dif", "dea", "macd", "open",
        "short", "long"
    ]
    datas = []
    kPatternMap = {}
    for kPatternValues in kPatterns:
        kPatternMap[kPatternValues] = True

    macd_list = []

    for code in lists:
        # for code in lists:
        name = sw.getSw2Name(code)
        barList = sw.getSW2Daily(code, start, end)
        indicator = Indicator(34)
        preBar = None
        for bar in barList:
            ##先识别形态
            kEncodeValue = None
            if indicator.inited:
                tmpKEncodeValue = KPattern.encode3KAgo1(indicator)
                if kPatternMap.__contains__(tmpKEncodeValue):
                    kEncodeValue = tmpKEncodeValue
            if kEncodeValue is None:
                indicator.update_bar(bar)
                preBar = bar
                continue
            ##昨天的kdj
            k, d, j = indicator.kdj(array=False)
            dif, dea, macd = indicator.macd(fast_period=12,
                                            slow_period=26,
                                            signal_period=9,
                                            array=False)

            ##第二天的收益
            short_pct = 100 * ((bar.high_price + bar.close_price) / 2 -
                               preBar.close_price) / preBar.close_price
            long_pct = 100 * ((bar.low_price + bar.close_price) / 2 -
                              preBar.close_price) / preBar.close_price
            open_pct = 100 * (bar.open_price -
                              preBar.close_price) / preBar.close_price

            item = []
            item.append(code)
            item.append(name)
            item.append(kEncodeValue)
            item.append(k)
            item.append(d)
            item.append(dif)
            item.append(dea)
            item.append(macd)
            #下个k线数据
            item.append(open_pct)
            item.append(short_pct)
            item.append(long_pct)
            datas.append(item)

            macd_list.append(macd)

            indicator.update_bar(bar)
            preBar = bar
    macd_list = np.array(macd_list)
    print(
        f"total size : {len(datas)},mean ={macd_list.mean()},max={macd_list.max()},min={macd_list.min()}"
    )
    wxl = pd.DataFrame(datas, columns=cloumns)
    return wxl