Пример #1
0
def batch_position(codelist, period=240, value='position', Cycle='D'):
    colNames = ['code', 'name', 'position', 'curup', 'curdown']
    dfPosition = DataFrame([], columns=colNames)
    index_date = DP.get_last_trade_time()

    for code, name in zip(codelist['code'], codelist['name']):
        code = DP.codeType(code)
        print(code)
        if (DI.is_tingpai(code)):
            continue
        df = ts.get_k_data(code, ktype=Cycle)
        if (len(df) == 0):
            continue
        closes = df['close'].values
        last_date = df.loc[len(df) - 1, 'date']
        if (len(df) < period or last_date != index_date):
            continue

        closes = closes[-period:]

        position, curup, curdown = position_in_period(closes)
        s = Series([code, name, position, curup, curdown], index=colNames)
        dfPosition = dfPosition.append(s, ignore_index=True)
    dfPosition = dfPosition.sort_values(by=value, ascending=True)
    dfPosition = DataFrame(dfPosition.values, columns=dfPosition.columns)
    return dfPosition
def batch_vectorized_divergence(dataset='hs300', cycle='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'
    ]
    codelist = DI.get_stockcode_list(dataset)

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

        name = dfScreen.loc[i, 'name']
        dfsub = vectorized_falsebreakout_divergence(code, cycle)
        dfsub['name'] = name
        dftotal = pd.concat([dftotal, dfsub])
    RootDir = os.path.join(os.pardir, 'data', 'Vectorized', StrategyName)
    if (not os.path.exists(RootDir)):
        DP.mkdir(RootDir)
    filename = dataset + 'whole' + cycle + '.xls'
    filepath = os.path.join(RootDir, filename)
    dftotal = dftotal.sort_values(by='time')
    dftotal = DataFrame(dftotal.values, columns=dftotal.columns)
    dftotal = Performance.vectorized_forward_return(dftotal, cycle)
    DI.Write_DF_T0_Excel(filepath, dftotal, 'selected')
Пример #3
0
def olsfit(ticker, bench, begdate, enddate):
    tickerdata = ts.get_k_data(ticker, start=begdate, end=enddate)
    benchdata = ts.get_k_data(bench, start=begdate, end=enddate)

    y = DP.closetoret(tickerdata['close'])
    x = DP.closetoret(benchdata['close'])

    x = sm.add_constant(x)
    model = sm.OLS(y, x)
    results = model.fit()
    return results.summary()
Пример #4
0
def rollingbeta(ticker, bench, begdate, enddate, window=252):
    tickerdata = ts.get_k_data(ticker, start=begdate, end=enddate)
    benchdata = ts.get_k_data(bench, start=begdate, end=enddate)

    y0 = DP.closetoret(tickerdata['close'])
    x0 = DP.closetoret(benchdata['close'])
    y0 = pd.Series(y0)
    x0 = pd.Series(x0)
    model = pd.ols(y=y0, x=x0, window=window)
    model.beta.plot()
    plt.show()
Пример #5
0
def smaexit(df,smaperiod,cycle):
    for i in range(len(df)):
        code = DP.codeType(df.loc[i, 'code'])
        curclose = df.loc[i, 'curclose']
        startdate = df.loc[i, 'time']
        tradata = ts.get_k_data(code, ktype=cycle)

        tradata = pd.DataFrame(tradata.values, columns=tradata.columns)

        posindex =list(tradata['date']).index(startdate)
        closes = tradata['close']
        posindex += 1
        while(posindex < len(closes)):
            posclose = tradata.loc[posindex,'close']
            possmaprice = sum(closes[posindex-smaperiod+1:posindex+1])/smaperiod
            if(posclose < possmaprice):
                exitprice = posclose
                exitdate = tradata.loc[posindex, 'date']
                exitreturn = (exitprice - curclose) * 100 / curclose
                break
            posindex += 1
        if(posindex == len(closes)):
            exitprice = posclose
            exitdate = tradata.loc[posindex-1, 'date']
            exitreturn = (exitprice - curclose) * 100 / curclose
        df.loc[i,'exitdate']  = exitdate
        df.loc[i,'exitprice'] = exitprice
        df.loc[i,'exitreturn'] = exitreturn
    return df
