Exemplo n.º 1
0
    def seperate(self):
        Base = future_baseInfo()
        codes = Base.getUsedMap(hasIndex=True, isquick=True)
        dd = str(public.getTime(style='%H:%M:%S'))
        maps = {}
        # 按结束时间分组分进程
        for doc in Base.getInfo(codes):
            if doc['code'] in self.banCodeList: continue

            uid = self.uidStyle % (doc['code'], doc['quickkline'][:-1],
                                   self.methodName)
            self.future_Map.append(uid.split("_"))
            key = doc['nightEnd']
            if '03:00:00' < key < dd: continue

            if key not in maps.keys():
                maps[key] = []

            maps[key].append(doc['code'])

        for key in maps.keys():
            if len(maps[key]) < 10:
                yield maps[key]
            else:
                l, t = len(maps[key]), len(maps[key]) // 10
                for i in range(t):
                    s, e = i * 10, l if (i + 1) * 10 > l else (i + 1) * 10
                    yield maps[key][s:e]
Exemplo n.º 2
0
    def seperate(self):
        Base = future_baseInfo()
        maps, codes = {}, []
        dd = str(public.getTime(style='%H:%M:%S'))

        # 按结束时间分组分进程
        for doc in Base.getInfo(self.combinCode()):
            key = key0 = doc['nightEnd']
            if '03:00:00' < key0 < dd: continue
            if '08:30:00' < dd < '15:00:00':
                key = '15:00:00' if '09:00:00' < key0 < '15:30:00' else '23:30:00' if '15:30:00' < key0 < '23:35:00' else '02:30:00'
                pass

            if key not in maps.keys():
                maps[key] = []

            maps[key].append(doc['code'])

        pc = 11
        for key in maps.keys():
            if len(maps[key]) < pc + 1:
                yield maps[key]
            else:
                l, t = len(maps[key]), len(maps[key]) // pc
                for i in range(t + 1):
                    s, e = i * pc, l if (i + 1) * pc > l else (i + 1) * pc
                    if s < e:
                        yield maps[key][s:e]
Exemplo n.º 3
0
 def getLastDay(self):
     dd = str(public.getTime(style='%H:%M:%S'))
     valids = self.getValidDate(start=-15, end=0)
     if ('18:15:00' < dd < '23:59:59'):
         date = public.getDate()
     else:
         date = str(valids[-2])
     return date
Exemplo n.º 4
0
    def point(self, row, row_1, tsize):
        ma, close, open, high, low, std, stdc, atr, atrc, dd = \
            (row[key] for key in
             "ma,close,open,high,low,std,stdc,atr,atrc,datetime".split(","))

        open = row_1['close']
        tt = str(public.getTime(style='%H:%M:%S'))
        kline = self.procMap.kline

        BL = 4.0 - float(kline) / 10

        #
        apart = (60 * kline) - (int(time.time()) % (60 * kline))
        if '09:00:00' <= tt < '09:15:00' or '21:00:00' <= tt < '21:10:00' or '14:45:00' <= tt < '15:00:01':
            BL += 5.0

        if apart > 10:
            BL += 0.5

        sign = 1 if high > (ma + 2 * std) else -1 if low < (ma -
                                                            2 * std) else 0

        # 计算长度、回撤率
        max = high if sign > 0 else low if sign < 0 else close
        diss = 0 if std == 0 else abs(max - ma) / std
        fall = abs(max - close) / abs(max - open) if max != open else 0

        # 条件
        opt0 = (diss > BL) and atrc > self.atrLine
        opt1 = (diss > (BL - 0.25)) and (atrc > (self.atrLine + 1.5))

        # 超长
        opt2 = diss > (BL + 1)

        # 超回收
        opt3 = diss > (BL - 0.35) and (fall > 0.5)

        opt8 = (abs(max - close) > 3 * tsize)
        opt9 = (atr / ma) * 10000 > 8 and std > 3 * tsize

        opt10 = stdc > 1.25
        powm = 0
        if opt8 and opt9:
            if opt10:
                powm = sign if opt0 else sign * 2 if opt1 else sign * 4 if opt3 else 0

            elif opt2:
                powm = sign * 3

        # 设置整点数据
        if int(time.time()) % 5 == 0:
            self.setLastClose(close)

        return powm, diss, fall
