Esempio n. 1
0
def get_cdlspinningtop(ohlc):
    cdlspinningtop = ta.CDLSPINNINGTOP(ohlc['1_open'], ohlc['2_high'],
                                       ohlc['3_low'], ohlc['4_close'])

    ohlc['cdlspinningtop'] = cdlspinningtop

    return ohlc
Esempio n. 2
0
def CDLSPINNINGTOP(open, high, low, close):
    ''' Spinning Top 纺锤

    分组: Pattern Recognition 形态识别

    简介: 一日K线,实体小。

    integer = CDLSPINNINGTOP(open, high, low, close)
    '''
    return talib.CDLSPINNINGTOP(open, high, low, close)
Esempio n. 3
0
 def spinning_top(self):
     """
     名称:Spinning Top 纺锤
     简介:一日K线,实体小。
     """
     result = talib.CDLSPINNINGTOP(open=np.array(self.dataframe['open']),
                                   high=np.array(self.dataframe['high']),
                                   low=np.array(self.dataframe['low']),
                                   close=np.array(self.dataframe['close']))
     self.dataframe['spinning_top'] = result
Esempio n. 4
0
    def spinning_top(self, sym, frequency):
        if not self.kbars_ready(sym, frequency):
            return []

        opens = self.open(sym, frequency)
        highs = self.high(sym, frequency)
        lows = self.low(sym, frequency)
        closes = self.close(sym, frequency)

        cdl = ta.CDLSPINNINGTOP(opens, highs, lows, closes)

        return cdl