Пример #6
0
def Var(ticker, begdate, enddate, nshares, ndays):
    x = ts.get_k_data(ticker, start=begdate, end=enddate)
    ret = DP.closetoret(x)
    position = nshares * x['close'][-1]
    VaR = position * std(ret) * sqrt(ndays)
    print("Holding=", position, "VaR=", round(VaR, 4), "in ", ndays, "Days")
    return VaR
Пример #7
0
def adftest(stockcode, begdate, enddate):
    '''
    example result (0.049177575166452235,
    0.96241494632563063,
    1,
    3771,
    {’1%’: -3.4320852842548395,
    ’10%’: -2.5671781529820348,
    ’5%’: -2.8623067530084247},
    19576.116041473877)
    Since the calculated value of the test statistic is larger than any of the critical values at the 1,
    5 or 10 percent levels, we cannot reject the null hypothesis of
     = 0 and thus we are unlikely to
    have found a mean reverting time series. This is in line with our tuition as most equities behave
    akin to Geometric Brownian Motion (GBM), i.e. a random walk.
    :param stockcode:
    :return:
    '''
    data = ts.get_k_data(stockcode, start=begdate, end=enddate)
    ret = DP.closetoret(data['close'])
    resultret = stattools.adfuller(ret)
    resultclose = stattools.adfuller(data['close'])
    print('return', resultret)
    print('close', resultclose)
    return resultret, resultclose
Пример #8
0
def batch_etf(etflist, cyclelist):
    stragegyname = 'etfMonitor'
    dataset = 'etfs'
    tradeCycle = ''
    filepath = DP.get_stragegy_filepath(stragegyname, dataset, tradeCycle)

    colNames = [
        'code', 'tradeCycle', 'curclose', 'sma', 'ATR', 'ATRRatio', 'ATRWZ',
        'ImpLight', 'upchannel', 'downchannel', 'valueWZ', 'rewardratio'
    ]
    df = pd.DataFrame([], columns=colNames)
    for etf in etflist:
        for cycle in cyclelist:
            s = DP.get_common_parameters(etf, cycle)
            df = df.append(s, ignore_index=True)
    DI.Write_DF_T0_Excel(filepath, df, 'etf')
    return df
Пример #9
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
Пример #10
0
def batch_stockset_selection(stockset='hs300'):
    rootDir = os.path.join(Config.dataDir, 'Applets', 'Index')
    filename = 'basic-position ' + stockset
    filepath = os.path.join(rootDir, filename + '.csv')
    dfwholeset = pd.read_csv(filepath, encoding='gbk')
    dfnotred = pd.DataFrame([], columns=dfwholeset.columns)
    dflightcontradict = pd.DataFrame([], columns=dfwholeset.columns)
    dfoversold = pd.DataFrame([], columns=dfwholeset.columns)

    for i in range(len(dfwholeset)):
        weeksimlight = dfwholeset.loc[i, 'W-SMALight']
        weekemalight = dfwholeset.loc[i, 'W-EMALight']
        daysimlight = dfwholeset.loc[i, 'D-SMALight']
        dayemalight = dfwholeset.loc[i, 'D-EMALight']
        DayATR = dfwholeset.loc[i, 'D-ATRWz']
        WeekATR = dfwholeset.loc[i, 'W-ATRWz']
        s = dfwholeset.ix[i]
        if (weekemalight != 'Red' and weeksimlight != 'Red'
                and dayemalight != 'Red' and daysimlight != 'Red'):
            dfnotred = dfnotred.append(s, ignore_index=True)
            if (DayATR < -2 or WeekATR < -2):
                dfoversold = dfoversold.append(s, ignore_index=True)
        elif (((weekemalight == 'Red' or weeksimlight == 'Red') and
               (weekemalight != weeksimlight))
              or ((dayemalight == 'Red' or daysimlight == 'Red') and
                  (dayemalight != daysimlight))):
            dflightcontradict = dflightcontradict.append(s, ignore_index=True)

    notredname = stockset + 'notred'
    contraname = stockset + 'contradict'
    oversoldname = stockset + 'oversold'

    notredfilepath = os.path.join(rootDir, notredname + '.xlsx')
    contrafilepath = os.path.join(rootDir, contraname + '.xlsx')
    oversoldfilepath = os.path.join(rootDir, oversoldname + '.xlsx')

    dfnotred = DP.rearrange(dfnotred, 'D-position')
    dflightcontradict = DP.rearrange(dflightcontradict, 'D-position')
    dfoversold = DP.rearrange(dfoversold, 'D-position')

    DI.Write_DF_T0_Excel(notredfilepath, dfnotred)
    DI.Write_DF_T0_Excel(contrafilepath, dflightcontradict)
    DI.Write_DF_T0_Excel(oversoldfilepath, dfoversold)
