def ImpluseScore(dates, closes):
    '''
    :param dates:日期
    :param closes: 收盘价
    :return: 脉冲评分:红0分,绿1分,蓝2分
    '''
    smadir = ta.SMA_Direction(dates, closes)
    macddir = ta.MACD_Direction(dates, closes)
    lightcolor = ImpluseLight(smadir, macddir)
    if (lightcolor == 'Red'):
        score = 0
    elif (lightcolor == 'green'):
        score = 1
    else:
        score = 2
    return score
예제 #2
0
def VecCycleIndicators(stockcode = None,Cycle = 'D'):
    dftotal = ts.get_k_data(stockcode, ktype=Cycle)
    totalrows = len(dftotal)
    if(totalrows <100):
        print('Insufficiennt Data for Analyze'
        )
        return None
    startIndex = 0

    colNames = ['date',Cycle+'-smadir',Cycle+'-macddir',Cycle+'-light',Cycle+'-bandratio',
                Cycle+'-upband',Cycle+'-lowband',Cycle+'-valuerel',Cycle+'-rsi']
    dfIndicator = DataFrame([],columns=colNames)

    while(startIndex + 100 <= totalrows):
        print(startIndex)
        df = dftotal[:startIndex + 100]
        dates = df['date'].values
        closes = df['close'].values
        lows = df['low'].values
        highs = df['high'].values

        date = dates[-1]

        smadir = ta.SMA_Direction(dates, closes)
        macddir = ta.MACD_Direction(dates, closes)
        lightcolor = trpscr.ImpluseLight(smadir,macddir)
        rsi = ta.get_cur_rsi(dates,closes)

        uppenetrationCounter, downpenetrationCounter, bandratio, upband, lowband \
            = ta.envelop_ratio(dates, highs, lows, closes)
        value_re = ta.SMAValueZone_GX(dates, closes)

        s = Series([date,smadir,macddir,lightcolor,bandratio,upband,lowband,value_re,rsi],index = colNames)
        dfIndicator = dfIndicator.append(s,ignore_index=True)
        startIndex += 1

    FileName = stockcode + Cycle +'.csv'
    FilePath = os.path.join(DataRoot,FileName)
    dfIndicator.to_csv(FilePath)
    return dfIndicator
예제 #3
0
def get_stock_basic_parameters(code, Cycle='D', period=480):
    '''
    :param code:股票代码
    :param Cycle: 分析周期
    :param period: 分析的时间周期
    :return:返回指标列表:
    ['EMADir','SMADir','MACDDir','SMALight','EMALight','valuerel','ATRWz','ATRRatio',
    'oneATR','twoATR','threeATR','moneATR','mtwoATR','mthreeATR','position','curup',
    'curdown']
    '''
    code = DP.codeType(code)
    print(code)
    dfdata = ts.get_k_data(code, ktype=Cycle)
    if (len(dfdata) < 60):
        return None
    closes = dfdata['close'].values
    dates = dfdata['date'].values
    EMADir = ta.EMA_Direction(dates, closes)
    SMADir = ta.SMA_Direction(dates, closes)
    MACDDir = ta.MACD_Direction(dates, closes)
    SMALight = Triple.ImpluseLight(SMADir, MACDDir)
    EMALight = Triple.ImpluseLight(EMADir, MACDDir)

    valuerel = ta.SMAValueZone_GX(dates, closes)

    highs = dfdata['high'].values
    lows = dfdata['low'].values
    curatr = ta.last_atr(dates, closes, highs, lows)
    absdis, perdis, maprice = ta.curdistosma(closes, 20)
    ATRWz = absdis / curatr
    ATRRatio = absdis / maprice
    oneATR = maprice + curatr
    twoATR = maprice + 2 * curatr
    threeATR = maprice + 3 * curatr
    moneATR = maprice - curatr
    mtwoATR = maprice - 2 * curatr
    mthreeATR = maprice - 3 * curatr

    if (len(closes) > period):
        closes = closes[-period:]
    position, curup, curdown = Statistical.position_in_period(closes)

    valuelist = [
        EMADir, SMADir, MACDDir, SMALight, EMALight, valuerel, ATRWz, ATRRatio,
        oneATR, twoATR, threeATR, moneATR, mtwoATR, mthreeATR, position, curup,
        curdown
    ]
    namelist = [
        'EMADir', 'SMADir', 'MACDDir', 'SMALight', 'EMALight', 'valuerel',
        'ATRWz', 'ATRRatio', 'oneATR', 'twoATR', 'threeATR', 'moneATR',
        'mtwoATR', 'mthreeATR', 'position', 'curup', 'curdown'
    ]
    colnames = []
    for ele in namelist:
        name = Cycle + '-' + ele
        colnames.append(name)
    s = pd.Series(valuelist, index=colnames)
    return s
def value_score(dates, closes):
    '''
    :param dates: 价值评分
    :param closes:
    :return: 在价值区域上0分,中1分,下两分
    '''
    value_re = ta.SMAValueZone_GX(dates, closes)
    if (value_re == 'in'):
        score = 1
    elif (value_re == 'above'):
        score = 0
    else:
        score = 2
    return score
