Пример #1
0
def bearish_candles(op, high, low, close):
	star = ta.CDLEVENINGSTAR(op, high, low, close, penetration=0)
	hanging = ta.CDLHANGINGMAN(op, high, low, close)
	engulf = engulf = ta.CDLENGULFING(op, high, low, close) # engulfing
	belt = ta.CDLBELTHOLD(op, high, low, close)

	return star, hanging, engulf, belt
Пример #2
0
def candle_patt(df,x,all_fig,params):
    '''ローソク足パターンのローソク足チャートへの描画'''
    
    # パターンチェック & シグナル値を描画用に置き換え
    df['Marubozu'] = ta.CDLMARUBOZU(df['Open'],df['High'],df['Low'],df['Close']) * df['High'] / 100
    df['Engulfing_Pattern'] = ta.CDLENGULFING(df['Open'],df['High'],df['Low'],df['High']) * df['Close'] / 100
    df['Hammer'] = ta.CDLHAMMER(df['Open'],df['High'],df['Low'],df['Close']) * df['High'] / 100
    df['Dragonfly_Doji'] = ta.CDLDRAGONFLYDOJI(df['Open'],df['High'],df['Low'],df['Close']) * df['High'] / 100    
    
    # 列名を作成
    pattern_list = list(df.loc[:,'Marubozu':'Dragonfly_Doji'].columns)
    label_list = [ k+'_label' for k in list(df.loc[:,'Marubozu':'Dragonfly_Doji'].columns)]
    
    # 0をNaNで埋める
    df[pattern_list] = df[pattern_list].where(~(df[pattern_list] == 0.0), np.nan)
        
    # 売り買いラベルの作成
    df[label_list] = df[pattern_list]
    df[label_list] = df[label_list].where(~(df[label_list] > 0), 1)
    df[label_list] = df[label_list].where(~(df[label_list] < 0), -1)
    df[label_list] = df[label_list].where(~(df[label_list] == 1), '買い')
    df[label_list] = df[label_list].where(~(df[label_list] == -1), '売り')
    
    # 発生価格の絶対値化
    df[pattern_list] = df[pattern_list].abs()
    
    # 各シグナルを描画
    for pattern in list(df.loc[:,'Marubozu':'Dragonfly_Doji'].columns):
        all_fig.add_trace(go.Scatter(x=x, y=df[pattern],mode='markers+text',text=df[label_list],textposition="top center",name=pattern,
                                    marker = dict(size = 9),opacity=0.8),row=1, col=1)
    
    return all_fig
Пример #3
0
def get_cdlengulfing(ohlc):
    cdlengulfing = ta.CDLENGULFING(ohlc['1_open'], ohlc['2_high'],
                                   ohlc['3_low'], ohlc['4_close'])

    ohlc['cdlengulfing'] = cdlengulfing

    return ohlc