Exemplo n.º 5
0
    def seperate(self):
        Base = future_baseInfo()
        maps, codes = {}, []
        dd = str(public.getTime(style='%H:%M:%S'))
        # 按结束时间分组分进程
        for doc in Base.getInfo(self.combinCode()):
            key = doc['nightEnd']
            #
            if '03:00:00' < key < dd: continue

            if key not in maps.keys():
                maps[key] = []
            maps[key].append(doc['code'])

        for key in maps.keys():
            yield maps[key]
Exemplo n.º 6
0
    def filterCodes(self):
        # 查询每周统计表
        if self.topUse:
            Top = train_total()
            Top.tablename = self.topTableName
            self.future_Map = Top.last_top1(num=self.topNumbers,
                                            method=self.methodName,
                                            minVol=self.minVol,
                                            ban=self.banCodeList)
        else:
            Base = future_baseInfo()

            codes = Base.getUsedMap(hasIndex=len(self.indexCodeList) > 0)
            for code in codes:
                if not code in self.banCodeList:
                    uid = self.uidStyle % (code, self.methodName)
                    #  if code in ['IC']: print(uid)
                    self.future_Map.append(uid.split("_"))

        num0 = len(self.future_Map)
        Record = future_orderForm()
        if not self.isWorking: Record.tablename = self.orderFormTest

        # 添加未平仓,并不再开仓
        codesList = [c[0] for c in self.future_Map]
        # 当前开仓清单
        openCodes = Record.currentOpenCodes(method=self.methodName,
                                            batchNum=self.batchNum)
        if openCodes is not None:
            for map in openCodes:
                if not map[0] in codesList and not map[0] in self.banCodeList:
                    self.future_Map.append(map[:-3])
                    self.noneUsed.append(map[0])

        # 调仓处理
        dd = str(public.getTime(style='%H:%M:%S'))
        if "10:15:00" < dd < "11:00:00":
            self.alterPosition(Record, openCodes)

        logger.info(('总监控币对:', len(self.future_Map), ' 新列表:', num0, ' 未平仓:',
                     len(self.noneUsed)))
        logger.info(([n[0] for n in self.future_Map]))
        logger.info(('暂停币对:', len(self.noneUsed), [n for n in self.noneUsed]))
Exemplo n.º 7
0
    def onTick(self, tick):
        # 计算参数
        # 当前时间
        tt = str(public.getTime(style='%H:%M:%S'))
        for map in self.used_future_Map:
            if map[0] in self.banCodeList: continue

            # 股指期货时间过滤
            if map[0] in self.indexList and '08:59:00' < tt < '09:30:00':
                continue
            if map[0] not in self.indexList and '13:00:00' < tt < '13:30:00':
                continue

            self.uid = self.procMap.setUid(map, num=self.batchNum)  # uid
            self.mCodes = [self.baseInfo.mCode(c)
                           for c in self.procMap.codes]  # 当前主力合约代码
            kline = self.procMap.kline

            # 按时长读取k线数据
            dfs = self.Rice.getKline(self.kTypeMap[kline],
                                     ktype=kline,
                                     key=str(kline) + 'm',
                                     num=1)

            # 检查间隔时间
            try:
                # 计算指标
                param = self.paramCalc(dfs, tick)
                #if map[0] =='SC' and self.itemCount % 20 ==0:
                #    print(tick[self.mCodes[0]])

                if param is not None and not np.isnan(param["ma"]):
                    # mongodb Record
                    self.debugT('', param=param)

                    # 执行策略,并下单
                    self.orderCheck(tick, param)

            except Exception as e:
                print(traceback.format_exc())