예제 #5
0
def sz50Daily():
    codelist = DI.get_stockcode_list('sz50')
    colNames = [
        'stockcode', 'smadir', 'uppenetrationCounter',
        'downpenetrationCounter', 'macddir', 'bandratio', 'upband', 'lowband',
        'value_re'
    ]
    filterdf = DataFrame([], columns=colNames)
    filepath = os.path.join(os.getcwd(), 'data', 'list')

    for stockcode in codelist['code']:

        df = ts.get_k_data(stockcode, ktype='D')

        dates = df['date'].values
        closes = df['close'].values
        lows = df['low'].values
        highs = df['high'].values

        smadir = ta.SMA_Direction(dates, closes)

        macddir = ta.MACD_Direction(dates, closes)

        uppenetrationCounter, downpenetrationCounter, bandratio, upband, lowband\
            = ta.envelop_ratio(dates,highs,lows,closes)
        #print(stockcode,uppenetrationCounter, downpenetrationCounter, bandratio, upband, lowband)

        value_re = ta.SMAValueZone_GX(dates, closes)

        s = Series([
            stockcode, smadir, uppenetrationCounter, downpenetrationCounter,
            macddir, bandratio, upband, lowband, value_re
        ],
                   index=colNames)
        filterdf = filterdf.append(s, ignore_index=True)

    filterdf.to_csv(filepath + '.csv')
예제 #6
0
def stock_in_divergece(code, tradeCycle='W', startdate='', enddate=''):

    dfdata = ts.get_k_data(code,
                           ktype=tradeCycle,
                           start=startdate,
                           end=enddate)
    if (len(dfdata) < 120):  # 剔除交易时间少于120天的个股
        return False
    dates = dfdata['date'].values
    closes = dfdata['close'].values
    highs = dfdata['high'].values
    lows = dfdata['low'].values

    macddiclist = ta.cal_macd(dates, closes)
    macd, dif, dea = DP.get_macd_list(macddiclist)

    divstatus = ta.macd_in_bulldivergence(dates, macd)
    divstatus['div']
    if (divstatus['div'] != 0):

        return True
    else:

        return False
예제 #7
0
def get_common_parameters(code, tradeCycle):
    from Analyze import Technical as ta
    from Strategies import False_Breakout_Divergence as FB
    smaperiod = 20
    colNames = [
        'code', 'tradeCycle', 'curclose', 'sma', 'ATR', 'ATRRatio', 'ATRWZ',
        'ImpLight', 'upchannel', 'downchannel', 'valueWZ', 'rewardratio'
    ]
    dfdata = ts.get_k_data(code, ktype=tradeCycle)
    if (len(dfdata) < 120):  # 剔除交易时间少于120天的个股
        print('No Enough Trading Days')
    dates = dfdata['date'].values
    closes = dfdata['close'].values
    highs = dfdata['high'].values
    lows = dfdata['low'].values
    macddiclist = ta.cal_macd(dates, closes)

    macd, dif, dea = get_macd_list(macddiclist)

    absdis, perdis, maprice = ta.curdistosma(closes, smaperiod)
    curATR = ta.last_atr(dates, closes, highs, lows)
    upchannel = maprice + 2 * curATR
    downchannel = maprice - 2 * curATR

    curClose = closes[-1]
    ATRRatio = curATR / curClose
    ATRWZ = absdis / curATR

    smadir = ta.SMA_Direction(dates, closes)
    macddir = ta.MACD_Direction(dates, closes)
    ImpLight = FB.ImpluseLight(smadir, macddir)

    rewardratio = (upchannel - curClose) * 100 / curClose
    value_re = ta.SMAValueZone_GX(dates, closes)

    curATR = round(curATR, 2)
    ATRRatio = round(ATRRatio * 100, 2)
    rewardratio = round(rewardratio, 2)
    ATRWZ = round(ATRWZ, 2)
    maprice = round(maprice, 2)
    upchannel = round(upchannel, 2)
    downchannel = round(downchannel, 2)
    s = pd.Series([
        code, tradeCycle, curClose, maprice, curATR, ATRRatio, ATRWZ, ImpLight,
        upchannel, downchannel, value_re, rewardratio
    ],
                  index=colNames)

    return s