Пример #4
0
def genTA(data, y, t): #t is timeperiod
    indicators  = {}
    y_ind = copy.deepcopy(y)
   
    for ticker in data:
    ## Overlap
        indicators[ticker] = ta.SMA(data[ticker].iloc[:,3], timeperiod=t).to_frame()        
        indicators[ticker]['EMA'] = ta.EMA(data[ticker].iloc[:,3], timeperiod=t)       
        indicators[ticker]['BBAND_Upper'], indicators[ticker]['BBAND_Middle' ], indicators[ticker]['BBAND_Lower' ] = ta.BBANDS(data[ticker].iloc[:,3], timeperiod=t, nbdevup=2, nbdevdn=2, matype=0)         
        indicators[ticker]['HT_TRENDLINE'] = ta.HT_TRENDLINE(data[ticker].iloc[:,3])
        indicators[ticker]['SAR'] = ta.SAR(data[ticker].iloc[:,1], data[ticker].iloc[:,2], acceleration=0, maximum=0)
        #rename SMA column
        indicators[ticker].rename(columns={indicators[ticker].columns[0]: "SMA"}, inplace=True)
    ## Momentum
        indicators[ticker]['RSI'] = ta.RSI(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['MOM'] = ta.MOM(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['ROC'] = ta.ROC(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['ROCP']= ta.ROCP(data[ticker].iloc[:,3],timeperiod=(t-1))
        indicators[ticker]['STOCH_SLOWK'], indicators[ticker]['STOCH_SLOWD'] = ta.STOCH(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], fastk_period=t, slowk_period=int(.6*t), slowk_matype=0, slowd_period=int(.6*t), slowd_matype=0)
        indicators[ticker]['MACD'], indicators[ticker]['MACDSIGNAL'], indicators[ticker]['MACDHIST'] = ta.MACD(data[ticker].iloc[:,3], fastperiod=t,slowperiod=2*t,signalperiod=int(.7*t))
        
    ## Volume
        indicators[ticker]['OBV'] = ta.OBV(data[ticker].iloc[:,3], data[ticker].iloc[:,4])
        indicators[ticker]['AD'] = ta.AD(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], data[ticker].iloc[:,4])
        indicators[ticker]['ADOSC'] = ta.ADOSC(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], data[ticker].iloc[:,4], fastperiod=int(.3*t), slowperiod=t)
        
    ## Cycle
        indicators[ticker]['HT_DCPERIOD'] = ta.HT_DCPERIOD(data[ticker].iloc[:,3])
        indicators[ticker]['HT_TRENDMODE']= ta.HT_TRENDMODE(data[ticker].iloc[:,3])
    
    ## Price
        indicators[ticker]['AVGPRICE'] = ta.AVGPRICE(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['TYPPRICE'] = ta.TYPPRICE(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
    
    ## Volatility
        indicators[ticker]['ATR'] = ta.ATR(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3],  timeperiod=(t-1))
    
    ## Statistics
        indicators[ticker]['BETA'] = ta.BETA(data[ticker].iloc[:,1], data[ticker].iloc[:,2], timeperiod=(t-1))
        indicators[ticker]['LINEARREG'] = ta.LINEARREG(data[ticker].iloc[:,3], timeperiod=t)
        indicators[ticker]['VAR'] = ta.VAR(data[ticker].iloc[:,3], timeperiod=t, nbdev=1)
    
    ## Math Transform
        indicators[ticker]['EXP'] = ta.EXP(data[ticker].iloc[:,3])
        indicators[ticker]['LN'] = ta.LN(data[ticker].iloc[:,3])
    
    ## Patterns (returns integers - but norming might not really do anything but wondering if they should be normed)
        indicators[ticker]['CDLENGULFING'] = ta.CDLENGULFING(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLDOJI']      = ta.CDLDOJI(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLHAMMER']    = ta.CDLHAMMER(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLHANGINGMAN']= ta.CDLHANGINGMAN(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        
    #drop 'nan' values
        indicators[ticker].drop(indicators[ticker].index[np.arange(0,63)], inplace=True)
        y_ind[ticker].drop(y_ind[ticker].index[np.arange(0,63)], inplace=True)
        
    #Normalize Features
    indicators_norm = normData(indicators)
        
    return indicators_norm, indicators, y_ind
Пример #5
0
def plot_Engulfing(data):
    """This function signals Engulfing pattern.
###################### CDLENGULFING - Engulfing Pattern ########################
explanation:"""

    engulfing_pattern = talib.CDLENGULFING(data['Open'], data['High'],
                                           data['Low'], data['Close'])
    return np.flatnonzero(engulfing_pattern)
Пример #6
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
Пример #7
0
 def engulfing(self):
     """
     名称:Engulfing Pattern 吞噬模式
     简介:两日K线模式,分多头吞噬和空头吞噬,以多头吞噬为例,第一日为阴线,第二日阳线,第一日的开盘价和收盘价在第二日开盘价收盘价之内,但不能完全相同。
     """
     result = talib.CDLENGULFING(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['engulfing'] = result
Пример #8
0
 def _collect_data():
     live_trades = api.get_eth_eur_values(from_dt_str="now()- 1d")
     candlestick_5m = create_candlesticks(live_trades, interval='5Min')
     candlestick_5m['engulfing'] = talib.CDLENGULFING(
         candlestick_5m['open'], candlestick_5m['high'],
         candlestick_5m['low'], candlestick_5m['close'])
     candlestick_5m['ema_10'] = talib.EMA(candlestick_5m['close'], 10)
     candlestick_5m['ema_20'] = talib.EMA(candlestick_5m['close'], 20)
     print("ema_10:", candlestick_5m[-2:-1]['ema_10'].values[0], "ema_20:",
           candlestick_5m[-2:-1]['ema_20'].values[0])
     return candlestick_5m
Пример #9
0
def CDLENGULFING(open, high, low, close):
    ''' Engulfing Pattern 吞噬模式

    分组: Pattern Recognition 形态识别

    简介: 两日K线模式,分多头吞噬和空头吞噬,以多头吞噬为例,
    第一日为阴线, 第二日阳线,第一日的开盘价和收盘价在第二日开盘价收盘价之内,但不能完全相同。

    integer = CDLENGULFING(open, high, low, close)
    '''
    return talib.CDLENGULFING(open, high, low, close)
Пример #10
0
 def confirm_bull_patterns(self):
     if (talib.CDLENGULFING(self.new.open, self.new.high, self.new.low,
                            self.new.close)[-1] == 100
             or talib.CDLMORNINGSTAR(
                 self.new.open, self.new.high, self.new.low,
                 self.new.close)[-1] == 100 or talib.CDLMORNINGDOJISTAR(
                     self.new.open, self.new.high, self.new.low,
                     self.new.close)[-1] == 100
             or talib.CDLPIERCING(self.new.open, self.new.high,
                                  self.new.low, self.new.close)[-1] == 100):
         return True
     return False
Пример #11
0
 def confirm_bear_patterns(self):
     if (talib.CDLENGULFING(self.new.open, self.new.high, self.new.low,
                            self.new.close)[-1] == -100
             or talib.CDLEVENINGSTAR(
                 self.new.open, self.new.high, self.new.low,
                 self.new.close)[-1] == 100 or talib.CDLEVENINGDOJISTAR(
                     self.new.open, self.new.high, self.new.low,
                     self.new.close)[-1] == 100 or talib.CDLDARKCLOUDCOVER(
                         self.new.open, self.new.high, self.new.low,
                         self.new.close)[-1] == 100):
         return True
     return False
Пример #12
0
    def engulfing(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.CDLENGULFING(opens, highs, lows, closes)

        return cdl
Пример #13
0
def the_twelve(df,return_candlelist=False):
    '''
    adds candles to the data frame
    if return_candle_list is True:
        RETURNS:
            a list of the candels:
                [
                'DOJI',
                'EVENINGSTAR',
                'MORNINGSTAR',
                'SHOOTINGSTAR',
                'HAMMER',
                'INVERTEDHAMMER',
                'HARAMI',
                'ENGULFING',
                'HANGINGMAN',
                'PIERCING',
                'BELTHOLD',
                'KICKING',
                'DARKCLOUDCOVER'
    '''

    df['DOJI'] = talib.CDLDOJI(df.open,df.high,df.low,df.close)
    df['EVENINGSTAR'] = talib.CDLEVENINGSTAR(df.open,df.high,df.low,df.close)
    df['MORNINGSTAR'] = talib.CDLMORNINGSTAR(df.open,df.high,df.low,df.close)
    df['SHOOTINGSTAR'] = talib.CDLSHOOTINGSTAR(df.open,df.high,df.low,df.close)
    df['HAMMER'] = talib.CDLHAMMER(df.open,df.high,df.low,df.close)
    df['INVERTEDHAMMER'] = talib.CDLINVERTEDHAMMER(df.open,df.high,df.low,df.close)
    df['HARAMI'] = talib.CDLHARAMI(df.open,df.high,df.low,df.close)
    df['ENGULFING'] = talib.CDLENGULFING(df.open,df.high,df.low,df.close)
    df['HANGINGMAN'] = talib.CDLHANGINGMAN(df.open,df.high,df.low,df.close)
    df['PIERCING'] = talib.CDLPIERCING(df.open,df.high,df.low,df.close)
    df['BELTHOLD'] = talib.CDLBELTHOLD(df.open,df.high,df.low,df.close)
    df['KICKING'] = talib.CDLKICKING(df.open,df.high,df.low,df.close)
    df['DARKCLOUDCOVER'] = talib.CDLDARKCLOUDCOVER(df.open,df.high,df.low,df.close)
    if return_candlelist == True:
        candle_list = [
            'DOJI',
            'EVENINGSTAR',
            'MORNINGSTAR',
            'SHOOTINGSTAR',
            'HAMMER',
            'INVERTEDHAMMER',
            'HARAMI',
            'ENGULFING',
            'HANGINGMAN',
            'PIERCING',
            'BELTHOLD',
            'KICKING',
            'DARKCLOUDCOVER'
        ]
        return candle_list
    def strat_RSIENGCDL(self, data=None, limit=60):
        if data is None:
            data = self.db.getData(60)

        rsi_sig = self.sig.sig_RSI(data)
        candle = talib.CDLENGULFING(data.open.values, data.high.values,
                                    data.high.values, data.close.values)[-1]
        if rsi_sig > 0 and candle == 100:
            return 1
        elif rsi_sig < 0 and candle == -100:
            return -1
        else:
            return 0
Пример #15
0
 def _collect_data(self):
     live_trades = api.get_eth_eur_values(from_dt_str="now()- 3d",
                                          measurement='binance_live_trades')
     candlestick_5m = create_candlesticks(live_trades, interval='5Min')
     candlestick_5m['engulfing'] = talib.CDLENGULFING(
         candlestick_5m['open'], candlestick_5m['high'],
         candlestick_5m['low'], candlestick_5m['close'])
     candlestick_5m['ema_3'] = talib.EMA(candlestick_5m['close'], 3)
     candlestick_5m['ema_6'] = talib.EMA(candlestick_5m['close'], 6)
     candlestick_5m['ema_9'] = talib.EMA(candlestick_5m['close'], 9)
     candlestick_5m['sma_21'] = talib.SMA(candlestick_5m['close'], 21)
     candlestick_5m['sma_50'] = talib.SMA(candlestick_5m['close'], 50)
     candlestick_5m['sma_100'] = talib.SMA(candlestick_5m['close'], 100)
     return candlestick_5m
Пример #16
0
def get_indicators(data,fast=20,slow=50):
    # Get MACD
    data["macd"], data["macd_signal"], data["macd_hist"] = talib.MACD(data['Close'])
    # Get RSI
    data["rsi"] = talib.RSI(data["Close"])
    # Get MAS and crossover
    data["ma_fast"] = talib.MA(data["Close"], timeperiod=fast)
    data["ma_slow"] = talib.MA(data["Close"], timeperiod=slow)
    data['prev_ma_fast'] = data['ma_fast'].shift(1)
    # data['prev_ma_slow'] = data['ma_slow'].shift(1)
    # data['ma_cross'] = np.where(data['ma_fast'] > data['ma_slow'] and data['prev_ma_fast'] < data['prev_ma_slow'],1,0)
    #get candle patterns
    data['engulfing'] = talib.CDLENGULFING(data.Open, data.High, data.Low, data.Close)
    data['morningstar'] = talib.CDLMORNINGSTAR(data.Open, data.High, data.Low, data.Close)
    return data
Пример #17
0
def add_up_pattern_recognition_factor(df):
    df['hammer'] = talib.CDLHAMMER(df['open'], df['high'], df['low'],
                                   df['close'])
    df['inverted_hammer'] = talib.CDLINVERTEDHAMMER(df['open'], df['high'],
                                                    df['low'], df['close'])
    df['engulfing'] = talib.CDLENGULFING(df['open'], df['high'], df['low'],
                                         df['close'])  # not sure the direction
    df['three_white_soldiers'] = talib.CDL3WHITESOLDIERS(
        df['open'], df['high'], df['low'], df['close'])  # strong up trend
    df['morning_doji_star'] = talib.CDLMORNINGDOJISTAR(df['open'],
                                                       df['high'],
                                                       df['low'],
                                                       df['close'],
                                                       penetration=0)

    return df
Пример #18
0
    def bull_gMarubozu_rMarubozu_green_top_wick(self, *args):

        mar = talib.CDLMARUBOZU(self.o, self.h, self.l, self.c)
        eng = talib.CDLENGULFING(self.o, self.h, self.l, self.c)
        idx = np.where(mar == 100)[0]
        idx3 = np.where(eng == 100)[0]

        o = []

        for x in idx3:
            if x - 2 in idx:
                o.append(x)

        a = np.zeros(len(self.o))
        a[o] = 1
        return a
Пример #19
0
def engulfing(exchange, symbol, timeframe, past=0) -> int:
    """
    is the current candle a engulfing pattern. returns 1 when is a bullish engulfing,
    and 0 when isn't, and -1 when is a bearish engulfing pattern.
    """
    if past != 0:
        candles = store.candles.get_candles(exchange, symbol,
                                            timeframe)[:-abs(past)]
    else:
        candles = store.candles.get_candles(exchange, symbol, timeframe)

    if len(candles) > 240:
        candles = candles[-240:]

    res = talib.CDLENGULFING(candles[:, 1], candles[:, 3], candles[:, 4],
                             candles[:, 2])[-1]

    return int(res / 100)
Пример #20
0
    def bear_engulfing_touch(self, *args):
        def logic(idx):
            if (np.all(self.array[idx[-1]] == self.array[-1])
                    and self.h[-1] != self.o[-1] and self.h[-2] != self.o[-2]):
                return 1
            return 0

        engulf = talib.CDLENGULFING(self.o, self.h, self.l, self.c)

        try:
            idx = np.where(engulf == -100)[0]
            if idx.size == 0 or len(self.array) < 2:
                return 0
        except Exception:
            return 0
        finally:
            if self.ilist is None:
                return logic(idx)
def findTAPattern(df, patternName):
    if patternName == '2CROWS':
        df[patternName] = talib.CDL2CROWS(df.Open.values, df.High.values,
                                          df.Low.values, df.Close.values)
    elif patternName == 'DOJI':
        df[patternName] = talib.CDLDOJI(df.Open.values, df.High.values,
                                        df.Low.values, df.Close.values)
    elif patternName == 'ENGULFING':
        df[patternName] = talib.CDLENGULFING(df.Open.values, df.High.values,
                                             df.Low.values, df.Close.values)
    elif patternName == 'EVENINGSTAR':
        df[patternName] = talib.CDLEVENINGSTAR(df.Open.values, df.High.values,
                                               df.Low.values, df.Close.values)
    elif patternName == 'MARUBOZU':
        df[patternName] = talib.CDLMARUBOZU(df.Open.values, df.High.values,
                                            df.Low.values, df.Close.values)
    else:
        print('Pattern not supported yet')

    patterned_df = df[df[patternName] != 0]
    return patterned_df
    print(patterned_df)
Пример #22
0
def engulfing_strgy(tickers, num):
    for ticker in tickers:
        try:
            df = get_klines(pair=ticker, interval=interval, depth=depth)
            if not df.empty:
                for i in ema_used:
                    df["EMA_" + str(i)] = ta.EMA(df["Close"], timeperiod=i)
                df_2 = df.tail(5)
                engulfing = ta.CDLENGULFING(df_2["Open"], df_2["High"],
                                            df_2["Low"], df_2["Close"])
                last_index = find_engulging(series=engulfing)

                if bool(last_index):
                    close_price = float(df["Close"][last_index])
                    volume = float(df["Volume"][last_index])
                    volume = round(volume, 2)
                    ema_50 = float(df["EMA_50"][last_index])
                    ema_100 = float(df["EMA_100"][last_index])
                    low_price = float(df["Low"][last_index])
                    pct_change = ((low_price * 100) / close_price) - 100
                    pct_change = round(pct_change, 2)
                    now = datetime.now()
                    now = now.minute
                    candle_time = last_index.minute

                    if (close_price > ema_50 or close_price > ema_100
                        ) and ema_50 > ema_100 and pct_change > -4 and (
                            candle_time == now - 15):
                        Signals.add(collection="Signals",
                                    ticker=ticker,
                                    volume=volume,
                                    pct_sl=pct_change)
        except:
            pass
    Signals.add(collection="Signals",
                ticker="End_" + str(num),
                volume=0,
                pct_sl=0)
def engulfing_strgy(tickers, num):
    for ticker in tickers:
        try:
            df = get_klines(pair = ticker, interval = interval, depth = depth)
            for i in ema_used:
                df["EMA_"+str(i)] = ta.EMA(df["Close"], timeperiod = i)
            engulfing = ta.CDLENGULFING(df["Open"], df["High"], df["Low"], df["Close"])
            last_index = find_engulfing(series = engulfing)

            if bool(last_index):
                close_price = float(df["Close"][last_index])
                volume = float(df["Volume"][last_index])
                volume = round(volume, 2)
                ema_50 = float(df["EMA_50"][last_index])
                ema_100 = float(df["EMA_100"][last_index])
                low_price = float(df["Low"][last_index])
                pct_change = ((low_price *100) / close_price) - 100
                pct_change = round(pct_change, 2)

                if (close_price > ema_50 or close_price > ema_100) and ema_50 > ema_100 and pct_change > -4 :
                    Signals.add(collection = "Signals", ticker = ticker, volume = volume)
        except:
            pass
    Signals.add(collection = "Signals", ticker = "End_"+num, volume = 0)
Пример #24
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)
def CDLENGULFING(DataFrame):
    res = talib.CDLENGULFING(DataFrame.open.values, DataFrame.high.values,
                             DataFrame.low.values, DataFrame.close.values)
    return pd.DataFrame({'CDLENGULFING': res}, index=DataFrame.index)
Пример #26
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
Пример #27
0
def TALIB_CDLENGULFING(close):
    '''00416,1,1'''
    return talib.CDLENGULFING(close)
Пример #28
0
import talib
import yfinance as yf

data = yf.download("GME", start="2020-01-01", end="2021-02-28")

morning_star = talib.CDLMORNINGSTAR(data['Open'], data['High'], data['Low'],
                                    data['Close'])

engulfing = talib.CDLENGULFING(data['Open'], data['High'], data['Low'],
                               data['Close'])

takuri = talib.CDLTAKURI(data['Open'], data['High'], data['Low'],
                         data['Close'])

ladderBottom = talib.CDLLADDERBOTTOM(data['Open'], data['High'], data['Low'],
                                     data['Close'])

kickingByLength = talib.CDLKICKINGBYLENGTH(data['Open'], data['High'],
                                           data['Low'], data['Close'])

data['Morning Star'] = morning_star
data['Engulfing'] = engulfing
data['Takuri'] = takuri
data['Ladder Bottom'] = ladderBottom
data['Kicking By Length'] = kickingByLength

engulfing_days = data[data['Engulfing'] != 0]
morning_star_days = data[data['Morning Star'] != 0]

print('Engulfing Days ', engulfing_days, 'Morning Star ', morning_star_days)
Пример #29
0
    def on_start(self, md, order, service, account):
        print self.symbol

        # First we need some historic data so lets grab 30 daily bars
        daily_bars = md.bar.daily(start=-30, include_empty=False)

        # most TALIB calls use OHLC (Open, High, Low, Close) in some form so lets pull those out so we have them ready
        open = daily_bars.open
        high = daily_bars.high
        low = daily_bars.low
        close = daily_bars.close
        volume = daily_bars.volume

        # now lets do a few TALIB calls and see what we get back

        # TALIB calls return numpy arrays, you can use numpy.ndarray.tolist() to convert to a normal list
        # These numpy arrays can contain floats such as a moving average price day to day
        # or they can contain a signal, often a series of zeros with 100 (and sometimes -100) indicating a signal
        # if there is insufficient data to return a result or a signal you will get a NAN
        # so for a 10 period moving average your first 9 entries will be NANs, the 10th will be your first Moving Average

        # TALIB.CDLENGULFING
        # returns a pandas array containing -100 for an engulfing red bar and 100 for an engulfing green bar.
        # CDLENGULFING is for the body of the candle only, not the wicks....
        engulf = talib.CDLENGULFING(
            open, high, low,
            close)  # call returns a numpy array of either 0 or 100
        engulflist = numpy.ndarray.tolist(
            engulf)  # if you prefer you can convert it to a normal list
        #        print "Engulf Numpy",engulf
        print "Engulf List", engulflist

        if engulf[-1] == 100:
            print "Yesterday Engulfed the previous day - Bullish (green bar) ********"
        elif engulf[-1] == -100:
            print "Yesterday Engulfed the previous day - Bearish (red bar)   ********"

        # TALIB.RSI
        RSI = talib.RSI(close, timeperiod=14)
        RSIlist = numpy.ndarray.tolist(RSI)
        #        print "RSI Numpy",RSI
        print "RSI List (Last 10 entries)", RSIlist[-10:]

        # TALIB.CDL3OUTSIDE
        # trend has a direction, oldest of three bars has the same direction, second bar consumes first bar and has opposite direction, third bar continues this direction
        ThreeOut = talib.CDL3OUTSIDE(open, high, low, close)
        ThreeOutlist = numpy.ndarray.tolist(ThreeOut)
        #        print "ThreeOutside Numpy",ThreeOut
        print "ThreeOutside List", ThreeOutlist
        if abs(ThreeOut[-1]) == 100:
            print "Three Outside Yesterday", self.symbol

        # TALIB.ADX if you put in 10, then your 20th data item will have a result.
        ADX = talib.ADX(high, low, close, timeperiod=14)
        MINUS_DI = talib.MINUS_DI(high, low, close, timeperiod=14)
        PLUS_DI = talib.PLUS_DI(high, low, close, timeperiod=14)
        ADXlist = numpy.ndarray.tolist(ADX)
        MINUS_DI_list = numpy.ndarray.tolist(MINUS_DI)
        PLUS_DI_list = numpy.ndarray.tolist(PLUS_DI)

        print "ADX List (last 10 entries)", ADXlist[-10:]
        print "MINUS_DI List (last 3 entries)", MINUS_DI_list[-3:]
        print "PLUS_DI list (last 3 entries)", PLUS_DI_list[-3:]

        #        if (ADX[-1] > 40.0) and (ADX[-2] < 40.0) and (PLUS_DI[-1] > MINUS_DI[-1]):
        if ADX[-1] > 50.0 and (PLUS_DI[-1] > MINUS_DI[-1]):
            print self.symbol, "Go Long   ", ADX[-1], ADX[-2], PLUS_DI[
                -1], MINUS_DI[-1]
#        elif (ADX[-1] > 40.0) and (ADX[-2] < 40.0) and (PLUS_DI[-1] < MINUS_DI[-1]):
        elif ADX[-1] > 50.0 and (PLUS_DI[-1] < MINUS_DI[-1]):
            print self.symbol, "Go Short  ", ADX[-1], ADX[-2], PLUS_DI[
                -1], MINUS_DI[-1]

        # TALIB.MA - Moving Average - matype=0 by default...
        # 0 = SMA (Simple Moving Average) (Default)
        # 1 = EMA (Exponential Moving Average)
        # 2 = WMA (Weighted Moving Average)
        # 3 = DEMA (Double Exponential Moving Average)
        # 4 = TEMA (Triple Exponential Moving Average)
        # 5 = TRIMA (Triangular Moving Average)
        # 6 = KAMA (Kaufman Adaptive Moving Average)
        # 7 = MAMA (MESA Adaptive Moving Average)
        # 8 = T3 (Triple Exponential Moving Average)

        SMA = talib.MA(close, timeperiod=20)
        SMAlist = numpy.ndarray.tolist(SMA)
        print "Simple Moving Average", SMAlist

        EMA = talib.MA(close, timeperiod=20, matype=1)
        EMAlist = numpy.ndarray.tolist(EMA)
        print "Exponential Moving Average", EMAlist

        print "Simple Moving Average      (last 3 entries)", SMAlist[-3:]
        print "Exponential Moving Average (last 3 entries)", EMAlist[-3:]
        print "Average of last 20 close prices", sum(close[-20:]) / len(
            close[-20:])
        print "Last Three close prices...", close[-3:]
        print
        service.terminate()
        return


#            if engulf[-1]==100:
#                print "Bearish Engulf yesterday",self.symbol
#        else:
#                print "Bullish Engulf yesterday",self.symbol
#        elif max(engulf)==100:
#            print engulflist,engulflist.index(100) # finds the location of the FIRST 100 entry in the list
#            print engulflist,engulflist[::-1].index(100) # finds the location of the LAST 100 entry ie the most recent.. the one we want!
#        elif min(engulf)==-100:
#            print engulflist,engulflist.index(-100) # finds the location of the FIRST -100 entry in the list
#            print engulflist,engulflist[::-1].index(-100) # finds the location of the LAST -100 entry ie the most recent.. the one we want!

#        service.terminate()
Пример #30
0
 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)
 df['CDLDRAGONFLYDOJI'] = talib.CDLDRAGONFLYDOJI(op, hp, lp, cp)
 df['CDLENGULFING'] = talib.CDLENGULFING(op, hp, lp, cp)
 df['CDLEVENINGDOJISTAR'] = talib.CDLEVENINGDOJISTAR(op, hp, lp, cp)
 df['CDLEVENINGSTAR'] = talib.CDLEVENINGSTAR(op, hp, lp, cp)
 df['CDLGAPSIDESIDEWHITE'] = talib.CDLGAPSIDESIDEWHITE(op, hp, lp, cp)
 df['CDLGRAVESTONEDOJI'] = talib.CDLGRAVESTONEDOJI(op, hp, lp, cp)
 df['CDLHAMMER'] = talib.CDLHAMMER(op, hp, lp, cp)
 df['CDLHANGINGMAN'] = talib.CDLHANGINGMAN(op, hp, lp, cp)
 df['CDLHARAMI'] = talib.CDLHARAMI(op, hp, lp, cp)
 df['CDLHARAMICROSS'] = talib.CDLHARAMICROSS(op, hp, lp, cp)
 df['CDLHIGHWAVE'] = talib.CDLHIGHWAVE(op, hp, lp, cp)
 df['CDLHIKKAKE'] = talib.CDLHIKKAKE(op, hp, lp, cp)
 df['CDLHIKKAKEMOD'] = talib.CDLHIKKAKEMOD(op, hp, lp, cp)
 df['CDLHOMINGPIGEON'] = talib.CDLHOMINGPIGEON(op, hp, lp, cp)
 df['CDLIDENTICAL3CROWS'] = talib.CDLIDENTICAL3CROWS(op, hp, lp, cp)
 df['CDLINNECK'] = talib.CDLINNECK(op, hp, lp, cp)
 df['CDLINVERTEDHAMMER'] = talib.CDLINVERTEDHAMMER(op, hp, lp, cp)