Esempio n. 1
0
 def black_crows3(cls, df):
     """
     三只乌鸦
     :param df:
     :return:
     """
     return ta.CDL3BLACKCROWS(df['open'], df['high'], df['low'], df['close'])
Esempio n. 2
0
    def pattern_checker(self):
        data = self.data
        thrusting = talib.CDLTHRUSTING(data['Open'].values, data['High'].values,\
                                     data['Low'].values, data['Close'].values)
        #bullish
        morning = talib.CDLMORNINGSTAR(data['Open'].values, data['High'].values,\
                                     data['Low'].values, data['Close'].values,penetration=0)
        #bullish
        threeline = talib.CDL3LINESTRIKE(data['Open'].values, data['High'].values,\
                                     data['Low'].values, data['Close'].values)
        #bearish
        black = talib.CDL3BLACKCROWS(data['Open'].values, data['High'].values,\
                                     data['Low'].values, data['Close'].values)
        #bearish
        eveningstar = talib.CDLEVENINGDOJISTAR(data['Open'].values, data['High'].values,\
                                     data['Low'].values, data['Close'].values,penetration=0)
        #bullish
        abandonedbaby = talib.CDLABANDONEDBABY(data['Open'].values, data['High'].values,\
                                     data['Low'].values, data['Close'].values,penetration=0)

        talist = [
            'thrusting', 'morning', 'threeline', 'black', 'eveningstar',
            'abandonedbaby'
        ]
        ta_name = thrusting, morning, threeline, black, eveningstar, abandonedbaby
        self.ta_dict = dict([(talist[i], ta_name[i])
                             for i in range(len(talist))])
        return thrusting, morning, threeline, black, eveningstar, abandonedbaby
Esempio n. 3
0
def get_cdl3blackcrows(ohlc):
    cdl3blackcrows = ta.CDL3BLACKCROWS(ohlc['1_open'], ohlc['2_high'],
                                       ohlc['3_low'], ohlc['4_close'])

    ohlc['cdl3blackcrows'] = cdl3blackcrows

    return ohlc
Esempio n. 4
0
def generateIndicatorCDL3BLACKCROWS(dictDataSpec):
    df = dictDataSpec['df']
    sIndicatorS = pd.Series(talib.CDL3BLACKCROWS(df.Open.values, df.High.values, df.Low.values, df.Close.values), index=df.index)
    sIndicatorL = pd.Series(talib.CDL3WHITESOLDIERS(df.Open.values, df.High.values, df.Low.values, df.Close.values), index=df.index)
    sIndicator = df['Close'].apply(lambda x: np.nan)
    sIndicator.ix[sIndicatorL[sIndicatorL!=0].index] = 1
    sIndicator.ix[sIndicatorS[sIndicatorS!=0].index] = -1
    return sIndicator
Esempio n. 5
0
def add_pattern_reconition_factor(df):
    df['two_crows'] = 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['three_inside'] = talib.CDL3INSIDE(df['open'], df['high'], df['low'],
                                          df['close'])
    df['three_line_strike'] = talib.CDL3LINESTRIKE(df['open'], df['high'],
                                                   df['low'], df['close'])
    df['three_outside'] = talib.CDL3OUTSIDE(df['open'], df['high'], df['low'],
                                            df['close'])
    df['three_star_south'] = talib.CDL3STARINSOUTH(df['open'], df['high'],
                                                   df['low'], df['close'])
    df['three_white_soldiers'] = talib.CDL3WHITESOLDIERS(
        df['open'], df['high'], df['low'], df['close'])
    df['abandoned_baby'] = talib.CDLABANDONEDBABY(df['open'], df['high'],
                                                  df['low'], df['close'])
    df['advance_block'] = talib.CDLADVANCEBLOCK(df['open'], df['high'],
                                                df['low'], df['close'])
    df['belt_hold'] = talib.CDLBELTHOLD(df['open'], df['high'], df['low'],
                                        df['close'])
    df['break_away'] = talib.CDLBREAKAWAY(df['open'], df['high'], df['low'],
                                          df['close'])
    df['closing_marubozu'] = talib.CDLCLOSINGMARUBOZU(df['open'], df['high'],
                                                      df['low'], df['close'])
    df['conceal_baby_swall'] = talib.CDLCONCEALBABYSWALL(
        df['open'], df['high'], df['low'], df['close'])
    df['counter_attack'] = talib.CDLCOUNTERATTACK(df['open'], df['high'],
                                                  df['low'], df['close'])
    df['dark_cloud_cover'] = talib.CDLDARKCLOUDCOVER(df['open'], df['high'],
                                                     df['low'], df['close'])
    df['doji'] = talib.CDLDOJI(df['open'], df['high'], df['low'], df['close'])
    df['doji_star'] = talib.CDLDOJISTAR(df['open'], df['high'], df['low'],
                                        df['close'])
    df['dragon_fly_doji'] = talib.CDLDRAGONFLYDOJI(df['open'], df['high'],
                                                   df['low'], df['close'])
    df['engulfing'] = talib.CDLENGULFING(df['open'], df['high'], df['low'],
                                         df['close'])
    df['evening_doji_star'] = talib.CDLEVENINGDOJISTAR(df['open'],
                                                       df['high'],
                                                       df['low'],
                                                       df['close'],
                                                       penetration=0)
    df['gap_sideside_white'] = talib.CDLGAPSIDESIDEWHITE(
        df['open'], df['high'], df['low'], df['close'])
    df['grave_stone_doji'] = talib.CDLGRAVESTONEDOJI(df['open'], df['high'],
                                                     df['low'], df['close'])
    df['hammer'] = talib.CDLHAMMER(df['open'], df['high'], df['low'],
                                   df['close'])
    df['morning_doji_star'] = talib.CDLMORNINGDOJISTAR(df['open'],
                                                       df['high'],
                                                       df['low'],
                                                       df['close'],
                                                       penetration=0)
    df['on_neck'] = talib.CDLONNECK(df['open'], df['high'], df['low'],
                                    df['close'])

    return df