예제 #8
0
def batch_divergence_monitor(stocklist=None):
    lasttradetimestr = DP.get_last_trade_time('D')
    if stocklist is None:
        stocklist = ['longtou', 'etf']
    for dataset in stocklist:
        for tradeCycle in ['W', 'D', '60', '30', '15']:
            colNames = [
                'code', 'name', 'cycle', 'period', 'curclose', 'sma', 'ATR',
                'ATRRatio', 'rewardrisk', 'primImpScore', 'tradeImpScore',
                'primdivscore', 'divscore', 'difdeascore', 'macdscore',
                'totalscore'
            ]

            filename = StrategyName + '-' + dataset
            RootDir = os.path.join(os.pardir, 'data', lasttradetimestr)
            DP.mkdir(RootDir)
            filepath = os.path.join(RootDir, filename + '.csv')

            codelist = DI.get_stockcode_list(dataset)

            dfSelected = pd.DataFrame([], columns=colNames)
            dfScreen = codelist[['code', 'name']]
            totalrows = len(dfScreen)
            for i in range(totalrows):
                code = dfScreen.loc[i, 'code']
                code = DP.codeType(code)

                name = dfScreen.loc[i, 'name']

                #if(DI.is_tingpai(code)):
                #    continue

                dfdata = ts.get_k_data(code, ktype=tradeCycle)
                if (len(dfdata) < 120):  #剔除交易时间少于120天的个股
                    continue

                dates = dfdata['date'].values
                closes = dfdata['close'].values
                highs = dfdata['high'].values
                lows = dfdata['low'].values

                macddiclist = ta.cal_macd(dates, closes)
                macd, dif, dea = DP.get_macd_list(macddiclist)

                divStatus = ta.macd_in_bulldivergence_signal(dates, macd)

                divscore = divStatus['div']
                macdscore = divStatus['macd']
                period = divStatus['period']

                if (divscore != 0):

                    print(code, name, tradeCycle, divscore, macdscore, period)
                    absdis, perdis, maprice = ta.curdistosma(closes, 20)
                    curATR = ta.last_atr(dates, closes, highs, lows)

                    ATRWZ = absdis / curATR
                    curClose = closes[-1]
                    ATRRatio = curATR / curClose

                    primCycle = GetPrimaryCycle(tradeCycle)
                    dataprimCycle = ts.get_k_data(code, ktype=primCycle)
                    primCloses = dataprimCycle['close'].values
                    primdates = dataprimCycle['date'].values
                    primlows = dataprimCycle['low'].values

                    primImpScore = FBD.ImpluseScore(primdates, primCloses)
                    tradeImpScore = FBD.ImpluseScore(dates, closes)

                    primmacd = pd.Series(ta.cal_macd(primdates, primCloses))
                    primmacd, primdif, primdea = DP.get_macd_list(primmacd)

                    primdivStatus = ta.macd_in_bulldivergence_signal(
                        primdates, primmacd)

                    primdivscore = primdivStatus['div']

                    if (primdivscore != 0):
                        primdivscore = 1

                    difdeadivscore = 0
                    if (ta.in_loose_bulldivergence(dif, period)):
                        difdeadivscore += 1
                    if (ta.in_loose_bulldivergence(dea, period)):
                        difdeadivscore += 1

                    totalscore = primImpScore + tradeImpScore + primdivscore + divscore + difdeadivscore + macdscore

                    curATR = round(curATR, 2)
                    ATRRatio = round(ATRRatio * 100, 2)

                    ATRWZ = round(ATRWZ, 2)

                    maprice = round(maprice, 2)

                    s = Series([
                        code, name, tradeCycle, period, curClose, maprice,
                        curATR, ATRRatio, ATRWZ, primImpScore, tradeImpScore,
                        primdivscore, divscore, difdeadivscore, macdscore,
                        totalscore
                    ],
                               index=colNames)

                    dfSelected = dfSelected.append(s, ignore_index=True)
            dfSelected = dfSelected.sort_values(by='totalscore',
                                                ascending=False)
            dfSelected = pd.DataFrame(dfSelected.values,
                                      columns=dfSelected.columns)

            if os.path.exists(filepath):
                dfSelected.to_csv(filepath, mode='a', header=None)
            else:
                dfSelected.to_csv(filepath)
예제 #9
0
def screener2():
    totalrows = len(dfScreen)
    for index in range(totalrows):

        code = dfScreen.loc[index, 'code']
        code = DP.codeType(code)
        stockcode = code

        df_trade = ts.get_k_data(code=stockcode, ktype=tradecycle)

        dates = df_trade['date']
        closes = df_trade['close']
        lows = df_trade['low']

        sma5 = ta.cal_sma(dates, closes, 5)
        sma5 = Series(sma5)

        macd = ta.cal_macd(dates, closes)
        macd = macd[len(macd) - len(sma5):]
        macd = Series(macd)

        sma5 = sma5[len(macd) - len(sma5):]
        sma5 = Series(sma5)

        df_trade = df_trade[len(df_trade) - len(sma5):]

        df_trade = DataFrame(df_trade.values, columns=df_trade.columns)
        df_trade['sma5'] = sma5
        df_trade['macd'] = macd

        totalrows = len(df_trade)
        i = 5
        while (i < totalrows):

            if (df_trade.loc[i, 'close'] > df_trade.loc[i, 'sma5']['sma5']
                    and df_trade.loc[i - 1,
                                     'close'] < df_trade.loc[i, 'sma5']['sma5']
                    and df_trade.loc[i, 'macd']['diff'] >
                    df_trade.loc[i, 'macd']['dea']):
                j = i
                while (j > 0):
                    if df_trade.loc[j, 'macd']['diff'] < df_trade.loc[
                            j, 'macd']['dea']:
                        break
                    j -= 1
                closesslice = closes[j:i]

                if (len(closesslice) < 8):
                    i += 1
                    continue
                print(closesslice)
                k = np.argmax(closesslice)

                print('here')
                print(j, k, i)
                if (min(closesslice[j:k]) < min(closesslice[k:i])):
                    date = df_trade.loc[i, 'date'][:10]

                    df_prim = ts.get_k_data(code=stockcode,
                                            ktype=primarycycle,
                                            start='2000-01-01',
                                            end=date)

                    primcloses = df_prim['close'][-5:]

                    primclose = primcloses.values[-1]
                    primsma5 = np.average(primcloses)

                    primmacd = ta.cal_macd(dates, closes)
                    primdiff = primmacd[len(primmacd) - 1]['diff']
                    primdea = primmacd[len(primmacd) - 1]['dea']
                    if (primclose > primsma5 and primdiff > primdea):
                        #print(df_trade.loc[i, 'date'])

                        curlows = lows[:i]
                        curdates = dates[:i]

                        difenxinglist = ta.get_pre_difenxing(
                            curdates, curlows, 4)
                        #print(difenxinglist)

                        if (len(difenxinglist) < 4):
                            continue
                        # difenxinglist[0]['low'] < difenxinglist[1]['low'] and
                        else:
                            if (difenxinglist[1]['low'] <
                                    difenxinglist[2]['low']
                                    and difenxinglist[2]['low'] <
                                    difenxinglist[3]['low']):
                                print(stockcode, df_trade.loc[i, 'date'])
            i += 1