Exemplo n.º 8
0
    def onTick(self, tick):
        # 计算参数
        ttt = str(public.getTime(style='%H:%M:%S'))
        opt0 = ("10:15:00" <= ttt < "10:30:00") or ("13:00:00" < ttt <
                                                    "13:30:00")
        opt1 = ("09:00:00" < ttt < "09:30:00")
        #print(opt0, opt1)
        for map in self.used_future_Map:
            if map[0] in self.banCodeList: continue

            # 上午休息时间,排除指数期货运行时间
            opt2 = len(self.indexList) > 0 and map[0] in self.indexList
            if (opt2 and opt1) or (not opt2 and opt0): continue

            self.uid = self.procMap.setUid(map, num=self.batchNum)  # uid
            self.mCodes = [self.baseInfo.mCode(c)
                           for c in self.procMap.codes]  # 当前主力合约代码

            kline = self.procMap.kline
            # 按时长读取k线数据
            dfs = self.Rice.getKline(self.kTypeMap[kline],
                                     ktype=kline,
                                     key='1d',
                                     num=120)

            # 检查间隔时间
            try:
                # 计算指标
                param = self.paramCalc(dfs, tick)

                if param is not None and not np.isnan(param["ma20"]):
                    # mongodb Record
                    self.debugT('', param=param)
                    # 执行策略,并下单
                    self.orderCheck(tick, param)
                    pass
            except Exception as e:
                print(traceback.format_exc())