def isfalsebreakout(closes, lows, highs, period=30):
    '''
    :param dates:
    :param closes:
    :param lows:
    :param highs:
    :param recent:
    :param period:
    :return:是否falsbreak,也即当前close是否已经收复前低。
    '''
    highs = highs[-period:]
    lows = lows[-period:]

    prelow = DP.get_pre_low(highs, lows)
    if (prelow is None):
        return False
    curclose = closes[-1]
    curhigh = highs[-1]
    if (curclose > prelow):
        return True
    else:
        return False
Пример #12
0
def TripleScreenAnalyze(stockcode = None,tradeCycle = 'D'):

    dftrade = VecCycleIndicators(stockcode,tradeCycle)
    primaryCycle = trpscr.GetPrimaryCycle(tradeCycle)
    dfprimary = VecCycleIndicators(stockcode,primaryCycle)

    colNames = [ primaryCycle + '-smadir', primaryCycle + '-macddir', primaryCycle + '-light',
                primaryCycle + '-bandratio', primaryCycle + '-upband', primaryCycle + '-lowband',
                primaryCycle + '-valuerel',primaryCycle +'-rsi']

    for i in range(len(dftrade)):
        date = dftrade.loc[i,'date']
        priIndex = DP.GetDateIndex(dfprimary,date)
        if(priIndex is None):
            break
        for colName in colNames:
            dftrade.loc[i,colName]  = dfprimary.loc[priIndex,colName]
        #dftrade.loc[i,'w-date']  = dfprimary.loc[priIndex,'date']

    FileName = stockcode + tradeCycle + primaryCycle + '.csv'
    FilePath = os.path.join(DataRoot, FileName)
    dftrade.to_csv(FilePath)
Пример #13
0
def vectorized_forward_return(df,cycle):
    forperiods = [1, 3, 5, 10, 15]
    for i in range(len(df)):
        code = DP.codeType(df.loc[i,'code'])
        curclose = df.loc[i,'curclose']
        startdate = df.loc[i,'time']
        tradata = ts.get_k_data(code,start=startdate,ktype=cycle)

        tradata = pd.DataFrame(tradata.values,columns=tradata.columns)

        closes = tradata['close']

        for period in forperiods:

            if (period < len(closes)):
                forclose = closes[period]
                forreturn = (forclose - curclose) * 100 / curclose
            else:
                forclose = None
                forreturn = None
            df.loc[i,'close'+str(period)] = forclose
            df.loc[i, 'return' + str(period)] = forreturn
    return df
Пример #14
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
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')
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
Пример #17
0
def AminudIlliq(closes, volume):
    p = closes
    dollar_vol = np.array(volume * p)
    ret = np.array(DP.closetoret(closes))
    illiq = np.mean(np.divide(abs(ret), dollar_vol[1:]))
    return illiq
Пример #18
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
Пример #19
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
Пример #20
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)
Пример #21
0
# -*- coding: utf-8 -
from Analyze import DataProcess as DP

curtime = DP.getcurrenttimestr()
curdatestr = curtime[:10]

#lasttradetime = DP.get_last_trade_time()

dataDir = 'E:\FinProjects\MechaTrade\Data'
Пример #22
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')