예제 #10
0
def batch_invaluezone_divergence(dataset='hs300', tradeCycle='D', recent=5):
    lasttradetimestr = DP.get_last_trade_time('D')

    colNames = [
        'code', 'name', 'period', 'curclose', 'sma', 'ATR', 'ATRRatio',
        'rewardrisk', 'primImpScore', 'tradeImpScore', 'primdivscore',
        'divscore', 'difdeascore', 'macdscore', 'totalscore'
    ]

    filename = StrategyName + lasttradetimestr + '-' + dataset + '-' + tradeCycle

    RootDir = os.path.join(os.pardir, 'data', lasttradetimestr)
    DP.mkdir(RootDir)
    filepath = os.path.join(RootDir, filename + '.xls')

    codelist = DI.get_stockcode_list(dataset)

    dfSelected = pd.DataFrame([], columns=colNames)
    dfScreen = codelist[['code', 'name']]
    totalrows = len(dfScreen)

    for i in range(totalrows):
        code = dfScreen.loc[i, 'code']
        code = DP.codeType(code)

        name = dfScreen.loc[i, 'name']
        if (DI.is_tingpai(code)):
            continue

        dfdata = ts.get_k_data(code, ktype=tradeCycle)
        if (len(dfdata) < 120):  #剔除交易时间少于120天的个股
            continue

        dates = dfdata['date'].values
        closes = dfdata['close'].values
        highs = dfdata['high'].values
        lows = dfdata['low'].values
        if (not ta.invaluezone(closes, 10, 20)):
            continue

        macddiclist = ta.cal_macd(dates, closes)
        macd, dif, dea = DP.get_macd_list(macddiclist)

        if (min(macd[-3:]) > 0):
            continue

        divStatus = ta.macd_in_bulldivergence(dates, macd)

        divscore = divStatus['div']
        macdscore = divStatus['macd']
        period = divStatus['period']

        if (divscore != 0):

            print(code, name, divscore, macdscore, period)
            absdis, perdis, maprice = ta.curdistosma(closes, 20)
            curATR = ta.last_atr(dates, closes, highs, lows)

            ATRWZ = absdis / curATR
            curClose = closes[-1]
            ATRRatio = curATR / curClose

            primCycle = GetPrimaryCycle(tradeCycle)
            dataprimCycle = ts.get_k_data(code, ktype=primCycle)
            primCloses = dataprimCycle['close'].values
            primdates = dataprimCycle['date'].values
            primlows = dataprimCycle['low'].values

            primImpScore = FBD.ImpluseScore(primdates, primCloses)
            tradeImpScore = FBD.ImpluseScore(dates, closes)

            primmacd = pd.Series(ta.cal_macd(primdates, primCloses))
            primmacd, primdif, primdea = DP.get_macd_list(primmacd)

            primdivStatus = ta.macd_in_bulldivergence_signal(
                primdates, primmacd)

            primdivscore = primdivStatus['div']

            if (primdivscore != 0):
                primdivscore = 1

            difdeadivscore = 0
            if (ta.in_loose_bulldivergence(dif, period)):
                difdeadivscore += 1
            if (ta.in_loose_bulldivergence(dea, period)):
                difdeadivscore += 1

            totalscore = primImpScore + tradeImpScore + primdivscore + divscore + difdeadivscore + macdscore

            curATR = round(curATR, 2)
            ATRRatio = round(ATRRatio * 100, 2)

            ATRWZ = round(ATRWZ, 2)

            maprice = round(maprice, 2)
            colNames = [
                'code', 'name', 'period', 'curclose', 'sma', 'ATR', 'ATRRatio',
                'ATRWZ', 'primImpScore', 'tradeImpScore', 'primdivscore',
                'divscore', 'difdeascore', 'macdscore', 'totalscore'
            ]
            s = Series([
                code, name, period, curClose, maprice, curATR, ATRRatio, ATRWZ,
                primImpScore, tradeImpScore, primdivscore, divscore,
                difdeadivscore, macdscore, totalscore
            ],
                       index=colNames)

            dfSelected = dfSelected.append(s, ignore_index=True)
    dfSelected = dfSelected.sort_values(by='totalscore', ascending=False)
    dfSelected = pd.DataFrame(dfSelected.values, columns=dfSelected.columns)

    DI.Write_DF_T0_Excel(filepath, dfSelected, 'selected')