Esempio n. 6
0
 def three_black_crows(self):
     """
     名称:Three Black Crows 三只乌鸦
     简介:三日K线模式,连续三根阴线,每日收盘价都下跌且接近最低价,每日开盘价都在上根K线实体内,预示股价下跌。
     """
     result = talib.CDL3BLACKCROWS(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['three_black_crows'] = result
Esempio n. 7
0
def CDL3BLACKCROWS(open, high, low, close):
    ''' Three Black Crows 三只乌鸦

    分组: Pattern Recognition 形态识别

    简介: 三日K线模式,连续三根阴线,每日收盘价都下跌且接近最低价,
    每日开盘价都在上根K线实体内,预示股价下跌。

    integer = CDL3BLACKCROWS(open, high, low, close)
    '''
    return talib.CDL3BLACKCROWS(open, high, low, close)
Esempio n. 8
0
    def three_black_crows(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.CDL3BLACKCROWS(opens, highs, lows, closes)

        return cdl
Esempio n. 9
0
def add_down_pattern_recognition_factor(df):
    df['hanging_man'] = talib.CDLHANGINGMAN(df['open'], df['high'], df['low'],
                                            df['close'])
    df['evening_doji_star'] = talib.CDLEVENINGDOJISTAR(df['open'],
                                                       df['high'],
                                                       df['low'],
                                                       df['close'],
                                                       penetration=0)
    df['three_black_crows'] = talib.CDL3BLACKCROWS(df['open'], df['high'],
                                                   df['low'], df['close'])
    df['dark_cloud_cover'] = talib.CDLDARKCLOUDCOVER(df['open'], df['high'],
                                                     df['low'], df['close'])
    df['shooting_star'] = talib.CDLSHOOTINGSTAR(df['open'], df['high'],
                                                df['low'], df['close'])
    return df
Esempio n. 10
0
 def three_black_crows():
     for i in range(len(ForexTraderSwitch.curr_pair_list)):
         close=(ForexTraderSwitch.curr_pair_history_data[i]['closeAsk'].tail(5).values+\
                ForexTraderSwitch.curr_pair_history_data[i]['closeBid'].tail(5).values)/2
         high=(ForexTraderSwitch.curr_pair_history_data[i]['highAsk'].tail(5).values+\
               ForexTraderSwitch.curr_pair_history_data[i]['highBid'].tail(5).values)/2
         low=(ForexTraderSwitch.curr_pair_history_data[i]['lowAsk'].tail(5).values+\
              ForexTraderSwitch.curr_pair_history_data[i]['lowBid'].tail(5).values)/2
         openv=(ForexTraderSwitch.curr_pair_history_data[i]['openAsk'].tail(5).values+\
                ForexTraderSwitch.curr_pair_history_data[i]['openBid'].tail(5).values)/2
         pattern = talib.CDL3BLACKCROWS(openv, high, low, close)
         pattern_signal = pattern[-1]
         #print(pattern_signal)
         ForexTraderSwitch.signal[i, 0] = pattern_signal
         if pattern_signal > 0:
             #trader.create_buy_order(ticker,units)
             ForexTraderSwitch.order[i, 0, 1] = 1
         elif pattern_signal < 0:
             #trader.create_sell_order(ticker,units)
             ForexTraderSwitch.order[i, 0, 2] = 1
         else:
             #print('No trade made')
             ForexTraderSwitch.order[i, 0, 0] = 1
                             np.array(df['Low'].shift(1)),
                             np.array(df['Adj Close'].shift(1)))
df['MEDPRICE'] = ta.MEDPRICE(np.array(df['High'].shift(1)),
                             np.array(df['Low'].shift(1)))
df['TYPPRICE'] = ta.TYPPRICE(np.array(df['High'].shift(1)),
                             np.array(df['Low'].shift(1)),
                             np.array(df['Adj Close'].shift(1)))
df['WCLPRICE'] = ta.WCLPRICE(np.array(df['High'].shift(1)),
                             np.array(df['Low'].shift(1)),
                             np.array(df['Adj Close'].shift(1)))

# Pattern Recognition Fuction
df['Two_Crows'] = ta.CDL2CROWS(np.array(df['Open']), np.array(df['High']),
                               np.array(df['Low']), np.array(df['Adj Close']))
df['Three_Crows'] = ta.CDL3BLACKCROWS(np.array(df['Open']),
                                      np.array(df['High']),
                                      np.array(df['Low']),
                                      np.array(df['Adj Close']))
df['Three_Inside_Up_Down'] = ta.CDL3INSIDE(np.array(df['Open']),
                                           np.array(df['High']),
                                           np.array(df['Low']),
                                           np.array(df['Adj Close']))
df['Three_Line_Strike'] = ta.CDL3LINESTRIKE(np.array(df['Open']),
                                            np.array(df['High']),
                                            np.array(df['Low']),
                                            np.array(df['Adj Close']))
df['Thre_Outside_Up_Down'] = ta.CDL3OUTSIDE(np.array(df['Open']),
                                            np.array(df['High']),
                                            np.array(df['Low']),
                                            np.array(df['Adj Close']))
df['Thre_Stars_In_The_South'] = ta.CDL3STARSINSOUTH(np.array(df['Open']),
                                                    np.array(df['High']),
Esempio n. 12
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
Esempio n. 13
0
def CDL3BLACKCROWS(data, **kwargs):
    _check_talib_presence()
    popen, phigh, plow, pclose, pvolume = _extract_ohlc(data)
    return talib.CDL3BLACKCROWS(popen, phigh, plow, pclose, **kwargs)
Esempio n. 14
0
def handle_pattern_recognition(args, axes, i, klines_df, close_times, display_count):
    # talib
    if args.CDL2CROWS:
        name = 'CDL2CROWS'
        integer = talib.CDL2CROWS(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDL3BLACKCROWS:
        name = 'CDL3BLACKCROWS'
        integer = talib.CDL3BLACKCROWS(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDL3INSIDE:
        name = 'CDL3INSIDE'
        integer = talib.CDL3INSIDE(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDL3LINESTRIKE:
        name = 'CDL3LINESTRIKE'
        integer = talib.CDL3LINESTRIKE(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDL3OUTSIDE:
        name = 'CDL3OUTSIDE'
        integer = talib.CDL3OUTSIDE(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDL3STARSINSOUTH:
        name = 'CDL3STARSINSOUTH'
        integer = talib.CDL3STARSINSOUTH(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDL3WHITESOLDIERS:
        name = 'CDL3WHITESOLDIERS'
        integer = talib.CDL3WHITESOLDIERS(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDLABANDONEDBABY:
        name = 'CDLABANDONEDBABY'
        integer = talib.CDLABANDONEDBABY(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    if args.CDLADVANCEBLOCK:
        name = 'CDLADVANCEBLOCK'
        integer = talib.CDLADVANCEBLOCK(klines_df["open"], klines_df["high"], klines_df["low"], klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, integer[-display_count:], "y:", label=name)

    '''
Esempio n. 15
0
 ohlc_df['high'] = high_list
 ohlc_df['low'] = low_list
 ohlc_df['close'] = close_list
 ohlc_df['volume'] = volume_list
 ohlc_df['avg_vol'] = ohlc_df['volume'].rolling(window=14).mean()
 ohlc_df['atr'] = ta.ATR(ohlc_df['high'],
                         ohlc_df['low'],
                         ohlc_df['close'],
                         timeperiod=14)
 ohlc_df['atr_pct'] = ohlc_df['atr'] / ohlc_df['close']
 ohlc_df['CDL2CROWS'] = ta.CDL2CROWS(ohlc_df['open'],
                                     ohlc_df['high'],
                                     ohlc_df['low'],
                                     ohlc_df['close'])
 ohlc_df['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDL3INSIDE'] = ta.CDL3INSIDE(ohlc_df['open'],
                                       ohlc_df['high'],
                                       ohlc_df['low'],
                                       ohlc_df['close'])
 ohlc_df['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
 ohlc_df['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(ohlc_df['open'],
                                         ohlc_df['high'],
                                         ohlc_df['low'],
                                         ohlc_df['close'])
 ohlc_df['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(
     ohlc_df['open'], ohlc_df['high'], ohlc_df['low'],
     ohlc_df['close'])
Esempio n. 16
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. 17
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
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
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. 20
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. 21
0
def get_datasets(asset, currency, granularity, datapoints):
    """Fetch the API and precess the desired pair

    Arguments:
        asset {str} -- First pair
        currency {str} -- Second pair
        granularity {str ['day', 'hour']} -- Granularity
        datapoints {int [100 - 2000]} -- [description]

    Returns:
        pandas.Dataframe -- The OHLCV and indicators dataframe
    """
    df_train_path = 'datasets/bot_train_{}_{}_{}.csv'.format(
        asset + currency, datapoints, granularity)
    df_rollout_path = 'datasets/bot_rollout_{}_{}_{}.csv'.format(
        asset + currency, datapoints, granularity)
    emojis = [
        ':moneybag:', ':yen:', ':dollar:', ':pound:', ':euro:',
        ':credit_card:', ':money_with_wings:', ':gem:'
    ]

    if not os.path.exists(df_rollout_path):
        headers = {
            'User-Agent':
            'Mozilla/5.0',
            'authorization':
            'Apikey 3d7d3e9e6006669ac00584978342451c95c3c78421268ff7aeef69995f9a09ce'
        }

        # OHLC
        # url = 'https://min-api.cryptocompare.com/data/histo{}?fsym={}&tsym={}&e=Binance&limit={}'.format(granularity, asset, currency, datapoints)
        url = 'https://min-api.cryptocompare.com/data/histo{}?fsym={}&tsym={}&limit={}'.format(
            granularity, asset, currency, datapoints)
        # print(emoji.emojize(':dizzy: :large_blue_diamond: :gem: :bar_chart: :crystal_ball: :chart_with_downwards_trend: :chart_with_upwards_trend: :large_orange_diamond: loading...', use_aliases=True))
        print(
            colored(
                emoji.emojize('> ' + random.choice(emojis) + ' downloading ' +
                              asset + '/' + currency,
                              use_aliases=True), 'green'))
        # print(colored('> downloading ' + asset + '/' + currency, 'green'))
        response = requests.get(url, headers=headers)
        json_response = response.json()
        status = json_response['Response']
        if status == "Error":
            print(colored('=== {} ==='.format(json_response['Message']),
                          'red'))
            raise AssertionError()
        result = json_response['Data']
        df = pd.DataFrame(result)
        print(df.tail())
        df['Date'] = pd.to_datetime(df['time'], utc=True, unit='s')
        df.drop('time', axis=1, inplace=True)

        # indicators
        # https://github.com/mrjbq7/ta-lib/blob/master/docs/func.md
        open_price, high, low, close = np.array(df['open']), np.array(
            df['high']), np.array(df['low']), np.array(df['close'])
        volume = np.array(df['volumefrom'])
        # cycle indicators
        df.loc[:, 'HT_DCPERIOD'] = talib.HT_DCPERIOD(close)
        df.loc[:, 'HT_DCPHASE'] = talib.HT_DCPHASE(close)
        df.loc[:,
               'HT_PHASOR_inphase'], df.loc[:,
                                            'HT_PHASOR_quadrature'] = talib.HT_PHASOR(
                                                close)
        df.loc[:, 'HT_SINE_sine'], df.loc[:,
                                          'HT_SINE_leadsine'] = talib.HT_SINE(
                                              close)
        df.loc[:, 'HT_TRENDMODE'] = talib.HT_TRENDMODE(close)
        # momemtum indicators
        df.loc[:, 'ADX'] = talib.ADX(high, low, close, timeperiod=12)
        df.loc[:, 'ADXR'] = talib.ADXR(high, low, close, timeperiod=13)
        df.loc[:, 'APO'] = talib.APO(close,
                                     fastperiod=5,
                                     slowperiod=10,
                                     matype=0)
        df.loc[:,
               'AROON_down'], df.loc[:,
                                     'AROON_up'] = talib.AROON(high,
                                                               low,
                                                               timeperiod=15)
        df.loc[:, 'AROONOSC'] = talib.AROONOSC(high, low, timeperiod=13)
        df.loc[:, 'BOP'] = talib.BOP(open_price, high, low, close)
        df.loc[:, 'CCI'] = talib.CCI(high, low, close, timeperiod=13)
        df.loc[:, 'CMO'] = talib.CMO(close, timeperiod=14)
        df.loc[:, 'DX'] = talib.DX(high, low, close, timeperiod=10)
        df['MACD'], df['MACD_signal'], df['MACD_hist'] = talib.MACD(
            close, fastperiod=5, slowperiod=10, signalperiod=20)
        df.loc[:, 'MFI'] = talib.MFI(high, low, close, volume, timeperiod=12)
        df.loc[:, 'MINUS_DI'] = talib.MINUS_DI(high, low, close, timeperiod=10)
        df.loc[:, 'MINUS_DM'] = talib.MINUS_DM(high, low, timeperiod=14)
        df.loc[:, 'MOM'] = talib.MOM(close, timeperiod=20)
        df.loc[:, 'PPO'] = talib.PPO(close,
                                     fastperiod=17,
                                     slowperiod=35,
                                     matype=2)
        df.loc[:, 'ROC'] = talib.ROC(close, timeperiod=12)
        df.loc[:, 'RSI'] = talib.RSI(close, timeperiod=25)
        df.loc[:, 'STOCH_k'], df.loc[:,
                                     'STOCH_d'] = talib.STOCH(high,
                                                              low,
                                                              close,
                                                              fastk_period=35,
                                                              slowk_period=12,
                                                              slowk_matype=0,
                                                              slowd_period=7,
                                                              slowd_matype=0)
        df.loc[:,
               'STOCHF_k'], df.loc[:,
                                   'STOCHF_d'] = talib.STOCHF(high,
                                                              low,
                                                              close,
                                                              fastk_period=28,
                                                              fastd_period=14,
                                                              fastd_matype=0)
        df.loc[:, 'STOCHRSI_K'], df.loc[:, 'STOCHRSI_D'] = talib.STOCHRSI(
            close,
            timeperiod=35,
            fastk_period=12,
            fastd_period=10,
            fastd_matype=1)
        df.loc[:, 'TRIX'] = talib.TRIX(close, timeperiod=30)
        df.loc[:, 'ULTOSC'] = talib.ULTOSC(high,
                                           low,
                                           close,
                                           timeperiod1=14,
                                           timeperiod2=28,
                                           timeperiod3=35)
        df.loc[:, 'WILLR'] = talib.WILLR(high, low, close, timeperiod=35)
        # overlap studies
        df.loc[:,
               'BBANDS_upper'], df.loc[:,
                                       'BBANDS_middle'], df.loc[:,
                                                                'BBANDS_lower'] = talib.BBANDS(
                                                                    close,
                                                                    timeperiod=
                                                                    12,
                                                                    nbdevup=2,
                                                                    nbdevdn=2,
                                                                    matype=0)
        df.loc[:, 'DEMA'] = talib.DEMA(close, timeperiod=30)
        df.loc[:, 'EMA'] = talib.EMA(close, timeperiod=7)
        df.loc[:, 'HT_TRENDLINE'] = talib.HT_TRENDLINE(close)
        df.loc[:, 'KAMA'] = talib.KAMA(close, timeperiod=5)
        df.loc[:, 'MA'] = talib.MA(close, timeperiod=5, matype=0)
        df.loc[:, 'MIDPOINT'] = talib.MIDPOINT(close, timeperiod=20)
        df.loc[:, 'WMA'] = talib.WMA(close, timeperiod=15)
        df.loc[:, 'SMA'] = talib.SMA(close)
        # pattern recoginition
        df.loc[:, 'CDL2CROWS'] = talib.CDL2CROWS(open_price, high, low, close)
        df.loc[:, 'CDL3BLACKCROWS'] = talib.CDL3BLACKCROWS(
            open_price, high, low, close)
        df.loc[:, 'CDL3INSIDE'] = talib.CDL3INSIDE(open_price, high, low,
                                                   close)
        df.loc[:, 'CDL3LINESTRIKE'] = talib.CDL3LINESTRIKE(
            open_price, high, low, close)
        # price transform
        df.loc[:, 'WCLPRICE'] = talib.WCLPRICE(high, low, close)
        # statistic funcitons
        df.loc[:, 'BETA'] = talib.BETA(high, low, timeperiod=20)
        df.loc[:, 'CORREL'] = talib.CORREL(high, low, timeperiod=20)
        df.loc[:, 'STDDEV'] = talib.STDDEV(close, timeperiod=20, nbdev=1)
        df.loc[:, 'TSF'] = talib.TSF(close, timeperiod=20)
        df.loc[:, 'VAR'] = talib.VAR(close, timeperiod=20, nbdev=1)
        # volatility indicators
        df.loc[:, 'ATR'] = talib.ATR(high, low, close, timeperiod=7)
        df.loc[:, 'NATR'] = talib.NATR(high, low, close, timeperiod=20)
        df.loc[:, 'TRANGE'] = talib.TRANGE(high, low, close)
        # volume indicators
        df.loc[:, 'AD'] = talib.AD(high, low, close, volume)
        df.loc[:, 'ADOSC'] = talib.ADOSC(high,
                                         low,
                                         close,
                                         volume,
                                         fastperiod=10,
                                         slowperiod=20)
        df.loc[:, 'OBV'] = talib.OBV(close, volume)

        # df.fillna(df.mean(), inplace=True)
        df.dropna(inplace=True)
        df.set_index('Date', inplace=True)
        print(colored('> caching' + asset + '/' + currency + ':)', 'cyan'))
        train_size = round(
            len(df) *
            DF_TRAIN_SIZE)  # 75% to train -> test with different value
        df_train = df[:train_size]
        df_rollout = df[train_size:]
        df_train.to_csv(df_train_path)
        df_rollout.to_csv(df_rollout_path)
        df_train = pd.read_csv(
            df_train_path)  # re-read to avoid indexing issue w/ Ray
        df_rollout = pd.read_csv(df_rollout_path)
    else:

        print(
            colored(
                emoji.emojize('> ' + random.choice(emojis) + ' feching ' +
                              asset + '/' + currency + ' from cache',
                              use_aliases=True), 'magenta'))

        # print(colored('> feching ' + asset + '/' + currency + ' from cache :)', 'magenta'))
        df_train = pd.read_csv(df_train_path)
        df_rollout = pd.read_csv(df_rollout_path)
        # df_train.set_index('Date', inplace=True)
        # df_rollout.set_index('Date', inplace=True)

    return df_train, df_rollout
    if daydifference > 10:  # Dead Stock
        print('Old Dead Stock,Code:', code)
        continue

    # Most Required Data
    df = df[prices + others]
    yf = df.copy()

    # Feature Space New Talib
    previous_columns = df.columns.values
    op = df['Open']
    hp = df['High']
    lp = df['Low']
    cp = df['Close']
    df['CDL2CROWS'] = talib.CDL2CROWS(op, hp, lp, cp)
    df['CDL3BLACKCROWS'] = talib.CDL3BLACKCROWS(op, hp, lp, cp)
    df['CDL3INSIDE'] = talib.CDL3INSIDE(op, hp, lp, cp)
    df['CDL3LINESTRIKE'] = talib.CDL3LINESTRIKE(op, hp, lp, cp)
    df['CDL3OUTSIDE'] = talib.CDL3OUTSIDE(op, hp, lp, cp)
    df['CDL3STARSINSOUTH'] = talib.CDL3STARSINSOUTH(op, hp, lp, cp)
    df['CDL3WHITESOLDIERS'] = talib.CDL3WHITESOLDIERS(op, hp, lp, cp)
    df['CDLABANDONEDBABY'] = talib.CDLABANDONEDBABY(op, hp, lp, cp)
    df['CDLADVANCEBLOCK'] = talib.CDLADVANCEBLOCK(op, hp, lp, cp)
    df['CDLBELTHOLD'] = talib.CDLBELTHOLD(op, hp, lp, cp)
    df['CDLBREAKAWAY'] = talib.CDLBREAKAWAY(op, hp, lp, cp)
    df['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(op, hp, lp, cp)
    df['CDLCONCEALBABYSWALL'] = talib.CDLCONCEALBABYSWALL(op, hp, lp, cp)
    df['CDLCOUNTERATTACK'] = talib.CDLCOUNTERATTACK(op, hp, lp, cp)
    df['CDLDARKCLOUDCOVER'] = talib.CDLDARKCLOUDCOVER(op, hp, lp, cp)
    df['CDLDOJI'] = talib.CDLDOJI(op, hp, lp, cp)
    df['CDLDOJISTAR'] = talib.CDLDOJISTAR(op, hp, lp, cp)
Esempio n. 23
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 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])
Esempio n. 25
0
def TALIB_CDL3BLACKCROWS(close):
    '''00399,1,1'''
    return talib.CDL3BLACKCROWS(close)
Esempio n. 26
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. 27
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. 28
0
def _extract_feature(candle, params, candle_type, target_dt):
    '''
    前に余分に必要なデータ量: {(stockf_fastk_period_l + stockf_fastk_period_l) * 最大分足 (min)} + window_size
    = (12 + 12) * 5 + 5 = 125 (min)
    '''
    o = candle.open
    h = candle.high
    l = candle.low
    c = candle.close
    v = candle.volume

    # OHLCV
    features = pd.DataFrame()
    features['open'] = o
    features['high'] = h
    features['low'] = l
    features['close'] = c
    features['volume'] = v

    ####################################
    #
    # Momentum Indicator Functions
    #
    ####################################

    # ADX = SUM((+DI - (-DI)) / (+DI + (-DI)), N) / N
    # N — 計算期間
    # SUM (..., N) — N期間の合計
    # +DI — プラスの価格変動の値(positive directional index)
    # -DI — マイナスの価格変動の値(negative directional index)
    # rsi_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要

    features['adx_s'] = ta.ADX(h, l, c, timeperiod=params['adx_timeperiod_s'])
    features['adx_m'] = ta.ADX(h, l, c, timeperiod=params['adx_timeperiod_m'])
    features['adx_l'] = ta.ADX(h, l, c, timeperiod=params['adx_timeperiod_l'])

    features['adxr_s'] = ta.ADXR(h, l, c, timeperiod=params['adxr_timeperiod_s'])
    features['adxr_m'] = ta.ADXR(h, l, c, timeperiod=params['adxr_timeperiod_m'])
    features['adxr_l'] = ta.ADXR(h, l, c, timeperiod=params['adxr_timeperiod_l'])

    # APO = Shorter Period EMA – Longer Period EMA
    features['apo_s'] = ta.APO(c, fastperiod=params['apo_fastperiod_s'], slowperiod=params['apo_slowperiod_s'], matype=ta.MA_Type.EMA)
    features['apo_m'] = ta.APO(c, fastperiod=params['apo_fastperiod_m'], slowperiod=params['apo_slowperiod_m'], matype=ta.MA_Type.EMA)

    # AroonUp = (N - 過去N日間の最高値からの経過期間) ÷ N × 100
    # AroonDown = (N - 過去N日間の最安値からの経過期間) ÷ N × 100
    # aroon_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要
    #features['aroondown_s'], features['aroonup_s'] = ta.AROON(h, l, timeperiod=params['aroon_timeperiod_s'])
    #features['aroondown_m'], features['aroonup_m'] = ta.AROON(h, l, timeperiod=params['aroon_timeperiod_m'])
    #features['aroondown_l'], features['aroonup_l'] = ta.AROON(h, l, timeperiod=params['aroon_timeperiod_l'])

    # Aronnオシレーター = AroonUp - AroonDown
    # aroonosc_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要
    features['aroonosc_s'] = ta.AROONOSC(h, l, timeperiod=params['aroonosc_timeperiod_s'])
    features['aroonosc_m'] = ta.AROONOSC(h, l, timeperiod=params['aroonosc_timeperiod_m'])
    features['aroonosc_l'] = ta.AROONOSC(h, l, timeperiod=params['aroonosc_timeperiod_l'])

    # BOP = (close - open) / (high - low)
    features['bop'] = ta.BOP(o, h, l, c)

    # CCI = (TP - MA) / (0.015 * MD)
    # TP: (高値+安値+終値) / 3
    # MA: TPの移動平均
    # MD: 平均偏差 = ((MA - TP1) + (MA - TP2) + ...) / N
    features['cci_s'] = ta.CCI(h, l, c, timeperiod=params['cci_timeperiod_s'])
    features['cci_m'] = ta.CCI(h, l, c, timeperiod=params['cci_timeperiod_m'])
    features['cci_l'] = ta.CCI(h, l, c, timeperiod=params['cci_timeperiod_l'])

    # CMO - Chande Momentum Oscillator
    #features['cmo_s'] = ta.CMO(c, timeperiod=params['cmo_timeperiod_s'])
    #features['cmo_m'] = ta.CMO(c, timeperiod=params['cmo_timeperiod_m'])
    #features['cmo_l'] = ta.CMO(c, timeperiod=params['cmo_timeperiod_l'])

    # DX - Directional Movement Index
    features['dx_s'] = ta.DX(h, l, c, timeperiod=params['dx_timeperiod_s'])
    features['dx_m'] = ta.DX(h, l, c, timeperiod=params['dx_timeperiod_m'])
    features['dx_l'] = ta.DX(h, l, c, timeperiod=params['dx_timeperiod_l'])

    # MACD=基準線-相対線
    # 基準線(EMA):過去12日(週・月)間の終値指数平滑平均
    # 相対線(EMA):過去26日(週・月)間の終値指数平滑平均
    # https://www.sevendata.co.jp/shihyou/technical/macd.html
    # macd_slowperiod_m = 30 の場合30分足で((30 + macd_signalperiod_m) * 30)/ 60 = 16.5時間必要(macd_signalperiod_m=3の時)
    macd, macdsignal, macdhist = ta.MACDEXT(c, fastperiod=params['macd_fastperiod_s'],
                                            slowperiod=params['macd_slowperiod_s'],
                                            signalperiod=params['macd_signalperiod_s'],
                                            fastmatype=ta.MA_Type.EMA, slowmatype=ta.MA_Type.EMA,
                                            signalmatype=ta.MA_Type.EMA)
    change_macd = calc_change(macd, macdsignal)
    change_macd.index = macd.index
    features['macd_s'] = macd
    features['macdsignal_s'] = macdsignal
    features['macdhist_s'] = macdhist
    features['change_macd_s'] = change_macd
    macd, macdsignal, macdhist = ta.MACDEXT(c, fastperiod=params['macd_fastperiod_m'],
                                            slowperiod=params['macd_slowperiod_m'],
                                            signalperiod=params['macd_signalperiod_m'],
                                            fastmatype=ta.MA_Type.EMA, slowmatype=ta.MA_Type.EMA,
                                            signalmatype=ta.MA_Type.EMA)
    change_macd = calc_change(macd, macdsignal)
    change_macd.index = macd.index
    features['macd_m'] = macd
    features['macdsignal_m'] = macdsignal
    features['macdhist_m'] = macdhist
    features['change_macd_m'] = change_macd

    # MFI - Money Flow Index
    features['mfi_s'] = ta.MFI(h, l, c, v, timeperiod=params['mfi_timeperiod_s'])
    features['mfi_m'] = ta.MFI(h, l, c, v, timeperiod=params['mfi_timeperiod_m'])
    features['mfi_l'] = ta.MFI(h, l, c, v, timeperiod=params['mfi_timeperiod_l'])

    # MINUS_DI - Minus Directional Indicator
    features['minus_di_s'] = ta.MINUS_DI(h, l, c, timeperiod=params['minus_di_timeperiod_s'])
    features['minus_di_m'] = ta.MINUS_DI(h, l, c, timeperiod=params['minus_di_timeperiod_m'])
    features['minus_di_l'] = ta.MINUS_DI(h, l, c, timeperiod=params['minus_di_timeperiod_l'])

    # MINUS_DM - Minus Directional Movement
    features['minus_dm_s'] = ta.MINUS_DM(h, l, timeperiod=params['minus_dm_timeperiod_s'])
    features['minus_dm_m'] = ta.MINUS_DM(h, l, timeperiod=params['minus_dm_timeperiod_m'])
    features['minus_dm_l'] = ta.MINUS_DM(h, l, timeperiod=params['minus_dm_timeperiod_l'])

    # MOM - Momentum
    features['mom_s'] = ta.MOM(c, timeperiod=params['mom_timeperiod_s'])
    features['mom_m'] = ta.MOM(c, timeperiod=params['mom_timeperiod_m'])
    features['mom_l'] = ta.MOM(c, timeperiod=params['mom_timeperiod_l'])

    # PLUS_DI - Minus Directional Indicator
    features['plus_di_s'] = ta.PLUS_DI(h, l, c, timeperiod=params['plus_di_timeperiod_s'])
    features['plus_di_m'] = ta.PLUS_DI(h, l, c, timeperiod=params['plus_di_timeperiod_m'])
    features['plus_di_l'] = ta.PLUS_DI(h, l, c, timeperiod=params['plus_di_timeperiod_l'])

    # PLUS_DM - Minus Directional Movement
    features['plus_dm_s'] = ta.PLUS_DM(h, l, timeperiod=params['plus_dm_timeperiod_s'])
    features['plus_dm_m'] = ta.PLUS_DM(h, l, timeperiod=params['plus_dm_timeperiod_m'])
    features['plus_dm_l'] = ta.PLUS_DM(h, l, timeperiod=params['plus_dm_timeperiod_l'])

    # PPO - Percentage Price Oscillator
    #features['ppo_s'] = ta.PPO(c, fastperiod=params['ppo_fastperiod_s'], slowperiod=params['ppo_slowperiod_s'], matype=ta.MA_Type.EMA)
    #features['ppo_m'] = ta.PPO(c, fastperiod=params['ppo_fastperiod_m'], slowperiod=params['ppo_slowperiod_m'], matype=ta.MA_Type.EMA)

    # ROC - Rate of change : ((price/prevPrice)-1)*100
    features['roc_s'] = ta.ROC(c, timeperiod=params['roc_timeperiod_s'])
    features['roc_m'] = ta.ROC(c, timeperiod=params['roc_timeperiod_m'])
    features['roc_l'] = ta.ROC(c, timeperiod=params['roc_timeperiod_l'])

    # ROCP = (price-prevPrice) / prevPrice
    # http://www.tadoc.org/indicator/ROCP.htm
    # rocp_timeperiod_l = 30 の場合、30分足で(30 * 30) / 60 = 15時間必要
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_s'])
    change_rocp = calc_change(rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_s'] = rocp
    features['change_rocp_s'] = change_rocp
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_m'])
    change_rocp = calc_change(rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_m'] = rocp
    features['change_rocp_m'] = change_rocp
    rocp = ta.ROCP(c, timeperiod=params['rocp_timeperiod_l'])
    change_rocp = calc_change(rocp, pd.Series(np.zeros(len(candle)), index=candle.index))
    change_rocp.index = rocp.index
    features['rocp_l'] = rocp
    features['change_rocp_l'] = change_rocp

    # ROCR - Rate of change ratio: (price/prevPrice)
    features['rocr_s'] = ta.ROCR(c, timeperiod=params['rocr_timeperiod_s'])
    features['rocr_m'] = ta.ROCR(c, timeperiod=params['rocr_timeperiod_m'])
    features['rocr_l'] = ta.ROCR(c, timeperiod=params['rocr_timeperiod_l'])

    # ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    features['rocr100_s'] = ta.ROCR100(c, timeperiod=params['rocr100_timeperiod_s'])
    features['rocr100_m'] = ta.ROCR100(c, timeperiod=params['rocr100_timeperiod_m'])
    features['rocr100_l'] = ta.ROCR100(c, timeperiod=params['rocr100_timeperiod_l'])

    # RSI = (100 * a) / (a + b) (a: x日間の値上がり幅の合計, b: x日間の値下がり幅の合計)
    # https://www.sevendata.co.jp/shihyou/technical/rsi.html
    # rsi_timeperiod_l=30の場合、30分足で、(30 * 30 / 60(min)) = 15時間必要
    #features['rsi_s'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_s'])
    #features['rsi_m'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_m'])
    #features['rsi_l'] = ta.RSI(c, timeperiod=params['rsi_timeperiod_l'])


    # FASTK(KPeriod) = 100 * (Today's Close - LowestLow) / (HighestHigh - LowestLow)
    # FASTD(FastDperiod) = MA Smoothed FASTK over FastDperiod
    # http://www.tadoc.org/indicator/STOCHF.htm
    # stockf_fastk_period_l=30の場合30分足で、(((30 + 30) * 30) / 60(min)) = 30時間必要 (LowestLowが移動平均の30分余分に必要なので60period余分に計算する)
    fastk, fastd = ta.STOCHF(h, l, c, fastk_period=params['stockf_fastk_period_s'], fastd_period=params['stockf_fastd_period_s'], fastd_matype=ta.MA_Type.EMA)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_s'] = fastk
    features['fastd_s'] = fastd
    features['fast_change_s'] = change_stockf
    fastk, fastd = ta.STOCHF(h, l, c, fastk_period=params['stockf_fastk_period_m'], fastd_period=params['stockf_fastd_period_m'], fastd_matype=ta.MA_Type.EMA)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_m'] = fastk
    features['fastd_m'] = fastd
    features['fast_change_m'] = change_stockf
    fastk, fastd = ta.STOCHF(h, l, c, fastk_period=params['stockf_fastk_period_l'], fastd_period=params['stockf_fastk_period_l'], fastd_matype=ta.MA_Type.EMA)
    change_stockf = calc_change(fastk, fastd)
    change_stockf.index = fastk.index
    features['fastk_l'] = fastk
    features['fastd_l'] = fastd
    features['fast_change_l'] = change_stockf

    # TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    features['trix_s'] = ta.TRIX(c, timeperiod=params['trix_timeperiod_s'])
    features['trix_m'] = ta.TRIX(c, timeperiod=params['trix_timeperiod_m'])
    features['trix_l'] = ta.TRIX(c, timeperiod=params['trix_timeperiod_l'])

    # ULTOSC - Ultimate Oscillator
    features['ultosc_s'] = ta.ULTOSC(h, l, c, timeperiod1=params['ultosc_timeperiod_s1'], timeperiod2=params['ultosc_timeperiod_s2'], timeperiod3=params['ultosc_timeperiod_s3'])

    # WILLR = (当日終値 - N日間の最高値) / (N日間の最高値 - N日間の最安値)× 100
    # https://inet-sec.co.jp/study/technical-manual/williamsr/
    # willr_timeperiod_l=30の場合30分足で、(30 * 30 / 60) = 15時間必要
    features['willr_s'] = ta.WILLR(h, l, c, timeperiod=params['willr_timeperiod_s'])
    features['willr_m'] = ta.WILLR(h, l, c, timeperiod=params['willr_timeperiod_m'])
    features['willr_l'] = ta.WILLR(h, l, c, timeperiod=params['willr_timeperiod_l'])

    ####################################
    #
    # Volume Indicator Functions
    #
    ####################################

    # Volume Indicator Functions
    # slowperiod_adosc_s = 10の場合、30分足で(10 * 30) / 60 = 5時間必要
    features['ad'] = ta.AD(h, l, c, v)
    features['adosc_s'] = ta.ADOSC(h, l, c, v, fastperiod=params['fastperiod_adosc_s'], slowperiod=params['slowperiod_adosc_s'])
    features['obv'] = ta.OBV(c, v)

    ####################################
    #
    # Volatility Indicator Functions
    #
    ####################################

    # ATR - Average True Range
    features['atr_s'] = ta.ATR(h, l, c, timeperiod=params['atr_timeperiod_s'])
    features['atr_m'] = ta.ATR(h, l, c, timeperiod=params['atr_timeperiod_m'])
    features['atr_l'] = ta.ATR(h, l, c, timeperiod=params['atr_timeperiod_l'])

    # NATR - Normalized Average True Range
    #features['natr_s'] = ta.NATR(h, l, c, timeperiod=params['natr_timeperiod_s'])
    #features['natr_m'] = ta.NATR(h, l, c, timeperiod=params['natr_timeperiod_m'])
    #features['natr_l'] = ta.NATR(h, l, c, timeperiod=params['natr_timeperiod_l'])

    # TRANGE - True Range
    features['trange'] = ta.TRANGE(h, l, c)

    ####################################
    #
    # Price Transform Functions
    #
    ####################################

    features['avgprice'] = ta.AVGPRICE(o, h, l, c)
    features['medprice'] = ta.MEDPRICE(h, l)
    #features['typprice'] = ta.TYPPRICE(h, l, c)
    #features['wclprice'] = ta.WCLPRICE(h, l, c)

    ####################################
    #
    # Cycle Indicator Functions
    #
    ####################################

    #features['ht_dcperiod'] = ta.HT_DCPERIOD(c)
    #features['ht_dcphase'] = ta.HT_DCPHASE(c)
    #features['inphase'], features['quadrature'] = ta.HT_PHASOR(c)
    #features['sine'], features['leadsine'] = ta.HT_SINE(c)
    features['integer'] = ta.HT_TRENDMODE(c)

    ####################################
    #
    # Statistic Functions
    #
    ####################################

    # BETA - Beta

    features['beta_s'] = ta.BETA(h, l, timeperiod=params['beta_timeperiod_s'])
    features['beta_m'] = ta.BETA(h, l, timeperiod=params['beta_timeperiod_m'])
    features['beta_l'] = ta.BETA(h, l, timeperiod=params['beta_timeperiod_l'])

    # CORREL - Pearson's Correlation Coefficient (r)
    #features['correl_s'] = ta.CORREL(h, l, timeperiod=params['correl_timeperiod_s'])
    #features['correl_m'] = ta.CORREL(h, l, timeperiod=params['correl_timeperiod_m'])
    #features['correl_l'] = ta.CORREL(h, l, timeperiod=params['correl_timeperiod_l'])

    # LINEARREG - Linear Regression
    #features['linearreg_s'] = ta.LINEARREG(c, timeperiod=params['linearreg_timeperiod_s'])
    #features['linearreg_m'] = ta.LINEARREG(c, timeperiod=params['linearreg_timeperiod_m'])
    #features['linearreg_l'] = ta.LINEARREG(c, timeperiod=params['linearreg_timeperiod_l'])

    # LINEARREG_ANGLE - Linear Regression Angle
    features['linearreg_angle_s'] = ta.LINEARREG_ANGLE(c, timeperiod=params['linearreg_angle_timeperiod_s'])
    features['linearreg_angle_m'] = ta.LINEARREG_ANGLE(c, timeperiod=params['linearreg_angle_timeperiod_m'])
    features['linearreg_angle_l'] = ta.LINEARREG_ANGLE(c, timeperiod=params['linearreg_angle_timeperiod_l'])

    # LINEARREG_INTERCEPT - Linear Regression Intercept
    features['linearreg_intercept_s'] = ta.LINEARREG_INTERCEPT(c, timeperiod=params['linearreg_intercept_timeperiod_s'])
    features['linearreg_intercept_m'] = ta.LINEARREG_INTERCEPT(c, timeperiod=params['linearreg_intercept_timeperiod_m'])
    features['linearreg_intercept_l'] = ta.LINEARREG_INTERCEPT(c, timeperiod=params['linearreg_intercept_timeperiod_l'])

    # LINEARREG_SLOPE - Linear Regression Slope
    features['linearreg_slope_s'] = ta.LINEARREG_SLOPE(c, timeperiod=params['linearreg_slope_timeperiod_s'])
    features['linearreg_slope_m'] = ta.LINEARREG_SLOPE(c, timeperiod=params['linearreg_slope_timeperiod_m'])
    features['linearreg_slope_l'] = ta.LINEARREG_SLOPE(c, timeperiod=params['linearreg_slope_timeperiod_l'])

    # STDDEV - Standard Deviation
    features['stddev_s'] = ta.STDDEV(c, timeperiod=params['stddev_timeperiod_s'], nbdev=1)
    features['stddev_m'] = ta.STDDEV(c, timeperiod=params['stddev_timeperiod_m'], nbdev=1)
    features['stddev_l'] = ta.STDDEV(c, timeperiod=params['stddev_timeperiod_l'], nbdev=1)

    # TSF - Time Series Forecast
    features['tsf_s'] = ta.TSF(c, timeperiod=params['tsf_timeperiod_s'])
    features['tsf_m'] = ta.TSF(c, timeperiod=params['tsf_timeperiod_m'])
    features['tsf_l'] = ta.TSF(c, timeperiod=params['tsf_timeperiod_l'])

    # VAR - Variance
    #features['var_s'] = ta.VAR(c, timeperiod=params['var_timeperiod_s'], nbdev=1)
    #features['var_m'] = ta.VAR(c, timeperiod=params['var_timeperiod_m'], nbdev=1)
    #features['var_l'] = ta.VAR(c, timeperiod=params['var_timeperiod_l'], nbdev=1)

    # ボリンジャーバンド
    # bbands_timeperiod_l = 30の場合、30分足で(30 * 30) / 60 = 15時間必要
    bb_upper, bb_middle, bb_lower = ta.BBANDS(c, timeperiod=params['bbands_timeperiod_s'],
                                              nbdevup=params['bbands_nbdevup_s'], nbdevdn=params['bbands_nbdevdn_s'],
                                              matype=ta.MA_Type.EMA)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_s'] = bb_upper
    features['bb_middle_s'] = bb_middle
    features['bb_lower_s'] = bb_lower
    features['bb_trend1_s'] = bb_trend1
    features['bb_trend2_s'] = bb_trend2
    bb_upper, bb_middle, bb_lower = ta.BBANDS(c, timeperiod=params['bbands_timeperiod_m'],
                                              nbdevup=params['bbands_nbdevup_m'], nbdevdn=params['bbands_nbdevdn_m'],
                                              matype=ta.MA_Type.EMA)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_m'] = bb_upper
    features['bb_middle_m'] = bb_middle
    features['bb_lower_m'] = bb_lower
    features['bb_trend1_m'] = bb_trend1
    features['bb_trend2_m'] = bb_trend2
    bb_upper, bb_middle, bb_lower = ta.BBANDS(c, timeperiod=params['bbands_timeperiod_l'],
                                              nbdevup=params['bbands_nbdevup_l'], nbdevdn=params['bbands_nbdevdn_l'],
                                              matype=ta.MA_Type.EMA)
    bb_trend1 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend1[c > bb_upper] = 1
    bb_trend1[c < bb_lower] = -1
    bb_trend2 = pd.Series(np.zeros(len(candle)), index=candle.index)
    bb_trend2[c > bb_middle] = 1
    bb_trend2[c < bb_middle] = -1
    features['bb_upper_l'] = bb_upper
    features['bb_middle_l'] = bb_middle
    features['bb_lower_l'] = bb_lower
    features['bb_trend1_l'] = bb_trend1
    features['bb_trend2_l'] = bb_trend2

    # ローソク足
    features['CDL2CROWS'] = ta.CDL2CROWS(o, h, l, c)
    features['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(o, h, l, c)
    features['CDL3INSIDE'] = ta.CDL3INSIDE(o, h, l, c)
    features['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(o, h, l, c)
    features['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(o, h, l, c)
    features['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(o, h, l, c)
    features['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(o, h, l, c)
    features['CDLABANDONEDBABY'] = ta.CDLABANDONEDBABY(o, h, l, c, penetration=0)
    features['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(o, h, l, c)
    features['CDLBELTHOLD'] = ta.CDLBELTHOLD(o, h, l, c)
    features['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(o, h, l, c)
    features['CDLCLOSINGMARUBOZU'] = ta.CDLCLOSINGMARUBOZU(o, h, l, c)
    features['CDLCONCEALBABYSWALL'] = ta.CDLCONCEALBABYSWALL(o, h, l, c)
    features['CDLCOUNTERATTACK'] = ta.CDLCOUNTERATTACK(o, h, l, c)
    features['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(o, h, l, c, penetration=0)
    #features['CDLDOJI'] = ta.CDLDOJI(o, h, l, c)
    features['CDLDOJISTAR'] = ta.CDLDOJISTAR(o, h, l, c)
    features['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(o, h, l, c)
    features['CDLENGULFING'] = ta.CDLENGULFING(o, h, l, c)
    features['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(o, h, l, c, penetration=0)
    features['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(o, h, l, c, penetration=0)
    #features['CDLGAPSIDESIDEWHITE'] = ta.CDLGAPSIDESIDEWHITE(o, h, l, c)
    features['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(o, h, l, c)
    features['CDLHAMMER'] = ta.CDLHAMMER(o, h, l, c)
    #features['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(o, h, l, c)
    features['CDLHARAMI'] = ta.CDLHARAMI(o, h, l, c)
    features['CDLHARAMICROSS'] = ta.CDLHARAMICROSS(o, h, l, c)
    features['CDLHIGHWAVE'] = ta.CDLHIGHWAVE(o, h, l, c)
    #features['CDLHIKKAKE'] = ta.CDLHIKKAKE(o, h, l, c)
    features['CDLHIKKAKEMOD'] = ta.CDLHIKKAKEMOD(o, h, l, c)
    features['CDLHOMINGPIGEON'] = ta.CDLHOMINGPIGEON(o, h, l, c)
    #features['CDLIDENTICAL3CROWS'] = ta.CDLIDENTICAL3CROWS(o, h, l, c)
    features['CDLINNECK'] = ta.CDLINNECK(o, h, l, c)
    #features['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(o, h, l, c)
    features['CDLKICKING'] = ta.CDLKICKING(o, h, l, c)
    features['CDLKICKINGBYLENGTH'] = ta.CDLKICKINGBYLENGTH(o, h, l, c)
    features['CDLLADDERBOTTOM'] = ta.CDLLADDERBOTTOM(o, h, l, c)
    #features['CDLLONGLEGGEDDOJI'] = ta.CDLLONGLEGGEDDOJI(o, h, l, c)
    features['CDLMARUBOZU'] = ta.CDLMARUBOZU(o, h, l, c)
    #features['CDLMATCHINGLOW'] = ta.CDLMATCHINGLOW(o, h, l, c)
    features['CDLMATHOLD'] = ta.CDLMATHOLD(o, h, l, c, penetration=0)
    features['CDLMORNINGDOJISTAR'] = ta.CDLMORNINGDOJISTAR(o, h, l, c, penetration=0)
    features['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(o, h, l, c, penetration=0)
    features['CDLONNECK'] = ta.CDLONNECK(o, h, l, c)
    features['CDLPIERCING'] = ta.CDLPIERCING(o, h, l, c)
    features['CDLRICKSHAWMAN'] = ta.CDLRICKSHAWMAN(o, h, l, c)
    features['CDLRISEFALL3METHODS'] = ta.CDLRISEFALL3METHODS(o, h, l, c)
    features['CDLSEPARATINGLINES'] = ta.CDLSEPARATINGLINES(o, h, l, c)
    #features['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(o, h, l, c)
    features['CDLSHORTLINE'] = ta.CDLSHORTLINE(o, h, l, c)
    #features['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(o, h, l, c)
    features['CDLSTALLEDPATTERN'] = ta.CDLSTALLEDPATTERN(o, h, l, c)
    features['CDLSTICKSANDWICH'] = ta.CDLSTICKSANDWICH(o, h, l, c)
    features['CDLTAKURI'] = ta.CDLTAKURI(o, h, l, c)
    features['CDLTASUKIGAP'] = ta.CDLTASUKIGAP(o, h, l, c)
    features['CDLTHRUSTING'] = ta.CDLTHRUSTING(o, h, l, c)
    features['CDLTRISTAR'] = ta.CDLTRISTAR(o, h, l, c)
    features['CDLUNIQUE3RIVER'] = ta.CDLUNIQUE3RIVER(o, h, l, c)
    features['CDLUPSIDEGAP2CROWS'] = ta.CDLUPSIDEGAP2CROWS(o, h, l, c)
    features['CDLXSIDEGAP3METHODS'] = ta.CDLXSIDEGAP3METHODS(o, h, l, c)

    '''
    # トレンドライン
    for dt in datetimerange(candle.index[0], candle.index[-1] + timedelta(minutes=1)):
        start_dt = (dt - timedelta(minutes=130)).strftime('%Y-%m-%d %H:%M:%S')
        end_dt = dt.strftime('%Y-%m-%d %H:%M:%S')
        tmp = candle.loc[(start_dt <= candle.index) & (candle.index <= end_dt)]
        for w_size, stride in [(15, 5), (30, 10), (60, 10), (120, 10)]:
        # for w_size, stride in [(120, 10)]:
            trendlines = calc_trendlines(tmp, w_size, stride)
            if len(trendlines) == 0:
                continue
            trendline_feature = calc_trendline_feature(tmp, trendlines)

            print('{}-{} {} {} {}'.format(dt - timedelta(minutes=130), dt, trendline_feature['high_a'], trendline_feature['high_b'], trendline_feature['high_diff']))

            features.loc[features.index == end_dt, 'trendline_high_a_{}'.format(w_size)] = trendline_feature['high_a']
            features.loc[features.index == end_dt, 'trendline_high_b_{}'.format(w_size)] = trendline_feature['high_b']
            features.loc[features.index == end_dt, 'trendline_high_diff_{}'.format(w_size)] = trendline_feature['high_diff']
            features.loc[features.index == end_dt, 'trendline_low_a_{}'.format(w_size)] = trendline_feature['low_a']
            features.loc[features.index == end_dt, 'trendline_low_b_{}'.format(w_size)] = trendline_feature['low_b']
            features.loc[features.index == end_dt, 'trendline_low_diff_{}'.format(w_size)] = trendline_feature['low_diff']
    '''

    window = 5
    features_ext = features
    for w in range(window):
        tmp = features.shift(periods=60 * (w + 1), freq='S')
        tmp.columns = [c + '_' + str(w + 1) + 'w' for c in features.columns]
        features_ext = pd.concat([features_ext, tmp], axis=1)
    
    if candle_type == '5min':
        features_ext = features_ext.shift(periods=300, freq='S')
        features_ext = features_ext.fillna(method='ffill')
    features_ext = features_ext[features_ext.index == target_dt]
    return features_ext
def CDL3BLACKCROWS(DataFrame):
    res = talib.CDL3BLACKCROWS(DataFrame.open.values, DataFrame.high.values,
                               DataFrame.low.values, DataFrame.close.values)
    return pd.DataFrame({'CDL3BLACKCROWS': res}, index=DataFrame.index)
Esempio n. 30
0
    def all_algo(self,curr_pair_history_data,db=False):
        order = np.zeros((self.num_curr,7,3))
        signal = np.zeros((self.num_curr,16))
        for i in range(len(self.curr_pair_list)):
            # Processing data
            close5=(curr_pair_history_data[i]['closeAsk'].tail(5).values+\
                    curr_pair_history_data[i]['closeBid'].tail(5).values)/2
            high5=(curr_pair_history_data[i]['highAsk'].tail(5).values+\
                   curr_pair_history_data[i]['highBid'].tail(5).values)/2
            low5=(curr_pair_history_data[i]['lowAsk'].tail(5).values+\
                  curr_pair_history_data[i]['lowBid'].tail(5).values)/2
            openv5=(curr_pair_history_data[i]['openAsk'].tail(5).values+\
                    curr_pair_history_data[i]['openBid'].tail(5).values)/2

            close=(curr_pair_history_data[i]['closeAsk'].values+\
                   curr_pair_history_data[i]['closeBid'].values)/2
            high=(curr_pair_history_data[i]['highAsk'].values+\
                  curr_pair_history_data[i]['highBid'].values)/2
            low=(curr_pair_history_data[i]['lowAsk'].values+\
                 curr_pair_history_data[i]['lowBid'].values)/2
            openv=(curr_pair_history_data[i]['openAsk'].values+\
                   curr_pair_history_data[i]['openBid'].values)/2

            # Generating signals
            pattern=talib.CDL3BLACKCROWS(openv5,high5,low5,close5)
            pattern_signal=pattern[-1]

            adx=talib.ADX(high,low,close,timeperiod=14)
            rsi=talib.RSI(close,timeperiod=14)
            adx_signal=adx[-1]
            rsi_signal=rsi[-1]

            bull, bear=talib.AROON(high,low,timeperiod=14)

            sma=talib.SMA(close,timeperiod=30)
            kama=talib.KAMA(close,timeperiod=30)

            DIF,DEA,BAR=talib.MACDFIX(close,signalperiod=9)

            mfi=talib.MFI(high,low,close,curr_pair_history_data[i]['volume'].values.astype(float),timeperiod=14)
            mfi_signal=mfi[-1]

            # Storing signals
            signal[i,0] = pattern_signal
            signal[i,1] = adx_signal
            signal[i,13] = rsi_signal
            signal[i,2] = bear[-2]
            signal[i,3] = bear[-1]
            signal[i,4] = bull[-2]
            signal[i,5] = bull[-1]
            signal[i,10] = kama[-2]
            signal[i,11] = kama[-1]
            signal[i,14] = sma[-2]
            signal[i,15] = sma[-1]
            signal[i,6] = DEA[-2]
            signal[i,7] = DEA[-1]
            signal[i,8] = DIF[-2]
            signal[i,9] = DIF[-1]
            signal[i,12] = mfi_signal

            # Creating orders
            if pattern_signal>0:
                #trader.create_buy_order(ticker,units)
                order[i,0,1] = 1
            elif pattern_signal<0:
                #trader.create_sell_order(ticker,units)
                order[i,0,2] = 1
            else:
                #print('No trade made')
                order[i,0,0] = 1

            if rsi_signal>70 and adx_signal>50:
                #trader.create_buy_order(ticker,units)
                order[i,1,1] = 1
            elif rsi_signal<30 and adx_signal>50:
                #trader.create_sell_order(ticker,units)
                order[i,1,2] = 1
            else:
                #print('No trade made')
                order[i,1,0] = 1

            if rsi_signal>70:
                #trader.create_buy_order(ticker,units)
                order[i,6,1] = 1
            elif rsi_signal<30:
                #trader.create_sell_order(ticker,units)
                order[i,6,2] = 1
            else:
                #print('No trade made')
                order[i,6,0] = 1

            if (bull[-1]>70 and bear[-1]<30) or (bull[-2]<bear[-2] and bull[-1]>=bear[-1]):
                #trader.create_buy_order(ticker,units)
                order[i,2,1] = 1
            elif (bull[-1]<30 and bear[-1]>70) or (bull[-2]>=bear[-2] and bull[-1]<bear[-1]):
                #trader.create_sell_order(ticker,units)
                order[i,2,2] = 1
            else:
                #print('No trade made')
                order[i,2,0] = 1

            if kama[-1]>=sma[-1] and kama[-2]<sma[-2]:
                #trader.create_buy_order(ticker,units)
                order[i,3,1] = 1
            elif kama[-1]<=sma[-1] and kama[-2]>=sma[-2]:
                #trader.create_sell_order(ticker,units)
                order[i,3,2] = 1
            else:
                #print("No trade made")
                order[i,3,0] = 1

            if DIF[-1]>0 and DEA[-1]>0 and DIF[-2]<DEA[-2] and DIF[-1]>DEA[-1]:
                #trader.create_buy_order(ticker,units)
                order[i,4,1] = 1
            elif DIF[-1]<0 and DEA[-1]<0 and DIF[-2]>DEA[-2] and DIF[-1]<DEA[-1]:
                #trader.create_sell_order(ticker,units)
                order[i,4,2] = 1
            else:
                #print("No trade made")
                order[i,4,0] = 1

            if mfi_signal>70:
                #trader.create_buy_order(ticker,units)
                order[i,5,1] = 1
            elif mfi_signal<30:
                #trader.create_sell_order(ticker,units)
                order[i,5,2] = 1
            else:
                #print('No trade made')
                order[i,5,0] = 1

            if db:
                #write to database here
                pass
        return order,signal