def ta(name, price_h, price_l, price_c, price_v, price_o):
    # function 'MAX'/'MAXINDEX'/'MIN'/'MININDEX'/'MINMAX'/'MINMAXINDEX'/'SUM' is missing
    if name == 'AD':
        return talib.AD(np.array(price_h), np.array(price_l),
                        np.array(price_c), np.asarray(price_v, dtype='float'))
    if name == 'ADOSC':
        return talib.ADOSC(np.array(price_h),
                           np.array(price_l),
                           np.array(price_c),
                           np.asarray(price_v, dtype='float'),
                           fastperiod=2,
                           slowperiod=10)
    if name == 'ADX':
        return talib.ADX(np.array(price_h),
                         np.array(price_l),
                         np.asarray(price_c, dtype='float'),
                         timeperiod=14)
    if name == 'ADXR':
        return talib.ADXR(np.array(price_h),
                          np.array(price_l),
                          np.asarray(price_c, dtype='float'),
                          timeperiod=14)
    if name == 'APO':
        return talib.APO(np.asarray(price_c, dtype='float'),
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
    if name == 'AROON':
        AROON_DWON, AROON2_UP = talib.AROON(np.array(price_h),
                                            np.asarray(price_l, dtype='float'),
                                            timeperiod=90)
        return (AROON_DWON, AROON2_UP)
    if name == 'AROONOSC':
        return talib.AROONOSC(np.array(price_h),
                              np.asarray(price_l, dtype='float'),
                              timeperiod=14)
    if name == 'ATR':
        return talib.ATR(np.array(price_h),
                         np.array(price_l),
                         np.asarray(price_c, dtype='float'),
                         timeperiod=14)
    if name == 'AVGPRICE':
        return talib.AVGPRICE(np.array(price_o), np.array(price_h),
                              np.array(price_l),
                              np.asarray(price_c, dtype='float'))
    if name == 'BBANDS':
        BBANDS1, BBANDS2, BBANDS3 = talib.BBANDS(np.asarray(price_c,
                                                            dtype='float'),
                                                 matype=MA_Type.T3)
        return BBANDS1
    if name == 'BETA':
        return talib.BETA(np.array(price_h),
                          np.asarray(price_l, dtype='float'),
                          timeperiod=5)
    if name == 'BOP':
        return talib.BOP(np.array(price_o), np.array(price_h),
                         np.array(price_l), np.asarray(price_c, dtype='float'))
    if name == 'CCI':
        return talib.CCI(np.array(price_h),
                         np.array(price_l),
                         np.asarray(price_c, dtype='float'),
                         timeperiod=14)
    if name == 'CDL2CROWS':
        return talib.CDL2CROWS(np.array(price_o), np.array(price_h),
                               np.array(price_l),
                               np.asarray(price_c, dtype='float'))
    if name == 'CDL3BLACKCROWS':
        return talib.CDL3BLACKCROWS(np.array(price_o), np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'))
    if name == 'CDL3INSIDE':
        return talib.CDL3INSIDE(np.array(price_o), np.array(price_h),
                                np.array(price_l),
                                np.asarray(price_c, dtype='float'))
    if name == 'CDL3LINESTRIKE':
        return talib.CDL3LINESTRIKE(np.array(price_o), np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'))
    if name == 'CDL3OUTSIDE':
        return talib.CDL3OUTSIDE(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDL3STARSINSOUTH':
        return talib.CDL3STARSINSOUTH(np.array(price_o), np.array(price_h),
                                      np.array(price_l),
                                      np.asarray(price_c, dtype='float'))
    if name == 'CDL3WHITESOLDIERS':
        return talib.CDL3WHITESOLDIERS(np.array(price_o), np.array(price_h),
                                       np.array(price_l),
                                       np.asarray(price_c, dtype='float'))
    if name == 'CDLABANDONEDBABY':
        return talib.CDLABANDONEDBABY(np.array(price_o),
                                      np.array(price_h),
                                      np.array(price_l),
                                      np.asarray(price_c, dtype='float'),
                                      penetration=0)
    if name == 'CDLADVANCEBLOCK':
        return talib.CDLADVANCEBLOCK(np.array(price_o), np.array(price_h),
                                     np.array(price_l),
                                     np.asarray(price_c, dtype='float'))
    if name == 'CDLBELTHOLD':
        return talib.CDLBELTHOLD(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDLBREAKAWAY':
        return talib.CDLBREAKAWAY(np.array(price_o), np.array(price_h),
                                  np.array(price_l),
                                  np.asarray(price_c, dtype='float'))
    if name == 'CDLCLOSINGMARUBOZU':
        return talib.CDLCLOSINGMARUBOZU(np.array(price_o), np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'))
    if name == 'CDLCONCEALBABYSWALL':
        return talib.CDLCONCEALBABYSWALL(np.array(price_o), np.array(price_h),
                                         np.array(price_l),
                                         np.asarray(price_c, dtype='float'))
    if name == 'CDLCOUNTERATTACK':
        return talib.CDLCOUNTERATTACK(np.array(price_o), np.array(price_h),
                                      np.array(price_l),
                                      np.asarray(price_c, dtype='float'))
    if name == 'CDLDARKCLOUDCOVER':
        return talib.CDLDARKCLOUDCOVER(np.array(price_o),
                                       np.array(price_h),
                                       np.array(price_l),
                                       np.asarray(price_c, dtype='float'),
                                       penetration=0)
    if name == 'CDLDOJI':
        return talib.CDLDOJI(np.array(price_o), np.array(price_h),
                             np.array(price_l),
                             np.asarray(price_c, dtype='float'))
    if name == 'CDLDOJISTAR':
        return talib.CDLDOJISTAR(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDLDRAGONFLYDOJI':
        return talib.CDLDRAGONFLYDOJI(np.array(price_o), np.array(price_h),
                                      np.array(price_l),
                                      np.asarray(price_c, dtype='float'))
    if name == 'CDLENGULFING':
        return talib.CDLENGULFING(np.array(price_o), np.array(price_h),
                                  np.array(price_l),
                                  np.asarray(price_c, dtype='float'))
    if name == 'CDLEVENINGDOJISTAR':
        return talib.CDLEVENINGDOJISTAR(np.array(price_o),
                                        np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'),
                                        penetration=0)
    if name == 'CDLEVENINGSTAR':
        return talib.CDLEVENINGSTAR(np.array(price_o),
                                    np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'),
                                    penetration=0)
    if name == 'CDLGAPSIDESIDEWHITE':
        return talib.CDLGAPSIDESIDEWHITE(np.array(price_o), np.array(price_h),
                                         np.array(price_l),
                                         np.asarray(price_c, dtype='float'))
    if name == 'CDLGRAVESTONEDOJI':
        return talib.CDLGRAVESTONEDOJI(np.array(price_o), np.array(price_h),
                                       np.array(price_l),
                                       np.asarray(price_c, dtype='float'))
    if name == 'CDLHAMMER':
        return talib.CDLHAMMER(np.array(price_o), np.array(price_h),
                               np.array(price_l),
                               np.asarray(price_c, dtype='float'))
    if name == 'CDLHANGINGMAN':
        return talib.CDLHANGINGMAN(np.array(price_o), np.array(price_h),
                                   np.array(price_l),
                                   np.asarray(price_c, dtype='float'))
    if name == 'CDLHARAMI':
        return talib.CDLHARAMI(np.array(price_o), np.array(price_h),
                               np.array(price_l),
                               np.asarray(price_c, dtype='float'))
    if name == 'CDLHARAMICROSS':
        return talib.CDLHARAMICROSS(np.array(price_o), np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'))
    if name == 'CDLHIGHWAVE':
        return talib.CDLHIGHWAVE(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDLHIKKAKE':
        return talib.CDLHIKKAKE(np.array(price_o), np.array(price_h),
                                np.array(price_l),
                                np.asarray(price_c, dtype='float'))
    if name == 'CDLHIKKAKEMOD':
        return talib.CDLHIKKAKEMOD(np.array(price_o), np.array(price_h),
                                   np.array(price_l),
                                   np.asarray(price_c, dtype='float'))
    if name == 'CDLHOMINGPIGEON':
        return talib.CDLHOMINGPIGEON(np.array(price_o), np.array(price_h),
                                     np.array(price_l),
                                     np.asarray(price_c, dtype='float'))
    if name == 'CDLIDENTICAL3CROWS':
        return talib.CDLIDENTICAL3CROWS(np.array(price_o), np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'))
    if name == 'CDLINNECK':
        return talib.CDLINNECK(np.array(price_o), np.array(price_h),
                               np.array(price_l),
                               np.asarray(price_c, dtype='float'))
    if name == 'CDLINVERTEDHAMMER':
        return talib.CDLINVERTEDHAMMER(np.array(price_o), np.array(price_h),
                                       np.array(price_l),
                                       np.asarray(price_c, dtype='float'))
    if name == 'CDLKICKING':
        return talib.CDLKICKING(np.array(price_o), np.array(price_h),
                                np.array(price_l),
                                np.asarray(price_c, dtype='float'))
    if name == 'CDLKICKINGBYLENGTH':
        return talib.CDLKICKINGBYLENGTH(np.array(price_o), np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'))

    if name == 'CDLLADDERBOTTOM':
        return talib.CDLLADDERBOTTOM(np.array(price_o), np.array(price_h),
                                     np.array(price_l),
                                     np.asarray(price_c, dtype='float'))
    if name == 'CDLLONGLEGGEDDOJI':
        return talib.CDLLONGLEGGEDDOJI(np.array(price_o), np.array(price_h),
                                       np.array(price_l),
                                       np.asarray(price_c, dtype='float'))
    if name == 'CDLLONGLINE':
        return talib.CDLLONGLINE(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDLMARUBOZU':
        return talib.CDLMARUBOZU(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDLMATCHINGLOW':
        return talib.CDLMATCHINGLOW(np.array(price_o), np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'))
    if name == 'CDLMATHOLD':
        return talib.CDLMATHOLD(np.array(price_o), np.array(price_h),
                                np.array(price_l),
                                np.asarray(price_c, dtype='float'))
    if name == 'CDLMORNINGDOJISTAR':
        return talib.CDLMORNINGDOJISTAR(np.array(price_o),
                                        np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'),
                                        penetration=0)
    if name == 'CDLMORNINGSTAR':
        return talib.CDLMORNINGSTAR(np.array(price_o),
                                    np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'),
                                    penetration=0)
    if name == 'CDLONNECK':
        return talib.CDLONNECK(np.array(price_o), np.array(price_h),
                               np.array(price_l),
                               np.asarray(price_c, dtype='float'))
    if name == 'CDLPIERCING':
        return talib.CDLPIERCING(np.array(price_o), np.array(price_h),
                                 np.array(price_l),
                                 np.asarray(price_c, dtype='float'))
    if name == 'CDLRICKSHAWMAN':
        return talib.CDLRICKSHAWMAN(np.array(price_o), np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'))
    if name == 'CDLRISEFALL3METHODS':
        return talib.CDLRISEFALL3METHODS(np.array(price_o), np.array(price_h),
                                         np.array(price_l),
                                         np.asarray(price_c, dtype='float'))
    if name == 'CDLSEPARATINGLINES':
        return talib.CDLSEPARATINGLINES(np.array(price_o), np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'))
    if name == 'CDLSHOOTINGSTAR':
        return talib.CDLSHOOTINGSTAR(np.array(price_o), np.array(price_h),
                                     np.array(price_l),
                                     np.asarray(price_c, dtype='float'))
    if name == 'CDLSHORTLINE':
        return talib.CDLSHORTLINE(np.array(price_o), np.array(price_h),
                                  np.array(price_l),
                                  np.asarray(price_c, dtype='float'))
    if name == 'CDLSPINNINGTOP':
        return talib.CDLSPINNINGTOP(np.array(price_o), np.array(price_h),
                                    np.array(price_l),
                                    np.asarray(price_c, dtype='float'))
    if name == 'CDLSTALLEDPATTERN':
        return talib.CDLSTALLEDPATTERN(np.array(price_o), np.array(price_h),
                                       np.array(price_l),
                                       np.asarray(price_c, dtype='float'))
    if name == 'CDLSTICKSANDWICH':
        return talib.CDLSTICKSANDWICH(np.array(price_o), np.array(price_h),
                                      np.array(price_l),
                                      np.asarray(price_c, dtype='float'))
    if name == 'CDLTAKURI':
        return talib.CDLTAKURI(np.array(price_o), np.array(price_h),
                               np.array(price_l),
                               np.asarray(price_c, dtype='float'))
    if name == 'CDLTASUKIGAP':
        return talib.CDLTASUKIGAP(np.array(price_o), np.array(price_h),
                                  np.array(price_l),
                                  np.asarray(price_c, dtype='float'))
    if name == 'CDLTHRUSTING':
        return talib.CDLTHRUSTING(np.array(price_o), np.array(price_h),
                                  np.array(price_l),
                                  np.asarray(price_c, dtype='float'))
    if name == 'CDLTRISTAR':
        return talib.CDLTRISTAR(np.array(price_o), np.array(price_h),
                                np.array(price_l),
                                np.asarray(price_c, dtype='float'))
    if name == 'CDLUNIQUE3RIVER':
        return talib.CDLUNIQUE3RIVER(np.array(price_o), np.array(price_h),
                                     np.array(price_l),
                                     np.asarray(price_c, dtype='float'))
    if name == 'CDLUPSIDEGAP2CROWS':
        return talib.CDLUPSIDEGAP2CROWS(np.array(price_o), np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'))
    if name == 'CDLXSIDEGAP3METHODS':
        return talib.CDLXSIDEGAP3METHODS(np.array(price_o), np.array(price_h),
                                         np.array(price_l),
                                         np.asarray(price_c, dtype='float'))
    if name == 'CMO':
        return talib.CMO(np.asarray(price_c, dtype='float'), timeperiod=14)
    if name == 'CORREL':
        return talib.CORREL(np.array(price_h),
                            np.asarray(price_l, dtype='float'),
                            timeperiod=30)
    if name == 'DEMA':
        return talib.DEMA(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'DX':
        return talib.DX(np.array(price_h),
                        np.array(price_l),
                        np.asarray(price_c, dtype='float'),
                        timeperiod=14)
    if name == 'EMA':
        return talib.EMA(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'HT_DCPERIOD':
        return talib.HT_DCPERIOD(np.asarray(price_c, dtype='float'))
    if name == 'HT_DCPHASE':
        return talib.HT_DCPHASE(np.asarray(price_c, dtype='float'))
    if name == 'HT_PHASOR':
        HT_PHASOR1, HT_PHASOR2 = talib.HT_PHASOR(
            np.asarray(price_c, dtype='float')
        )  # use HT_PHASOR1 for the indication of up and down
        return HT_PHASOR1
    if name == 'HT_SINE':
        HT_SINE1, HT_SINE2 = talib.HT_SINE(np.asarray(price_c, dtype='float'))
        return HT_SINE1
    if name == 'HT_TRENDLINE':
        return talib.HT_TRENDLINE(np.asarray(price_c, dtype='float'))
    if name == 'HT_TRENDMODE':
        return talib.HT_TRENDMODE(np.asarray(price_c, dtype='float'))
    if name == 'KAMA':
        return talib.KAMA(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'LINEARREG':
        return talib.LINEARREG(np.asarray(price_c, dtype='float'),
                               timeperiod=14)
    if name == 'LINEARREG_ANGLE':
        return talib.LINEARREG_ANGLE(np.asarray(price_c, dtype='float'),
                                     timeperiod=14)
    if name == 'LINEARREG_INTERCEPT':
        return talib.LINEARREG_INTERCEPT(np.asarray(price_c, dtype='float'),
                                         timeperiod=14)
    if name == 'LINEARREG_SLOPE':
        return talib.LINEARREG_SLOPE(np.asarray(price_c, dtype='float'),
                                     timeperiod=14)
    if name == 'MA':
        return talib.MA(np.asarray(price_c, dtype='float'),
                        timeperiod=30,
                        matype=0)
    if name == 'MACD':
        MACD1, MACD2, MACD3 = talib.MACD(np.asarray(price_c, dtype='float'),
                                         fastperiod=12,
                                         slowperiod=26,
                                         signalperiod=9)
        return MACD1
    if nam == 'MACDEXT':
        return talib.MACDEXT(np.asarray(price_c, dtype='float'),
                             fastperiod=12,
                             fastmatype=0,
                             slowperiod=26,
                             slowmatype=0,
                             signalperiod=9,
                             signalmatype=0)
    if name == 'MACDFIX':
        MACDFIX1, MACDFIX2, MACDFIX3 = talib.MACDFIX(np.asarray(price_c,
                                                                dtype='float'),
                                                     signalperiod=9)
        return MACDFIX1
    if name == 'MAMA':
        MAMA1, MAMA2 = talib.MAMA(np.asarray(price_c, dtype='float'),
                                  fastlimit=0,
                                  slowlimit=0)
        return MAMA1
    if name == 'MEDPRICE':
        return talib.MEDPRICE(np.array(price_h),
                              np.asarray(price_l, dtype='float'))
    if name == 'MINUS_DI':
        return talib.MINUS_DI(np.array(price_h),
                              np.array(price_l),
                              np.asarray(price_c, dtype='float'),
                              timeperiod=14)
    if name == 'MINUS_DM':
        return talib.MINUS_DM(np.array(price_h),
                              np.asarray(price_l, dtype='float'),
                              timeperiod=14)
    if name == 'MOM':
        return talib.MOM(np.asarray(price_c, dtype='float'), timeperiod=10)
    if name == 'NATR':
        return talib.NATR(np.array(price_h),
                          np.array(price_l),
                          np.asarray(price_c, dtype='float'),
                          timeperiod=14)
    if name == 'OBV':
        return talib.OBV(np.array(price_c), np.asarray(price_v, dtype='float'))
    if name == 'PLUS_DI':
        return talib.PLUS_DI(np.array(price_h),
                             np.array(price_l),
                             np.asarray(price_c, dtype='float'),
                             timeperiod=14)
    if name == 'PLUS_DM':
        return talib.PLUS_DM(np.array(price_h),
                             np.asarray(price_l, dtype='float'),
                             timeperiod=14)
    if name == 'PPO':
        return talib.PPO(np.asarray(price_c, dtype='float'),
                         fastperiod=12,
                         slowperiod=26,
                         matype=0)
    if name == 'ROC':
        return talib.ROC(np.asarray(price_c, dtype='float'), timeperiod=10)
    if name == 'ROCP':
        return talib.ROCP(np.asarray(price_c, dtype='float'), timeperiod=10)
    if name == 'ROCR100':
        return talib.ROCR100(np.asarray(price_c, dtype='float'), timeperiod=10)
    if name == 'RSI':
        return talib.RSI(np.asarray(price_c, dtype='float'), timeperiod=14)
    if name == 'SAR':
        return talib.SAR(np.array(price_h),
                         np.asarray(price_l, dtype='float'),
                         acceleration=0,
                         maximum=0)
    if name == 'SAREXT':
        return talib.SAREXT(np.array(price_h),
                            np.asarray(price_l, dtype='float'),
                            startvalue=0,
                            offsetonreverse=0,
                            accelerationinitlong=0,
                            accelerationlong=0,
                            accelerationmaxlong=0,
                            accelerationinitshort=0,
                            accelerationshort=0,
                            accelerationmaxshort=0)
    if name == 'SMA':
        return talib.SMA(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'STDDEV':
        return talib.STDDEV(np.asarray(price_c, dtype='float'),
                            timeperiod=5,
                            nbdev=1)
    if name == 'STOCH':
        STOCH1, STOCH2 = talib.STOCH(np.array(price_h),
                                     np.array(price_l),
                                     np.asarray(price_c, dtype='float'),
                                     fastk_period=5,
                                     slowk_period=3,
                                     slowk_matype=0,
                                     slowd_period=3,
                                     slowd_matype=0)
        return STOCH1
    if name == 'STOCHF':
        STOCHF1, STOCHF2 = talib.STOCHF(np.array(price_h),
                                        np.array(price_l),
                                        np.asarray(price_c, dtype='float'),
                                        fastk_period=5,
                                        fastd_period=3,
                                        fastd_matype=0)
        return STOCHF1
    if name == 'STOCHRSI':
        STOCHRSI1, STOCHRSI2 = talib.STOCHRSI(np.asarray(price_c,
                                                         dtype='float'),
                                              timeperiod=14,
                                              fastk_period=5,
                                              fastd_period=3,
                                              fastd_matype=0)
        return STOCHRSI1
    if name == 'T3':
        return talib.T3(np.asarray(price_c, dtype='float'),
                        timeperiod=5,
                        vfactor=0)
    if name == 'TEMA':
        return talib.TEMA(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'TRANGE':
        return talib.TRANGE(np.array(price_h), np.array(price_l),
                            np.asarray(price_c, dtype='float'))
    if name == 'TRIMA':
        return talib.TRIMA(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'TRIX':
        return talib.TRIX(np.asarray(price_c, dtype='float'), timeperiod=30)
    if name == 'TSF':
        return talib.TSF(np.asarray(price_c, dtype='float'), timeperiod=14)
    if name == 'TYPPRICE':
        return talib.TYPPRICE(np.array(price_h), np.array(price_l),
                              np.asarray(price_c, dtype='float'))
    if name == 'ULTOSC':
        return talib.ULTOSC(np.array(price_h),
                            np.array(price_l),
                            np.asarray(price_c, dtype='float'),
                            timeperiod1=7,
                            timeperiod2=14,
                            timeperiod3=28)
    if name == 'VAR':
        return talib.VAR(np.asarray(price_c, dtype='float'),
                         timeperiod=5,
                         nbdev=1)
    if name == 'WCLPRICE':
        return talib.WCLPRICE(np.array(price_h), np.array(price_l),
                              np.asarray(price_c, dtype='float'))
    if name == 'WILLR':
        return talib.WILLR(np.array(price_h),
                           np.array(price_l),
                           np.asarray(price_c, dtype='float'),
                           timeperiod=14)
    if name == 'WMA':
        return talib.WMA(np.asarray(price_c, dtype='float'), timeperiod=30)
Esempio n. 6
0
def technical(df):
    open = df['open'].values
    close = df['close'].values
    high = df['high'].values
    low = df['low'].values
    volume = df['volume'].values
    # define the technical analysis matrix
    retn = np.array([
        tb.MA(close, timeperiod=60),  # 1
        tb.MA(close, timeperiod=120),  # 2
        tb.ADX(high, low, close, timeperiod=14),  # 3
        tb.ADXR(high, low, close, timeperiod=14),  # 4
        tb.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)[0],  # 5
        tb.RSI(close, timeperiod=14),  # 6
        tb.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0],  # 7
        tb.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1],  # 8
        tb.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2],  # 9
        tb.AD(high, low, close, volume),  # 10
        tb.ATR(high, low, close, timeperiod=14),  # 11
        tb.HT_DCPERIOD(close),  # 12
        tb.CDL2CROWS(open, high, low, close),  # 13
        tb.CDL3BLACKCROWS(open, high, low, close),  # 14
        tb.CDL3INSIDE(open, high, low, close),  # 15
        tb.CDL3LINESTRIKE(open, high, low, close),  # 16
        tb.CDL3OUTSIDE(open, high, low, close),  # 17
        tb.CDL3STARSINSOUTH(open, high, low, close),  # 18
        tb.CDL3WHITESOLDIERS(open, high, low, close),  # 19
        tb.CDLABANDONEDBABY(open, high, low, close, penetration=0),  # 20
        tb.CDLADVANCEBLOCK(open, high, low, close),  # 21
        tb.CDLBELTHOLD(open, high, low, close),  # 22
        tb.CDLBREAKAWAY(open, high, low, close),  # 23
        tb.CDLCLOSINGMARUBOZU(open, high, low, close),  # 24
        tb.CDLCONCEALBABYSWALL(open, high, low, close),  # 25
        tb.CDLCOUNTERATTACK(open, high, low, close),  # 26
        tb.CDLDARKCLOUDCOVER(open, high, low, close, penetration=0),  # 27
        tb.CDLDOJI(open, high, low, close),  # 28
        tb.CDLDOJISTAR(open, high, low, close),  # 29
        tb.CDLDRAGONFLYDOJI(open, high, low, close),  # 30
        tb.CDLENGULFING(open, high, low, close),  # 31
        tb.CDLEVENINGDOJISTAR(open, high, low, close, penetration=0),  # 32
        tb.CDLEVENINGSTAR(open, high, low, close, penetration=0),  # 33
        tb.CDLGAPSIDESIDEWHITE(open, high, low, close),  # 34
        tb.CDLGRAVESTONEDOJI(open, high, low, close),  # 35
        tb.CDLHAMMER(open, high, low, close),  # 36
        tb.CDLHANGINGMAN(open, high, low, close),  # 37
        tb.CDLHARAMI(open, high, low, close),  # 38
        tb.CDLHARAMICROSS(open, high, low, close),  # 39
        tb.CDLHIGHWAVE(open, high, low, close),  # 40
        tb.CDLHIKKAKE(open, high, low, close),  # 41
        tb.CDLHIKKAKEMOD(open, high, low, close),  # 42
        tb.CDLHOMINGPIGEON(open, high, low, close),  # 43
        tb.CDLIDENTICAL3CROWS(open, high, low, close),  # 44
        tb.CDLINNECK(open, high, low, close),  # 45
        tb.CDLINVERTEDHAMMER(open, high, low, close),  # 46
        tb.CDLKICKING(open, high, low, close),  # 47
        tb.CDLKICKINGBYLENGTH(open, high, low, close),  # 48
        tb.CDLLADDERBOTTOM(open, high, low, close),  # 49
        tb.CDLLONGLEGGEDDOJI(open, high, low, close),  # 50
        tb.CDLLONGLINE(open, high, low, close),  # 51
        tb.CDLMARUBOZU(open, high, low, close),  # 52
        tb.CDLMATCHINGLOW(open, high, low, close),  # 53
        tb.CDLMATHOLD(open, high, low, close, penetration=0),  # 54
        tb.CDLMORNINGDOJISTAR(open, high, low, close, penetration=0),  # 55
        tb.CDLMORNINGSTAR(open, high, low, close, penetration=0),  # 56
        tb.CDLONNECK(open, high, low, close),  # 57
        tb.CDLPIERCING(open, high, low, close),  # 58
        tb.CDLRICKSHAWMAN(open, high, low, close),  # 59
        tb.CDLRISEFALL3METHODS(open, high, low, close),  # 60
        tb.CDLSEPARATINGLINES(open, high, low, close),  # 61
        tb.CDLSHOOTINGSTAR(open, high, low, close),  # 62
        tb.CDLSHORTLINE(open, high, low, close),  # 63
        tb.CDLSPINNINGTOP(open, high, low, close),  # 64
        tb.CDLSTALLEDPATTERN(open, high, low, close),  # 65
        tb.CDLSTICKSANDWICH(open, high, low, close),  # 66
        tb.CDLTAKURI(open, high, low, close),  # 67
        tb.CDLTASUKIGAP(open, high, low, close),  # 68
        tb.CDLTHRUSTING(open, high, low, close),  # 69
        tb.CDLTRISTAR(open, high, low, close),  # 70
        tb.CDLUNIQUE3RIVER(open, high, low, close),  # 71
        tb.CDLUPSIDEGAP2CROWS(open, high, low, close),  # 72
        tb.CDLXSIDEGAP3METHODS(open, high, low, close)  # 73
    ]).T
    return retn
Esempio n. 7
0
def CDLSPINNINGTOP(open, high, low, close):
    return talib.CDLSPINNINGTOP(open, high, low, close)
        cdlrickshawman = ta.CDLRICKSHAWMAN(openp, high, low, close)

        #CDLRISEFALL3METHODS - Rising/Falling Three Methods
        cdlrisefall3methods = ta.CDLRISEFALL3METHODS(openp, high, low, close)

        #CDLSEPARATINGLINES - Separating Lines
        cdlseperatinglines = ta.CDLSEPARATINGLINES(openp, high, low, close)

        #CDLSHOOTINGSTAR - Shooting Star
        cdlshootingstar = ta.CDLSHOOTINGSTAR(openp, high, low, close)

        #CDLSHORTLINE - Short Line Candle
        cdlshortline = ta.CDLSHORTLINE(openp, high, low, close)

        #CDLSPINNINGTOP - Spinning Top
        cdlspinningtop = ta.CDLSPINNINGTOP(openp, high, low, close)

        #CDLSTALLEDPATTERN - Stalled Pattern
        cdlstalledpattern = ta.CDLSTALLEDPATTERN(openp, high, low, close)

        #CDLSTICKSANDWICH - Stick Sandwich
        cdlsticksandwich = ta.CDLSTICKSANDWICH(openp, high, low, close)

        #CDLTAKURI - Takuri (Dragonfly Doji with very long lower shadow)
        cdltakuri = ta.CDLTAKURI(openp, high, low, close)

        #CDLTASUKIGAP - Tasuki Gap
        cdltasukigap = ta.CDLTASUKIGAP(openp, high, low, close)

        #CDLTHRUSTING - Thrusting Pattern
        cdlthrusting = ta.CDLTHRUSTING(openp, high, low, close)
Esempio n. 9
0
def CDLSPINNINGTOP(data, **kwargs):
    _check_talib_presence()
    popen, phigh, plow, pclose, pvolume = _extract_ohlc(data)
    return talib.CDLSPINNINGTOP(popen, phigh, plow, pclose, **kwargs)
Esempio n. 10
0
     ohlc_df['close'])
 ohlc_df['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDLSHORTLINE'] = ta.CDLSHORTLINE(ohlc_df['open'],
                                           ohlc_df['high'],
                                           ohlc_df['low'],
                                           ohlc_df['close'])
 ohlc_df['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDLTAKURI'] = ta.CDLTAKURI(ohlc_df['open'],
                                     ohlc_df['high'],
                                     ohlc_df['low'],
                                     ohlc_df['close'])
 ohlc_df['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(ohlc_df['open'],
                                           ohlc_df['high'],
                                           ohlc_df['low'],
                                           ohlc_df['close'])
Esempio n. 11
0
     resorted['close'])
 CDLRISEFALL3METHODS_real = talib.CDLRISEFALL3METHODS(
     resorted['open'], resorted['high'], resorted['low'],
     resorted['close'])
 CDLSEPARATINGLINES_real = talib.CDLSEPARATINGLINES(
     resorted['open'], resorted['high'], resorted['low'],
     resorted['close'])
 CDLSHOOTINGSTAR_real = talib.CDLSHOOTINGSTAR(
     resorted['open'], resorted['high'], resorted['low'],
     resorted['close'])
 CDLSHORTLINE_real = talib.CDLSHORTLINE(resorted['open'],
                                        resorted['high'],
                                        resorted['low'],
                                        resorted['close'])
 CDLSPINNINGTOP_real = talib.CDLSPINNINGTOP(
     resorted['open'], resorted['high'], resorted['low'],
     resorted['close'])
 CDLSTALLEDPATTERN_real = talib.CDLSTALLEDPATTERN(
     resorted['open'], resorted['high'], resorted['low'],
     resorted['close'])
 CDLSTICKSANDWICH_real = talib.CDLSTICKSANDWICH(
     resorted['open'], resorted['high'], resorted['low'],
     resorted['close'])
 CDLTAKURI_real = talib.CDLTAKURI(resorted['open'],
                                  resorted['high'],
                                  resorted['low'],
                                  resorted['close'])
 CDLTASUKIGAP_real = talib.CDLTASUKIGAP(resorted['open'],
                                        resorted['high'],
                                        resorted['low'],
                                        resorted['close'])
Esempio n. 12
0
def create_signal_dataframe(df_):
    o = np.array(df_['始値'])
    c = np.array(df_['終値'])
    l = np.array(df_['安値'])
    h = np.array(df_['高値'])
    df = df_.copy()
    df['CDL2CROWS'] = ta.CDL2CROWS(o, h, l, c)
    df['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(o, h, l, c)
    df['CDL3INSIDE'] = ta.CDL3INSIDE(o, h, l, c)
    df['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(o, h, l, c)
    df['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(o, h, l, c)
    df['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(o, h, l, c)
    df['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(o, h, l, c)
    df['CDLABANDONEDBABY'] = ta.CDLABANDONEDBABY(o, h, l, c)
    df['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(o, h, l, c)
    df['CDLBELTHOLD'] = ta.CDLBELTHOLD(o, h, l, c)
    df['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(o, h, l, c)
    df['CDLCLOSINGMARUBOZU'] = ta.CDLCLOSINGMARUBOZU(o, h, l, c)
    df['CDLCONCEALBABYSWALL'] = ta.CDLCONCEALBABYSWALL(o, h, l, c)
    df['CDLCOUNTERATTACK'] = ta.CDLCOUNTERATTACK(o, h, l, c)
    df['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(o, h, l, c)
    df['CDLDOJI'] = ta.CDLDOJI(o, h, l, c)
    df['CDLDOJISTAR'] = ta.CDLDOJISTAR(o, h, l, c)
    df['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(o, h, l, c)
    df['CDLENGULFING'] = ta.CDLENGULFING(o, h, l, c)
    df['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(o, h, l, c)
    df['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(o, h, l, c)
    df['CDLGAPSIDESIDEWHITE'] = ta.CDLGAPSIDESIDEWHITE(o, h, l, c)
    df['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(o, h, l, c)
    df['CDLHAMMER'] = ta.CDLHAMMER(o, h, l, c)
    df['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(o, h, l, c)
    df['CDLHARAMI'] = ta.CDLHARAMI(o, h, l, c)
    df['CDLHARAMICROSS'] = ta.CDLHARAMICROSS(o, h, l, c)
    df['CDLHIGHWAVE'] = ta.CDLHIGHWAVE(o, h, l, c)
    df['CDLHIKKAKE'] = ta.CDLHIKKAKE(o, h, l, c)
    df['CDLHIKKAKEMOD'] = ta.CDLHIKKAKEMOD(o, h, l, c)
    df['CDLHOMINGPIGEON'] = ta.CDLHOMINGPIGEON(o, h, l, c)
    df['CDLIDENTICAL3CROWS'] = ta.CDLIDENTICAL3CROWS(o, h, l, c)
    df['CDLINNECK'] = ta.CDLINNECK(o, h, l, c)
    df['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(o, h, l, c)
    df['CDLKICKING'] = ta.CDLKICKING(o, h, l, c)
    df['CDLKICKINGBYLENGTH'] = ta.CDLKICKINGBYLENGTH(o, h, l, c)
    df['CDLLADDERBOTTOM'] = ta.CDLLADDERBOTTOM(o, h, l, c)
    df['CDLLONGLEGGEDDOJI'] = ta.CDLLONGLEGGEDDOJI(o, h, l, c)
    df['CDLLONGLINE'] = ta.CDLLONGLINE(o, h, l, c)
    df['CDLMARUBOZU'] = ta.CDLMARUBOZU(o, h, l, c)
    df['CDLMATCHINGLOW'] = ta.CDLMATCHINGLOW(o, h, l, c)
    df['CDLMATHOLD'] = ta.CDLMATHOLD(o, h, l, c)
    df['CDLMORNINGDOJISTAR'] = ta.CDLMORNINGDOJISTAR(o, h, l, c)
    df['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(o, h, l, c)
    df['CDLONNECK'] = ta.CDLONNECK(o, h, l, c)
    df['CDLPIERCING'] = ta.CDLPIERCING(o, h, l, c)
    df['CDLRICKSHAWMAN'] = ta.CDLRICKSHAWMAN(o, h, l, c)
    df['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(o, h, l, c)
    df['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(o, h, l, c)
    df['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(o, h, l, c)
    df['CDLSHORTLINE'] = ta.CDLSHORTLINE(o, h, l, c)
    df['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(o, h, l, c)
    df['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(o, h, l, c)
    df['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(o, h, l, c)
    df['CDLTAKURI'] = ta.CDLTAKURI(o, h, l, c)
    df['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(o, h, l, c)
    df['CDLTHRUSTING'] = ta.CDLTHRUSTING(o, h, l, c)
    df['CDLTRISTAR'] = ta.CDLTRISTAR(o, h, l, c)
    df['CDLUNIQUE3RIVER'] = ta.CDLUNIQUE3RIVER(o, h, l, c)
    df['CDLUPSIDEGAP2CROWS'] = ta.CDLUPSIDEGAP2CROWS(o, h, l, c)
    df['CDLXSIDEGAP3METHODS'] = ta.CDLXSIDEGAP3METHODS(o, h, l, c)
    return df
Esempio n. 13
0
File: DC.py Progetto: kzil88/huobi
    def collectDATA(self, start_dt, end_dt, para_min, threshold):
        # 建立数据库连接,剔除已入库的部分
        db = pymysql.connect(host='127.0.0.1',
                             user='******',
                             passwd='admin',
                             db='stock',
                             charset='utf8')
        cursor = db.cursor()
        if para_min == 'day':
            sql_done_set = "SELECT * FROM btc_day a where state_dt >= '%s' and state_dt <= '%s' order by state_dt asc" % (
                start_dt, end_dt)
        else:
            sql_done_set = "SELECT * FROM btc_%smin a where state_dt >= '%s' and state_dt <= '%s' order by state_dt asc" % (
                str(para_min), start_dt, end_dt)
        cursor.execute(sql_done_set)
        done_set = cursor.fetchall()
        if len(done_set) == 0:
            raise Exception
        self.date_seq = []
        self.open_list = []
        self.close_list = []
        self.high_list = []
        self.low_list = []
        self.vol_list = []
        self.amount_list = []
        self.tor_list = []
        self.vr_list = []
        self.ma5_list = []
        self.ma10_list = []
        self.ma20_list = []
        self.ma30_list = []
        self.ma60_list = []
        for i in range(len(done_set)):
            self.date_seq.append(done_set[i][0])
            self.open_list.append(float(done_set[i][1]))
            self.close_list.append(float(done_set[i][2]))
            self.high_list.append(float(done_set[i][3]))
            self.low_list.append(float(done_set[i][4]))
            self.vol_list.append(float(done_set[i][6]))
            self.amount_list.append(float(done_set[i][5]))
        db.close()

        cdl_2crows = ta.CDL2CROWS(np.array(self.open_list),
                                  np.array(self.high_list),
                                  np.array(self.low_list),
                                  np.array(self.close_list))
        cdl_3blackcrows = ta.CDL3BLACKCROWS(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_3inside = ta.CDL3INSIDE(np.array(self.open_list),
                                    np.array(self.high_list),
                                    np.array(self.low_list),
                                    np.array(self.close_list))
        cdl_3linestrike = ta.CDL3LINESTRIKE(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_3outside = ta.CDL3OUTSIDE(np.array(self.open_list),
                                      np.array(self.high_list),
                                      np.array(self.low_list),
                                      np.array(self.close_list))
        cdl_3starsinsouth = ta.CDL3STARSINSOUTH(np.array(self.open_list),
                                                np.array(self.high_list),
                                                np.array(self.low_list),
                                                np.array(self.close_list))
        cdl_3whitesoldiers = ta.CDL3WHITESOLDIERS(np.array(self.open_list),
                                                  np.array(self.high_list),
                                                  np.array(self.low_list),
                                                  np.array(self.close_list))
        cdl_abandonedbaby = ta.CDLABANDONEDBABY(np.array(self.open_list),
                                                np.array(self.high_list),
                                                np.array(self.low_list),
                                                np.array(self.close_list))
        cdl_advancedblock = ta.CDLADVANCEBLOCK(np.array(self.open_list),
                                               np.array(self.high_list),
                                               np.array(self.low_list),
                                               np.array(self.close_list))
        cdl_belthold = ta.CDLBELTHOLD(np.array(self.open_list),
                                      np.array(self.high_list),
                                      np.array(self.low_list),
                                      np.array(self.close_list))
        cdl_breakaway = ta.CDLBREAKAWAY(np.array(self.open_list),
                                        np.array(self.high_list),
                                        np.array(self.low_list),
                                        np.array(self.close_list))
        cdl_closing = ta.CDLCLOSINGMARUBOZU(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_conbaby = ta.CDLCONCEALBABYSWALL(np.array(self.open_list),
                                             np.array(self.high_list),
                                             np.array(self.low_list),
                                             np.array(self.close_list))
        cdl_counterattack = ta.CDLCOUNTERATTACK(np.array(self.open_list),
                                                np.array(self.high_list),
                                                np.array(self.low_list),
                                                np.array(self.close_list))
        cdl_darkcloud = ta.CDLDARKCLOUDCOVER(np.array(self.open_list),
                                             np.array(self.high_list),
                                             np.array(self.low_list),
                                             np.array(self.close_list))
        cdl_doji = ta.CDLDOJI(np.array(self.open_list),
                              np.array(self.high_list),
                              np.array(self.low_list),
                              np.array(self.close_list))
        cdl_dojistar = ta.CDLDOJISTAR(np.array(self.open_list),
                                      np.array(self.high_list),
                                      np.array(self.low_list),
                                      np.array(self.close_list))
        cdl_dragondoji = ta.CDLDRAGONFLYDOJI(np.array(self.open_list),
                                             np.array(self.high_list),
                                             np.array(self.low_list),
                                             np.array(self.close_list))
        cdl_eng = ta.CDLENGULFING(np.array(self.open_list),
                                  np.array(self.high_list),
                                  np.array(self.low_list),
                                  np.array(self.close_list))
        cdl_evedoji = ta.CDLEVENINGDOJISTAR(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_evestar = ta.CDLEVENINGSTAR(np.array(self.open_list),
                                        np.array(self.high_list),
                                        np.array(self.low_list),
                                        np.array(self.close_list))
        cdl_gapside = ta.CDLGAPSIDESIDEWHITE(np.array(self.open_list),
                                             np.array(self.high_list),
                                             np.array(self.low_list),
                                             np.array(self.close_list))
        cdl_gravedoji = ta.CDLGRAVESTONEDOJI(np.array(self.open_list),
                                             np.array(self.high_list),
                                             np.array(self.low_list),
                                             np.array(self.close_list))
        cdl_hammer = ta.CDLHAMMER(np.array(self.open_list),
                                  np.array(self.high_list),
                                  np.array(self.low_list),
                                  np.array(self.close_list))
        cdl_hanging = ta.CDLHANGINGMAN(np.array(self.open_list),
                                       np.array(self.high_list),
                                       np.array(self.low_list),
                                       np.array(self.close_list))
        cdl_hara = ta.CDLHARAMI(np.array(self.open_list),
                                np.array(self.high_list),
                                np.array(self.low_list),
                                np.array(self.close_list))
        cdl_haracross = ta.CDLHARAMICROSS(np.array(self.open_list),
                                          np.array(self.high_list),
                                          np.array(self.low_list),
                                          np.array(self.close_list))
        cdl_highwave = ta.CDLHIGHWAVE(np.array(self.open_list),
                                      np.array(self.high_list),
                                      np.array(self.low_list),
                                      np.array(self.close_list))
        cdl_hikk = ta.CDLHIKKAKE(np.array(self.open_list),
                                 np.array(self.high_list),
                                 np.array(self.low_list),
                                 np.array(self.close_list))
        cdl_hikkmod = ta.CDLHIKKAKEMOD(np.array(self.open_list),
                                       np.array(self.high_list),
                                       np.array(self.low_list),
                                       np.array(self.close_list))
        cdl_homing = ta.CDLHOMINGPIGEON(np.array(self.open_list),
                                        np.array(self.high_list),
                                        np.array(self.low_list),
                                        np.array(self.close_list))
        cdl_i3crows = ta.CDLIDENTICAL3CROWS(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_inneck = ta.CDLINNECK(np.array(self.open_list),
                                  np.array(self.high_list),
                                  np.array(self.low_list),
                                  np.array(self.close_list))
        cdl_inverhammer = ta.CDLINVERTEDHAMMER(np.array(self.open_list),
                                               np.array(self.high_list),
                                               np.array(self.low_list),
                                               np.array(self.close_list))
        cdl_kicking = ta.CDLKICKING(np.array(self.open_list),
                                    np.array(self.high_list),
                                    np.array(self.low_list),
                                    np.array(self.close_list))
        cdl_kicking2 = ta.CDLKICKINGBYLENGTH(np.array(self.open_list),
                                             np.array(self.high_list),
                                             np.array(self.low_list),
                                             np.array(self.close_list))
        cdl_ladder = ta.CDLLADDERBOTTOM(np.array(self.open_list),
                                        np.array(self.high_list),
                                        np.array(self.low_list),
                                        np.array(self.close_list))
        cdl_longdoji = ta.CDLLONGLEGGEDDOJI(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_longline = ta.CDLLONGLINE(np.array(self.open_list),
                                      np.array(self.high_list),
                                      np.array(self.low_list),
                                      np.array(self.close_list))
        cdl_marubo = ta.CDLMARUBOZU(np.array(self.open_list),
                                    np.array(self.high_list),
                                    np.array(self.low_list),
                                    np.array(self.close_list))
        cdl_matchinglow = ta.CDLMATCHINGLOW(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_mathold = ta.CDLMATHOLD(np.array(self.open_list),
                                    np.array(self.high_list),
                                    np.array(self.low_list),
                                    np.array(self.close_list))
        cdl_morningdoji = ta.CDLMORNINGDOJISTAR(np.array(self.open_list),
                                                np.array(self.high_list),
                                                np.array(self.low_list),
                                                np.array(self.close_list))
        cdl_morningstar = ta.CDLMORNINGSTAR(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_onneck = ta.CDLONNECK(np.array(self.open_list),
                                  np.array(self.high_list),
                                  np.array(self.low_list),
                                  np.array(self.close_list))
        cdl_pier = ta.CDLPIERCING(np.array(self.open_list),
                                  np.array(self.high_list),
                                  np.array(self.low_list),
                                  np.array(self.close_list))
        cdl_rick = ta.CDLRICKSHAWMAN(np.array(self.open_list),
                                     np.array(self.high_list),
                                     np.array(self.low_list),
                                     np.array(self.close_list))
        cdl_3methords = ta.CDLRISEFALL3METHODS(np.array(self.open_list),
                                               np.array(self.high_list),
                                               np.array(self.low_list),
                                               np.array(self.close_list))
        cdl_seprate = ta.CDLSEPARATINGLINES(np.array(self.open_list),
                                            np.array(self.high_list),
                                            np.array(self.low_list),
                                            np.array(self.close_list))
        cdl_shoot = ta.CDLSHOOTINGSTAR(np.array(self.open_list),
                                       np.array(self.high_list),
                                       np.array(self.low_list),
                                       np.array(self.close_list))
        cdl_shortcandle = ta.CDLSHORTLINE(np.array(self.open_list),
                                          np.array(self.high_list),
                                          np.array(self.low_list),
                                          np.array(self.close_list))
        cdl_spin = ta.CDLSPINNINGTOP(np.array(self.open_list),
                                     np.array(self.high_list),
                                     np.array(self.low_list),
                                     np.array(self.close_list))
        cdl_stalled = ta.CDLSTALLEDPATTERN(np.array(self.open_list),
                                           np.array(self.high_list),
                                           np.array(self.low_list),
                                           np.array(self.close_list))
        cdl_sandwich = ta.CDLSTICKSANDWICH(np.array(self.open_list),
                                           np.array(self.high_list),
                                           np.array(self.low_list),
                                           np.array(self.close_list))
        cdl_taku = ta.CDLTAKURI(np.array(self.open_list),
                                np.array(self.high_list),
                                np.array(self.low_list),
                                np.array(self.close_list))
        cdl_takugap = ta.CDLTASUKIGAP(np.array(self.open_list),
                                      np.array(self.high_list),
                                      np.array(self.low_list),
                                      np.array(self.close_list))
        cdl_thrust = ta.CDLTHRUSTING(np.array(self.open_list),
                                     np.array(self.high_list),
                                     np.array(self.low_list),
                                     np.array(self.close_list))
        cdl_tristar = ta.CDLTRISTAR(np.array(self.open_list),
                                    np.array(self.high_list),
                                    np.array(self.low_list),
                                    np.array(self.close_list))
        cdl_uni = ta.CDLUNIQUE3RIVER(np.array(self.open_list),
                                     np.array(self.high_list),
                                     np.array(self.low_list),
                                     np.array(self.close_list))
        cdl_upgap = ta.CDLUPSIDEGAP2CROWS(np.array(self.open_list),
                                          np.array(self.high_list),
                                          np.array(self.low_list),
                                          np.array(self.close_list))
        cdl_xside = ta.CDLXSIDEGAP3METHODS(np.array(self.open_list),
                                           np.array(self.high_list),
                                           np.array(self.low_list),
                                           np.array(self.close_list))

        self.data_train = []
        self.data_target = []
        self.data_target_onehot = []
        for i in range(len(self.close_list) - 5):
            train = [
                cdl_2crows[i], cdl_3blackcrows[i], cdl_3inside[i],
                cdl_3linestrike[i], cdl_3outside[i], cdl_3starsinsouth[i],
                cdl_3whitesoldiers[i], cdl_abandonedbaby[i],
                cdl_advancedblock[i], cdl_belthold[i], cdl_breakaway[i],
                cdl_closing[i], cdl_conbaby[i], cdl_counterattack[i],
                cdl_darkcloud[i], cdl_doji[i], cdl_dojistar[i],
                cdl_dragondoji[i], cdl_eng[i], cdl_evedoji[i], cdl_evestar[i],
                cdl_gapside[i], cdl_gravedoji[i], cdl_hammer[i],
                cdl_hanging[i], cdl_hara[i], cdl_haracross[i], cdl_highwave[i],
                cdl_hikk[i], cdl_hikkmod[i], cdl_homing[i], cdl_i3crows[i],
                cdl_inneck[i], cdl_inverhammer[i], cdl_kicking[i],
                cdl_kicking2[i], cdl_ladder[i], cdl_longdoji[i],
                cdl_longline[i], cdl_marubo[i], cdl_matchinglow[i],
                cdl_mathold[i], cdl_morningdoji[i], cdl_morningstar[i],
                cdl_onneck[i], cdl_pier[i], cdl_rick[i], cdl_3methords[i],
                cdl_seprate[i], cdl_shoot[i], cdl_shortcandle[i], cdl_spin[i],
                cdl_stalled[i], cdl_sandwich[i], cdl_taku[i], cdl_takugap[i],
                cdl_thrust[i], cdl_tristar[i], cdl_uni[i], cdl_upgap[i],
                cdl_xside[i]
            ]
            self.data_train.append(np.array(train))
            # after_max_price = max(self.close_list[i+1:i + 5])
            # after_min_price = min(self.close_list[i+1:i+5])
            # if after_max_price / self.close_list[i] >= 1.01:
            #     self.data_target.append(float(1.00))
            #     self.data_target_onehot.append([1,0,0])
            # elif after_min_price / self.close_list[i] < 0.99:
            #     self.data_target.append(float(-1.00))
            #     self.data_target_onehot.append([0,1,0])
            # else:
            #     self.data_target.append(float(0.00))
            #     self.data_target_onehot.append([0,0,1])

            after_mean_price = np.array(self.close_list[i + 1:i + 5]).mean()
            if after_mean_price / self.close_list[i] > threshold:
                self.data_target.append(float(1.00))
                self.data_target_onehot.append([1, 0, 0])
            else:
                self.data_target.append(float(-1.00))
                self.data_target_onehot.append([0, 1, 0])
        self.cnt_pos = 0
        self.cnt_pos = len([x for x in self.data_target if x == 1.00])

        self.test_case = []
        self.test_case = np.array([
            cdl_2crows[-1], cdl_3blackcrows[-1], cdl_3inside[-1],
            cdl_3linestrike[-1], cdl_3outside[-1], cdl_3starsinsouth[-1],
            cdl_3whitesoldiers[-1], cdl_abandonedbaby[-1],
            cdl_advancedblock[-1], cdl_belthold[-1], cdl_breakaway[-1],
            cdl_closing[-1], cdl_conbaby[-1], cdl_counterattack[-1],
            cdl_darkcloud[-1], cdl_doji[-1], cdl_dojistar[-1],
            cdl_dragondoji[-1], cdl_eng[-1], cdl_evedoji[-1], cdl_evestar[-1],
            cdl_gapside[-1], cdl_gravedoji[-1], cdl_hammer[-1],
            cdl_hanging[-1], cdl_hara[-1], cdl_haracross[-1], cdl_highwave[-1],
            cdl_hikk[-1], cdl_hikkmod[-1], cdl_homing[-1], cdl_i3crows[-1],
            cdl_inneck[-1], cdl_inverhammer[-1], cdl_kicking[-1],
            cdl_kicking2[-1], cdl_ladder[-1], cdl_longdoji[-1],
            cdl_longline[-1], cdl_marubo[-1], cdl_matchinglow[-1],
            cdl_mathold[-1], cdl_morningdoji[-1], cdl_morningstar[-1],
            cdl_onneck[-1], cdl_pier[-1], cdl_rick[-1], cdl_3methords[-1],
            cdl_seprate[-1], cdl_shoot[-1], cdl_shortcandle[-1], cdl_spin[-1],
            cdl_stalled[-1], cdl_sandwich[-1], cdl_taku[-1], cdl_takugap[-1],
            cdl_thrust[-1], cdl_tristar[-1], cdl_uni[-1], cdl_upgap[-1],
            cdl_xside[-1]
        ])
        self.data_train = np.array(self.data_train)
        self.data_target = np.array(self.data_target)
Esempio n. 14
0
def add_indicator(data):
    open = data.Open
    high = data.High
    low = data.Low
    close = data.Close
    volume = data.Volume

    data['CDL2CROWS'] = talib.CDL2CROWS(open, high, low, close)
    data['CDL3BLACKCROWS'] = talib.CDL3BLACKCROWS(open, high, low, close)
    data['CDL3INSIDE'] = talib.CDL3INSIDE(open, high, low, close)
    data['CDL3LINESTRIKE'] = talib.CDL3LINESTRIKE(open, high, low, close)
    data['CDL3OUTSIDE'] = talib.CDL3OUTSIDE(open, high, low, close)
    data['CDL3STARSINSOUTH'] = talib.CDL3STARSINSOUTH(open, high, low, close)
    data['CDL3WHITESOLDIERS'] = talib.CDL3WHITESOLDIERS(open, high, low, close)
    data['CDLABANDONEDBABY'] = talib.CDLABANDONEDBABY(open,
                                                      high,
                                                      low,
                                                      close,
                                                      penetration=0)

    data['CDLADVANCEBLOCK'] = talib.CDLADVANCEBLOCK(open, high, low, close)
    data['CDLBELTHOLD'] = talib.CDLBELTHOLD(open, high, low, close)
    data['CDLBREAKAWAY'] = talib.CDLBREAKAWAY(open, high, low, close)
    data['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(
        open, high, low, close)
    data['CDLCONCEALBABYSWALL'] = talib.CDLCONCEALBABYSWALL(
        open, high, low, close)
    data['CDLCOUNTERATTACK'] = talib.CDLCOUNTERATTACK(open, high, low, close)
    data['CDLDARKCLOUDCOVER'] = talib.CDLDARKCLOUDCOVER(open,
                                                        high,
                                                        low,
                                                        close,
                                                        penetration=0)

    data['CDLDOJI'] = talib.CDLDOJI(open, high, low, close)
    data['CDLDOJISTAR'] = talib.CDLDOJISTAR(open, high, low, close)
    data['CDLDRAGONFLYDOJI'] = talib.CDLDRAGONFLYDOJI(open, high, low, close)
    data['CDLENGULFING'] = talib.CDLENGULFING(open, high, low, close)
    data['CDLEVENINGDOJISTAR'] = talib.CDLEVENINGDOJISTAR(open,
                                                          high,
                                                          low,
                                                          close,
                                                          penetration=0)

    data['CDLEVENINGSTAR'] = talib.CDLEVENINGSTAR(open,
                                                  high,
                                                  low,
                                                  close,
                                                  penetration=0)

    data['CDLGAPSIDESIDEWHITE'] = talib.CDLGAPSIDESIDEWHITE(
        open, high, low, close)
    data['CDLGRAVESTONEDOJI'] = talib.CDLGRAVESTONEDOJI(open, high, low, close)
    data['CDLHAMMER'] = talib.CDLHAMMER(open, high, low, close)
    data['CDLHANGINGMAN'] = talib.CDLHANGINGMAN(open, high, low, close)
    data['CDLHARAMI'] = talib.CDLHARAMI(open, high, low, close)
    data['CDLHARAMICROSS'] = talib.CDLHARAMICROSS(open, high, low, close)
    data['CDLHIGHWAVE'] = talib.CDLHIGHWAVE(open, high, low, close)
    data['CDLHIKKAKE'] = talib.CDLHIKKAKE(open, high, low, close)
    data['CDLHIKKAKEMOD'] = talib.CDLHIKKAKEMOD(open, high, low, close)
    data['CDLHOMINGPIGEON'] = talib.CDLHOMINGPIGEON(open, high, low, close)
    data['CDLIDENTICAL3CROWS'] = talib.CDLIDENTICAL3CROWS(
        open, high, low, close)
    data['CDLINNECK'] = talib.CDLINNECK(open, high, low, close)
    data['CDLINVERTEDHAMMER'] = talib.CDLINVERTEDHAMMER(open, high, low, close)
    data['CDLKICKING'] = talib.CDLKICKING(open, high, low, close)
    data['CDLKICKINGBYLENGTH'] = talib.CDLKICKINGBYLENGTH(
        open, high, low, close)
    data['CDLLADDERBOTTOM'] = talib.CDLLADDERBOTTOM(open, high, low, close)
    data['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(open, high, low, close)
    data['CDLLONGLINE'] = talib.CDLLONGLINE(open, high, low, close)
    data['CDLMARUBOZU'] = talib.CDLMARUBOZU(open, high, low, close)
    data['CDLMATCHINGLOW'] = talib.CDLMATCHINGLOW(open, high, low, close)
    data['CDLMATHOLD'] = talib.CDLMATHOLD(open,
                                          high,
                                          low,
                                          close,
                                          penetration=0)

    data['CDLMORNINGDOJISTAR'] = talib.CDLMORNINGDOJISTAR(open,
                                                          high,
                                                          low,
                                                          close,
                                                          penetration=0)

    data['CDLMORNINGSTAR'] = talib.CDLMORNINGSTAR(open,
                                                  high,
                                                  low,
                                                  close,
                                                  penetration=0)

    data['CDLONNECK'] = talib.CDLONNECK(open, high, low, close)
    data['CDLPIERCING'] = talib.CDLPIERCING(open, high, low, close)
    data['CDLRICKSHAWMAN'] = talib.CDLRICKSHAWMAN(open, high, low, close)
    data['CDLRISEFALL3METHODS'] = talib.CDLRISEFALL3METHODS(
        open, high, low, close)
    data['CDLSEPARATINGLINES'] = talib.CDLSEPARATINGLINES(
        open, high, low, close)
    data['CDLSHOOTINGSTAR'] = talib.CDLSHOOTINGSTAR(open, high, low, close)
    data['CDLSHORTLINE'] = talib.CDLSHORTLINE(open, high, low, close)
    data['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(open, high, low, close)
    data['CDLSTALLEDPATTERN'] = talib.CDLSTALLEDPATTERN(open, high, low, close)
    data['CDLSTICKSANDWICH'] = talib.CDLSTICKSANDWICH(open, high, low, close)
    data['CDLTAKURI'] = talib.CDLTAKURI(open, high, low, close)
    data['CDLTASUKIGAP'] = talib.CDLTASUKIGAP(open, high, low, close)
    data['CDLTHRUSTING'] = talib.CDLTHRUSTING(open, high, low, close)
    data['CDLTRISTAR'] = talib.CDLTRISTAR(open, high, low, close)
    data['CDLUNIQUE3RIVER'] = talib.CDLUNIQUE3RIVER(open, high, low, close)
    data['CDLUPSIDEGAP2CROWS'] = talib.CDLUPSIDEGAP2CROWS(
        open, high, low, close)
    data['CDLXSIDEGAP3METHODS'] = talib.CDLXSIDEGAP3METHODS(
        open, high, low, close)
    #   data['ADX'] = talib.ADX(high, low, close, timeperiod=14)

    data['MACDFAS'], data['MACDSLO'], data['MACDSIGNA'] = talib.MACD(
        close, fastperiod=12, slowperiod=26, signalperiod=9)
    data['3day MA'] = close.shift(1).rolling(window=3).mean()
    data['10day MA'] = close.shift(1).rolling(window=10).mean()
    data['30day MA'] = close.shift(1).rolling(window=30).mean()
    data['RSI_9'] = talib.RSI(close.values, timeperiod=9)
    data['S_10'] = close.rolling(window=10).mean()
    data['Corr'] = close.rolling(window=10).corr(data['S_10'])
    data['Williams %R'] = talib.WILLR(data['High'].values, data['Low'].values,
                                      data['Close'].values, 7)

    return data
Esempio n. 15
0
def calcind(df):
    # Calculate indicators and interpret them into buy or sell signals
    # Note 1:  If the dataframe is not sorted in timeframe order, the results will be worthless
    # Note 2:  The dataframe must have the following OHLCV attributes at a minimum:
    #   {
    #       "o": 100            <-- open value
    #       "h": 150            <-- high value
    #       "l": 90             <-- low value
    #       "c": 110            <-- close value
    #       "v": 3000           <-- volume value
    #   }

    if not df.empty:
        # calculate the technical indicators if there is data to do so
        # Ref:  https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html

        # Momentum indicators
        df['ADX14'] = ta.ADX(df['h'], df['l'], df['c'])
        df['ADXR14'] = ta.ADXR(df['h'], df['l'], df['c'])
        df['APO12'] = ta.APO(df['c'], fastperiod=12, slowperiod=26, matype=0)
        df['AROONUP'], df['AROONDN'] = ta.AROON(df['h'],
                                                df['l'],
                                                timeperiod=14)
        df['BOP'] = ta.BOP(df['o'], df['h'], df['l'], df['c'])
        df['CCI14'] = ta.CCI(df['h'], df['l'], df['c'], timeperiod=14)
        df['CMO14'] = ta.CMO(df['c'], timeperiod=14)
        df['DX14'] = ta.DX(df['h'], df['l'], df['c'], timeperiod=14)
        df['MACD'], df['MACDSIG'], df['MACDHIST'] = ta.MACD(df['c'],
                                                            fastperiod=12,
                                                            slowperiod=26,
                                                            signalperiod=9)
        df['MFI4'] = ta.MFI(df['h'], df['l'], df['c'], df['v'], timeperiod=14)
        df['MOM10'] = ta.MOM(df['c'], timeperiod=10)
        df['PPO12'] = ta.PPO(df['c'], fastperiod=12, slowperiod=26, matype=0)
        df['ROC10'] = ta.MOM(df['c'], timeperiod=10)
        df['RSI14'] = ta.RSI(df['c'], timeperiod=14)
        df['STOCHK'], df['STOCHD'] = ta.STOCH(df['h'],
                                              df['l'],
                                              df['c'],
                                              fastk_period=5,
                                              slowk_period=3,
                                              slowk_matype=0,
                                              slowd_period=3,
                                              slowd_matype=0)
        df['STOCHRSIK'], df['STOCHRSID'] = ta.STOCHRSI(df['c'],
                                                       timeperiod=14,
                                                       fastk_period=5,
                                                       fastd_period=3,
                                                       fastd_matype=0)
        df['TRIX30'] = ta.TRIX(df['c'], timeperiod=30)
        df['ULTOSC'] = ta.ULTOSC(df['h'],
                                 df['l'],
                                 df['c'],
                                 timeperiod1=7,
                                 timeperiod2=14,
                                 timeperiod3=28)

        # Moving Average or Overlap functions
        df['BBUPPER'], df['BBMID'], df['BBLOWER'] = ta.BBANDS(df['c'],
                                                              timeperiod=5,
                                                              nbdevup=2,
                                                              nbdevdn=2,
                                                              matype=0)
        df['EMA14'] = ta.EMA(df['c'], timeperiod=14)
        df['SMA14'] = ta.SMA(df['c'], timeperiod=14)

        # Volume Indicators
        df['AD'] = ta.AD(df['h'], df['l'], df['c'], df['v'])
        df['ADOSC'] = ta.ADOSC(df['h'],
                               df['l'],
                               df['c'],
                               df['v'],
                               fastperiod=3,
                               slowperiod=10)
        df['OBV'] = ta.OBV(df['c'], df['v'])

        # Candlestick Patterns
        df['DJI'] = ta.CDLDOJI(df['o'], df['h'], df['l'], df['c'])
        df['ENG'] = ta.CDLENGULFING(df['o'], df['h'], df['l'], df['c'])
        df['HMR'] = ta.CDLHAMMER(df['o'], df['h'], df['l'], df['c'])
        df['HGM'] = ta.CDLHANGINGMAN(df['o'], df['h'], df['l'], df['c'])
        df['PRC'] = ta.CDLPIERCING(df['o'], df['h'], df['l'], df['c'])
        df['DCC'] = ta.CDLDARKCLOUDCOVER(df['o'],
                                         df['h'],
                                         df['l'],
                                         df['c'],
                                         penetration=0)
        df['MSR'] = ta.CDLMORNINGSTAR(df['o'],
                                      df['h'],
                                      df['l'],
                                      df['c'],
                                      penetration=0)
        df['ESR'] = ta.CDLEVENINGSTAR(df['o'],
                                      df['h'],
                                      df['l'],
                                      df['c'],
                                      penetration=0)
        df['KKR'] = ta.CDLKICKING(df['o'], df['h'], df['l'], df['c'])
        df['SSR'] = ta.CDLSHOOTINGSTAR(df['o'], df['h'], df['l'], df['c'])
        df['IHM'] = ta.CDLINVERTEDHAMMER(df['o'], df['h'], df['l'], df['c'])
        df['TWS'] = ta.CDL3WHITESOLDIERS(df['o'], df['h'], df['l'], df['c'])
        df['TBC'] = ta.CDL3BLACKCROWS(df['o'], df['h'], df['l'], df['c'])
        df['STP'] = ta.CDLSPINNINGTOP(df['o'], df['h'], df['l'], df['c'])

        # ADX Trend Strength
        df['ADXTREND'] = 'Weak'
        df.loc[df['ADX14'] >= 25, 'ADXTREND'] = 'Changing'
        df.loc[df['ADX14'] >= 50, 'ADXTREND'] = 'Strong'
        df.loc[df['ADX14'] >= 75, 'ADXTREND'] = 'Very Strong'

        # ADXR Trend Strength
        df['ADXRTREND'] = 'Weak'
        df.loc[df['ADXR14'] >= 25, 'ADXRTREND'] = 'Changing'
        df.loc[df['ADXR14'] >= 50, 'ADXRTREND'] = 'Strong'
        df.loc[df['ADXR14'] >= 75, 'ADXRTREND'] = 'Very Strong'

        # AROON Oscillator
        df['AROONOSC'] = df['AROONDN'] - df['AROONUP']
        df['AROONVOTE'] = 0
        df.loc[df['AROONOSC'] >= 25,
               'AROONVOTE'] = 1  # This threshold is a guess
        df.loc[df['AROONOSC'] <= -25,
               'AROONVOTE'] = -1  # This threshold is a guess

        # BOP Signal
        df['BOPVOTE'] = 0
        df.loc[(df['BOP'] > 0), 'BOPVOTE'] = 1
        df.loc[(df['BOP'] < 0), 'BOPVOTE'] = -1

        # CCI Vote
        df['CCIVOTE'] = 0
        df.loc[df['CCI14'] >= 100, 'CCIVOTE'] = 1
        df.loc[df['CCI14'] <= -100, 'CCIVOTE'] = -1

        # CMO Votes
        df['CMOVOTE'] = 0
        df.loc[df['CMO14'] < -50, 'CMOVOTE'] = 1
        df.loc[df['CMO14'] > 50, 'CMOVOTE'] = -1

        # MACD Vote; based on when the histogram crosses the zero line
        df['MACDVOTE'] = 0
        df.loc[(df['MACDHIST'] > 0) &
               (df['MACDHIST'].shift(periods=-1) < df['MACDHIST']),
               'MACDVOTE'] = 1
        df.loc[(df['MACDHIST'] < 0) &
               (df['MACDHIST'].shift(periods=-1) > df['MACDHIST']),
               'MACDVOTE'] = -1
        df.loc[df['MACDHIST'] == 0, 'MACDVOTE'] = 0

        # MFI Votes
        # Skipping interpretting MFI because it correlates to the direction of price

        # MOM Votes
        # Skipping basic momentum because it's not a good signal for buy or sell

        # PPO Votes; cousin of MACD
        df['PPOVOTE'] = 0
        #df.loc[df['PPO12'] >= 0, 'RSIVOTE'] = 1
        #df.loc[df['PPO12'] <= 0, 'RSIVOTE'] = -1

        # ROC Votes
        # Not using ROC because it's prone to whipsaws near the 0 line; and, this isn't used to trade

        # RSI Votes
        df['RSIVOTE'] = 0
        df.loc[df['RSI14'] >= 70, 'RSIVOTE'] = -1
        df.loc[df['RSI14'] <= 30, 'RSIVOTE'] = 1

        # STOCH Votes
        df['STOCHVOTE'] = 0
        df.loc[(df['STOCHK'] >= 80) & (df['STOCHD'] >= 80), 'STOCHVOTE'] = -1
        df.loc[(df['STOCHK'] <= 20) & (df['STOCHD'] <= 20), 'STOCHVOTE'] = 1

        # STOCHRSI Votes
        df['STOCHRSIVOTE'] = 0
        df.loc[(df['STOCHRSIK'] >= 80) & (df['STOCHRSID'] >= 80),
               'STOCHRSIVOTE'] = -1
        df.loc[(df['STOCHRSIK'] <= 20) & (df['STOCHRSID'] <= 20),
               'STOCHRSIVOTE'] = 1

        # TRIX Votes
        df['TRIXVOTE'] = 0
        df.loc[df['TRIX30'] > 0, 'TRIXVOTE'] = 1
        df.loc[df['TRIX30'] < 0, 'TRIXVOTE'] = -1

        # ULTOSC Votes
        # I'm skipping this oscillator because the buy/sell conditions are three-pronged and not clear

        # ADOSC Votes
        df['ADOSCVOTE'] = 0
        df.loc[df['ADOSC'] > 0, 'ADOSCVOTE'] = 1
        df.loc[df['ADOSC'] < 0, 'ADOSCVOTE'] = -1

        # Drop rows where there isn't enough information to vote
        # Note 1:  TRIX30 should be cleaned up, but the period is too long and it removes too much data.
        # Note 2:  MACD has a long period as well and will essentially eliminate trading before 10:00 AM
        df.dropna(subset=[
            'AROONUP', 'AROONDN', 'BOP', 'CCI14', 'CMO14', 'MACDHIST', 'PPO12',
            'RSI14', 'STOCHK', 'STOCHD', 'STOCHRSIK', 'STOCHRSID', 'ADOSC'
        ],
                  inplace=True)

        for x in df.index:
            #print (df.loc[x, 'STRATEGY_ID'][0])
            a = chr(66 + df.loc[x, 'AROONVOTE'])
            b = chr(66 + df.loc[x, 'BOPVOTE'])
            c = chr(66 + df.loc[x, 'CCIVOTE'])
            d = chr(66 + df.loc[x, 'CMOVOTE'])
            e = chr(66 + df.loc[x, 'MACDVOTE'])
            f = chr(66 + df.loc[x, 'PPOVOTE'])
            g = chr(66 + df.loc[x, 'RSIVOTE'])
            h = chr(66 + df.loc[x, 'STOCHVOTE'])
            i = chr(66 + df.loc[x, 'STOCHRSIVOTE'])
            j = chr(66 + df.loc[x, 'TRIXVOTE'])
            k = chr(66 + df.loc[x, 'ADOSCVOTE'])
            df.loc[x,
                   'STRATEGY_ID'] = a + b + c + d + e + f + g + h + i + j + k

        return df
Esempio n. 16
0
 def CDLSPINNINGTOP(self):
     integer = talib.CDLSPINNINGTOP(self.open, self.high, self.low, self.close)
     return integer
Esempio n. 17
0
def data_construct(DataFrame, lookUp, predictionWindow, pairName):
    '''function to construct the features from the inspection window and to create the supervised x,y pairs for training.

    Parameters
    ----------
    DataFrame : dataFrame
    LookUp : int
    predictionWindow : int
    pairName : str

    Returns
    -------
    output : dict
        a dict containing inputs matrix, targets matrix, raw inputs and mapping dict for features

    '''
    # fetch data for indicators calculations
    openPrice = DataFrame.o.values.astype("double")
    closePrice = DataFrame.c.values.astype("double")
    highPrice = DataFrame.h.values.astype("double")
    lowPrice = DataFrame.l.values.astype("double")
    volume = DataFrame.volume.values.astype("double")

    # calculate technical indicators values
    simple_ma_slow = ta.SMA(closePrice, 30)  # slow moving average
    simple_ma_fast = ta.SMA(closePrice, 15)  # fast moving average
    exp_ma_slow = ta.EMA(closePrice, 20)  # slow exp moving average
    exp_ma_fast = ta.EMA(closePrice, 10)  # fast exp moving average
    bbands = ta.BBANDS(closePrice, timeperiod=15)  # calculate bollinger bands
    deltaBands = (bbands[0] - bbands[2]
                  ) / bbands[2]  # deltas between bands vector (bollinger)
    macd_s1, macd_s2, macd_hist = ta.MACD(
        closePrice)  # MACD values calculation
    sar = ta.SAR(highPrice, lowPrice)  # prabolic SAR
    stochK, stochD = ta.STOCH(highPrice, lowPrice,
                              closePrice)  # stochastic calculations
    rsi = ta.RSI(closePrice, timeperiod=15)  # RSI indicator
    adx = ta.ADX(highPrice, lowPrice, closePrice,
                 timeperiod=15)  # ADX indicator
    mfi = ta.MFI(highPrice, lowPrice, closePrice, volume,
                 timeperiod=15)  # money flow index

    # calculate statistical indicators values
    beta = ta.BETA(highPrice, lowPrice, timeperiod=5)  # beta from CAPM model
    slope = ta.LINEARREG_ANGLE(
        closePrice,
        timeperiod=5)  # slope for fitting linera reg. to the last x points

    # calculate candle indicators values
    spinTop = ta.CDLSPINNINGTOP(openPrice, highPrice, lowPrice, closePrice)
    doji = ta.CDLDOJI(openPrice, highPrice, lowPrice, closePrice)
    dojiStar = ta.CDLDOJISTAR(openPrice, highPrice, lowPrice, closePrice)
    marubozu = ta.CDLMARUBOZU(openPrice, highPrice, lowPrice, closePrice)
    hammer = ta.CDLHAMMER(openPrice, highPrice, lowPrice, closePrice)
    invHammer = ta.CDLINVERTEDHAMMER(openPrice, highPrice, lowPrice,
                                     closePrice)
    hangingMan = ta.CDLHANGINGMAN(openPrice, highPrice, lowPrice, closePrice)
    shootingStar = ta.CDLSHOOTINGSTAR(openPrice, highPrice, lowPrice,
                                      closePrice)
    engulfing = ta.CDLENGULFING(openPrice, highPrice, lowPrice, closePrice)
    morningStar = ta.CDLMORNINGSTAR(openPrice, highPrice, lowPrice, closePrice)
    eveningStar = ta.CDLEVENINGSTAR(openPrice, highPrice, lowPrice, closePrice)
    whiteSoldier = ta.CDL3WHITESOLDIERS(openPrice, highPrice, lowPrice,
                                        closePrice)
    blackCrow = ta.CDL3BLACKCROWS(openPrice, highPrice, lowPrice, closePrice)
    insideThree = ta.CDL3INSIDE(openPrice, highPrice, lowPrice, closePrice)

    # prepare the final matrix
    '''
    matrix configurations ::> [o,c,h,l,ma_slow,ma_fast,exp_slow,exp_fast,
                           deltaBands,macd_s1,macd_s2,sar,stochK,
                           stochD,rsi,adx,mfi,beta,slope,spinTop,doji,dojiStar,
                           marubozu,hammer,invHammer,hangingMan,shootingStar,engulfing,
                           morningStar,eveningStar,whiteSoldier,blackCrow,insideThree]
    a 33 features matrix in total
    '''
    DataMatrix = np.column_stack(
        (openPrice, closePrice, highPrice, lowPrice, simple_ma_slow,
         simple_ma_fast, exp_ma_slow, exp_ma_fast, deltaBands, macd_s1,
         macd_s2, sar, stochK, stochD, rsi, adx, mfi, beta, slope, spinTop,
         doji, dojiStar, marubozu, hammer, invHammer, hangingMan, shootingStar,
         engulfing, morningStar, eveningStar, whiteSoldier, blackCrow,
         insideThree))

    # remove undifined values
    DataMatrix = DataMatrix[~np.isnan(DataMatrix).any(
        axis=1)]  # remove all raws containing nan values

    # define number of windows to analyze
    framesCount = DataMatrix.shape[0] - (
        lookUp +
        predictionWindow) + 1  # 1D convolution outputsize = ceil[((n-f)/s)+1]

    # define input/output arrays container
    rawInputs = {}
    inputsOpen = np.zeros((framesCount, lookUp))
    inputsClose = np.zeros((framesCount, lookUp))
    inputsHigh = np.zeros((framesCount, lookUp))
    inputsLow = np.zeros((framesCount, lookUp))
    inputs = np.zeros((framesCount, 62))
    outputs = np.zeros((framesCount, 1))

    # main loop and data
    for i in range(framesCount):
        mainFrame = DataMatrix[i:i + lookUp + predictionWindow, :]
        window = np.array_split(mainFrame, [lookUp])[0]
        windowForecast = np.array_split(mainFrame, [lookUp])[1]
        '''
        window configurations ::>
        [0:o,1:c,2:h,3:l,4:ma_slow,5:ma_fast,6:exp_slow,7:exp_fast,
         8:deltaBands,9:macd_slow,10:macd_fast,11:sar,12:stochK,
         13:stochD,14:rsi,15:adx,16:mfi,17:beta,18:slope,19:spinTop,20:doji,21:dojiStar,
         22:marubozu,23:hammer,24:invHammer,25:hangingMan,26:shootingStar,27:engulfing,
         28:morningStar,29:eveningStar,30:whiteSoldier,31:blackCrow,32:insideThree]
        '''

        #sma features detection
        ma_slow = window[:, 4]
        ma_fast = window[:, 5]
        uptrend_cross = ma_fast > ma_slow
        uptrend_cross = np.concatenate(
            (np.array([False]),
             (uptrend_cross[:-1] <
              uptrend_cross[1:])))  # check the false->true transition
        try:
            uptrend_cross_location = np.where(uptrend_cross == True)[0][
                -1]  # latest uptrend cross_over location
        except:
            uptrend_cross_location = -1
        downtrend_cross = ma_slow > ma_fast
        downtrend_cross = np.concatenate(
            (np.array([False]),
             (downtrend_cross[:-1] <
              downtrend_cross[1:])))  # check the false->true transition
        try:
            downtrend_cross_location = np.where(downtrend_cross == True)[0][
                -1]  # latest downtrend cross_over location
        except:
            downtrend_cross_location = -1
        if (uptrend_cross_location >
                downtrend_cross_location):  # latest cross is an uptrend
            sma_latest_crossover = 1  # uptrend sign
            sma_location_of_latest_crossover = uptrend_cross_location
            alpha_1 = (math.atan(ma_slow[uptrend_cross_location] -
                                 ma_slow[uptrend_cross_location - 1])) * (
                                     180 / math.pi)
            alpha_2 = (math.atan(ma_fast[uptrend_cross_location] -
                                 ma_fast[uptrend_cross_location - 1])) * (
                                     180 / math.pi)
            sma_latest_crossover_angle = alpha_1 + alpha_2
        elif (downtrend_cross_location >
              uptrend_cross_location):  # latest cross is a downtrend
            sma_latest_crossover = -1  # downtrend sign
            sma_location_of_latest_crossover = downtrend_cross_location
            alpha_1 = (math.atan(ma_slow[downtrend_cross_location] -
                                 ma_slow[downtrend_cross_location - 1])) * (
                                     180 / math.pi)
            alpha_2 = (math.atan(ma_fast[downtrend_cross_location] -
                                 ma_fast[downtrend_cross_location - 1])) * (
                                     180 / math.pi)
            sma_latest_crossover_angle = alpha_1 + alpha_2
        else:  # no cross in the given window
            sma_latest_crossover = 0  # no sign
            sma_location_of_latest_crossover = -1
            sma_latest_crossover_angle = 0
        up_count = np.sum(ma_fast > ma_slow)
        down_count = np.sum(ma_slow > ma_fast)
        if (up_count > down_count):
            sma_dominant_type_fast_slow = 1
        elif (down_count > up_count):
            sma_dominant_type_fast_slow = -1
        else:
            sma_dominant_type_fast_slow = 0

        #ema features detection
        exp_slow = window[:, 6]
        exp_fast = window[:, 7]
        uptrend_cross = exp_fast > exp_slow
        uptrend_cross = np.concatenate(
            (np.array([False]),
             (uptrend_cross[:-1] <
              uptrend_cross[1:])))  # check the false->true transition
        try:
            uptrend_cross_location = np.where(uptrend_cross == True)[0][
                -1]  # latest uptrend cross_over location
        except:
            uptrend_cross_location = -1
        downtrend_cross = exp_slow > exp_fast
        downtrend_cross = np.concatenate(
            (np.array([False]),
             (downtrend_cross[:-1] <
              downtrend_cross[1:])))  # check the false->true transition
        try:
            downtrend_cross_location = np.where(downtrend_cross == True)[0][
                -1]  # latest downtrend cross_over location
        except:
            downtrend_cross_location = -1
        if (uptrend_cross_location >
                downtrend_cross_location):  # latest cross is an uptrend
            ema_latest_crossover = 1  # uptrend sign
            ema_location_of_latest_crossover = uptrend_cross_location
            alpha_1 = (math.atan(exp_slow[uptrend_cross_location] -
                                 exp_slow[uptrend_cross_location - 1])) * (
                                     180 / math.pi)
            alpha_2 = (math.atan(exp_fast[uptrend_cross_location] -
                                 exp_fast[uptrend_cross_location - 1])) * (
                                     180 / math.pi)
            ema_latest_crossover_angle = alpha_1 + alpha_2
        elif (downtrend_cross_location >
              uptrend_cross_location):  # latest cross is a downtrend
            ema_latest_crossover = -1  # downtrend sign
            ema_location_of_latest_crossover = downtrend_cross_location
            alpha_1 = (math.atan(exp_slow[downtrend_cross_location] -
                                 exp_slow[downtrend_cross_location - 1])) * (
                                     180 / math.pi)
            alpha_2 = (math.atan(exp_fast[downtrend_cross_location] -
                                 exp_fast[downtrend_cross_location - 1])) * (
                                     180 / math.pi)
            ema_latest_crossover_angle = alpha_1 + alpha_2
        else:  # no cross in the given window
            ema_latest_crossover = 0  # no sign
            ema_location_of_latest_crossover = -1
            ema_latest_crossover_angle = 0
        up_count = np.sum(exp_fast > exp_slow)
        down_count = np.sum(exp_slow > exp_fast)
        if (up_count > down_count):
            ema_dominant_type_fast_slow = 1
        elif (down_count > up_count):
            ema_dominant_type_fast_slow = -1
        else:
            ema_dominant_type_fast_slow = 0

        # B.Bands features detection
        deltaBands = window[:, 8]
        deltaBands_mean = np.mean(deltaBands)
        deltaBands_std = np.std(deltaBands)
        deltaBands_maximum_mean = np.amax(deltaBands) / deltaBands_mean
        deltaBands_maximum_location = np.where(
            deltaBands == np.amax(deltaBands))[0][-1]  # location of maximum
        deltaBands_minimum_mean = np.amin(deltaBands) / deltaBands_mean
        deltaBands_minimum_location = np.where(
            deltaBands == np.amin(deltaBands))[0][-1]  # location of maximum

        # macd features detection
        macd_slow = window[:, 9]
        macd_fast = window[:, 10]
        uptrend_cross = macd_fast > macd_slow
        uptrend_cross = np.concatenate(
            (np.array([False]),
             (uptrend_cross[:-1] <
              uptrend_cross[1:])))  # check the false->true transition
        try:
            uptrend_cross_location = np.where(uptrend_cross == True)[0][
                -1]  # latest uptrend cross_over location
        except:
            uptrend_cross_location = -1
        downtrend_cross = macd_slow > macd_fast
        downtrend_cross = np.concatenate(
            (np.array([False]),
             (downtrend_cross[:-1] <
              downtrend_cross[1:])))  # check the false->true transition
        try:
            downtrend_cross_location = np.where(downtrend_cross == True)[0][
                -1]  # latest downtrend cross_over location
        except:
            downtrend_cross_location = -1
        if (uptrend_cross_location >
                downtrend_cross_location):  # latest cross is an uptrend
            macd_latest_crossover = 1  # uptrend sign
            macd_location_of_latest_crossover = uptrend_cross_location
            alpha_1 = (math.atan(macd_slow[uptrend_cross_location] -
                                 macd_slow[uptrend_cross_location - 1])) * (
                                     180 / math.pi)
            alpha_2 = (math.atan(macd_fast[uptrend_cross_location] -
                                 macd_fast[uptrend_cross_location - 1])) * (
                                     180 / math.pi)
            macd_latest_crossover_angle = alpha_1 + alpha_2
        elif (downtrend_cross_location >
              uptrend_cross_location):  # latest cross is a downtrend
            macd_latest_crossover = -1  # downtrend sign
            macd_location_of_latest_crossover = downtrend_cross_location
            alpha_1 = (math.atan(macd_slow[downtrend_cross_location] -
                                 macd_slow[downtrend_cross_location - 1])) * (
                                     180 / math.pi)
            alpha_2 = (math.atan(macd_fast[downtrend_cross_location] -
                                 macd_fast[downtrend_cross_location - 1])) * (
                                     180 / math.pi)
            macd_latest_crossover_angle = alpha_1 + alpha_2
        else:  # no cross in the given window
            macd_latest_crossover = 0  # no sign
            macd_location_of_latest_crossover = -1
            macd_latest_crossover_angle = 0
        up_count = np.sum(macd_fast > macd_slow)
        down_count = np.sum(macd_slow > macd_fast)
        if (up_count > down_count):
            macd_dominant_type_fast_slow = 1
        elif (down_count > up_count):
            macd_dominant_type_fast_slow = -1
        else:
            macd_dominant_type_fast_slow = 0

        # sar features detection
        average_price = (window[:, 0] + window[:, 1] + window[:, 2] +
                         window[:, 3]) / 4
        sar = window[:, 11]
        uptrend = sar < average_price
        uptrend = np.concatenate(
            (np.array([False]),
             (uptrend[:-1] < uptrend[1:])))  # check the false->true transition
        try:
            uptrend_location = np.where(
                uptrend == True)[0][-1]  # latest uptrend location
        except:
            uptrend_location = -1
        downtrend = sar > average_price
        downtrend = np.concatenate(
            (np.array([False]),
             (downtrend[:-1] <
              downtrend[1:])))  # check the false->true transition
        try:
            downtrend_location = np.where(
                downtrend == True)[0][-1]  # latest downtrend location
        except:
            downtrend_location = -1
        if (uptrend_location >
                downtrend_location):  # latest signal is an uptrend
            sar_latest_shiftPoint = 1
            sar_latest_shiftPoint_location = uptrend_location
        elif (downtrend_location >
              uptrend_location):  # latest signal is a downtrend
            sar_latest_shiftPoint = -1
            sar_latest_shiftPoint_location = downtrend_location
        else:  # same direction along the frame under question
            sar_latest_shiftPoint = 0  # no sign
            sar_latest_shiftPoint_location = -1
        sar_total_number_shifts = np.where(
            downtrend == True)[0].shape[0] + np.where(
                uptrend == True)[0].shape[0]

        # stochastic(K) features detection
        stochK = window[:, 12]
        stochK_mean = np.mean(stochK)
        stochK_std = np.std(stochK)
        uptrend = stochK <= 20
        uptrend = np.concatenate(
            (np.array([False]),
             (uptrend[:-1] < uptrend[1:])))  # check the false->true transition
        try:
            uptrend_location = np.where(
                uptrend == True)[0][-1]  # latest uptrend location
        except:
            uptrend_location = -1
        downtrend = stochK >= 80
        downtrend = np.concatenate(
            (np.array([False]),
             (downtrend[:-1] <
              downtrend[1:])))  # check the false->true transition
        try:
            downtrend_location = np.where(
                downtrend == True)[0][-1]  # latest downtrend location
        except:
            downtrend_location = -1
        if (uptrend_location >
                downtrend_location):  # latest signal is an uptrend
            stochK_latest_event = 1
            stochK_event_location = uptrend_location
        elif (downtrend_location >
              uptrend_location):  # latest signal is a downtrend
            stochK_latest_event = -1
            stochK_event_location = downtrend_location
        else:  # same direction along the frame under question
            stochK_latest_event = 0  # no sign
            stochK_event_location = -1

        # stochastic(D) features detection
        stochD = window[:, 13]
        stochD_mean = np.mean(stochD)
        stochD_std = np.std(stochD)
        uptrend = stochD <= 20
        uptrend = np.concatenate(
            (np.array([False]),
             (uptrend[:-1] < uptrend[1:])))  # check the false->true transition
        try:
            uptrend_location = np.where(
                uptrend == True)[0][-1]  # latest uptrend location
        except:
            uptrend_location = -1
        downtrend = stochD >= 80
        downtrend = np.concatenate(
            (np.array([False]),
             (downtrend[:-1] <
              downtrend[1:])))  # check the false->true transition
        try:
            downtrend_location = np.where(
                downtrend == True)[0][-1]  # latest downtrend location
        except:
            downtrend_location = -1
        if (uptrend_location >
                downtrend_location):  # latest signal is an uptrend
            stochD_latest_event = 1
            stochD_event_location = uptrend_location
        elif (downtrend_location >
              uptrend_location):  # latest signal is a downtrend
            stochD_latest_event = -1
            stochD_event_location = downtrend_location
        else:  # same direction along the frame under question
            stochD_latest_event = 0  # no sign
            stochD_event_location = -1

        # rsi features detection
        rsi = window[:, 14]
        rsi_mean = np.mean(rsi)
        rsi_std = np.std(rsi)
        uptrend = rsi <= 30
        uptrend = np.concatenate(
            (np.array([False]),
             (uptrend[:-1] < uptrend[1:])))  # check the false->true transition
        try:
            uptrend_location = np.where(
                uptrend == True)[0][-1]  # latest uptrend location
        except:
            uptrend_location = -1
        downtrend = rsi >= 70
        downtrend = np.concatenate(
            (np.array([False]),
             (downtrend[:-1] <
              downtrend[1:])))  # check the false->true transition
        try:
            downtrend_location = np.where(
                downtrend == True)[0][-1]  # latest downtrend location
        except:
            downtrend_location = -1
        if (uptrend_location >
                downtrend_location):  # latest signal is an uptrend
            rsi_latest_event = 1
            rsi_event_location = uptrend_location
        elif (downtrend_location >
              uptrend_location):  # latest signal is a downtrend
            rsi_latest_event = -1
            rsi_event_location = downtrend_location
        else:  # same direction along the frame under question
            rsi_latest_event = 0  # no sign
            rsi_event_location = -1

        # adx features detection
        adx = window[:, 15]
        adx_mean = np.mean(adx)
        adx_std = np.std(adx)
        splitted_array = np.array_split(adx, 2)
        m0 = np.mean(splitted_array[0])
        m1 = np.mean(splitted_array[1])
        adx_mean_delta_bet_first_second_half = (m1 - m0) / m0

        # mfi features detection
        mfi = window[:, 16]
        mfi_mean = np.mean(mfi)
        mfi_std = np.std(mfi)
        splitted_array = np.array_split(mfi, 2)
        m0 = np.mean(splitted_array[0])
        m1 = np.mean(splitted_array[1])
        mfi_mean_delta_bet_first_second_half = (m1 - m0) / m0

        # resistance levels features detection
        closePrice = window[:, 1]
        resLevels = argrelextrema(closePrice, np.greater, order=4)[0]
        if (resLevels.shape[0] == 0):
            relation_r1_close = 0
            relation_r2_close = 0
            relation_r3_close = 0
        elif (resLevels.shape[0] == 1):
            relation_r1_close = (closePrice[-1] -
                                 closePrice[resLevels[-1]]) / closePrice[-1]
            relation_r2_close = 0
            relation_r3_close = 0
        elif (resLevels.shape[0] == 2):
            relation_r1_close = (closePrice[-1] -
                                 closePrice[resLevels[-1]]) / closePrice[-1]
            relation_r2_close = (closePrice[-1] -
                                 closePrice[resLevels[-2]]) / closePrice[-1]
            relation_r3_close = 0
        else:
            relation_r1_close = (closePrice[-1] -
                                 closePrice[resLevels[-1]]) / closePrice[-1]
            relation_r2_close = (closePrice[-1] -
                                 closePrice[resLevels[-2]]) / closePrice[-1]
            relation_r3_close = (closePrice[-1] -
                                 closePrice[resLevels[-3]]) / closePrice[-1]

        # support levels features detection
        closePrice = window[:, 1]
        supLevels = argrelextrema(closePrice, np.less, order=4)[0]
        if (supLevels.shape[0] == 0):
            relation_s1_close = 0
            relation_s2_close = 0
            relation_s3_close = 0
        elif (supLevels.shape[0] == 1):
            relation_s1_close = (closePrice[-1] -
                                 closePrice[supLevels[-1]]) / closePrice[-1]
            relation_s2_close = 0
            relation_s3_close = 0
        elif (supLevels.shape[0] == 2):
            relation_s1_close = (closePrice[-1] -
                                 closePrice[supLevels[-1]]) / closePrice[-1]
            relation_s2_close = (closePrice[-1] -
                                 closePrice[supLevels[-2]]) / closePrice[-1]
            relation_s3_close = 0
        else:
            relation_s1_close = (closePrice[-1] -
                                 closePrice[supLevels[-1]]) / closePrice[-1]
            relation_s2_close = (closePrice[-1] -
                                 closePrice[supLevels[-2]]) / closePrice[-1]
            relation_s3_close = (closePrice[-1] -
                                 closePrice[supLevels[-3]]) / closePrice[-1]

        # slope features detection
        slope = window[:, 18]
        slope_mean = np.mean(slope)

        # beta features detection
        beta = window[:, 17]
        beta_mean = np.mean(beta)
        beta_std = np.std(beta)

        # spinTop features detection    np.sum(np.where(a==1)[0])
        count100plus = np.sum(np.where(window[:, 19] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 19] == -100)[0])) * -1
        spinTop_number_occurrence = count100plus + count100minus

        # doji features detection
        count100plus = np.sum(np.where(window[:, 20] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 20] == -100)[0])) * -1
        doji_number_occurrence = count100plus + count100minus

        # dojiStar features detection
        count100plus = np.sum(np.where(window[:, 21] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 21] == -100)[0])) * -1
        dojiStar_number_occurrence = count100plus + count100minus

        # marubozu features detection
        count100plus = np.sum(np.where(window[:, 22] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 22] == -100)[0])) * -1
        marubozu_number_occurrence = count100plus + count100minus

        # hammer features detection
        count100plus = np.sum(np.where(window[:, 23] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 23] == -100)[0])) * -1
        hammer_number_occurrence = count100plus + count100minus

        # invHammer features detection
        count100plus = np.sum(np.where(window[:, 24] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 24] == -100)[0])) * -1
        invHammer_number_occurrence = count100plus + count100minus

        # hangingMan features detection
        count100plus = np.sum(np.where(window[:, 25] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 25] == -100)[0])) * -1
        hangingMan_number_occurrence = count100plus + count100minus

        # shootingStar features detection
        count100plus = np.sum(np.where(window[:, 26] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 26] == -100)[0])) * -1
        shootingStar_number_occurrence = count100plus + count100minus

        # engulfing features detection
        count100plus = np.sum(np.where(window[:, 27] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 27] == -100)[0])) * -1
        engulfing_number_occurrence = count100plus + count100minus

        # morningStar features detection
        count100plus = np.sum(np.where(window[:, 28] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 28] == -100)[0])) * -1
        morningStar_number_occurrence = count100plus + count100minus

        # eveningStar features detection
        count100plus = np.sum(np.where(window[:, 29] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 29] == -100)[0])) * -1
        eveningStar_number_occurrence = count100plus + count100minus

        # whiteSoldier features detection
        count100plus = np.sum(np.where(window[:, 30] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 30] == -100)[0])) * -1
        whiteSoldier_number_occurrence = count100plus + count100minus

        # blackCrow features detection
        count100plus = np.sum(np.where(window[:, 31] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 31] == -100)[0])) * -1
        blackCrow_number_occurrence = count100plus + count100minus

        # insideThree features detection
        count100plus = np.sum(np.where(window[:, 32] == 100)[0])
        count100minus = (np.sum(np.where(window[:, 32] == -100)[0])) * -1
        insideThree_number_occurrence = count100plus + count100minus

        # fill the inputs matrix
        inputs[i, 0] = sma_latest_crossover
        inputs[i, 1] = sma_location_of_latest_crossover
        inputs[i, 2] = sma_latest_crossover_angle
        inputs[i, 3] = sma_dominant_type_fast_slow
        inputs[i, 4] = ema_latest_crossover
        inputs[i, 5] = ema_location_of_latest_crossover
        inputs[i, 6] = ema_latest_crossover_angle
        inputs[i, 7] = ema_dominant_type_fast_slow
        inputs[i, 8] = deltaBands_mean
        inputs[i, 9] = deltaBands_std
        inputs[i, 10] = deltaBands_maximum_mean
        inputs[i, 11] = deltaBands_maximum_location
        inputs[i, 12] = deltaBands_minimum_mean
        inputs[i, 13] = deltaBands_minimum_location
        inputs[i, 14] = macd_latest_crossover
        inputs[i, 15] = macd_location_of_latest_crossover
        inputs[i, 16] = macd_latest_crossover_angle
        inputs[i, 17] = macd_dominant_type_fast_slow
        inputs[i, 18] = sar_latest_shiftPoint
        inputs[i, 19] = sar_latest_shiftPoint_location
        inputs[i, 20] = sar_total_number_shifts
        inputs[i, 21] = stochK_mean
        inputs[i, 22] = stochK_std
        inputs[i, 23] = stochK_latest_event
        inputs[i, 24] = stochK_event_location
        inputs[i, 25] = stochD_mean
        inputs[i, 26] = stochD_std
        inputs[i, 27] = stochD_latest_event
        inputs[i, 28] = stochD_event_location
        inputs[i, 29] = rsi_mean
        inputs[i, 30] = rsi_std
        inputs[i, 31] = rsi_latest_event
        inputs[i, 32] = rsi_event_location
        inputs[i, 33] = adx_mean
        inputs[i, 34] = adx_std
        inputs[i, 35] = adx_mean_delta_bet_first_second_half
        inputs[i, 36] = mfi_mean
        inputs[i, 37] = mfi_std
        inputs[i, 38] = mfi_mean_delta_bet_first_second_half
        inputs[i, 39] = relation_r1_close
        inputs[i, 40] = relation_r2_close
        inputs[i, 41] = relation_r3_close
        inputs[i, 42] = relation_s1_close
        inputs[i, 43] = relation_s2_close
        inputs[i, 44] = relation_s3_close
        inputs[i, 45] = slope_mean
        inputs[i, 46] = beta_mean
        inputs[i, 47] = beta_std
        inputs[i, 48] = spinTop_number_occurrence
        inputs[i, 49] = doji_number_occurrence
        inputs[i, 50] = dojiStar_number_occurrence
        inputs[i, 51] = marubozu_number_occurrence
        inputs[i, 52] = hammer_number_occurrence
        inputs[i, 53] = invHammer_number_occurrence
        inputs[i, 54] = hangingMan_number_occurrence
        inputs[i, 55] = shootingStar_number_occurrence
        inputs[i, 56] = engulfing_number_occurrence
        inputs[i, 57] = morningStar_number_occurrence
        inputs[i, 58] = eveningStar_number_occurrence
        inputs[i, 59] = whiteSoldier_number_occurrence
        inputs[i, 60] = blackCrow_number_occurrence
        inputs[i, 61] = insideThree_number_occurrence

        # fill raw inputs matrices
        inputsOpen[i, :] = window[:, 0].reshape(1, lookUp)
        inputsClose[i, :] = window[:, 1].reshape(1, lookUp)
        inputsHigh[i, :] = window[:, 2].reshape(1, lookUp)
        inputsLow[i, :] = window[:, 3].reshape(1, lookUp)

        # fill the output matrix
        futureClose = windowForecast[:, 1]
        if (pairName == "USD_JPY"):
            outputs[
                i, 0] = (futureClose[-1] - futureClose[0]
                         ) / 0.01  # one pip = 0.01 for any pair containing JPY
        else:
            outputs[i, 0] = (futureClose[-1] - futureClose[0]
                             ) / 0.0001  # one pip = 0.0001 for this pairs

    # create mapping dict.
    mappingDict = {
        "sma_latest_crossover": 0,
        "sma_location_of_latest_crossover": 1,
        "sma_latest_crossover_angle": 2,
        "sma_dominant_type_fast_slow": 3,
        "ema_latest_crossover": 4,
        "ema_location_of_latest_crossover": 5,
        "ema_latest_crossover_angle": 6,
        "ema_dominant_type_fast_slow": 7,
        "deltaBands_mean": 8,
        "deltaBands_std": 9,
        "deltaBands_maximum_mean": 10,
        "deltaBands_maximum_location": 11,
        "deltaBands_minimum_mean": 12,
        "deltaBands_minimum_location": 13,
        "macd_latest_crossover": 14,
        "macd_location_of_latest_crossover": 15,
        "macd_latest_crossover_angle": 16,
        "macd_dominant_type_fast_slow": 17,
        "sar_latest_shiftPoint": 18,
        "sar_latest_shiftPoint_location": 19,
        "sar_total_number_shifts": 20,
        "stochK_mean": 21,
        "stochK_std": 22,
        "stochK_latest_event": 23,
        "stochK_event_location": 24,
        "stochD_mean": 25,
        "stochD_std": 26,
        "stochD_latest_event": 27,
        "stochD_event_location": 28,
        "rsi_mean": 29,
        "rsi_std": 30,
        "rsi_latest_event": 31,
        "rsi_event_location": 32,
        "adx_mean": 33,
        "adx_std": 34,
        "adx_mean_delta_bet_first_second_half": 35,
        "mfi_mean": 36,
        "mfi_std": 37,
        "mfi_mean_delta_bet_first_second_half": 38,
        "relation_r1_close": 39,
        "relation_r2_close": 40,
        "relation_r3_close": 41,
        "relation_s1_close": 42,
        "relation_s2_close": 43,
        "relation_s3_close": 44,
        "slope_mean": 45,
        "beta_mean": 46,
        "beta_std": 47,
        "spinTop_number_occurrence": 48,
        "doji_number_occurrence": 49,
        "dojiStar_number_occurrence": 50,
        "marubozu_number_occurrence": 51,
        "hammer_number_occurrence": 52,
        "invHammer_number_occurrence": 53,
        "hangingMan_number_occurrence": 54,
        "shootingStar_number_occurrence": 55,
        "engulfing_number_occurrence": 56,
        "morningStar_number_occurrence": 57,
        "eveningStar_number_occurrence": 58,
        "whiteSoldier_number_occurrence": 59,
        "blackCrow_number_occurrence": 60,
        "insideThree_number_occurrence": 61
    }

    # remove undifined values from the output
    refMatrix = inputs
    inputs = inputs[~np.isnan(refMatrix).any(
        axis=1)]  # remove all raws containing nan values
    outputs = outputs[~np.isnan(refMatrix).any(
        axis=1)]  # remove all raws containing nan values
    inputsOpen = inputsOpen[~np.isnan(refMatrix).any(
        axis=1)]  # remove all raws containing nan values
    inputsClose = inputsClose[~np.isnan(refMatrix).any(
        axis=1)]  # remove all raws containing nan values
    inputsHigh = inputsHigh[~np.isnan(refMatrix).any(
        axis=1)]  # remove all raws containing nan values
    inputsLow = inputsLow[~np.isnan(refMatrix).any(
        axis=1)]  # remove all raws containing nan values

    # create raw inputs dict.
    rawInputs["open"] = inputsOpen
    rawInputs["close"] = inputsClose
    rawInputs["high"] = inputsHigh
    rawInputs["low"] = inputsLow

    # return the function output
    output = {
        "mappingDict": mappingDict,
        "rawInputs": rawInputs,
        "inputFeatures": inputs,
        "targets": outputs
    }
    return (output)
Esempio n. 18
0
def patern(dataframe):
	"""
	Pattern Recognition:
	CDL2CROWS            Two Crows
	CDL3BLACKCROWS       Three Black Crows
	CDL3INSIDE           Three Inside Up/Down
	CDL3LINESTRIKE       Three-Line Strike
	CDL3OUTSIDE          Three Outside Up/Down
	CDL3STARSINSOUTH     Three Stars In The South
	CDL3WHITESOLDIERS    Three Advancing White Soldiers
	CDLABANDONEDBABY     Abandoned Baby
	CDLADVANCEBLOCK      Advance Block
	CDLBELTHOLD          Belt-hold
	CDLBREAKAWAY         Breakaway
	CDLCLOSINGMARUBOZU   Closing Marubozu
	CDLCONCEALBABYSWALL  Concealing Baby SwalLow
	CDLCOUNTERATTACK     Counterattack
	CDLDARKCLOUDCOVER    Dark Cloud Cover
	CDLDOJI              Doji
	CDLDOJISTAR          Doji Star
	CDLDRAGONFLYDOJI     Dragonfly Doji
	CDLENGULFING         Engulfing Pattern
	CDLEVENINGDOJISTAR   Evening Doji Star
	CDLEVENINGSTAR       Evening Star
	CDLGAPSIDESIDEWHITE  Up/Down-gap side-by-side white lines
	CDLGRAVESTONEDOJI    Gravestone Doji
	CDLHAMMER            Hammer
	CDLHANGINGMAN        Hanging Man
	CDLHARAMI            Harami Pattern
	CDLHARAMICROSS       Harami Cross Pattern
	CDLHighWAVE          High-Wave Candle
	CDLHIKKAKE           Hikkake Pattern
	CDLHIKKAKEMOD        Modified Hikkake Pattern
	CDLHOMINGPIGEON      Homing Pigeon
	CDLIDENTICAL3CROWS   Identical Three Crows
	CDLINNECK            In-Neck Pattern
	CDLINVERTEDHAMMER    Inverted Hammer
	CDLKICKING           Kicking
	CDLKICKINGBYLENGTH   Kicking - bull/bear determined by the longer marubozu
	CDLLADDERBOTTOM      Ladder Bottom
	CDLLONGLEGGEDDOJI    Long Legged Doji
	CDLLONGLINE          Long Line Candle
	CDLMARUBOZU          Marubozu
	CDLMATCHINGLow       Matching Low
	CDLMATHOLD           Mat Hold
	CDLMORNINGDOJISTAR   Morning Doji Star
	CDLMORNINGSTAR       Morning Star
	CDLONNECK            On-Neck Pattern
	CDLPIERCING          Piercing Pattern
	CDLRICKSHAWMAN       Rickshaw Man
	CDLRISEFALL3METHODS  Rising/Falling Three Methods
	CDLSEPARATINGLINES   Separating Lines
	CDLSHOOTINGSTAR      Shooting Star
	CDLSHORTLINE         Short Line Candle
	CDLSPINNINGTOP       Spinning Top
	CDLSTALLEDPATTERN    Stalled Pattern
	CDLSTICKSANDWICH     Stick Sandwich
	CDLTAKURI            Takuri (Dragonfly Doji with very long Lower shadow)
	CDLTASUKIGAP         Tasuki Gap
	CDLTHRUSTING         Thrusting Pattern
	CDLTRISTAR           Tristar Pattern
	CDLUNIQUE3RIVER      Unique 3 River
	CDLUPSIDEGAP2CROWS   Upside Gap Two Crows
	CDLXSIDEGAP3METHODS  Upside/Downside Gap Three Methods

	"""

	#CDL2CROWS - Two Crows
	df[f'{ratio}_CDL2CROWS'] = talib.CDL2CROWS(Open,High, Low, Close)
	#CDL2CROWS - Three Black Crows
	df[f'{ratio}_CDL2CROWS'] = talib.CDL3BLACKCROWS(Open,High, Low, Close)
	#CDL3INSIDE - Three Inside Up/Down
	df[f'{ratio}_CDL3INSIDE'] = talib.CDL3INSIDE(Open,High, Low, Close)
	#CDL3LINESTRIKE - Three-Line Strike
	df[f'{ratio}_CDL3LINESTRIKE'] = talib.CDL3LINESTRIKE(Open,High, Low, Close)
	#CDL3OUTSIDE - Three Outside Up/Down
	df[f'{ratio}_CDL3OUTSIDE'] = talib.CDL3OUTSIDE(Open,High, Low, Close)
	#CDL3STARSINSOUTH - Three Stars In The South
	df[f'{ratio}_CDL3STARSINSOUTH'] = talib.CDL3STARSINSOUTH(Open,High, Low, Close)
	#CDL3WHITESOLDIERS - Three Advancing White Soldiers
	df[f'{ratio}_CDL3WHITESOLDIERS'] = talib.CDL3WHITESOLDIERS(Open,High, Low, Close)
	#CDLABANDONEDBABY - Abandoned Baby
	df[f'{ratio}_CDLABANDONEDBABY'] = talib.CDLABANDONEDBABY(Open,High, Low, Close, penetration=0)
	#CDLADVANCEBLOCK - Advance Block
	df[f'{ratio}_CDLADVANCEBLOCK'] = talib.CDLADVANCEBLOCK(Open,High, Low, Close)
	#CDLBELTHOLD - Belt-hold
	df[f'{ratio}_CDLBELTHOLD'] = talib.CDLBELTHOLD(Open,High, Low, Close)
	#CDLBREAKAWAY - Breakaway
	df[f'{ratio}_CDLBREAKAWAY'] = talib.CDLBREAKAWAY(Open,High, Low, Close)
	#CDLCLOSINGMARUBOZU - Closing Marubozu
	df[f'{ratio}_CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(Open,High, Low, Close)
	#CDLCONCEALBABYSWALL - Concealing Baby SwalLow
	df[f'{ratio}_CDLCLOSINGMARUBOZU'] = talib.CDLCONCEALBABYSWALL(Open,High, Low, Close)
	#CDLCOUNTERATTACK - Counterattack
	df[f'{ratio}_CDLCLOSINGMARUBOZU'] = talib.CDLCOUNTERATTACK(Open,High, Low, Close)
	#CDLDARKCLOUDCOVER - Dark Cloud Cover
	df[f'{ratio}_CDLCLOSINGMARUBOZU'] = talib.CDLDARKCLOUDCOVER(Open,High, Low, Close, penetration=0)
	#CDLDOJI - Doji
	df[f'{ratio}_CDLDOJI'] = talib.CDLDOJI(Open,High, Low, Close)
	#CDLDOJISTAR - Doji Star
	df[f'{ratio}_CDLDOJISTAR'] = talib.CDLDOJISTAR(Open,High, Low, Close)
	#CDLDRAGONFLYDOJI - Dragonfly Doji
	df[f'{ratio}_CDLDRAGONFLYDOJI'] = talib.CDLDRAGONFLYDOJI(Open,High, Low, Close)
	#CDLENGULFING - Engulfing Pattern
	df[f'{ratio}_CDLENGULFING'] = talib.CDLENGULFING(Open,High, Low, Close)
	#CDLEVENINGDOJISTAR - Evening Doji Star
	df[f'{ratio}_CDLEVENINGDOJISTAR'] = talib.CDLEVENINGDOJISTAR(Open,High, Low, Close, penetration=0)
	#CDLEVENINGSTAR - Evening Star
	df[f'{ratio}_CDLEVENINGSTAR'] = talib.CDLEVENINGSTAR(Open,High, Low, Close, penetration=0)
	#CDLGAPSIDESIDEWHITE - Up/Down-gap side-by-side white lines
	df[f'{ratio}_CDLEVENINGSTAR'] = talib.CDLGAPSIDESIDEWHITE(Open,High, Low, Close)
	#CDLGRAVESTONEDOJI - Gravestone Doji
	df[f'{ratio}_CDLGRAVESTONEDOJI'] = talib.CDLGRAVESTONEDOJI(Open,High, Low, Close)
	#CDLHAMMER - Hammer
	df[f'{ratio}_CDLGRAVESTONEDOJI'] = talib.CDLHAMMER(Open,High, Low, Close)
	#CDLHANGINGMAN - Hanging Man
	df[f'{ratio}_CDLGRAVESTONEDOJI'] = talib.CDLHANGINGMAN(Open,High, Low, Close)
	#CDLHARAMI - Harami Pattern
	df[f'{ratio}_CDLGRAVESTONEDOJI'] = talib.CDLHARAMI(Open,High, Low, Close)
	#CDLHARAMICROSS - Harami Cross Pattern
	df[f'{ratio}_CDLHARAMICROSS'] = talib.CDLHARAMICROSS(Open,High, Low, Close)
	#CDLHighWAVE -High-Wave Candle
	#df[f'{ratio}_CDLHighWAVE'] = talib.CDLHighWAVE(Open,High, Low, Close)
	#CDLHIKKAKE - Hikkake Pattern
	df[f'{ratio}_CDLHIKKAKE'] = talib.CDLHIKKAKE(Open,High, Low, Close)
	#CDLHIKKAKEMOD - Modified Hikkake Pattern
	df[f'{ratio}_CDLHIKKAKEMOD'] = talib.CDLHIKKAKEMOD(Open,High, Low, Close)
	#CDLHOMINGPIGEON - Homing Pigeon
	df[f'{ratio}_CDLHOMINGPIGEON'] = talib.CDLHOMINGPIGEON(Open,High, Low, Close)
	#CDLIDENTICAL3CROWS - Identical Three Crows
	df[f'{ratio}_CDLIDENTICAL3CROWS'] = talib.CDLIDENTICAL3CROWS(Open,High, Low, Close)
	#CDLINNECK - In-Neck Pattern
	df[f'{ratio}_CDLINNECK'] = talib.CDLINNECK(Open,High, Low, Close)
	#CDLINVERTEDHAMMER - Inverted Hammer
	df[f'{ratio}_CDLINVERTEDHAMMER'] = talib.CDLINVERTEDHAMMER(Open,High, Low, Close)
	#CDLKICKING - Kicking
	df[f'{ratio}_CDLKICKING'] = talib.CDLKICKING(Open,High, Low, Close)
	#CDLKICKINGBYLENGTH - Kicking - bull/bear determined by the longer marubozu
	df[f'{ratio}_CDLKICKINGBYLENGTH'] = talib.CDLKICKINGBYLENGTH(Open,High, Low, Close)
	#CDLLADDERBOTTOM - Ladder Bottom
	df[f'{ratio}_CDLLADDERBOTTOM'] = talib.CDLLADDERBOTTOM(Open,High, Low, Close)
	#CDLLONGLEGGEDDOJI - Long Legged Doji
	df[f'{ratio}_CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(Open,High, Low, Close)
	#CDLLONGLINE - Long Line Candle
	df[f'{ratio}_CDLLONGLINE'] = talib.CDLLONGLINE(Open,High, Low, Close)
	#CDLMARUBOZU - Marubozu
	df[f'{ratio}_DLMARUBOZU'] = talib.CDLMARUBOZU(Open,High, Low, Close)
	#CDLMATCHINGLow - Matching Low
	#df[f'{ratio}_CDLMATCHINGLow'] = talib.CDLMATCHINGLow(Open,High, Low, Close)
	#CDLMATHOLD - Mat Hold
	df[f'{ratio}_CDLMATHOLD'] = talib.CDLMATHOLD(Open,High, Low, Close, penetration=0)
	#CDLMORNINGDOJISTAR - Morning Doji Star
	df[f'{ratio}_CDLMORNINGDOJISTAR'] = talib.CDLMORNINGDOJISTAR(Open,High, Low, Close, penetration=0)
	#CDLMORNINGSTAR - Morning Star
	df[f'{ratio}_CDLMORNINGSTAR'] = talib.CDLMORNINGSTAR(Open,High, Low, Close, penetration=0)
	#CDLONNECK - On-Neck Pattern
	df[f'{ratio}_CDLONNECK'] = talib.CDLONNECK(Open,High, Low, Close)
	#CDLPIERCING - Piercing Pattern
	df[f'{ratio}_CDLPIERCING'] = talib.CDLPIERCING(Open,High, Low, Close)
	#CDLRICKSHAWMAN - Rickshaw Man
	df[f'{ratio}_CDLRICKSHAWMAN'] = talib.CDLRICKSHAWMAN(Open,High, Low, Close)
	#CDLRISEFALL3METHODS - Rising/Falling Three Methods
	df[f'{ratio}_CDLRISEFALL3METHODS'] = talib.CDLRISEFALL3METHODS(Open,High, Low, Close)
	#CDLSEPARATINGLINES - Separating Lines
	df[f'{ratio}_CDLSEPARATINGLINES'] = talib.CDLSEPARATINGLINES(Open,High, Low, Close)
	#CDLSHOOTINGSTAR - Shooting Star
	df[f'{ratio}_CDLSHOOTINGSTAR'] = talib.CDLSHOOTINGSTAR(Open,High, Low, Close)
	#CDLSHORTLINE - Short Line Candle
	df[f'{ratio}_CDLSHORTLINE'] = talib.CDLSHORTLINE(Open,High, Low, Close)
	#CDLSPINNINGTOP - Spinning Top
	df[f'{ratio}_CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(Open,High, Low, Close)
	#CDLSTALLEDPATTERN - Stalled Pattern
	df[f'{ratio}_CDLSTALLEDPATTERN'] = talib.CDLSTALLEDPATTERN(Open,High, Low, Close)
	#CDLSTICKSANDWICH - Stick Sandwich
	df[f'{ratio}_CDLSTICKSANDWICH'] = talib.CDLSTICKSANDWICH(Open,High, Low, Close)
	#CDLTAKURI - Takuri (Dragonfly Doji with very long Lower shadow)
	df[f'{ratio}_CDLTAKURI'] = talib.CDLTAKURI(Open,High, Low, Close)
	#CDLTASUKIGAP - Tasuki Gap
	df[f'{ratio}_CDLTASUKIGAP'] = talib.CDLTASUKIGAP(Open,High, Low, Close)
	#CDLTHRUSTING - Thrusting Pattern
	df[f'{ratio}_CDLTHRUSTING'] = talib.CDLTHRUSTING(Open,High, Low, Close)
	#CDLTRISTAR - Tristar Pattern
	df[f'{ratio}_CDLTRISTAR'] = talib.CDLTRISTAR(Open,High, Low, Close)
	#CDLUNIQUE3RIVER - Unique 3 River
	df[f'{ratio}_CDLUNIQUE3RIVER'] = talib.CDLUNIQUE3RIVER(Open,High, Low, Close)
	#CDLUPSIDEGAP2CROWS - Upside Gap Two Crows
	df[f'{ratio}_CDLUPSIDEGAP2CROWS'] = talib.CDLUPSIDEGAP2CROWS(Open,High, Low, Close)
	#CDLXSIDEGAP3METHODS - Upside/Downside Gap Three Methods
	df[f'{ratio}_CDLXSIDEGAP3METHODS'] = talib.CDLXSIDEGAP3METHODS(Open,High, Low, Close)

	return patern
Esempio n. 19
0
def add_ta_features(df, ta_settings):
    """Add technial analysis features from typical financial dataset that
    typically include columns such as "open", "high", "low", "price" and
    "volume".

    http://mrjbq7.github.io/ta-lib/

    Args:
        df(pandas.DataFrame): original DataFrame.
        ta_settings(dict): configuration.
    Returns:
        pandas.DataFrame: DataFrame with new features included.
    """

    open = df['open']
    high = df['high']
    low = df['low']
    close = df['price']
    volume = df['volume']

    if ta_settings['overlap']:

        df['ta_overlap_bbands_upper'], df['ta_overlap_bbands_middle'], df[
            'ta_overlap_bbands_lower'] = ta.BBANDS(close,
                                                   timeperiod=5,
                                                   nbdevup=2,
                                                   nbdevdn=2,
                                                   matype=0)
        df['ta_overlap_dema'] = ta.DEMA(
            close, timeperiod=15)  # NOTE: Changed to avoid a lot of Nan values
        df['ta_overlap_ema'] = ta.EMA(close, timeperiod=30)
        df['ta_overlap_kama'] = ta.KAMA(close, timeperiod=30)
        df['ta_overlap_ma'] = ta.MA(close, timeperiod=30, matype=0)
        df['ta_overlap_mama_mama'], df['ta_overlap_mama_fama'] = ta.MAMA(close)
        period = np.random.randint(10, 20, size=len(close)).astype(float)
        df['ta_overlap_mavp'] = ta.MAVP(close,
                                        period,
                                        minperiod=2,
                                        maxperiod=30,
                                        matype=0)
        df['ta_overlap_midpoint'] = ta.MIDPOINT(close, timeperiod=14)
        df['ta_overlap_midprice'] = ta.MIDPRICE(high, low, timeperiod=14)
        df['ta_overlap_sar'] = ta.SAR(high, low, acceleration=0, maximum=0)
        df['ta_overlap_sarext'] = ta.SAREXT(high,
                                            low,
                                            startvalue=0,
                                            offsetonreverse=0,
                                            accelerationinitlong=0,
                                            accelerationlong=0,
                                            accelerationmaxlong=0,
                                            accelerationinitshort=0,
                                            accelerationshort=0,
                                            accelerationmaxshort=0)
        df['ta_overlap_sma'] = ta.SMA(close, timeperiod=30)
        df['ta_overlap_t3'] = ta.T3(close, timeperiod=5, vfactor=0)
        df['ta_overlap_tema'] = ta.TEMA(
            close, timeperiod=12)  # NOTE: Changed to avoid a lot of Nan values
        df['ta_overlap_trima'] = ta.TRIMA(close, timeperiod=30)
        df['ta_overlap_wma'] = ta.WMA(close, timeperiod=30)

        # NOTE: Commented to avoid a lot of Nan values
        # df['ta_overlap_ht_trendline'] = ta.HT_TRENDLINE(close)

    if ta_settings['momentum']:

        df['ta_momentum_adx'] = ta.ADX(high, low, close, timeperiod=14)
        df['ta_momentum_adxr'] = ta.ADXR(high, low, close, timeperiod=14)
        df['ta_momentum_apo'] = ta.APO(close,
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        df['ta_momentum_aroondown'], df['ta_momentum_aroonup'] = ta.AROON(
            high, low, timeperiod=14)
        df['ta_momentum_aroonosc'] = ta.AROONOSC(high, low, timeperiod=14)
        df['ta_momentum_bop'] = ta.BOP(open, high, low, close)
        df['ta_momentum_cci'] = ta.CCI(high, low, close, timeperiod=14)
        df['ta_momentum_cmo'] = ta.CMO(close, timeperiod=14)
        df['ta_momentum_dx'] = ta.DX(high, low, close, timeperiod=14)
        df['ta_momentum_macd_macd'], df['ta_momentum_macd_signal'], df[
            'ta_momentum_macd_hist'] = ta.MACD(close,
                                               fastperiod=12,
                                               slowperiod=26,
                                               signalperiod=9)
        df['ta_momentum_macdext_macd'], df['ta_momentum_macdext_signal'], df[
            'ta_momentum_macdext_hist'] = ta.MACDEXT(close,
                                                     fastperiod=12,
                                                     fastmatype=0,
                                                     slowperiod=26,
                                                     slowmatype=0,
                                                     signalperiod=9,
                                                     signalmatype=0)
        df['ta_momentum_macdfix_macd'], df['ta_momentum_macdfix_signal'], df[
            'ta_momentum_macdfix_hist'] = ta.MACDFIX(close, signalperiod=9)
        df['ta_momentum_mfi'] = ta.MFI(high, low, close, volume, timeperiod=14)
        df['ta_momentum_minus_di'] = ta.MINUS_DI(high,
                                                 low,
                                                 close,
                                                 timeperiod=14)
        df['ta_momentum_minus_dm'] = ta.MINUS_DM(high, low, timeperiod=14)
        df['ta_momentum_mom'] = ta.MOM(close, timeperiod=10)
        df['ta_momentum_plus_di'] = ta.PLUS_DI(high, low, close, timeperiod=14)
        df['ta_momentum_plus_dm'] = ta.PLUS_DM(high, low, timeperiod=14)
        df['ta_momentum_ppo'] = ta.PPO(close,
                                       fastperiod=12,
                                       slowperiod=26,
                                       matype=0)
        df['ta_momentum_roc'] = ta.ROC(close, timeperiod=10)
        df['ta_momentum_rocp'] = ta.ROCP(close, timeperiod=10)
        df['ta_momentum_rocr'] = ta.ROCR(close, timeperiod=10)
        df['ta_momentum_rocr100'] = ta.ROCR100(close, timeperiod=10)
        df['ta_momentum_rsi'] = ta.RSI(close, timeperiod=14)
        df['ta_momentum_slowk'], df['ta_momentum_slowd'] = ta.STOCH(
            high,
            low,
            close,
            fastk_period=5,
            slowk_period=3,
            slowk_matype=0,
            slowd_period=3,
            slowd_matype=0)
        df['ta_momentum_fastk'], df['ta_momentum_fastd'] = ta.STOCHF(
            high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0)
        df['ta_momentum_fastk'], df['ta_momentum_fastd'] = ta.STOCHRSI(
            close,
            timeperiod=14,
            fastk_period=5,
            fastd_period=3,
            fastd_matype=0)
        df['ta_momentum_trix'] = ta.TRIX(
            close, timeperiod=12)  # NOTE: Changed to avoid a lot of Nan values
        df['ta_momentum_ultosc'] = ta.ULTOSC(high,
                                             low,
                                             close,
                                             timeperiod1=7,
                                             timeperiod2=14,
                                             timeperiod3=28)
        df['ta_momentum_willr'] = ta.WILLR(high, low, close, timeperiod=14)

    if ta_settings['volume']:

        df['ta_volume_ad'] = ta.AD(high, low, close, volume)
        df['ta_volume_adosc'] = ta.ADOSC(high,
                                         low,
                                         close,
                                         volume,
                                         fastperiod=3,
                                         slowperiod=10)
        df['ta_volume_obv'] = ta.OBV(close, volume)

    if ta_settings['volatility']:

        df['ta_volatility_atr'] = ta.ATR(high, low, close, timeperiod=14)
        df['ta_volatility_natr'] = ta.NATR(high, low, close, timeperiod=14)
        df['ta_volatility_trange'] = ta.TRANGE(high, low, close)

    if ta_settings['price']:

        df['ta_price_avgprice'] = ta.AVGPRICE(open, high, low, close)
        df['ta_price_medprice'] = ta.MEDPRICE(high, low)
        df['ta_price_typprice'] = ta.TYPPRICE(high, low, close)
        df['ta_price_wclprice'] = ta.WCLPRICE(high, low, close)

    if ta_settings['cycle']:

        df['ta_cycle_ht_dcperiod'] = ta.HT_DCPERIOD(close)
        df['ta_cycle_ht_phasor_inphase'], df[
            'ta_cycle_ht_phasor_quadrature'] = ta.HT_PHASOR(close)
        df['ta_cycle_ht_trendmode'] = ta.HT_TRENDMODE(close)

        # NOTE: Commented to avoid a lot of Nan values
        # df['ta_cycle_ht_dcphase'] = ta.HT_DCPHASE(close)
        # df['ta_cycle_ht_sine_sine'], df['ta_cycle_ht_sine_leadsine'] = ta.HT_SINE(close)

    if ta_settings['pattern']:

        df['ta_pattern_cdl2crows'] = ta.CDL2CROWS(open, high, low, close)
        df['ta_pattern_cdl3blackrows'] = ta.CDL3BLACKCROWS(
            open, high, low, close)
        df['ta_pattern_cdl3inside'] = ta.CDL3INSIDE(open, high, low, close)
        df['ta_pattern_cdl3linestrike'] = ta.CDL3LINESTRIKE(
            open, high, low, close)
        df['ta_pattern_cdl3outside'] = ta.CDL3OUTSIDE(open, high, low, close)
        df['ta_pattern_cdl3starsinsouth'] = ta.CDL3STARSINSOUTH(
            open, high, low, close)
        df['ta_pattern_cdl3whitesoldiers'] = ta.CDL3WHITESOLDIERS(
            open, high, low, close)
        df['ta_pattern_cdlabandonedbaby'] = ta.CDLABANDONEDBABY(open,
                                                                high,
                                                                low,
                                                                close,
                                                                penetration=0)
        df['ta_pattern_cdladvanceblock'] = ta.CDLADVANCEBLOCK(
            open, high, low, close)
        df['ta_pattern_cdlbelthold'] = ta.CDLBELTHOLD(open, high, low, close)
        df['ta_pattern_cdlbreakaway'] = ta.CDLBREAKAWAY(open, high, low, close)
        df['ta_pattern_cdlclosingmarubozu'] = ta.CDLCLOSINGMARUBOZU(
            open, high, low, close)
        df['ta_pattern_cdlconcealbabyswall'] = ta.CDLCONCEALBABYSWALL(
            open, high, low, close)
        df['ta_pattern_cdlcounterattack'] = ta.CDLCOUNTERATTACK(
            open, high, low, close)
        df['ta_pattern_cdldarkcloudcover'] = ta.CDLDARKCLOUDCOVER(
            open, high, low, close, penetration=0)
        df['ta_pattern_cdldoji'] = ta.CDLDOJI(open, high, low, close)
        df['ta_pattern_cdldojistar'] = ta.CDLDOJISTAR(open, high, low, close)
        df['ta_pattern_cdldragonflydoji'] = ta.CDLDRAGONFLYDOJI(
            open, high, low, close)
        df['ta_pattern_cdlengulfing'] = ta.CDLENGULFING(open, high, low, close)
        df['ta_pattern_cdleveningdojistar'] = ta.CDLEVENINGDOJISTAR(
            open, high, low, close, penetration=0)
        df['ta_pattern_cdleveningstar'] = ta.CDLEVENINGSTAR(open,
                                                            high,
                                                            low,
                                                            close,
                                                            penetration=0)
        df['ta_pattern_cdlgapsidesidewhite'] = ta.CDLGAPSIDESIDEWHITE(
            open, high, low, close)
        df['ta_pattern_cdlgravestonedoji'] = ta.CDLGRAVESTONEDOJI(
            open, high, low, close)
        df['ta_pattern_cdlhammer'] = ta.CDLHAMMER(open, high, low, close)
        df['ta_pattern_cdlhangingman'] = ta.CDLHANGINGMAN(
            open, high, low, close)
        df['ta_pattern_cdlharami'] = ta.CDLHARAMI(open, high, low, close)
        df['ta_pattern_cdlharamicross'] = ta.CDLHARAMICROSS(
            open, high, low, close)
        df['ta_pattern_cdlhighwave'] = ta.CDLHIGHWAVE(open, high, low, close)
        df['ta_pattern_cdlhikkake'] = ta.CDLHIKKAKE(open, high, low, close)
        df['ta_pattern_cdlhikkakemod'] = ta.CDLHIKKAKEMOD(
            open, high, low, close)
        df['ta_pattern_cdlhomingpigeon'] = ta.CDLHOMINGPIGEON(
            open, high, low, close)
        df['ta_pattern_cdlidentical3crows'] = ta.CDLIDENTICAL3CROWS(
            open, high, low, close)
        df['ta_pattern_cdlinneck'] = ta.CDLINNECK(open, high, low, close)
        df['ta_pattern_cdlinvertedhammer'] = ta.CDLINVERTEDHAMMER(
            open, high, low, close)
        df['ta_pattern_cdlkicking'] = ta.CDLKICKING(open, high, low, close)
        df['ta_pattern_cdlkickingbylength'] = ta.CDLKICKINGBYLENGTH(
            open, high, low, close)
        df['ta_pattern_cdlladderbottom'] = ta.CDLLADDERBOTTOM(
            open, high, low, close)
        df['ta_pattern_cdllongleggeddoji'] = ta.CDLLONGLEGGEDDOJI(
            open, high, low, close)
        df['ta_pattern_cdllongline'] = ta.CDLLONGLINE(open, high, low, close)
        df['ta_pattern_cdlmarubozu'] = ta.CDLMARUBOZU(open, high, low, close)
        df['ta_pattern_cdlmatchinglow'] = ta.CDLMATCHINGLOW(
            open, high, low, close)
        df['ta_pattern_cdlmathold'] = ta.CDLMATHOLD(open,
                                                    high,
                                                    low,
                                                    close,
                                                    penetration=0)
        df['ta_pattern_cdlmorningdojistar'] = ta.CDLMORNINGDOJISTAR(
            open, high, low, close, penetration=0)
        df['ta_pattern_cdlmorningstar'] = ta.CDLMORNINGSTAR(open,
                                                            high,
                                                            low,
                                                            close,
                                                            penetration=0)
        df['ta_pattern_cdllonneck'] = ta.CDLONNECK(open, high, low, close)
        df['ta_pattern_cdlpiercing'] = ta.CDLPIERCING(open, high, low, close)
        df['ta_pattern_cdlrickshawman'] = ta.CDLRICKSHAWMAN(
            open, high, low, close)
        df['ta_pattern_cdlrisefall3methods'] = ta.CDLRISEFALL3METHODS(
            open, high, low, close)
        df['ta_pattern_cdlseparatinglines'] = ta.CDLSEPARATINGLINES(
            open, high, low, close)
        df['ta_pattern_cdlshootingstar'] = ta.CDLSHOOTINGSTAR(
            open, high, low, close)
        df['ta_pattern_cdlshortline'] = ta.CDLSHORTLINE(open, high, low, close)
        df['ta_pattern_cdlspinningtop'] = ta.CDLSPINNINGTOP(
            open, high, low, close)
        df['ta_pattern_cdlstalledpattern'] = ta.CDLSTALLEDPATTERN(
            open, high, low, close)
        df['ta_pattern_cdlsticksandwich'] = ta.CDLSTICKSANDWICH(
            open, high, low, close)
        df['ta_pattern_cdltakuri'] = ta.CDLTAKURI(open, high, low, close)
        df['ta_pattern_cdltasukigap'] = ta.CDLTASUKIGAP(open, high, low, close)
        df['ta_pattern_cdlthrusting'] = ta.CDLTHRUSTING(open, high, low, close)
        df['ta_pattern_cdltristar'] = ta.CDLTRISTAR(open, high, low, close)
        df['ta_pattern_cdlunique3river'] = ta.CDLUNIQUE3RIVER(
            open, high, low, close)
        df['ta_pattern_cdlupsidegap2crows'] = ta.CDLUPSIDEGAP2CROWS(
            open, high, low, close)
        df['ta_pattern_cdlxsidegap3methods'] = ta.CDLXSIDEGAP3METHODS(
            open, high, low, close)

    if ta_settings['statistic']:

        df['ta_statistic_beta'] = ta.BETA(high, low, timeperiod=5)
        df['ta_statistic_correl'] = ta.CORREL(high, low, timeperiod=30)
        df['ta_statistic_linearreg'] = ta.LINEARREG(close, timeperiod=14)
        df['ta_statistic_linearreg_angle'] = ta.LINEARREG_ANGLE(close,
                                                                timeperiod=14)
        df['ta_statistic_linearreg_intercept'] = ta.LINEARREG_INTERCEPT(
            close, timeperiod=14)
        df['ta_statistic_linearreg_slope'] = ta.LINEARREG_SLOPE(close,
                                                                timeperiod=14)
        df['ta_statistic_stddev'] = ta.STDDEV(close, timeperiod=5, nbdev=1)
        df['ta_statistic_tsf'] = ta.TSF(close, timeperiod=14)
        df['ta_statistic_var'] = ta.VAR(close, timeperiod=5, nbdev=1)

    if ta_settings['math_transforms']:

        df['ta_math_transforms_atan'] = ta.ATAN(close)
        df['ta_math_transforms_ceil'] = ta.CEIL(close)
        df['ta_math_transforms_cos'] = ta.COS(close)
        df['ta_math_transforms_floor'] = ta.FLOOR(close)
        df['ta_math_transforms_ln'] = ta.LN(close)
        df['ta_math_transforms_log10'] = ta.LOG10(close)
        df['ta_math_transforms_sin'] = ta.SIN(close)
        df['ta_math_transforms_sqrt'] = ta.SQRT(close)
        df['ta_math_transforms_tan'] = ta.TAN(close)

    if ta_settings['math_operators']:

        df['ta_math_operators_add'] = ta.ADD(high, low)
        df['ta_math_operators_div'] = ta.DIV(high, low)
        df['ta_math_operators_min'], df['ta_math_operators_max'] = ta.MINMAX(
            close, timeperiod=30)
        df['ta_math_operators_minidx'], df[
            'ta_math_operators_maxidx'] = ta.MINMAXINDEX(close, timeperiod=30)
        df['ta_math_operators_mult'] = ta.MULT(high, low)
        df['ta_math_operators_sub'] = ta.SUB(high, low)
        df['ta_math_operators_sum'] = ta.SUM(close, timeperiod=30)

    return df
Esempio n. 20
0
def CDLSPINNINGTOP(data):
    res = talib.CDLSPINNINGTOP(
        data.open.values, data.high.values, data.low.values, data.close.values)
    return pd.DataFrame({'CDLSPINNINGTOP': res}, index=data.index)
Esempio n. 21
0
def candles(source):
    open = source['open']
    high = source['high']
    low = source['low']
    close = source['close']

    source = source.join(
        pd.Series(talib.CDL2CROWS(open, high, low, close), name='CDL2CROWS'))
    source = source.join(
        pd.Series(talib.CDL3BLACKCROWS(open, high, low, close),
                  name='CDL3BLACKCROWS'))
    source = source.join(
        pd.Series(talib.CDL3INSIDE(open, high, low, close), name='CDL3INSIDE'))
    source = source.join(
        pd.Series(talib.CDL3OUTSIDE(open, high, low, close),
                  name='CDL3OUTSIDE'))
    source = source.join(
        pd.Series(talib.CDL3STARSINSOUTH(open, high, low, close),
                  name='CDL3STARSINSOUTH'))
    source = source.join(
        pd.Series(talib.CDL3WHITESOLDIERS(open, high, low, close),
                  name='CDL3WHITESOLDIERS'))
    source = source.join(
        pd.Series(talib.CDLABANDONEDBABY(open, high, low, close),
                  name='CDLABANDONEDBABY'))
    source = source.join(
        pd.Series(talib.CDLADVANCEBLOCK(open, high, low, close),
                  name='CDLADVANCEBLOCK'))
    source = source.join(
        pd.Series(talib.CDLBELTHOLD(open, high, low, close),
                  name='CDLBELTHOLD'))
    source = source.join(
        pd.Series(talib.CDLBREAKAWAY(open, high, low, close),
                  name='CDLBREAKAWAY'))
    source = source.join(
        pd.Series(talib.CDLCLOSINGMARUBOZU(open, high, low, close),
                  name='CDLCLOSINGMARUBOZU'))
    source = source.join(
        pd.Series(talib.CDLCONCEALBABYSWALL(open, high, low, close),
                  name='CDLCONCEALBABYSWALL'))
    source = source.join(
        pd.Series(talib.CDLCOUNTERATTACK(open, high, low, close),
                  name='CDLCOUNTERATTACK'))
    source = source.join(
        pd.Series(talib.CDLDARKCLOUDCOVER(open, high, low, close),
                  name='CDLDARKCLOUDCOVER'))
    source = source.join(
        pd.Series(talib.CDLDOJI(open, high, low, close), name='CDLDOJI'))
    source = source.join(
        pd.Series(talib.CDLDOJISTAR(open, high, low, close),
                  name='CDLDOJISTAR'))
    source = source.join(
        pd.Series(talib.CDLDRAGONFLYDOJI(open, high, low, close),
                  name='CDLDRAGONFLYDOJI'))
    source = source.join(
        pd.Series(talib.CDLENGULFING(open, high, low, close),
                  name='CDLENGULFING'))
    source = source.join(
        pd.Series(talib.CDLEVENINGDOJISTAR(open, high, low, close),
                  name='CDLEVENINGDOJISTAR'))
    source = source.join(
        pd.Series(talib.CDLEVENINGSTAR(open, high, low, close),
                  name='CDLEVENINGSTAR'))
    source = source.join(
        pd.Series(talib.CDLGAPSIDESIDEWHITE(open, high, low, close),
                  name='CDLGAPSIDESIDEWHITE'))
    source = source.join(
        pd.Series(talib.CDLGRAVESTONEDOJI(open, high, low, close),
                  name='CDLGRAVESTONEDOJI'))
    source = source.join(
        pd.Series(talib.CDLHAMMER(open, high, low, close), name='CDLHAMMER'))
    source = source.join(
        pd.Series(talib.CDLHANGINGMAN(open, high, low, close),
                  name='CDLHANGINGMAN'))
    source = source.join(
        pd.Series(talib.CDLHARAMI(open, high, low, close), name='CDLHARAMI'))
    source = source.join(
        pd.Series(talib.CDLHARAMICROSS(open, high, low, close),
                  name='CDLHARAMICROSS'))
    source = source.join(
        pd.Series(talib.CDLHIGHWAVE(open, high, low, close),
                  name='CDLHIGHWAVE'))
    source = source.join(
        pd.Series(talib.CDLHIKKAKE(open, high, low, close), name='CDLHIKKAKE'))
    source = source.join(
        pd.Series(talib.CDLHIKKAKEMOD(open, high, low, close),
                  name='CDLHIKKAKEMOD'))
    source = source.join(
        pd.Series(talib.CDLHOMINGPIGEON(open, high, low, close),
                  name='CDLHOMINGPIGEON'))
    source = source.join(
        pd.Series(talib.CDLIDENTICAL3CROWS(open, high, low, close),
                  name='CDLIDENTICAL3CROWS'))
    source = source.join(
        pd.Series(talib.CDLINNECK(open, high, low, close), name='CDLINNECK'))
    source = source.join(
        pd.Series(talib.CDLINVERTEDHAMMER(open, high, low, close),
                  name='CDLINVERTEDHAMMER'))
    source = source.join(
        pd.Series(talib.CDLKICKING(open, high, low, close), name='CDLKICKING'))
    source = source.join(
        pd.Series(talib.CDLKICKINGBYLENGTH(open, high, low, close),
                  name='CDLKICKINGBYLENGTH'))
    source = source.join(
        pd.Series(talib.CDLLADDERBOTTOM(open, high, low, close),
                  name='CDLLADDERBOTTOM'))
    source = source.join(
        pd.Series(talib.CDLLONGLEGGEDDOJI(open, high, low, close),
                  name='CDLLONGLEGGEDDOJI'))
    source = source.join(
        pd.Series(talib.CDLLONGLINE(open, high, low, close),
                  name='CDLLONGLINE'))
    source = source.join(
        pd.Series(talib.CDLMARUBOZU(open, high, low, close),
                  name='CDLMARUBOZU'))
    source = source.join(
        pd.Series(talib.CDLMATCHINGLOW(open, high, low, close),
                  name='CDLMATCHINGLOW'))
    source = source.join(
        pd.Series(talib.CDLMATHOLD(open, high, low, close), name='CDLMATHOLD'))
    source = source.join(
        pd.Series(talib.CDLMORNINGDOJISTAR(open, high, low, close),
                  name='CDLMORNINGDOJISTAR'))
    source = source.join(
        pd.Series(talib.CDLMORNINGSTAR(open, high, low, close),
                  name='CDLMORNINGSTAR'))
    source = source.join(
        pd.Series(talib.CDLONNECK(open, high, low, close), name='CDLONNECK'))
    source = source.join(
        pd.Series(talib.CDLPIERCING(open, high, low, close),
                  name='CDLPIERCING'))
    source = source.join(
        pd.Series(talib.CDLRICKSHAWMAN(open, high, low, close),
                  name='CDLRICKSHAWMAN'))
    source = source.join(
        pd.Series(talib.CDLRISEFALL3METHODS(open, high, low, close),
                  name='CDLRISEFALL3METHODS'))
    source = source.join(
        pd.Series(talib.CDLSEPARATINGLINES(open, high, low, close),
                  name='CDLSEPARATINGLINES'))
    source = source.join(
        pd.Series(talib.CDLSHOOTINGSTAR(open, high, low, close),
                  name='CDLSHOOTINGSTAR'))
    source = source.join(
        pd.Series(talib.CDLSHORTLINE(open, high, low, close),
                  name='CDLSHORTLINE'))
    source = source.join(
        pd.Series(talib.CDLSPINNINGTOP(open, high, low, close),
                  name='CDLSPINNINGTOP'))
    source = source.join(
        pd.Series(talib.CDLSTALLEDPATTERN(open, high, low, close),
                  name='CDLSTALLEDPATTERN'))
    source = source.join(
        pd.Series(talib.CDLSTICKSANDWICH(open, high, low, close),
                  name='CDLSTICKSANDWICH'))
    source = source.join(
        pd.Series(talib.CDLTAKURI(open, high, low, close), name='CDLTAKURI'))
    source = source.join(
        pd.Series(talib.CDLTASUKIGAP(open, high, low, close),
                  name='CDLTASUKIGAP'))
    source = source.join(
        pd.Series(talib.CDLTHRUSTING(open, high, low, close),
                  name='CDLTHRUSTING'))
    source = source.join(
        pd.Series(talib.CDLTRISTAR(open, high, low, close), name='CDLTRISTAR'))
    source = source.join(
        pd.Series(talib.CDLUNIQUE3RIVER(open, high, low, close),
                  name='CDLUNIQUE3RIVER'))
    source = source.join(
        pd.Series(talib.CDLUPSIDEGAP2CROWS(open, high, low, close),
                  name='CDLUPSIDEGAP2CROWS'))
    source = source.join(
        pd.Series(talib.CDLXSIDEGAP3METHODS(open, high, low, close),
                  name='CDLXSIDEGAP3METHODS'))

    return source
 df['CDLLADDERBOTTOM'] = talib.CDLLADDERBOTTOM(op, hp, lp, cp)
 df['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(op, hp, lp, cp)
 df['CDLLONGLINE'] = talib.CDLLONGLINE(op, hp, lp, cp)
 df['CDLMARUBOZU'] = talib.CDLMARUBOZU(op, hp, lp, cp)
 df['CDLMATCHINGLOW'] = talib.CDLMATCHINGLOW(op, hp, lp, cp)
 df['CDLMATHOLD'] = talib.CDLMATHOLD(op, hp, lp, cp)
 df['CDLMORNINGDOJISTAR'] = talib.CDLMORNINGDOJISTAR(op, hp, lp, cp)
 df['CDLMORNINGSTAR'] = talib.CDLMORNINGSTAR(op, hp, lp, cp)
 df['CDLONNECK'] = talib.CDLONNECK(op, hp, lp, cp)
 df['CDLPIERCING'] = talib.CDLPIERCING(op, hp, lp, cp)
 df['CDLRICKSHAWMAN'] = talib.CDLRICKSHAWMAN(op, hp, lp, cp)
 df['CDLRISEFALL3METHODS'] = talib.CDLRISEFALL3METHODS(op, hp, lp, cp)
 df['CDLSEPARATINGLINES'] = talib.CDLSEPARATINGLINES(op, hp, lp, cp)
 df['CDLSHOOTINGSTAR'] = talib.CDLSHOOTINGSTAR(op, hp, lp, cp)
 df['CDLSHORTLINE'] = talib.CDLSHORTLINE(op, hp, lp, cp)
 df['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(op, hp, lp, cp)
 df['CDLSTALLEDPATTERN'] = talib.CDLSTALLEDPATTERN(op, hp, lp, cp)
 df['CDLSTICKSANDWICH'] = talib.CDLSTICKSANDWICH(op, hp, lp, cp)
 df['CDLTAKURI'] = talib.CDLTAKURI(op, hp, lp, cp)
 df['CDLTASUKIGAP'] = talib.CDLTASUKIGAP(op, hp, lp, cp)
 df['CDLTHRUSTING'] = talib.CDLTHRUSTING(op, hp, lp, cp)
 df['CDLTRISTAR'] = talib.CDLTRISTAR(op, hp, lp, cp)
 df['CDLUNIQUE3RIVER'] = talib.CDLUNIQUE3RIVER(op, hp, lp, cp)
 df['CDLUPSIDEGAP2CROWS'] = talib.CDLUPSIDEGAP2CROWS(op, hp, lp, cp)
 df['CDLXSIDEGAP3METHODS'] = talib.CDLXSIDEGAP3METHODS(op, hp, lp, cp)
 post_rc = df.shape[0]
 df = df.drop(previous_columns, axis=1)
 if post_rc == n:
     print('Done Talib, Code', code, ' Pcc:', pcc, '/', lenCodes)
 else:
     print('Error At New Talib')
    np.array(df['Open']), np.array(df['High']), np.array(df['Low']),
    np.array(df['Adj Close']))
df['Separating_Lines'] = ta.CDLSEPARATINGLINES(np.array(df['Open']),
                                               np.array(df['High']),
                                               np.array(df['Low']),
                                               np.array(df['Adj Close']))
df['Shooting_Star'] = ta.CDLSHOOTINGSTAR(np.array(df['Open']),
                                         np.array(df['High']),
                                         np.array(df['Low']),
                                         np.array(df['Adj Close']))
df['Short_Line_Candle'] = ta.CDLSHORTLINE(np.array(df['Open']),
                                          np.array(df['High']),
                                          np.array(df['Low']),
                                          np.array(df['Adj Close']))
df['Spinning_Top'] = ta.CDLSPINNINGTOP(np.array(df['Open']),
                                       np.array(df['High']),
                                       np.array(df['Low']),
                                       np.array(df['Adj Close']))
df['Stalled_Pattern'] = ta.CDLSTALLEDPATTERN(np.array(df['Open']),
                                             np.array(df['High']),
                                             np.array(df['Low']),
                                             np.array(df['Adj Close']))
df['Stick_Sandwich'] = ta.CDLSTICKSANDWICH(np.array(df['Open']),
                                           np.array(df['High']),
                                           np.array(df['Low']),
                                           np.array(df['Adj Close']))
df['Takuri'] = ta.CDLTAKURI(np.array(df['Open']), np.array(df['High']),
                            np.array(df['Low']), np.array(df['Adj Close']))
df['Tasuki_Gap'] = ta.CDLTASUKIGAP(np.array(df['Open']), np.array(df['High']),
                                   np.array(df['Low']),
                                   np.array(df['Adj Close']))
df['Thrusting_Pattern'] = ta.CDLTHRUSTING(np.array(df['Open']),
Esempio n. 24
0
def pattern_recognition(candles: np.ndarray, pattern_type, penetration=0, sequential=False) -> Union[int, np.ndarray]:
    """
    Pattern Recognition

    :param candles: np.ndarray
    :param penetration: int - default = 0
    :param pattern_type: str
    :param sequential: bool - default=False

    :return: int | np.ndarray
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    if pattern_type == "CDL2CROWS":
        res = talib.CDL2CROWS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDL3BLACKCROWS":
        res = talib.CDL3BLACKCROWS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDL3INSIDE":
        res = talib.CDL3INSIDE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDL3LINESTRIKE":
        res = talib.CDL3LINESTRIKE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDL3OUTSIDE":
        res = talib.CDL3OUTSIDE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDL3STARSINSOUTH":
        res = talib.CDL3STARSINSOUTH(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDL3WHITESOLDIERS":
        res = talib.CDL3WHITESOLDIERS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLABANDONEDBABY":
        res = talib.CDLABANDONEDBABY(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2],
                                     penetration=penetration)
    elif pattern_type == "CDLADVANCEBLOCK":
        res = talib.CDLADVANCEBLOCK(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLBELTHOLD":
        res = talib.CDLBELTHOLD(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLBREAKAWAY":
        res = talib.CDLBREAKAWAY(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLCLOSINGMARUBOZU":
        res = talib.CDLCLOSINGMARUBOZU(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLCONCEALBABYSWALL":
        res = talib.CDLCONCEALBABYSWALL(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLCOUNTERATTACK":
        res = talib.CDLCOUNTERATTACK(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLDARKCLOUDCOVER":
        res = talib.CDLDARKCLOUDCOVER(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2],
                                      penetration=penetration)
    elif pattern_type == "CDLDOJI":
        res = talib.CDLDOJI(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLDOJISTAR":
        res = talib.CDLDOJISTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLDRAGONFLYDOJI":
        res = talib.CDLDRAGONFLYDOJI(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLENGULFING":
        res = talib.CDLENGULFING(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLEVENINGDOJISTAR":
        res = talib.CDLEVENINGDOJISTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2],
                                       penetration=penetration)
    elif pattern_type == "CDLEVENINGSTAR":
        res = talib.CDLEVENINGSTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2], penetration=penetration)
    elif pattern_type == "CDLGAPSIDESIDEWHITE":
        res = talib.CDLGAPSIDESIDEWHITE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLGRAVESTONEDOJI":
        res = talib.CDLGRAVESTONEDOJI(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHAMMER":
        res = talib.CDLHAMMER(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHANGINGMAN":
        res = talib.CDLHANGINGMAN(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHARAMI":
        res = talib.CDLHARAMI(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHARAMICROSS":
        res = talib.CDLHARAMICROSS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHIGHWAVE":
        res = talib.CDLHIGHWAVE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHIKKAKE":
        res = talib.CDLHIKKAKE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHIKKAKEMOD":
        res = talib.CDLHIKKAKEMOD(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLHOMINGPIGEON":
        res = talib.CDLHOMINGPIGEON(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLIDENTICAL3CROWS":
        res = talib.CDLIDENTICAL3CROWS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLINNECK":
        res = talib.CDLINNECK(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLINVERTEDHAMMER":
        res = talib.CDLINVERTEDHAMMER(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLKICKING":
        res = talib.CDLKICKING(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLKICKINGBYLENGTH":
        res = talib.CDLKICKINGBYLENGTH(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLLADDERBOTTOM":
        res = talib.CDLLADDERBOTTOM(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLLONGLEGGEDDOJI":
        res = talib.CDLLONGLEGGEDDOJI(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLLONGLINE":
        res = talib.CDLLONGLINE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLMARUBOZU":
        res = talib.CDLMARUBOZU(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLMATCHINGLOW":
        res = talib.CDLMATCHINGLOW(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLMATHOLD":
        res = talib.CDLMATHOLD(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2], penetration=penetration)
    elif pattern_type == "CDLMORNINGDOJISTAR":
        res = talib.CDLMORNINGDOJISTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2],
                                       penetration=penetration)
    elif pattern_type == "CDLMORNINGSTAR":
        res = talib.CDLMORNINGSTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2], penetration=penetration)
    elif pattern_type == "CDLONNECK":
        res = talib.CDLONNECK(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLPIERCING":
        res = talib.CDLPIERCING(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLRICKSHAWMAN":
        res = talib.CDLRICKSHAWMAN(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLRISEFALL3METHODS":
        res = talib.CDLRISEFALL3METHODS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLSEPARATINGLINES":
        res = talib.CDLSEPARATINGLINES(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLSHOOTINGSTAR":
        res = talib.CDLSHOOTINGSTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLSHORTLINE":
        res = talib.CDLSHORTLINE(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLSPINNINGTOP":
        res = talib.CDLSPINNINGTOP(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLSTALLEDPATTERN":
        res = talib.CDLSTALLEDPATTERN(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLSTICKSANDWICH":
        res = talib.CDLSTICKSANDWICH(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLTAKURI":
        res = talib.CDLTAKURI(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLTASUKIGAP":
        res = talib.CDLTASUKIGAP(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLTHRUSTING":
        res = talib.CDLTHRUSTING(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLTRISTAR":
        res = talib.CDLTRISTAR(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLUNIQUE3RIVER":
        res = talib.CDLUNIQUE3RIVER(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLUPSIDEGAP2CROWS":
        res = talib.CDLUPSIDEGAP2CROWS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    elif pattern_type == "CDLXSIDEGAP3METHODS":
        res = talib.CDLXSIDEGAP3METHODS(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2])
    else:
        raise ValueError('pattern type string not recognised')

    return res / 100 if sequential else res[-1] / 100
Esempio n. 25
0
def TALIB_CDLSPINNINGTOP(close):
    '''00449,1,1'''
    return talib.CDLSPINNINGTOP(close)
def get_technical_indicators(dataset):
    # Create 7 and 21 days Moving Average
    dataset['ma7'] = dataset['Adj Close'].rolling(window=7).mean()
    dataset['ma21'] = dataset['Adj Close'].rolling(window=21).mean()

    # Create Exponential moving average
    dataset['ema'] = dataset['Adj Close'].ewm(com=0.5).mean()

    # Create MACD
    dataset['26ema'] = dataset['Adj Close'].ewm(span=26).mean()
    dataset['12ema'] = dataset['Adj Close'].ewm(span=12).mean()
    dataset['MACD'] = (dataset['12ema'] - dataset['26ema'])

    # Create Momentum
    dataset['momentum'] = dataset['Adj Close'] - 1

    # Create Bollinger Bands
    dataset['20sd'] = dataset['Adj Close'].rolling(20).std()
    dataset['upper_band'] = dataset['ma21'] + (dataset['20sd'] * 2)
    dataset['lower_band'] = dataset['ma21'] - (dataset['20sd'] * 2)

    # Create RSI indicator
    dataset['RSI'] = ta.RSI(np.array(dataset['Adj Close']))

    #Part I: Create Cycle Indicators
    #Create HT_DCPERIOD - Hilbert Transform - Dominant Cycle Period
    dataset['HT_DCPERIOD'] = ta.HT_DCPERIOD(np.array(dataset['Adj Close']))

    #Create HT_DCPHASE - Hilbert Transform - Dominant Cycle Phase
    dataset['HT_DCPHASE'] = ta.HT_DCPHASE(np.array(dataset['Adj Close']))

    #HT_TRENDMODE - Hilbert Transform - Trend vs Cycle Mode
    dataset['HT_TRENDMODE'] = ta.HT_TRENDMODE(np.array(dataset['Adj Close']))

    #Part II: Create Volatility Indicators
    #Create Average True Range
    dataset['ATR'] = ta.ATR(np.array(dataset['High']),
                            np.array(dataset['Low']),
                            np.array(dataset['Adj Close']),
                            timeperiod=14)

    #Create NATR - Normalized Average True Range
    dataset['NATR'] = ta.NATR(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)

    #Create TRANGE - True Range
    dataset['TRANGE'] = ta.TRANGE(np.array(dataset['High']),
                                  np.array(dataset['Low']),
                                  np.array(dataset['Adj Close']))

    #Part III Overlap Studies
    #Create DEMA - Double Exponential Moving Average
    dataset['DEMA'] = ta.DEMA(np.array(dataset['Adj Close']), timeperiod=30)

    #Create HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline
    dataset['HT_TRENDLINE'] = ta.HT_TRENDLINE(np.array(dataset['Adj Close']))

    #Create KAMA - Kaufman Adaptive Moving Average
    dataset['KAMA'] = ta.KAMA(np.array(dataset['Adj Close']), timeperiod=30)

    #Create MIDPOINT - MidPoint over period
    dataset['MIDPOINT'] = ta.MIDPOINT(np.array(dataset['Adj Close']),
                                      timeperiod=14)

    #Create MIDPRICE - Midpoint Price over period
    dataset['MIDPRICE'] = ta.MIDPRICE(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      timeperiod=14)

    #Create SAR - Parabolic SAR
    dataset['SAR'] = ta.SAR(np.array(dataset['High']),
                            np.array(dataset['Low']),
                            acceleration=0,
                            maximum=0)

    #Create SMA - Simple Moving Average
    dataset['SMA10'] = ta.SMA(np.array(dataset['Adj Close']), timeperiod=10)

    #Create T3 - Triple Exponential Moving Average (T3)
    dataset['T3'] = ta.T3(np.array(dataset['Adj Close']),
                          timeperiod=5,
                          vfactor=0)

    #Create TRIMA - Triangular Moving Average
    dataset['TRIMA'] = ta.TRIMA(np.array(dataset['Adj Close']), timeperiod=30)

    #Create WMA - Weighted Moving Average
    dataset['WMA'] = ta.WMA(np.array(dataset['Adj Close']), timeperiod=30)

    #PART IV Momentum Indicators
    #Create ADX - Average Directional Movement Index
    dataset['ADX14'] = ta.ADX(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)
    dataset['ADX20'] = ta.ADX(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=20)

    #Create ADXR - Average Directional Movement Index Rating
    dataset['ADXR'] = ta.ADXR(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)

    #Create APO - Absolute Price Oscillator
    dataset['APO'] = ta.APO(np.array(dataset['Adj Close']),
                            fastperiod=12,
                            slowperiod=26,
                            matype=0)

    #Create AROONOSC - Aroon Oscillator
    dataset['AROONOSC'] = ta.AROONOSC(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      timeperiod=14)

    #Create BOP - Balance Of Power
    dataset['BOP'] = ta.BOP(np.array(dataset['Open']),
                            np.array(dataset['High']),
                            np.array(dataset['Low']),
                            np.array(dataset['Adj Close']))

    #Create CCI - Commodity Channel Index
    dataset['CCI3'] = ta.CCI(np.array(dataset['High']),
                             np.array(dataset['Low']),
                             np.array(dataset['Adj Close']),
                             timeperiod=3)
    dataset['CCI5'] = ta.CCI(np.array(dataset['High']),
                             np.array(dataset['Low']),
                             np.array(dataset['Adj Close']),
                             timeperiod=5)
    dataset['CCI10'] = ta.CCI(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=10)
    dataset['CCI14'] = ta.CCI(np.array(dataset['High']),
                              np.array(dataset['Low']),
                              np.array(dataset['Adj Close']),
                              timeperiod=14)

    #Create CMO - Chande Momentum Oscillator
    dataset['CMO'] = ta.CMO(np.array(dataset['Adj Close']), timeperiod=14)

    #Create DX - Directional Movement Index
    dataset['DX'] = ta.DX(np.array(dataset['High']),
                          np.array(dataset['Low']),
                          np.array(dataset['Adj Close']),
                          timeperiod=14)

    #Create MINUS_DI - Minus Directional Indicator
    dataset['MINUS_DI'] = ta.MINUS_DI(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      np.array(dataset['Adj Close']),
                                      timeperiod=14)

    #Create MINUS_DM - Minus Directional Movement
    dataset['MINUS_DM'] = ta.MINUS_DM(np.array(dataset['High']),
                                      np.array(dataset['Low']),
                                      timeperiod=14)

    #Create MOM - Momentum
    dataset['MOM3'] = ta.MOM(np.array(dataset['Adj Close']), timeperiod=3)
    dataset['MOM5'] = ta.MOM(np.array(dataset['Adj Close']), timeperiod=5)
    dataset['MOM10'] = ta.MOM(np.array(dataset['Adj Close']), timeperiod=10)

    #Create PLUS_DI - Plus Directional Indicator
    dataset['PLUS_DI'] = ta.PLUS_DI(np.array(dataset['High']),
                                    np.array(dataset['Low']),
                                    np.array(dataset['Adj Close']),
                                    timeperiod=14)

    #Create PLUS_DM - Plus Directional Movement
    dataset['PLUS_DM'] = ta.PLUS_DM(np.array(dataset['High']),
                                    np.array(dataset['Low']),
                                    timeperiod=14)

    #Create PPO - Percentage Price Oscillator
    dataset['PPO'] = ta.PPO(np.array(dataset['Adj Close']),
                            fastperiod=12,
                            slowperiod=26,
                            matype=0)

    #Create ROC - Rate of change : ((price/prevPrice)-1)*100
    dataset['ROC'] = ta.ROC(np.array(dataset['Adj Close']), timeperiod=10)

    #Create ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice
    dataset['ROCP'] = ta.ROCP(np.array(dataset['Adj Close']), timeperiod=10)

    #Create ROCR - Rate of change ratio: (price/prevPrice)
    dataset['ROCR'] = ta.ROCR(np.array(dataset['Adj Close']), timeperiod=10)

    #Create ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    dataset['ROCR100'] = ta.ROCR100(np.array(dataset['Adj Close']),
                                    timeperiod=10)

    #Create RSI - Relative Strength Index
    dataset['RSI5'] = ta.RSI(np.array(dataset['Adj Close']), timeperiod=5)
    dataset['RSI10'] = ta.RSI(np.array(dataset['Adj Close']), timeperiod=10)
    dataset['RSI14'] = ta.RSI(np.array(dataset['Adj Close']), timeperiod=14)

    #Create TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    dataset['TRIX'] = ta.TRIX(np.array(dataset['Adj Close']), timeperiod=30)

    #Create ULTOSC - Ultimate Oscillator
    dataset['ULTOSC'] = ta.ULTOSC(np.array(dataset['High']),
                                  np.array(dataset['Low']),
                                  np.array(dataset['Adj Close']),
                                  timeperiod1=7,
                                  timeperiod2=14,
                                  timeperiod3=28)

    #Create WILLR - Williams' %R
    dataset['WILLR'] = ta.WILLR(np.array(dataset['High']),
                                np.array(dataset['Low']),
                                np.array(dataset['Adj Close']),
                                timeperiod=14)

    #Part V Pattern Recognition
    #Create  CDL2CROWS - Two Crows
    dataset['CDL2CROWS'] = ta.CDL2CROWS(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDL3BLACKCROWS - Three Black Crows
    dataset['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDL3INSIDE - Three Inside Up/Down
    dataset['CDL3INSIDE'] = ta.CDL3INSIDE(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDL3LINESTRIKE - Three-Line Strike
    dataset['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDL3OUTSIDE - Three Outside Up/Down
    dataset['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDL3STARSINSOUTH - Three Stars In The South
    dataset['CDL3STARSINSOUTH '] = ta.CDL3STARSINSOUTH(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDL3WHITESOLDIERS - Three Advancing White Soldiers
    dataset['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLABANDONEDBABY - Abandoned Baby
    dataset['CDLABANDONEDBABY'] = ta.CDLABANDONEDBABY(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLADVANCEBLOCK - Advance Block
    dataset['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLBELTHOLD - Belt-hold
    dataset['CDLBELTHOLD'] = ta.CDLBELTHOLD(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLBREAKAWAY - Breakaway
    dataset['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLCLOSINGMARUBOZU - Closing Marubozu
    dataset['CDLCLOSINGMARUBOZU'] = ta.CDLCLOSINGMARUBOZU(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLCONCEALBABYSWALL - Concealing Baby Swalnp.array(dataset['Low'])
    dataset['CDLCONCEALBABYSWALL'] = ta.CDLCONCEALBABYSWALL(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLCOUNTERATTACK - Counterattack
    dataset['CDLCOUNTERATTACK'] = ta.CDLCOUNTERATTACK(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLDARKCLOUDCOVER - Dark Cloud Cover
    dataset['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLDOJI - Doji
    dataset['CDLDOJI'] = ta.CDLDOJI(np.array(dataset['Open']),
                                    np.array(dataset['High']),
                                    np.array(dataset['Low']),
                                    np.array(dataset['Adj Close']))

    #Create CDLDOJISTAR - Doji Star
    dataset['CDLDOJISTAR'] = ta.CDLDOJISTAR(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLDRAGONFLYDOJI - Dragonfly Doji
    dataset['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLENGULFING - Engulfing Pattern
    dataset['CDLENGULFING'] = ta.CDLENGULFING(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLEVENINGDOJISTAR - Evening Doji Star
    dataset['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLEVENINGSTAR - Evening Star
    dataset['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(np.array(dataset['Open']),
                                                  np.array(dataset['High']),
                                                  np.array(dataset['Low']),
                                                  np.array(
                                                      dataset['Adj Close']),
                                                  penetration=0)

    #Create CDLGAPSIDESIDEWHITE - Up/Down-gap side-by-side white lines
    dataset['CDLGAPSIDESIDEWHITE'] = ta.CDLGAPSIDESIDEWHITE(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLGRAVESTONEDOJI - Gravestone Doji
    dataset['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLHAMMER - Hammer
    dataset['CDLHAMMER'] = ta.CDLHAMMER(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLHANGINGMAN - Hanging Man
    dataset['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(np.array(dataset['Open']),
                                                np.array(dataset['High']),
                                                np.array(dataset['Low']),
                                                np.array(dataset['Adj Close']))

    #Create CDLHARAMI - Harami Pattern
    dataset['CDLHARAMI'] = ta.CDLHARAMI(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLHARAMICROSS - Harami Cross Pattern
    dataset['CDLHARAMICROSS'] = ta.CDLHARAMICROSS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLHIGHWAVE - High-Wave Candle
    dataset['CDLHIGHWAVE'] = ta.CDLHIGHWAVE(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLHIKKAKE - Hikkake Pattern
    dataset['CDLHIKKAKE'] = ta.CDLHIKKAKE(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDLHIKKAKEMOD - Modified Hikkake Pattern
    dataset['CDLHIKKAKEMOD'] = ta.CDLHIKKAKEMOD(np.array(dataset['Open']),
                                                np.array(dataset['High']),
                                                np.array(dataset['Low']),
                                                np.array(dataset['Adj Close']))

    #Create CDLHOMINGPIGEON - Homing Pigeon
    dataset['CDLHOMINGPIGEON'] = ta.CDLHOMINGPIGEON(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLIDENTICAL3CROWS - Identical Three Crows
    dataset['CDLIDENTICAL3CROWS'] = ta.CDLIDENTICAL3CROWS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLINNECK - In-Neck Pattern
    dataset['CDLINNECK'] = ta.CDLINNECK(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLINVERTEDHAMMER - Inverted Hammer
    dataset['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLKICKING - Kicking
    dataset['CDLKICKING'] = ta.CDLKICKING(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDLKICKINGBYLENGTH - Kicking - bull/bear determined by the longer marubozu
    dataset['CDLKICKINGBYLENGTH'] = ta.CDLKICKINGBYLENGTH(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLLADDERBOTTOM - Ladder Bottom
    dataset['CDLLADDERBOTTOM'] = ta.CDLLADDERBOTTOM(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLLONGLEGGEDDOJI - Long Legged Doji
    dataset['CDLLONGLEGGEDDOJI'] = ta.CDLLONGLEGGEDDOJI(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLLONGLINE - Long Line Candle
    dataset['CDLLONGLINE'] = ta.CDLLONGLINE(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLMARUBOZU - Marubozu
    dataset['CDLMARUBOZU'] = ta.CDLMARUBOZU(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLMATCHINGLOW - Matching Low
    dataset['CDLMATCHINGLOW'] = ta.CDLMATCHINGLOW(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLMATHOLD - Mat Hold
    dataset['CDLMATHOLD'] = ta.CDLMATHOLD(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']),
                                          penetration=0)

    #Create CDLMORNINGDOJISTAR - Morning Doji Star
    dataset['CDLMORNINGDOJISTAR'] = ta.CDLMORNINGDOJISTAR(
        np.array(dataset['Open']),
        np.array(dataset['High']),
        np.array(dataset['Low']),
        np.array(dataset['Adj Close']),
        penetration=0)

    #Create CDLMORNINGSTAR - Morning Star
    dataset['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(np.array(dataset['Open']),
                                                  np.array(dataset['High']),
                                                  np.array(dataset['Low']),
                                                  np.array(
                                                      dataset['Adj Close']),
                                                  penetration=0)

    #Create CDLONNECK - On-Neck Pattern
    dataset['CDLONNECK'] = ta.CDLONNECK(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLPIERCING - Piercing Pattern
    dataset['CDLPIERCING'] = ta.CDLPIERCING(np.array(dataset['Open']),
                                            np.array(dataset['High']),
                                            np.array(dataset['Low']),
                                            np.array(dataset['Adj Close']))

    #Create CDLRICKSHAWMAN - Rickshaw Man
    dataset['CDLRICKSHAWMAN'] = ta.CDLRICKSHAWMAN(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLRISEFALL3METHODS - Rising/Falling Three Methods
    dataset['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSEPARATINGLINES - Separating Lines
    dataset['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSHOOTINGSTAR - Shooting Star
    dataset['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSHORTLINE - Short Line Candle
    dataset['CDLSHORTLINE'] = ta.CDLSHORTLINE(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLSPINNINGTOP - Spinning Top
    dataset['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSTALLEDPATTERN - Stalled Pattern
    dataset['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLSTICKSANDWICH - Stick Sandwich
    dataset['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLTAKURI - Takuri (Dragonfly Doji with very long np.array(dataset['Low'])er shadow)
    dataset['CDLTAKURI'] = ta.CDLTAKURI(np.array(dataset['Open']),
                                        np.array(dataset['High']),
                                        np.array(dataset['Low']),
                                        np.array(dataset['Adj Close']))

    #Create CDLTASUKIGAP - Tasuki Gap
    dataset['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLTHRUSTING - Thrusting Pattern
    dataset['CDLTHRUSTING'] = ta.CDLTHRUSTING(np.array(dataset['Open']),
                                              np.array(dataset['High']),
                                              np.array(dataset['Low']),
                                              np.array(dataset['Adj Close']))

    #Create CDLTRISTAR - Tristar Pattern
    dataset['CDLTRISTAR'] = ta.CDLTRISTAR(np.array(dataset['Open']),
                                          np.array(dataset['High']),
                                          np.array(dataset['Low']),
                                          np.array(dataset['Adj Close']))

    #Create CDLUNIQUE3RIVER - Unique 3 River
    dataset['CDLUNIQUE3RIVER'] = ta.CDLUNIQUE3RIVER(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLUPSIDEGAP2CROWS - Upside Gap Two Crows
    dataset['CDLUPSIDEGAP2CROWS'] = ta.CDLUPSIDEGAP2CROWS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    #Create CDLXSIDEGAP3METHODS - Upside/Downside Gap Three Methods
    dataset['CDLXSIDEGAP3METHODS'] = ta.CDLXSIDEGAP3METHODS(
        np.array(dataset['Open']), np.array(dataset['High']),
        np.array(dataset['Low']), np.array(dataset['Adj Close']))

    return dataset
Esempio n. 27
0
    def calculate(self, para):

        self.t = self.inputdata[:, 0]
        self.op = self.inputdata[:, 1]
        self.high = self.inputdata[:, 2]
        self.low = self.inputdata[:, 3]
        self.close = self.inputdata[:, 4]
        #adjusted close
        self.close1 = self.inputdata[:, 5]
        self.volume = self.inputdata[:, 6]
        #Overlap study

        #Overlap Studies
        #Overlap Studies
        if para is 'BBANDS':  #Bollinger Bands
            upperband, middleband, lowerband = ta.BBANDS(self.close,
                                                         timeperiod=self.tp,
                                                         nbdevup=2,
                                                         nbdevdn=2,
                                                         matype=0)
            self.output = [upperband, middleband, lowerband]

        elif para is 'DEMA':  #Double Exponential Moving Average
            self.output = ta.DEMA(self.close, timeperiod=self.tp)

        elif para is 'EMA':  #Exponential Moving Average
            self.output = ta.EMA(self.close, timeperiod=self.tp)

        elif para is 'HT_TRENDLINE':  #Hilbert Transform - Instantaneous Trendline
            self.output = ta.HT_TRENDLINE(self.close)

        elif para is 'KAMA':  #Kaufman Adaptive Moving Average
            self.output = ta.KAMA(self.close, timeperiod=self.tp)

        elif para is 'MA':  #Moving average
            self.output = ta.MA(self.close, timeperiod=self.tp, matype=0)

        elif para is 'MAMA':  #MESA Adaptive Moving Average
            mama, fama = ta.MAMA(self.close, fastlimit=0, slowlimit=0)

        elif para is 'MAVP':  #Moving average with variable period
            self.output = ta.MAVP(self.close,
                                  periods=10,
                                  minperiod=self.tp,
                                  maxperiod=self.tp1,
                                  matype=0)

        elif para is 'MIDPOINT':  #MidPoint over period
            self.output = ta.MIDPOINT(self.close, timeperiod=self.tp)

        elif para is 'MIDPRICE':  #Midpoint Price over period
            self.output = ta.MIDPRICE(self.high, self.low, timeperiod=self.tp)

        elif para is 'SAR':  #Parabolic SAR
            self.output = ta.SAR(self.high,
                                 self.low,
                                 acceleration=0,
                                 maximum=0)

        elif para is 'SAREXT':  #Parabolic SAR - Extended
            self.output = ta.SAREXT(self.high,
                                    self.low,
                                    startvalue=0,
                                    offsetonreverse=0,
                                    accelerationinitlong=0,
                                    accelerationlong=0,
                                    accelerationmaxlong=0,
                                    accelerationinitshort=0,
                                    accelerationshort=0,
                                    accelerationmaxshort=0)

        elif para is 'SMA':  #Simple Moving Average
            self.output = ta.SMA(self.close, timeperiod=self.tp)

        elif para is 'T3':  #Triple Exponential Moving Average (T3)
            self.output = ta.T3(self.close, timeperiod=self.tp, vfactor=0)

        elif para is 'TEMA':  #Triple Exponential Moving Average
            self.output = ta.TEMA(self.close, timeperiod=self.tp)

        elif para is 'TRIMA':  #Triangular Moving Average
            self.output = ta.TRIMA(self.close, timeperiod=self.tp)

        elif para is 'WMA':  #Weighted Moving Average
            self.output = ta.WMA(self.close, timeperiod=self.tp)

        #Momentum Indicators
        elif para is 'ADX':  #Average Directional Movement Index
            self.output = ta.ADX(self.high,
                                 self.low,
                                 self.close,
                                 timeperiod=self.tp)

        elif para is 'ADXR':  #Average Directional Movement Index Rating
            self.output = ta.ADXR(self.high,
                                  self.low,
                                  self.close,
                                  timeperiod=self.tp)

        elif para is 'APO':  #Absolute Price Oscillator
            self.output = ta.APO(self.close,
                                 fastperiod=12,
                                 slowperiod=26,
                                 matype=0)

        elif para is 'AROON':  #Aroon
            aroondown, aroonup = ta.AROON(self.high,
                                          self.low,
                                          timeperiod=self.tp)
            self.output = [aroondown, aroonup]

        elif para is 'AROONOSC':  #Aroon Oscillator
            self.output = ta.AROONOSC(self.high, self.low, timeperiod=self.tp)

        elif para is 'BOP':  #Balance Of Power
            self.output = ta.BOP(self.op, self.high, self.low, self.close)

        elif para is 'CCI':  #Commodity Channel Index
            self.output = ta.CCI(self.high,
                                 self.low,
                                 self.close,
                                 timeperiod=self.tp)

        elif para is 'CMO':  #Chande Momentum Oscillator
            self.output = ta.CMO(self.close, timeperiod=self.tp)

        elif para is 'DX':  #Directional Movement Index
            self.output = ta.DX(self.high,
                                self.low,
                                self.close,
                                timeperiod=self.tp)

        elif para is 'MACD':  #Moving Average Convergence/Divergence
            macd, macdsignal, macdhist = ta.MACD(self.close,
                                                 fastperiod=12,
                                                 slowperiod=26,
                                                 signalperiod=9)
            self.output = [macd, macdsignal, macdhist]
        elif para is 'MACDEXT':  #MACD with controllable MA type
            macd, macdsignal, macdhist = ta.MACDEXT(self.close,
                                                    fastperiod=12,
                                                    fastmatype=0,
                                                    slowperiod=26,
                                                    slowmatype=0,
                                                    signalperiod=9,
                                                    signalmatype=0)
            self.output = [macd, macdsignal, macdhist]
        elif para is 'MACDFIX':  #Moving Average Convergence/Divergence Fix 12/26
            macd, macdsignal, macdhist = ta.MACDFIX(self.close, signalperiod=9)
            self.output = [macd, macdsignal, macdhist]
        elif para is 'MFI':  #Money Flow Index
            self.output = ta.MFI(self.high,
                                 self.low,
                                 self.close,
                                 self.volume,
                                 timeperiod=self.tp)

        elif para is 'MINUS_DI':  #Minus Directional Indicator
            self.output = ta.MINUS_DI(self.high,
                                      self.low,
                                      self.close,
                                      timeperiod=self.tp)

        elif para is 'MINUS_DM':  #Minus Directional Movement
            self.output = ta.MINUS_DM(self.high, self.low, timeperiod=self.tp)

        elif para is 'MOM':  #Momentum
            self.output = ta.MOM(self.close, timeperiod=10)

        elif para is 'PLUS_DI':  #Plus Directional Indicator
            self.output = ta.PLUS_DI(self.high,
                                     self.low,
                                     self.close,
                                     timeperiod=self.tp)

        elif para is 'PLUS_DM':  #Plus Directional Movement
            self.output = ta.PLUS_DM(self.high, self.low, timeperiod=self.tp)

        elif para is 'PPO':  #Percentage Price Oscillator
            self.output = ta.PPO(self.close,
                                 fastperiod=12,
                                 slowperiod=26,
                                 matype=0)

        elif para is 'ROC':  #Rate of change : ((price/prevPrice)-1)*100
            self.output = ta.ROC(self.close, timeperiod=10)

        elif para is 'ROCP':  #Rate of change Percentage: (price-prevPrice)/prevPrice
            self.output = ta.ROCP(self.close, timeperiod=10)

        elif para is 'ROCR':  #Rate of change ratio: (price/prevPrice)
            self.output = ta.ROCR(self.close, timeperiod=10)

        elif para is 'ROCR100':  #Rate of change ratio 100 scale: (price/prevPrice)*100
            self.output = ta.ROCR100(self.close, timeperiod=10)

        elif para is 'RSI':  #Relative Strength Index
            self.output = ta.RSI(self.close, timeperiod=self.tp)

        elif para is 'STOCH':  #Stochastic
            slowk, slowd = ta.STOCH(self.high,
                                    self.low,
                                    self.close,
                                    fastk_period=5,
                                    slowk_period=3,
                                    slowk_matype=0,
                                    slowd_period=3,
                                    slowd_matype=0)
            self.output = [slowk, slowd]

        elif para is 'STOCHF':  #Stochastic Fast
            fastk, fastd = ta.STOCHF(self.high,
                                     self.low,
                                     self.close,
                                     fastk_period=5,
                                     fastd_period=3,
                                     fastd_matype=0)
            self.output = [fastk, fastd]

        elif para is 'STOCHRSI':  #Stochastic Relative Strength Index
            fastk, fastd = ta.STOCHRSI(self.close,
                                       timeperiod=self.tp,
                                       fastk_period=5,
                                       fastd_period=3,
                                       fastd_matype=0)
            self.output = [fastk, fastd]

        elif para is 'TRIX':  #1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
            self.output = ta.TRIX(self.close, timeperiod=self.tp)

        elif para is 'ULTOSC':  #Ultimate Oscillator
            self.output = ta.ULTOSC(self.high,
                                    self.low,
                                    self.close,
                                    timeperiod1=self.tp,
                                    timeperiod2=self.tp1,
                                    timeperiod3=self.tp2)

        elif para is 'WILLR':  #Williams' %R
            self.output = ta.WILLR(self.high,
                                   self.low,
                                   self.close,
                                   timeperiod=self.tp)

        # Volume Indicators    : #
        elif para is 'AD':  #Chaikin A/D Line
            self.output = ta.AD(self.high, self.low, self.close, self.volume)

        elif para is 'ADOSC':  #Chaikin A/D Oscillator
            self.output = ta.ADOSC(self.high,
                                   self.low,
                                   self.close,
                                   self.volume,
                                   fastperiod=3,
                                   slowperiod=10)

        elif para is 'OBV':  #On Balance Volume
            self.output = ta.OBV(self.close, self.volume)

    # Volatility Indicators: #
        elif para is 'ATR':  #Average True Range
            self.output = ta.ATR(self.high,
                                 self.low,
                                 self.close,
                                 timeperiod=self.tp)

        elif para is 'NATR':  #Normalized Average True Range
            self.output = ta.NATR(self.high,
                                  self.low,
                                  self.close,
                                  timeperiod=self.tp)

        elif para is 'TRANGE':  #True Range
            self.output = ta.TRANGE(self.high, self.low, self.close)

        #Price Transform      : #
        elif para is 'AVGPRICE':  #Average Price
            self.output = ta.AVGPRICE(self.op, self.high, self.low, self.close)

        elif para is 'MEDPRICE':  #Median Price
            self.output = ta.MEDPRICE(self.high, self.low)

        elif para is 'TYPPRICE':  #Typical Price
            self.output = ta.TYPPRICE(self.high, self.low, self.close)

        elif para is 'WCLPRICE':  #Weighted Close Price
            self.output = ta.WCLPRICE(self.high, self.low, self.close)

        #Cycle Indicators     : #
        elif para is 'HT_DCPERIOD':  #Hilbert Transform - Dominant Cycle Period
            self.output = ta.HT_DCPERIOD(self.close)

        elif para is 'HT_DCPHASE':  #Hilbert Transform - Dominant Cycle Phase
            self.output = ta.HT_DCPHASE(self.close)

        elif para is 'HT_PHASOR':  #Hilbert Transform - Phasor Components
            inphase, quadrature = ta.HT_PHASOR(self.close)
            self.output = [inphase, quadrature]

        elif para is 'HT_SINE':  #Hilbert Transform - SineWave #2
            sine, leadsine = ta.HT_SINE(self.close)
            self.output = [sine, leadsine]

        elif para is 'HT_TRENDMODE':  #Hilbert Transform - Trend vs Cycle Mode
            self.integer = ta.HT_TRENDMODE(self.close)

        #Pattern Recognition  : #
        elif para is 'CDL2CROWS':  #Two Crows
            self.integer = ta.CDL2CROWS(self.op, self.high, self.low,
                                        self.close)

        elif para is 'CDL3BLACKCROWS':  #Three Black Crows
            self.integer = ta.CDL3BLACKCROWS(self.op, self.high, self.low,
                                             self.close)

        elif para is 'CDL3INSIDE':  #Three Inside Up/Down
            self.integer = ta.CDL3INSIDE(self.op, self.high, self.low,
                                         self.close)

        elif para is 'CDL3LINESTRIKE':  #Three-Line Strike
            self.integer = ta.CDL3LINESTRIKE(self.op, self.high, self.low,
                                             self.close)

        elif para is 'CDL3OUTSIDE':  #Three Outside Up/Down
            self.integer = ta.CDL3OUTSIDE(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDL3STARSINSOUTH':  #Three Stars In The South
            self.integer = ta.CDL3STARSINSOUTH(self.op, self.high, self.low,
                                               self.close)

        elif para is 'CDL3WHITESOLDIERS':  #Three Advancing White Soldiers
            self.integer = ta.CDL3WHITESOLDIERS(self.op, self.high, self.low,
                                                self.close)

        elif para is 'CDLABANDONEDBABY':  #Abandoned Baby
            self.integer = ta.CDLABANDONEDBABY(self.op,
                                               self.high,
                                               self.low,
                                               self.close,
                                               penetration=0)

        elif para is 'CDLBELTHOLD':  #Belt-hold
            self.integer = ta.CDLBELTHOLD(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDLBREAKAWAY':  #Breakaway
            self.integer = ta.CDLBREAKAWAY(self.op, self.high, self.low,
                                           self.close)

        elif para is 'CDLCLOSINGMARUBOZU':  #Closing Marubozu
            self.integer = ta.CDLCLOSINGMARUBOZU(self.op, self.high, self.low,
                                                 self.close)

        elif para is 'CDLCONCEALBABYSWALL':  #Concealing Baby Swallow
            self.integer = ta.CDLCONCEALBABYSWALL(self.op, self.high, self.low,
                                                  self.close)

        elif para is 'CDLCOUNTERATTACK':  #Counterattack
            self.integer = ta.CDLCOUNTERATTACK(self.op, self.high, self.low,
                                               self.close)

        elif para is 'CDLDARKCLOUDCOVER':  #Dark Cloud Cover
            self.integer = ta.CDLDARKCLOUDCOVER(self.op,
                                                self.high,
                                                self.low,
                                                self.close,
                                                penetration=0)

        elif para is 'CDLDOJI':  #Doji
            self.integer = ta.CDLDOJI(self.op, self.high, self.low, self.close)

        elif para is 'CDLDOJISTAR':  #Doji Star
            self.integer = ta.CDLDOJISTAR(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDLDRAGONFLYDOJI':  #Dragonfly Doji
            self.integer = ta.CDLDRAGONFLYDOJI(self.op, self.high, self.low,
                                               self.close)

        elif para is 'CDLENGULFING':  #Engulfing Pattern
            self.integer = ta.CDLENGULFING(self.op, self.high, self.low,
                                           self.close)

        elif para is 'CDLEVENINGDOJISTAR':  #Evening Doji Star
            self.integer = ta.CDLEVENINGDOJISTAR(self.op,
                                                 self.high,
                                                 self.low,
                                                 self.close,
                                                 penetration=0)

        elif para is 'CDLEVENINGSTAR':  #Evening Star
            self.integer = ta.CDLEVENINGSTAR(self.op,
                                             self.high,
                                             self.low,
                                             self.close,
                                             penetration=0)

        elif para is 'CDLGAPSIDESIDEWHITE':  #Up/Down-gap side-by-side white lines
            self.integer = ta.CDLGAPSIDESIDEWHITE(self.op, self.high, self.low,
                                                  self.close)

        elif para is 'CDLGRAVESTONEDOJI':  #Gravestone Doji
            self.integer = ta.CDLGRAVESTONEDOJI(self.op, self.high, self.low,
                                                self.close)

        elif para is 'CDLHAMMER':  #Hammer
            self.integer = ta.CDLHAMMER(self.op, self.high, self.low,
                                        self.close)

        elif para is 'CDLHANGINGMAN':  #Hanging Man
            self.integer = ta.CDLHANGINGMAN(self.op, self.high, self.low,
                                            self.close)

        elif para is 'CDLHARAMI':  #Harami Pattern
            self.integer = ta.CDLHARAMI(self.op, self.high, self.low,
                                        self.close)

        elif para is 'CDLHARAMICROSS':  #Harami Cross Pattern
            self.integer = ta.CDLHARAMICROSS(self.op, self.high, self.low,
                                             self.close)

        elif para is 'CDLHIGHWAVE':  #High-Wave Candle
            self.integer = ta.CDLHIGHWAVE(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDLHIKKAKE':  #Hikkake Pattern
            self.integer = ta.CDLHIKKAKE(self.op, self.high, self.low,
                                         self.close)

        elif para is 'CDLHIKKAKEMOD':  #Modified Hikkake Pattern
            self.integer = ta.CDLHIKKAKEMOD(self.op, self.high, self.low,
                                            self.close)

        elif para is 'CDLHOMINGPIGEON':  #Homing Pigeon
            self.integer = ta.CDLHOMINGPIGEON(self.op, self.high, self.low,
                                              self.close)

        elif para is 'CDLIDENTICAL3CROWS':  #Identical Three Crows
            self.integer = ta.CDLIDENTICAL3CROWS(self.op, self.high, self.low,
                                                 self.close)

        elif para is 'CDLINNECK':  #In-Neck Pattern
            self.integer = ta.CDLINNECK(self.op, self.high, self.low,
                                        self.close)

        elif para is 'CDLINVERTEDHAMMER':  #Inverted Hammer
            self.integer = ta.CDLINVERTEDHAMMER(self.op, self.high, self.low,
                                                self.close)

        elif para is 'CDLKICKING':  #Kicking
            self.integer = ta.CDLKICKING(self.op, self.high, self.low,
                                         self.close)

        elif para is 'CDLKICKINGBYLENGTH':  #Kicking - bull/bear determined by the longer marubozu
            self.integer = ta.CDLKICKINGBYLENGTH(self.op, self.high, self.low,
                                                 self.close)

        elif para is 'CDLLADDERBOTTOM':  #Ladder Bottom
            self.integer = ta.CDLLADDERBOTTOM(self.op, self.high, self.low,
                                              self.close)

        elif para is 'CDLLONGLEGGEDDOJI':  #Long Legged Doji
            self.integer = ta.CDLLONGLEGGEDDOJI(self.op, self.high, self.low,
                                                self.close)

        elif para is 'CDLLONGLINE':  #Long Line Candle
            self.integer = ta.CDLLONGLINE(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDLMARUBOZU':  #Marubozu
            self.integer = ta.CDLMARUBOZU(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDLMATCHINGLOW':  #Matching Low
            self.integer = ta.CDLMATCHINGLOW(self.op, self.high, self.low,
                                             self.close)

        elif para is 'CDLMATHOLD':  #Mat Hold
            self.integer = ta.CDLMATHOLD(self.op,
                                         self.high,
                                         self.low,
                                         self.close,
                                         penetration=0)

        elif para is 'CDLMORNINGDOJISTAR':  #Morning Doji Star
            self.integer = ta.CDLMORNINGDOJISTAR(self.op,
                                                 self.high,
                                                 self.low,
                                                 self.close,
                                                 penetration=0)

        elif para is 'CDLMORNINGSTAR':  #Morning Star
            self.integer = ta.CDLMORNINGSTAR(self.op,
                                             self.high,
                                             self.low,
                                             self.close,
                                             penetration=0)

        elif para is 'CDLONNECK':  #On-Neck Pattern
            self.integer = ta.CDLONNECK(self.op, self.high, self.low,
                                        self.close)

        elif para is 'CDLPIERCING':  #Piercing Pattern
            self.integer = ta.CDLPIERCING(self.op, self.high, self.low,
                                          self.close)

        elif para is 'CDLRICKSHAWMAN':  #Rickshaw Man
            self.integer = ta.CDLRICKSHAWMAN(self.op, self.high, self.low,
                                             self.close)

        elif para is 'CDLRISEFALL3METHODS':  #Rising/Falling Three Methods
            self.integer = ta.CDLRISEFALL3METHODS(self.op, self.high, self.low,
                                                  self.close)

        elif para is 'CDLSEPARATINGLINES':  #Separating Lines
            self.integer = ta.CDLSEPARATINGLINES(self.op, self.high, self.low,
                                                 self.close)

        elif para is 'CDLSHOOTINGSTAR':  #Shooting Star
            self.integer = ta.CDLSHOOTINGSTAR(self.op, self.high, self.low,
                                              self.close)

        elif para is 'CDLSHORTLINE':  #Short Line Candle
            self.integer = ta.CDLSHORTLINE(self.op, self.high, self.low,
                                           self.close)

        elif para is 'CDLSPINNINGTOP':  #Spinning Top
            self.integer = ta.CDLSPINNINGTOP(self.op, self.high, self.low,
                                             self.close)

        elif para is 'CDLSTALLEDPATTERN':  #Stalled Pattern
            self.integer = ta.CDLSTALLEDPATTERN(self.op, self.high, self.low,
                                                self.close)

        elif para is 'CDLSTICKSANDWICH':  #Stick Sandwich
            self.integer = ta.CDLSTICKSANDWICH(self.op, self.high, self.low,
                                               self.close)

        elif para is 'CDLTAKURI':  #Takuri (Dragonfly Doji with very long lower shadow)
            self.integer = ta.CDLTAKURI(self.op, self.high, self.low,
                                        self.close)

        elif para is 'CDLTASUKIGAP':  #Tasuki Gap
            self.integer = ta.CDLTASUKIGAP(self.op, self.high, self.low,
                                           self.close)

        elif para is 'CDLTHRUSTING':  #Thrusting Pattern
            self.integer = ta.CDLTHRUSTING(self.op, self.high, self.low,
                                           self.close)

        elif para is 'CDLTRISTAR':  #Tristar Pattern
            self.integer = ta.CDLTRISTAR(self.op, self.high, self.low,
                                         self.close)

        elif para is 'CDLUNIQUE3RIVER':  #Unique 3 River
            self.integer = ta.CDLUNIQUE3RIVER(self.op, self.high, self.low,
                                              self.close)

        elif para is 'CDLUPSIDEGAP2CROWS':  #Upside Gap Two Crows
            self.integer = ta.CDLUPSIDEGAP2CROWS(self.op, self.high, self.low,
                                                 self.close)

        elif para is 'CDLXSIDEGAP3METHODS':  #Upside/Downside Gap Three Methods
            self.integer = ta.CDLXSIDEGAP3METHODS(self.op, self.high, self.low,
                                                  self.close)

        #Statistic Functions  : #
        elif para is 'BETA':  #Beta
            self.output = ta.BETA(self.high, self.low, timeperiod=5)

        elif para is 'CORREL':  #Pearson's Correlation Coefficient (r)
            self.output = ta.CORREL(self.high, self.low, timeperiod=self.tp)

        elif para is 'LINEARREG':  #Linear Regression
            self.output = ta.LINEARREG(self.close, timeperiod=self.tp)

        elif para is 'LINEARREG_ANGLE':  #Linear Regression Angle
            self.output = ta.LINEARREG_ANGLE(self.close, timeperiod=self.tp)

        elif para is 'LINEARREG_INTERCEPT':  #Linear Regression Intercept
            self.output = ta.LINEARREG_INTERCEPT(self.close,
                                                 timeperiod=self.tp)

        elif para is 'LINEARREG_SLOPE':  #Linear Regression Slope
            self.output = ta.LINEARREG_SLOPE(self.close, timeperiod=self.tp)

        elif para is 'STDDEV':  #Standard Deviation
            self.output = ta.STDDEV(self.close, timeperiod=5, nbdev=1)

        elif para is 'TSF':  #Time Series Forecast
            self.output = ta.TSF(self.close, timeperiod=self.tp)

        elif para is 'VAR':  #Variance
            self.output = ta.VAR(self.close, timeperiod=5, nbdev=1)

        else:
            print('You issued command:' + para)
Esempio n. 28
0
def all_candels(df):
    df['two_crow'] = talib.CDL2CROWS(df.open,df.high,df.low,df.close)
    df['three_black_crows'] = talib.CDL3BLACKCROWS(df.open,df.high,df.low,df.close)
    df['threeinside updown'] = talib.CDL3INSIDE(df.open,df.high,df.low,df.close)
    df['threelinestrike'] = talib.CDL3LINESTRIKE(df.open,df.high,df.low,df.close)
    df['3outside'] = talib.CDL3OUTSIDE(df.open,df.high,df.low,df.close)
    df['3starsinsouth'] = talib.CDL3STARSINSOUTH(df.open,df.high,df.low,df.close)
    df['3WHITESOLDIERS'] = talib.CDL3WHITESOLDIERS(df.open,df.high,df.low,df.close)
    df['ABANDONEDBABY'] = talib.CDLABANDONEDBABY(df.open,df.high,df.low,df.close)
    df['ADVANCEBLOCK'] = talib.CDLADVANCEBLOCK(df.open,df.high,df.low,df.close)
    df['BELTHOLD'] = talib.CDLBELTHOLD(df.open,df.high,df.low,df.close)
    df['BREAKAWAY'] = talib.CDLBREAKAWAY(df.open,df.high,df.low,df.close)
    df['CLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(df.open,df.high,df.low,df.close)
    df['CONCEALBABYSWALL'] = talib.CDLCONCEALBABYSWALL(df.open,df.high,df.low,df.close)
    df['COUNTERATTACK'] = talib.CDLCOUNTERATTACK(df.open,df.high,df.low,df.close)

    df['DARKCLOUDCOVER'] = talib.CDLDARKCLOUDCOVER(df.open,df.high,df.low,df.close)
    df['DOJI'] = talib.CDLDOJI(df.open,df.high,df.low,df.close)
    df['DOJISTAR'] = talib.CDLDOJISTAR(df.open,df.high,df.low,df.close)
    df['DRAGONFLYDOJI'] = talib.CDLDRAGONFLYDOJI(df.open,df.high,df.low,df.close)
    df['ENGULFING'] = talib.CDLENGULFING(df.open,df.high,df.low,df.close)
    df['EVENINGDOJISTAR'] = talib.CDLEVENINGDOJISTAR(df.open,df.high,df.low,df.close)
    df['EVENINGSTAR'] = talib.CDLEVENINGSTAR(df.open,df.high,df.low,df.close)
    df['GAPSIDESIDEWHITE'] = talib.CDLGAPSIDESIDEWHITE(df.open,df.high,df.low,df.close)
    df['GRAVESTONEDOJI'] = talib.CDLGRAVESTONEDOJI(df.open,df.high,df.low,df.close)
    df['HAMMER'] = talib.CDLHAMMER(df.open,df.high,df.low,df.close)
    df['HANGINGMAN'] = talib.CDLHANGINGMAN(df.open,df.high,df.low,df.close)
    df['HARAMI'] = talib.CDLHARAMI(df.open,df.high,df.low,df.close)
    df['HARAMICROSS'] = talib.CDLHARAMICROSS(df.open,df.high,df.low,df.close)
    df['HIGHWAVE'] = talib.CDLHIGHWAVE(df.open,df.high,df.low,df.close)

    df['HIKKAKE'] = talib.CDLHIKKAKE(df.open,df.high,df.low,df.close)
    df['HIKKAKEMOD'] = talib.CDLHIKKAKEMOD(df.open,df.high,df.low,df.close)
    df['HOMINGPIGEON'] = talib.CDLHOMINGPIGEON(df.open,df.high,df.low,df.close)
    df['IDENTICAL3CROWS'] = talib.CDLIDENTICAL3CROWS(df.open,df.high,df.low,df.close)
    df['INNECK'] = talib.CDLINNECK(df.open,df.high,df.low,df.close)
    df['INVERTEDHAMMER'] = talib.CDLINVERTEDHAMMER(df.open,df.high,df.low,df.close)
    df['KICKING'] = talib.CDLKICKING(df.open,df.high,df.low,df.close)
    df['KICKINGBYLENGTH'] = talib.CDLKICKINGBYLENGTH(df.open,df.high,df.low,df.close)
    df['LADDERBOTTOM'] = talib.CDLLADDERBOTTOM(df.open,df.high,df.low,df.close)
    df['LONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(df.open,df.high,df.low,df.close)
    df['LONGLINE'] = talib.CDLLONGLINE(df.open,df.high,df.low,df.close)
    df['MARUBOZU'] = talib.CDLMARUBOZU(df.open,df.high,df.low,df.close)
    df['MATCHINGLOW'] = talib.CDLMATCHINGLOW(df.open,df.high,df.low,df.close)
    df['MATHOLD'] = talib.CDLMATHOLD(df.open,df.high,df.low,df.close)
    df['MORNINGDOJISTAR'] = talib.CDLMORNINGDOJISTAR(df.open,df.high,df.low,df.close)
    df['MORNINGSTAR'] = talib.CDLMORNINGSTAR(df.open,df.high,df.low,df.close)

    df['ONNECK'] = talib.CDLONNECK(df.open,df.high,df.low,df.close)
    df['PIERCING'] = talib.CDLPIERCING(df.open,df.high,df.low,df.close)
    df['RICKSHAWMAN'] = talib.CDLRICKSHAWMAN(df.open,df.high,df.low,df.close)
    df['RISEFALL3METHODS'] = talib.CDLRISEFALL3METHODS(df.open,df.high,df.low,df.close)
    df['SEPARATINGLINES'] = talib.CDLSEPARATINGLINES(df.open,df.high,df.low,df.close)
    df['SHOOTINGSTAR'] = talib.CDLSHOOTINGSTAR(df.open,df.high,df.low,df.close)
    df['SHORTLINE'] = talib.CDLSHORTLINE(df.open,df.high,df.low,df.close)
    df['SPINNINGTOP'] = talib.CDLSPINNINGTOP(df.open,df.high,df.low,df.close)
    df['STALLEDPATTERN'] = talib.CDLSTALLEDPATTERN(df.open,df.high,df.low,df.close)
    df['STICKSANDWICH'] = talib.CDLSTICKSANDWICH(df.open,df.high,df.low,df.close)
    df['TAKURI'] = talib.CDLTAKURI(df.open,df.high,df.low,df.close)
    df['TASUKIGAP'] = talib.CDLTASUKIGAP(df.open,df.high,df.low,df.close)
    df['THRUSTING'] = talib.CDLTHRUSTING(df.open,df.high,df.low,df.close)
    df['TRISTAR'] = talib.CDLTRISTAR(df.open,df.high,df.low,df.close)
    df['UNIQUE3RIVER'] = talib.CDLUNIQUE3RIVER(df.open,df.high,df.low,df.close)
    df['UPSIDEGAP2CROWS'] = talib.CDLUPSIDEGAP2CROWS(df.open,df.high,df.low,df.close)

    df['XSIDEGAP3METHODS'] = talib.CDLXSIDEGAP3METHODS(df.open,df.high,df.low,df.close)
    return df
def CDLSPINNINGTOP(DataFrame):
    res = talib.CDLSPINNINGTOP(DataFrame.open.values, DataFrame.high.values,
                               DataFrame.low.values, DataFrame.close.values)
    return pd.DataFrame({'CDLSPINNINGTOP': res}, index=DataFrame.index)
def built_in_scanners(ticker="SPY"):
    data = yf.download(ticker,
                       start="2020-01-01",
                       end=datetime.today().strftime('%Y-%m-%d'))
    open = data['Open']
    high = data['High']
    low = data['Low']
    close = data['Close']

    # The library's functions runs on yesterday's date, so subtract 1 from today's date.

    current_date = datetime.today() - timedelta(days=1)
    current_date_formatted = current_date.strftime('%Y-%m-%d')

    two_crows = talib.CDL2CROWS(open, high, low, close)[current_date_formatted]
    three_black_crows = talib.CDL3BLACKCROWS(open, high, low,
                                             close)[current_date_formatted]
    three_inside = talib.CDL3INSIDE(open, high, low,
                                    close)[current_date_formatted]
    three_line_strike = talib.CDL3LINESTRIKE(open, high, low,
                                             close)[current_date_formatted]
    three_outside = talib.CDL3OUTSIDE(open, high, low,
                                      close)[current_date_formatted]
    three_stars_in_south = talib.CDL3STARSINSOUTH(
        open, high, low, close)[current_date_formatted]
    three_white_soldiers = talib.CDL3WHITESOLDIERS(
        open, high, low, close)[current_date_formatted]
    abandoned_baby = talib.CDLABANDONEDBABY(open, high, low,
                                            close)[current_date_formatted]
    advance_block = talib.CDLADVANCEBLOCK(open, high, low,
                                          close)[current_date_formatted]
    belt_hold = talib.CDLBELTHOLD(open, high, low,
                                  close)[current_date_formatted]
    breakaway = talib.CDLBREAKAWAY(open, high, low,
                                   close)[current_date_formatted]
    closing_marubozu = talib.CDLCLOSINGMARUBOZU(open, high, low,
                                                close)[current_date_formatted]
    concealing_baby_swallow = talib.CDLCONCEALBABYSWALL(
        open, high, low, close)[current_date_formatted]
    talib.CDLCOUNTERATTACK(open, high, low, close)[current_date_formatted]
    dark_cloud_cover = talib.CDLDARKCLOUDCOVER(
        open, high, low, close, penetration=0)[current_date_formatted]
    doji = talib.CDLDOJI(open, high, low, close)[current_date_formatted]
    doji_star = talib.CDLDOJISTAR(open, high, low,
                                  close)[current_date_formatted]
    dragonfly_doji = talib.CDLDRAGONFLYDOJI(open, high, low,
                                            close)[current_date_formatted]
    engulfing_candle = talib.CDLENGULFING(open, high, low,
                                          close)[current_date_formatted]
    evening_doji_star = talib.CDLEVENINGDOJISTAR(
        open, high, low, close, penetration=0)[current_date_formatted]
    evening_star = talib.CDLEVENINGSTAR(open, high, low, close,
                                        penetration=0)[current_date_formatted]
    gaps = talib.CDLGAPSIDESIDEWHITE(open, high, low,
                                     close)[current_date_formatted]
    gravestone_doji = talib.CDLGRAVESTONEDOJI(open, high, low,
                                              close)[current_date_formatted]
    hammer = talib.CDLHAMMER(open, high, low, close)[current_date_formatted]
    hanging_man = talib.CDLHANGINGMAN(open, high, low,
                                      close)[current_date_formatted]
    harami = talib.CDLHARAMI(open, high, low, close)[current_date_formatted]
    harami_cross = talib.CDLHARAMICROSS(open, high, low,
                                        close)[current_date_formatted]
    high_wave = talib.CDLHIGHWAVE(
        open, high, low, close)[current_date_formatted][talib.CDLHIGHWAVE != 0]
    hikkake = talib.CDLHIKKAKE(open, high, low, close)[current_date_formatted]
    hikkakemod = talib.CDLHIKKAKEMOD(open, high, low,
                                     close)[current_date_formatted]
    homing_pigeon = talib.CDLHOMINGPIGEON(open, high, low,
                                          close)[current_date_formatted]
    identical_three_crows = talib.CDLIDENTICAL3CROWS(
        open, high, low, close)[current_date_formatted]
    in_neck = talib.CDLINNECK(open, high, low, close)[current_date_formatted]
    inverted_hammer = talib.CDLINVERTEDHAMMER(open, high, low,
                                              close)[current_date_formatted]
    kicking = talib.CDLKICKING(open, high, low, close)[current_date_formatted]
    kicking_by_length = talib.CDLKICKINGBYLENGTH(open, high, low,
                                                 close)[current_date_formatted]
    ladder_bottom = talib.CDLLADDERBOTTOM(open, high, low,
                                          close)[current_date_formatted]
    long_legged_doji = talib.CDLLONGLEGGEDDOJI(open, high, low,
                                               close)[current_date_formatted]
    long_line = talib.CDLLONGLINE(open, high, low,
                                  close)[current_date_formatted]
    marubozu = talib.CDLMARUBOZU(open, high, low,
                                 close)[current_date_formatted]
    matching_low = talib.CDLMATCHINGLOW(open, high, low,
                                        close)[current_date_formatted]
    mat_hold = talib.CDLMATHOLD(open, high, low, close,
                                penetration=0)[current_date_formatted]
    morning_doji_star = talib.CDLMORNINGDOJISTAR(
        open, high, low, close, penetration=0)[current_date_formatted]
    morning_star = talib.CDLMORNINGSTAR(open, high, low, close,
                                        penetration=0)[current_date_formatted]
    on_neck = talib.CDLONNECK(open, high, low, close)[current_date_formatted]
    piercing = talib.CDLPIERCING(open, high, low,
                                 close)[current_date_formatted]
    rickshawman = talib.CDLRICKSHAWMAN(open, high, low,
                                       close)[current_date_formatted]
    rise_fall_3_methods = talib.CDLRISEFALL3METHODS(
        open, high, low, close)[current_date_formatted]
    separating_lines = talib.CDLSEPARATINGLINES(open, high, low,
                                                close)[current_date_formatted]
    shooting_star = talib.CDLSHOOTINGSTAR(open, high, low,
                                          close)[current_date_formatted]
    shortline = talib.CDLSHORTLINE(open, high, low,
                                   close)[current_date_formatted]
    spinning_top = talib.CDLSPINNINGTOP(open, high, low,
                                        close)[current_date_formatted]
    stalled_pattern = talib.CDLSTALLEDPATTERN(open, high, low,
                                              close)[current_date_formatted]
    stick_sandwich = talib.CDLSTICKSANDWICH(open, high, low,
                                            close)[current_date_formatted]
    takuri = talib.CDLTAKURI(open, high, low, close)[current_date_formatted]
    tasuki_gap = talib.CDLTASUKIGAP(open, high, low,
                                    close)[current_date_formatted]
    thrusting = talib.CDLTHRUSTING(open, high, low,
                                   close)[current_date_formatted]
    tristar = talib.CDLTRISTAR(open, high, low, close)[current_date_formatted]
    unique_three_river = talib.CDLUNIQUE3RIVER(open, high, low,
                                               close)[current_date_formatted]
    upside_gap_two_crows = talib.CDLUPSIDEGAP2CROWS(
        open, high, low, close)[current_date_formatted]
    upside_downside_gap_three_methods = talib.CDLXSIDEGAP3METHODS(
        open, high, low, close)[current_date_formatted]

    patterns = list(vars().keys())[7:]
    values = list(vars().values())[7:]

    for index in range(0, len(patterns)):
        if (values[index] != 0):
            print(patterns[index])
            print(values[index])