def vectorized_falsebreakout_divergence(code='510300',
                                        tradeCycle='D',
                                        recent=5):
    colNames = [
        'code', 'time', 'period', 'curclose', 'sma', 'ATR', 'ATRRatio',
        'rewardratio', 'riskratio', 'targetprice', 'cutshort', 'ATRWZ',
        'rewardrisk', 'primImpScore', 'tradeImpScore', 'valuescore',
        'primdivscore', 'divscore', 'difdeascore', 'macdscore', 'totalscore',
        'targetprice1', 'targetprice2'
    ]

    filename = StrategyName + '-' + code + '-' + tradeCycle
    dfSelected = pd.DataFrame([], columns=colNames)
    RootDir = os.path.join(os.pardir, 'data', 'Vectorized')
    DP.mkdir(RootDir)
    filepath = os.path.join(RootDir, filename + '.xls')

    code = DP.codeType(code)

    dfdata = ts.get_k_data(code, start='2000-01-01',
                           ktype=tradeCycle)  #start = '2016-01-01',
    if (len(dfdata) < 120):  #剔除交易时间少于120天的个股
        print('Not Enough data for decision making.')

    totaldates = dfdata['date'].values
    totalcloses = dfdata['close'].values
    totalhighs = dfdata['high'].values
    totallows = dfdata['low'].values

    macddiclist = ta.cal_macd(totaldates, totalcloses)
    totalmacd, totaldif, totaldea = DP.get_macd_list(macddiclist)
    i = 120

    while i < len(totalcloses):
        closes = totalcloses[:i]
        highs = totalhighs[:i]
        lows = totallows[:i]
        macd = totalmacd[:i]
        dif = totaldif[:i]
        dea = totaldea[:i]

        dates = totaldates[:i]

        if (macd[-1] < macd[-2] or macd[-3] <
                macd[-2]):  #macd[-1]> 0 这个条件由于without right shoulder删除
            i = i + 1
            continue

        divStatus = ta.macd_in_bulldivergence_signal(dates, macd)

        divscore = divStatus['div']
        macdscore = divStatus['macd']
        period = divStatus['period']

        if (divscore != 0 and isPriceNewLow(lows, recent, period, tradeCycle)):
            date = dates[-1]

            absdis, perdis, maprice = ta.curdistosma(closes, 20)
            curATR = ta.last_atr(dates, closes, highs, lows)
            targetprice = maprice + 2 * curATR  #应该是前高更合理

            prelow = min(lows[-recent:])  # 因此此处要求近recent天创period天新低
            cutshort = prelow
            ATRWZ = absdis / curATR
            curClose = closes[-1]
            targetprice2 = curClose + 2 * curATR
            targetprice3 = np.max(closes[-period:])
            ATRRatio = curATR / curClose
            rewardratio = (targetprice - curClose) * 100 / curClose
            riskratio = (curClose - cutshort) * 100 / curClose
            rewardrisk = (targetprice - curClose) / (curClose - cutshort)

            primCycle = GetPrimaryCycle(tradeCycle)
            dataprimCycle = ts.get_k_data(code, ktype=primCycle)
            primCloses = dataprimCycle['close'].values
            primdates = dataprimCycle['date'].values
            primlows = dataprimCycle['low'].values

            primImpScore = ImpluseScore(primdates, primCloses)
            tradeImpScore = ImpluseScore(dates, closes)
            valuescore = value_score(dates, closes)

            primmacd = pd.Series(ta.cal_macd(primdates, primCloses))
            primmacd, primdif, primdea = DP.get_macd_list(primmacd)

            isPrimNewLow = isPriceNewLow(primlows, recent, 30)

            primdivStatus = ta.macd_in_bulldivergence_signal(
                primdates, primmacd)

            primdivscore = primdivStatus['div']

            if (primdivscore != 0 and isPrimNewLow != 0):
                primdivscore = 2
            elif (primdivscore != 0):
                primdivscore = 1

            difdeadivscore = 0
            if (ta.in_loose_bulldivergence(dif, period)):
                difdeadivscore += 1
            if (ta.in_loose_bulldivergence(dea, period)):
                difdeadivscore += 1

            totalscore = primImpScore + tradeImpScore + valuescore + primdivscore + divscore + difdeadivscore + macdscore

            curATR = round(curATR, 2)
            ATRRatio = round(ATRRatio * 100, 2)
            rewardratio = round(rewardratio, 2)
            riskratio = round(riskratio, 2)
            ATRWZ = round(ATRWZ, 2)
            rewardrisk = round(rewardrisk, 2)
            targetprice = round(targetprice, 2)
            maprice = round(maprice, 2)
            s = Series([
                code, date, period, curClose, maprice, curATR, ATRRatio,
                rewardratio, riskratio, targetprice, cutshort, ATRWZ,
                rewardrisk, primImpScore, tradeImpScore, valuescore,
                primdivscore, divscore, difdeadivscore, macdscore, totalscore,
                targetprice2, targetprice3
            ],
                       index=colNames)

            dfSelected = dfSelected.append(s, ignore_index=True)

        i += 1

    #dfSelected = dfSelected.sort_values(by='totalscore',ascending=False)
    dfSelected = pd.DataFrame(dfSelected.values, columns=dfSelected.columns)
    #dfSelected.to_csv(filepath)
    DI.Write_DF_T0_Excel(filepath, dfSelected, 'selected')
    return dfSelected