Exemplo n.º 9
0
    def autoCreateAtr(self, type=0):
        Rice = interface_Rice()
        Rice.setIndexList(self.indexCodeList)
        Base = future_baseInfo()
        Record = self.Record = future_orderForm()
        Model = model_future_zhao_v1()

        methods = ['mZhao', 'mZhao55']
        self.iniAmount, self.stopLine = 15400000, 0.0025
        if type == 1:
            methods = ['zhao', 'zhao55']
            self.iniAmount, self.stopLine = 20000000, 0.0025

        codes = Base.getUsedMap(hasIndex=True)
        BI = BaseInfo(codes)
        mCodes = Rice.getMain(codes)
        #print(codes)

        end = None
        dd = str(public.getTime(style='%H:%M:%S'))
        valids = Rice.getValidDate(start=-15, end=0)

        if ('18:15:00' < dd < '23:59:59'):
            end = public.getDate(diff=0)
        else:
            end = str(valids[-2])

        dfs = Rice.kline(mCodes,
                         period='1d',
                         start=public.getDate(diff=-150),
                         end=end,
                         pre=20)
        docs = []

        Tmap = Record.trendMap(methods)

        Pos = []
        j = 0
        for m in methods:
            Pos.append(Record.getOpenMap(method=m, batchNum=1))

        for mcode in mCodes:
            code = BI.parseCode(mcode)
            if code in self.banCodeList: continue

            df = dfs[mcode]

            close = df['close']
            df["datetime"] = df.index

            df["ma10"] = ma10 = ta.MA(close, timeperiod=10)
            df["ma20"] = ma20 = ta.MA(close, timeperiod=20)
            df["ma55"] = ta.MA(close, timeperiod=55)

            atr21 = ta.ATR(df['high'], df['low'], close, timeperiod=21)
            df['3atr'] = atr21 * 3

            # 计算ma10-ma20 穿越线间距
            df['mac'] = mac = ma10 - ma20
            df['mac2'] = mac.shift(2)
            df['mac3'] = mac.shift(3)

            # isPoint
            df['mad'] = mac * mac.shift(1)
            df['mam'] = mam = df.apply(lambda row: self.isMam(row), axis=1)
            minidx, maxidx = ta.MINMAXINDEX(mam, timeperiod=75)
            df['interval'] = abs(minidx - maxidx)

            # 修正不正常K线
            df['high'] = df.apply(lambda row: self.k_fix(row, 1), axis=1)
            df['low'] = df.apply(lambda row: self.k_fix(row, -1), axis=1)

            # 唐奇安线18日
            df['tu_s'] = ta.MAX(df['high'], timeperiod=18 - 1)
            df['td_s'] = ta.MIN(df['low'], timeperiod=18 - 1)

            # 唐奇安线27日
            df['tu_s1'] = ta.MAX(df['high'], timeperiod=27 - 1)
            df['td_s1'] = ta.MIN(df['low'], timeperiod=27 - 1)

            # 唐奇安线34日
            df['tu_34'] = ta.MAX(df['high'], timeperiod=33)
            df['td_34'] = ta.MIN(df['low'], timeperiod=33)

            # 40日低点
            ld = close[close.notnull()]
            p = 40 if len(ld) > 40 else len(ld) - 1
            df['tu_d'] = ta.MAX(df['high'], timeperiod=p - 1)
            df['td_d'] = ta.MIN(df['low'], timeperiod=p - 1)

            fp, fd = 27, 5

            # 计算穿越值
            out = df.apply(lambda row: self.isout0(row), axis=1)
            df['out_s'] = ta.SUM(out, timeperiod=fp)
            df['trend'] = df['out_s'].apply(lambda x: -1 if x > fd else 1
                                            if x < -fd else 0)

            #posTrend = 0 if code not in trendMap else trendMap[code]['trend']
            df['isout'] = isout = df.apply(lambda row: self.isout(row, 0),
                                           axis=1)
            df['isout3'] = ta.SUM(isout, timeperiod=3)
            df['isout5'] = ta.SUM(isout, timeperiod=5)

            param = copy.deepcopy(df.iloc[-1]).to_dict()
            isLong, type = 1, 0
            if code in Tmap:
                isLong = Tmap[code]['trend']
                type = 1
            elif param['trend'] != 0:
                isLong = param['trend']
                type = 2
            else:
                isLong = -1 if param['ma20'] > param['ma55'] else 1
                type = 3

            j += 1
            isL = -1 if code in self.shortCodeList else 1 if code in self.longCodeList else 0

            if code in []:
                print(code, isLong, isL, param['trend'])
                file = Rice.basePath + '%s_%s_%s.csv' % (
                    code, public.getDatetime(style='%Y%m%d_%H%M%S'),
                    methods[0])
                df.to_csv(file, index=0)

            # 计算交易手数
            mul = BI.att(code, "contract_multiplier")
            dp = param['td_d'] if isLong > 0 else param['tu_d']
            p18 = param['tu_s'] if isLong > 0 else param['td_s']
            p27 = param['tu_s1'] if isLong > 0 else param['td_s1']

            if np.isnan(param['ma55']) or np.isnan(p18):
                print('period no long:', code)
                continue

            ma20v_18 = (self.iniAmount * self.stopLine / abs(p18 - dp) / mul)
            ma20v_18 = int(ma20v_18 + 0.2)

            ma20v_27 = (self.iniAmount * self.stopLine / abs(p27 - dp) / mul)

            ma20v_27 = int(ma20v_27 + 0.2)
            #
            ma55v = (self.iniAmount * self.stopLine / param['3atr'] / mul)
            ma55v = int(ma55v + 0.2)

            # 固定一手交易
            if code in self.oneCodeList:
                ma55v = ma20v_18 = ma20v_27 = 1

            # 计算持仓和止损
            p = np.zeros((2, 3))
            i = 0
            mp = 0

            for pos in Pos:
                if code in pos:
                    d = pos[code][0]

                    # 最近高点
                    sign = np.sign(int(d['mode']))
                    p[i][0] = sign * d['hands']
                    p[i][2] = mul * d['hands'] * (param['close'] -
                                                  d['price']) * sign

                    if i == 0:
                        p[i][1] = param['td_d'] if sign > 0 else param['tu_d']
                    else:
                        mp = self.getMax(df, d['createdate'],
                                         public.getDate(diff=1), d['mode'])
                        if np.isnan(mp):
                            print('no max Price:', code, mp)

                        p[i][1] = round(mp, 1) - sign * round(param['3atr'], 1)
                i += 1

            param.update({
                'code': mcode,
                '方向': '多' if isLong == 1 else '空',
                'price_18': p18,
                'vol_18': ma20v_18,
                'price_27': p27,
                'vol_27': ma20v_27,
                'vol_55': ma55v,
                '乘数': mul,
                '3ATR': round(param['3atr'], 1),
                '系统1持仓': p[0][0],
                'price_40': dp,
                '40日止损价': p[0][1],
                '浮盈1': p[0][2],
                '系统2持仓': p[1][0],
                '最高点': mp,
                '3ATR止损价': p[1][1],
                '浮盈2': p[1][2],
                '状态': Model.getStatus(methods, code),
                '指定方向': Model.getTrend(code),
            })
            docs.append(param)

        res = pd.DataFrame(docs,
                           columns=[
                               'code', 'close', '方向', 'price_40', 'price_18',
                               'vol_18', 'price_27', 'vol_27', '3ATR',
                               'vol_55', '乘数', '系统1持仓', '40日止损价', '浮盈1',
                               '系统2持仓', '最高点', '3ATR止损价', '浮盈2', '状态', '指定方向'
                           ])

        res = res.sort_values('code', ascending=True)
        file = Rice.basePath + 'future_%s_%s.csv' % (public.getDate(),
                                                     methods[0])
        res.to_csv(file, index=0)
        logger.info(('autoCreateAtr finished:', len(docs)))
        return res