def batch_falsebreakout_divergence(dataset='hs300', tradeCycle='D', recent=3):
    lasttradetimestr = DP.get_last_trade_time('D')
    '''
    colNames = ['code', 'time', 'period', 'curclose', 'sma', 'ATR', 'ATRRatio', 'rewardratio',
                'riskratio', 'targetprice', 'cutshort', 'ATRWZ', 'rewardrisk', 'primImpScore',
                'tradeImpScore', 'valuescore', 'primdivscore', 'divscore', 'difdeascore', 'macdscore',
                'totalscore','targetprice1','targetprice2']
    '''
    colNames = [
        'code', 'name', 'time', 'period', 'curclose', 'sma', 'ATR', 'ATRRatio',
        'rewardratio', 'riskratio', 'targetprice', 'cutshort', 'ATRWZ',
        'rewardrisk', 'primImpScore', 'tradeImpScore', 'valuescore',
        'primdivscore', 'divscore', 'difdeascore', 'macdscore', 'totalscore',
        'targetprice2', 'targetprice3'
    ]
    filename = StrategyName + lasttradetimestr + '-' + dataset + '-' + tradeCycle

    RootDir = os.path.join(os.pardir, 'data', lasttradetimestr)
    DP.mkdir(RootDir)
    filepath = os.path.join(RootDir, filename + '.xls')

    codelist = DI.get_stockcode_list(dataset)

    dfSelected = pd.DataFrame([], columns=colNames)
    dfScreen = codelist[['code', 'name']]
    totalrows = len(dfScreen)

    for i in range(totalrows):

        code = dfScreen.loc[i, 'code']
        code = DP.codeType(code)

        name = dfScreen.loc[i, 'name']
        if (DI.is_tingpai(code)):
            continue

        dfdata = ts.get_k_data(code, ktype=tradeCycle)
        if (len(dfdata) < 120):  #剔除交易时间少于120天的个股
            continue
        dates = dfdata['date'].values
        closes = dfdata['close'].values
        highs = dfdata['high'].values
        lows = dfdata['low'].values

        macddiclist = ta.cal_macd(dates, closes)
        macd, dif, dea = DP.get_macd_list(macddiclist)

        if (not (macd[-2] < 0 and macd[-2] < macd[-1]
                 and macd[-2] < macd[-3])):
            continue

        if (code in dfSelected['code'].values):
            continue

        divStatus = ta.macd_in_bulldivergence_signal(dates, macd)

        divscore = divStatus['div']
        macdscore = divStatus['macd']
        period = divStatus['period']

        if (divscore != 0 and isPriceNewLow(lows, recent, period)):

            absdis, perdis, maprice = ta.curdistosma(closes, 20)
            curATR = ta.last_atr(dates, closes, highs, lows)
            targetprice = maprice + 2 * curATR
            prelow = min(lows[-recent:])  #因此此处要求近recent天创period天新低

            ATRWZ = absdis / curATR
            curClose = closes[-1]
            #cutshort = min(prelow, curClose - curATR)
            cutshort = prelow
            ATRRatio = curATR / curClose
            #rewardratio = (targetprice-curClose)*100/curClose
            riskratio = (curClose - cutshort) * 100 / curClose
            #rewardrisk = (targetprice-curClose)/(curClose-cutshort)

            primCycle = GetPrimaryCycle(tradeCycle)
            dataprimCycle = ts.get_k_data(code, ktype=primCycle)
            primCloses = dataprimCycle['close'].values
            primdates = dataprimCycle['date'].values
            primlows = dataprimCycle['low'].values

            primImpScore = ImpluseScore(primdates, primCloses)
            tradeImpScore = ImpluseScore(dates, closes)
            valuescore = value_score(dates, closes)

            primmacd = pd.Series(ta.cal_macd(primdates, primCloses))
            primmacd, primdif, primdea = DP.get_macd_list(primmacd)

            isPrimNewLow = isPriceNewLow(primlows, recent, 30)

            primdivStatus = ta.macd_in_bulldivergence_signal(
                primdates, primmacd)

            primdivscore = primdivStatus['div']

            if (primdivscore != 0 and isPrimNewLow != 0):
                primdivscore = 2
            elif (primdivscore != 0):
                primdivscore = 1

            difdeadivscore = 0
            if (ta.in_loose_bulldivergence(dif, period)):
                difdeadivscore += 1
            if (ta.in_loose_bulldivergence(dea, period)):
                difdeadivscore += 1

            totalscore = primImpScore + tradeImpScore + valuescore + primdivscore + divscore + difdeadivscore + macdscore

            curATR = round(curATR, 4)
            targetprice2 = curClose + 2 * curATR
            targetprice3 = np.max(closes[-period:])

            target = np.min(
                [float(targetprice),
                 float(targetprice2),
                 float(targetprice3)])
            rewardratio = (target - curClose) * 100 / curClose

            rewardrisk = (target - curClose) / (curClose - cutshort)

            ATRRatio = round(ATRRatio * 100, 3)
            rewardratio = round(rewardratio, 3)
            riskratio = round(riskratio, 3)
            ATRWZ = round(ATRWZ, 3)
            rewardrisk = round(rewardrisk, 3)
            targetprice = round(targetprice, 3)
            maprice = round(maprice, 3)
            cutshort = round(cutshort, 3)
            import datetime
            curtime = datetime.datetime.now()

            selectedcolNames = [
                'ATR', 'ATRRatio', 'code', 'name', 'time', 'curclose',
                'cutshort', 'rewardratio', 'riskratio', 'rewardrisk', 'sma',
                'targetprice', 'targetprice2', 'targetprice3'
            ]

            print(curATR, ATRRatio, code, tradeCycle, name, curtime, curClose,
                  cutshort, rewardratio, riskratio, rewardrisk, maprice,
                  targetprice, targetprice2, targetprice3)

            s = Series([
                code, name, curtime, period, curClose, maprice, curATR,
                ATRRatio, rewardratio, riskratio, targetprice, cutshort, ATRWZ,
                rewardrisk, primImpScore, tradeImpScore, valuescore,
                primdivscore, divscore, difdeadivscore, macdscore, totalscore,
                targetprice2, targetprice3
            ],
                       index=colNames)
            dfSelected = dfSelected.append(s, ignore_index=True)
            dfSelected = dfSelected[selectedcolNames]
    dfSelected = dfSelected.sort_values(by='time', ascending=False)
    dfSelected = pd.DataFrame(dfSelected.values, columns=dfSelected.columns)

    if (not os.path.exists(filepath)):
        DI.Write_DF_T0_Excel(filepath, dfSelected, 'selected')
    else:
        dftotal = DI.Get_TrdData_FromExcel(filepath, 'selected')
        dftotal = pd.concat([dftotal, dfSelected])
        DI.Write_DF_T0_Excel(filepath, dftotal, 'selected')
예제 #13
0
def basic_pos_statistics(dfindusbasic, feature):
    '''
    :param dfindusbasic:带有股票集内各成分股基本面和技术面信息的DataFrame
    :param feature: 对于股票集的特征
    :return:带有股票集统计描述的Series,特征如colName描述
    '''

    colNames = [
        'feature', 'avgPE', 'avgPB', 'WRed', 'WBlue', 'WGreen', 'WAbove',
        'WIn', 'WBelow', 'DRed', 'DBlue', 'DGreen', 'DAbove', 'DIn', 'DBelow',
        'Wonetwotwo', 'Wtwotothree', 'Wzerotoone', 'Wabovethree',
        'Wmzerotoone', 'Wmabovethree', 'Wmonetotwo', 'Wmtwotothree',
        'DonetDotDo', 'DtDotothree', 'Dzerotoone', 'Dabovethree',
        'Dmzerotoone', 'Dmabovethree', 'DmonetotDo', 'DmtDotothree',
        'WPosition', 'DPosition'
    ]

    s = dfindusbasic['pe']
    avgpe = sum(s) / sum(s != 0)
    avgpe = avgpe.round(2)
    s = dfindusbasic['pb']
    for key in s.index:
        if (s[key] <= 0):
            s[key] = 0
    avgpb = sum(s) / sum(s > 0)
    avgpb = avgpb.round(2)

    s = dfindusbasic['W-SMALight']
    WRed = int(sum(s == 'Red'))
    WBlue = int(sum(s == 'Blue'))
    WGreen = int(sum(s == 'Green'))

    s = dfindusbasic['W-valuerel']
    WAbove = int(sum(s == 'above'))
    WBelow = int(sum(s == 'below'))
    WIn = int(sum(s == 'in'))

    s = dfindusbasic['D-SMALight']
    DRed = int(sum(s == 'Red'))
    DBlue = int(sum(s == 'Blue'))
    DGreen = int(sum(s == 'Green'))

    s = dfindusbasic['D-valuerel']
    DAbove = int(sum(s == 'above'))
    DBelow = int(sum(s == 'below'))
    DIn = int(sum(s == 'in'))

    s = dfindusbasic['W-ATRWz']
    WATRCounter = ta.ATRCounter(s)
    Wonetwotwo = int(WATRCounter['onetotwo'])
    Wtwotothree = int(WATRCounter['twotothree'])
    Wzerotoone = int(WATRCounter['zerotoone'])
    Wabovethree = int(WATRCounter['abovethree'])
    Wmzerotoone = int(WATRCounter['mzerotoone'])
    Wmabovethree = int(WATRCounter['mabovethree'])
    Wmonetotwo = int(WATRCounter['monetotwo'])
    Wmtwotothree = int(WATRCounter['mtwotothree'])

    s = dfindusbasic['D-ATRWz']
    DATRCounter = ta.ATRCounter(s)
    DonetDotDo = int(DATRCounter['onetotwo'])
    DtDotothree = int(DATRCounter['twotothree'])
    Dzerotoone = int(DATRCounter['zerotoone'])
    Dabovethree = int(DATRCounter['abovethree'])
    Dmzerotoone = int(DATRCounter['mzerotoone'])
    Dmabovethree = int(DATRCounter['mabovethree'])
    DmonetotDo = int(DATRCounter['monetotwo'])
    DmtDotothree = int(DATRCounter['mtwotothree'])

    s = dfindusbasic['W-position']
    s = s.replace(np.nan, 0)

    WPosition = sum(s) / len(s)
    WPosition = WPosition.round(2)

    s = dfindusbasic['D-position']
    s = s.replace(np.nan, 0)
    DPosition = sum(s) / len(s)
    DPosition = DPosition.round(2)

    values = [
        feature, avgpe, avgpb, WRed, WBlue, WGreen, WAbove, WIn, WBelow, DRed,
        DBlue, DGreen, DAbove, DIn, DBelow, Wonetwotwo, Wtwotothree,
        Wzerotoone, Wabovethree, Wmzerotoone, Wmabovethree, Wmonetotwo,
        Wmtwotothree, DonetDotDo, DtDotothree, Dzerotoone, Dabovethree,
        Dmzerotoone, Dmabovethree, DmonetotDo, DmtDotothree, WPosition,
        DPosition
    ]

    colNames = [
        'feature', 'avgPE', 'avgPB', 'WRed', 'WBlue', 'WGreen', 'WAbove',
        'WIn', 'WBelow', 'DRed', 'DBlue', 'DGreen', 'DAbove', 'DIn', 'DBelow',
        'Wonetwotwo', 'Wtwotothree', 'Wzerotoone', 'Wabovethree',
        'Wmzerotoone', 'Wmabovethree', 'Wmonetotwo', 'Wmtwotothree',
        'DonetDotDo', 'DtDotothree', 'Dzerotoone', 'Dabovethree',
        'Dmzerotoone', 'Dmabovethree', 'DmonetotDo', 'DmtDotothree',
        'WPosition', 'DPosition'
    ]

    s = pd.Series(values, index=colNames)
    print(s)
    return s