Exemplo n.º 10
0
    def stageApply(self, df0, df1, period=40, uid=''):
        self.records = []
        """
            布林带策略:            
        """
        status, isOpen = 0, 0
        adjusts = [c[1] for c in self.adjustDates]

        for i in range(period, len(df0)):
            isRun, isstop = False, 0

            close, date, ma10, ma20, ma55, atrb, tu_s, td_s, tu_d, td_d, tu_s1, td_s1, isout3, isout5, interval = (
                df0.ix[i, key] for key in
                "close,datetime,ma10,ma20,ma55,atrb,tu_s,td_s,tu_d,td_d,tu_s1,td_s1,isout3,isout5,interval"
                .split(","))

            if isOpen == 0:
                """
                    开盘策略 
                    1、20分钟线策略
                    2、55分钟策略
                """
                dd = str(public.getTime(style='%H:%M:%S'))

                opt1 = (close > ma55 and (isout3 > 2 or isout5 > 2)) or (
                    close < ma55 and (isout3 < -2 or isout5 < -2))

                if opt1 and (abs(isout3) or abs(isout5)) > 2:
                    isOpen, isRun = 5 * np.sign(ma10 - ma55), True

            elif isOpen != 0:
                """
                    交叉点: sarm结束点 
                    1、结束突变状态,变为布林带处理
                    2、根据节点状况开平新仓,状态为6 
                """
                # 平仓
                if self.preNode is not None:
                    # 掉仓
                    # 调仓
                    if date in adjusts:
                        self.adjustOrder(df0.iloc[i], date)

                        # 平仓并反向开仓
                    opt1 = (ma10 > ma20 and close > tu_s
                            and isOpen < 0) or (ma10 < ma20 and close < td_s
                                                and isOpen > 0)
                    opt2 = (close < td_s1 and isOpen > 0) or (close > tu_s1
                                                              and isOpen < 0)

                    if (opt1 and interval > 12) or opt2:
                        # 平仓并反向开仓
                        if self.order(df0.iloc[i], None, 0, uid, df0,
                                      isstop=2):
                            isOpen, isRun = np.sign(ma10 - ma20) * 3, True
                    else:
                        Pd, s = self.preNode[0]['price'], self.preNode[0][
                            'createdate']
                        mp = self.getMax(df0, s, date, isOpen)
                        mp = close if np.isnan(mp) else mp

                        # 3倍 atr 平仓
                        if not np.isnan(mp) and (np.sign(isOpen) *
                                                 (mp - close) > 3.0 * atrb):
                            isOpen, isRun, isstop = 0, True, 3

            if isRun:
                self.order(df0.iloc[i], None, isOpen, uid, df0, isstop=isstop)

        return self.records