예제 #14
0
def vectorized_smabreak_divergence(code='510300', tradeCycle='D'):
    colNames = [
        'time', 'code', 'curclose', 'sma', 'ATR', 'ATRRatio', 'ATRWZ',
        'tradeImpScore', 'primImpScore'
    ]

    filename = StrategyName + '-' + code + '-' + tradeCycle
    dfSelected = pd.DataFrame([], columns=colNames)
    RootDir = os.path.join(os.pardir, 'data', 'Vectorized')

    filepath = os.path.join(RootDir, filename + '.xls')

    code = DP.codeType(code)
    startdate = '2000-01-01'
    dfdata = ts.get_k_data(code, start=startdate, end='', ktype=tradeCycle)
    if (len(dfdata) < 120):  # 剔除交易时间少于120天的个股
        print('Not Enough data for decision making.')

    totaldates = dfdata['date'].values
    totalcloses = dfdata['close'].values
    totalhighs = dfdata['high'].values
    totallows = dfdata['low'].values

    macddiclist = ta.cal_macd(totaldates, totalcloses)
    totalmacd, totaldif, totaldea = DP.get_macd_list(macddiclist)
    i = 120

    while i < len(totalcloses):

        closes = totalcloses[:i]
        highs = totalhighs[:i]
        lows = totallows[:i]
        dates = totaldates[:i]
        if (not ta.smaupcrosssignal(closes, 20)):
            i += 1
            continue
        primCycle = GetPrimaryCycle(tradeCycle)
        if (stock_in_divergece(code,
                               primCycle,
                               startdate=startdate,
                               enddate=dates[-1])):

            absdis, perdis, maprice = ta.curdistosma(closes, 20)
            curATR = ta.last_atr(dates, closes, highs, lows)

            ATRWZ = absdis / curATR
            curClose = closes[-1]
            ATRRatio = curATR / curClose

            tradeImpScore = FBD.ImpluseScore(dates, closes)

            curATR = round(curATR, 2)
            ATRRatio = round(ATRRatio * 100, 2)

            ATRWZ = round(ATRWZ, 2)

            maprice = round(maprice, 2)

            dataprimCycle = ts.get_k_data(code, ktype=primCycle)
            primCloses = dataprimCycle['close'].values
            primdates = dataprimCycle['date'].values

            primImpScore = FBD.ImpluseScore(primdates, primCloses)

            s = Series([
                dates[-1], code, curClose, maprice, curATR, ATRRatio, ATRWZ,
                tradeImpScore, primImpScore
            ],
                       index=colNames)

            dfSelected = dfSelected.append(s, ignore_index=True)
        else:

            pass
        i += 1
    # dfSelected = dfSelected.sort_values(by='totalscore',ascending=False)
    dfSelected = pd.DataFrame(dfSelected.values, columns=dfSelected.columns)
    # dfSelected.to_csv(filepath)
    DI.Write_DF_T0_Excel(filepath, dfSelected, 'selected')
    return dfSelected