Esempio n. 1
0
    def get_momentum_indicators(self):
        # https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html
        if self.verbose:
            print self.ticker, 'get_momentum_indicators'

        _a = ['open', 'high', 'low', 'close', 'volume']
        inputs = {_a[i]: self.data[_a[i]].values for i in range(len(_a))}

        # average directional movement index
        self.data['mi_adx_14'] = abstract.ADX(inputs, timeperiod=14)

        # average directional movement index rating
        self.data['mi_adxr_14'] = abstract.ADX(inputs, timeperiod=14)

        # absolute price oscillator
        self.data['mi_apo'] = abstract.APO(inputs,
                                           fastperiod=12,
                                           slowperiod=26,
                                           matype=0)

        # aroon
        self.data['mi_aroon_d'], self.data['mi_aroon_u'] = abstract.AROON(
            inputs, timeperiod=14)

        # aroon oscillator
        self.data['mi_aroonosc'] = abstract.AROONOSC(inputs, timeperiod=14)
Esempio n. 2
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        # Set Up Bollinger Bands
        upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'],
                                                  timeperiod=36)
        upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(
            qtpylib.typical_price(dataframe), timeperiod=12)

        # Only putting some bands into dataframe as the others are not used elsewhere in the strategy
        dataframe['lower-bb1'] = lower_bb1
        dataframe['lower-bb2'] = lower_bb2
        dataframe['mid-bb2'] = mid_bb2

        dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs()
        dataframe['closedelta'] = (dataframe['close'] -
                                   dataframe['close'].shift()).abs()
        dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs()

        # Additional indicators
        dataframe['ema_fast'] = ta.EMA(dataframe['close'], timeperiod=6)
        dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48)
        dataframe['volume_mean_slow'] = dataframe['volume'].rolling(
            window=24).mean()

        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy)
        rsi = 0.1 * (dataframe['rsi'] - 50)
        dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)

        # Informative Pair Indicators
        coin, stake = metadata['pair'].split('/')
        fiat = self.fiat
        stake_fiat = f"{stake}/{self.fiat}"
        coin_fiat = f"{coin}/{self.fiat}"

        coin_fiat_inf = self.dp.get_pair_dataframe(pair=f"{coin}/{fiat}",
                                                   timeframe=self.timeframe)
        dataframe['coin-fiat-adx'] = ta.ADX(coin_fiat_inf, timeperiod=21)
        coin_aroon = ta.AROON(coin_fiat_inf, timeperiod=25)
        dataframe['coin-fiat-aroon-down'] = coin_aroon['aroondown']
        dataframe['coin-fiat-aroon-up'] = coin_aroon['aroonup']

        stake_fiat_inf = self.dp.get_pair_dataframe(pair=f"{stake}/{fiat}",
                                                    timeframe=self.timeframe)
        dataframe['stake-fiat-adx'] = ta.ADX(stake_fiat_inf, timeperiod=21)
        stake_aroon = ta.AROON(stake_fiat_inf, timeperiod=25)
        dataframe['stake-fiat-aroon-down'] = stake_aroon['aroondown']
        dataframe['stake-fiat-aroon-up'] = stake_aroon['aroonup']

        # These indicators are used to persist a buy signal in live trading only
        # They dramatically slow backtesting down
        if self.config['runmode'].value in ('live', 'dry_run'):
            dataframe['sar'] = ta.SAR(dataframe)

        return dataframe
Esempio n. 3
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe['adx'] = ta.ADX(dataframe, timeperiod=14)
        dataframe['plus_di'] = ta.PLUS_DI(dataframe, timeperiod=25)
        dataframe['minus_di'] = ta.MINUS_DI(dataframe, timeperiod=25)
        dataframe['sar'] = ta.SAR(dataframe)
        dataframe['mom'] = ta.MOM(dataframe, timeperiod=14)

        dataframe['sell-adx'] = ta.ADX(dataframe, timeperiod=14)
        dataframe['sell-plus_di'] = ta.PLUS_DI(dataframe, timeperiod=25)
        dataframe['sell-minus_di'] = ta.MINUS_DI(dataframe, timeperiod=25)
        dataframe['sell-sar'] = ta.SAR(dataframe)
        dataframe['sell-mom'] = ta.MOM(dataframe, timeperiod=14)

        return dataframe
Esempio n. 4
0
def populate_indicators_and_buy_signal(dataframe):
    dataframe['ema'] = ta.EMA(dataframe, timeperiod=33)
    dataframe['sar'] = ta.SAR(dataframe, 0.02, 0.22)
    dataframe['adx'] = ta.ADX(dataframe)

    prev_sar = dataframe['sar'].shift(1)
    prev_close = dataframe['close'].shift(1)
    prev_sar2 = dataframe['sar'].shift(2)
    prev_close2 = dataframe['close'].shift(2)

    # wait for stable turn from bearish to bullish market
    dataframe.loc[(dataframe['close'] > dataframe['sar']) &
                  (prev_close > prev_sar) & (prev_close2 < prev_sar2),
                  'swap'] = 1

    # consider prices above ema to be in upswing
    dataframe.loc[dataframe['ema'] <= dataframe['close'], 'upswing'] = 1

    dataframe.loc[(dataframe['upswing'] == 1) & (dataframe['swap'] == 1) & (
        dataframe['adx'] > 25),  # adx over 25 tells there's enough momentum
                  'buy'] = 1

    dataframe.loc[dataframe['buy'] == 1, 'buy_price'] = dataframe['close']

    return dataframe, info_msg % (dataframe.iloc[-1]['ema'],
                                  dataframe.iloc[-1]['sar'],
                                  dataframe.iloc[-1]['adx'])
Esempio n. 5
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe = self.resample(dataframe, self.ticker_interval,
                                  self.resample_factor)

        dataframe['ema_high'] = ta.EMA(dataframe, timeperiod=5, price='high')
        dataframe['ema_close'] = ta.EMA(dataframe, timeperiod=5, price='close')
        dataframe['ema_low'] = ta.EMA(dataframe, timeperiod=5, price='low')
        stoch_fast = ta.STOCHF(dataframe, 5.0, 3.0, 0.0, 3.0, 0.0)
        dataframe['fastd'] = stoch_fast['fastd']
        dataframe['fastk'] = stoch_fast['fastk']
        dataframe['adx'] = ta.ADX(dataframe)
        dataframe['cci'] = ta.CCI(dataframe, timeperiod=20)
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['mfi'] = ta.MFI(dataframe)

        # required for graphing
        bollinger = qtpylib.bollinger_bands(dataframe['close'],
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe['bb_middleband'] = bollinger['mid']

        return dataframe
Esempio n. 6
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        tf_res = timeframe_to_minutes(self.timeframe) * 5
        df_res = resample_to_interval(dataframe, tf_res)
        df_res['sma'] = ta.SMA(df_res, 50, price='close')
        dataframe = resampled_merge(dataframe, df_res, fill_na=True)
        dataframe['resample_sma'] = dataframe[f'resample_{tf_res}_sma']

        dataframe['ema_high'] = ta.EMA(dataframe, timeperiod=5, price='high')
        dataframe['ema_close'] = ta.EMA(dataframe, timeperiod=5, price='close')
        dataframe['ema_low'] = ta.EMA(dataframe, timeperiod=5, price='low')
        stoch_fast = ta.STOCHF(dataframe, 5, 3, 0, 3, 0)
        dataframe['fastd'] = stoch_fast['fastd']
        dataframe['fastk'] = stoch_fast['fastk']
        dataframe['adx'] = ta.ADX(dataframe)
        dataframe['cci'] = ta.CCI(dataframe, timeperiod=20)
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['mfi'] = ta.MFI(dataframe)

        # required for graphing
        bollinger = qtpylib.bollinger_bands(dataframe['close'],
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe['bb_middleband'] = bollinger['mid']

        return dataframe
Esempio n. 7
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        # Set Up Bollinger Bands
        upper_bb1, mid_bb1, lower_bb1 = ta.BBANDS(dataframe['close'],
                                                  timeperiod=40)
        upper_bb2, mid_bb2, lower_bb2 = ta.BBANDS(
            qtpylib.typical_price(dataframe), timeperiod=20)

        # only putting some bands into dataframe as the others are not used elsewhere in the strategy
        dataframe['lower-bb1'] = lower_bb1
        dataframe['lower-bb2'] = lower_bb2
        dataframe['mid-bb2'] = mid_bb2

        dataframe['bb1-delta'] = (mid_bb1 - dataframe['lower-bb1']).abs()
        dataframe['closedelta'] = (dataframe['close'] -
                                   dataframe['close'].shift()).abs()
        dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs()

        dataframe['ema_slow'] = ta.EMA(dataframe['close'], timeperiod=48)
        dataframe['volume_mean_slow'] = dataframe['volume'].rolling(
            window=24).mean()

        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        # # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy)
        rsi = 0.1 * (dataframe['rsi'] - 50)
        dataframe['fisher-rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)

        dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
        dataframe['adx'] = ta.ADX(dataframe)

        return dataframe
Esempio n. 8
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe['adx'] = ta.ADX(dataframe, timeperiod=14)
        dataframe['short'] = ta.SMA(dataframe, timeperiod=3)
        dataframe['long'] = ta.SMA(dataframe, timeperiod=6)

        return dataframe
Esempio n. 9
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        dataframe['ema_high'] = ta.EMA(dataframe, timeperiod=5, price='high')
        dataframe['ema_close'] = ta.EMA(dataframe, timeperiod=5, price='close')
        dataframe['ema_low'] = ta.EMA(dataframe, timeperiod=5, price='low')
        stoch_fast = ta.STOCHF(dataframe, 5.0, 3.0, 0.0, 3.0, 0.0)
        dataframe['fastd'] = stoch_fast['fastd']
        dataframe['fastk'] = stoch_fast['fastk']
        dataframe['adx'] = ta.ADX(dataframe)
        dataframe['cci'] = ta.CCI(dataframe, timeperiod=20)
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['mfi'] = ta.MFI(dataframe)

        # required for graphing
        bollinger = qtpylib.bollinger_bands(dataframe['close'],
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe['bb_middleband'] = bollinger['mid']

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']
        dataframe['cci'] = ta.CCI(dataframe)

        return dataframe
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Add several indicators needed for buy and sell strategies defined below.
        """
        # ADX
        dataframe['adx'] = ta.ADX(dataframe)
        # MACD
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        # MFI
        dataframe['mfi'] = ta.MFI(dataframe)
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)
        # Stochastic Fast
        stoch_fast = ta.STOCHF(dataframe)
        dataframe['fastd'] = stoch_fast['fastd']
        # Minus-DI
        dataframe['minus_di'] = ta.MINUS_DI(dataframe)
        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        # SAR
        dataframe['sar'] = ta.SAR(dataframe)

        return dataframe
Esempio n. 11
0
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['rsi'] = numpy.nan_to_num(ta.RSI(dataframe, timeperiod=5))
        dataframe['emarsi'] = numpy.nan_to_num(ta.EMA(dataframe['rsi'], timeperiod=5))

        dataframe['adx'] = numpy.nan_to_num(ta.ADX(dataframe))

        dataframe['minusdi'] = numpy.nan_to_num(ta.MINUS_DI(dataframe))
        dataframe['minusdiema'] = numpy.nan_to_num(ta.EMA(dataframe['minusdi'], timeperiod=25))
        dataframe['plusdi'] = numpy.nan_to_num(ta.PLUS_DI(dataframe))
        dataframe['plusdiema'] = numpy.nan_to_num(ta.EMA(dataframe['plusdi'], timeperiod=5))

        dataframe['lowsma'] = numpy.nan_to_num(ta.EMA(dataframe, timeperiod=60))
        dataframe['highsma'] = numpy.nan_to_num(ta.EMA(dataframe, timeperiod=120))
        dataframe['fastsma'] = numpy.nan_to_num(ta.SMA(dataframe, timeperiod=120))
        dataframe['slowsma'] = numpy.nan_to_num(ta.SMA(dataframe, timeperiod=240))

        dataframe['bigup'] = dataframe['fastsma'].gt(dataframe['slowsma']) & ((dataframe['fastsma'] - dataframe['slowsma']) > dataframe['close'] / 300)
        dataframe['bigdown'] = ~dataframe['bigup']
        dataframe['trend'] = dataframe['fastsma'] - dataframe['slowsma']

        dataframe['preparechangetrend'] = dataframe['trend'].gt(dataframe['trend'].shift())
        dataframe['preparechangetrendconfirm'] = dataframe['preparechangetrend'] & dataframe['trend'].shift().gt(dataframe['trend'].shift(2))
        dataframe['continueup'] = dataframe['slowsma'].gt(dataframe['slowsma'].shift()) & dataframe['slowsma'].shift().gt(dataframe['slowsma'].shift(2))

        dataframe['delta'] = dataframe['fastsma'] - dataframe['fastsma'].shift()
        dataframe['slowingdown'] = dataframe['delta'].lt(dataframe['delta'].shift())
        return dataframe
Esempio n. 12
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # ADX
        dataframe['adx'] = ta.ADX(dataframe)

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)

        # Bollinger Bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_middleband'] = bollinger['mid']
        dataframe['bb_upperband'] = bollinger['upper']
        dataframe["bb_percent"] = (
            (dataframe["close"] - dataframe["bb_lowerband"]) /
            (dataframe["bb_upperband"] - dataframe["bb_lowerband"]))
        dataframe["bb_width"] = (
            (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) /
            dataframe["bb_middleband"])

        # TEMA
        dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)

        return dataframe
Esempio n. 13
0
    def __init__(self, equityDataFrame, tickerCode):
        """
        Create the Average Directional-specific logic. Everything else lives in the Indicator Base Class.

        :param equityDataFrame: A Pandas DataFrame from the Equity Class.
        :param tickerCode: Ticker Code (String).
        """

        tableName = "Indicator_ADX"
        tickerCode = tickerCode

        insertQuery = "insert or replace into %s (Date, Code, ADX, ADX_ROC) values (?,?,?,?)" % (
            tableName)

        # Create a new DataFrame with just Date and Code
        indicatorDataFrame = equityDataFrame.ix[:, 'Code':]

        # Stick the Indicator Values into the new DataFrame
        indicatorDataFrame['ADX'] = abstract.ADX(
            equityDataFrame, timeperiod=14, prices=['High', 'Low', 'Close'])
        indicatorDataFrame['ADX_ROC'] = abstract.ROC(indicatorDataFrame,
                                                     timeperiod=5,
                                                     price='ADX')

        Indicator.__init__(self, tableName, tickerCode, insertQuery,
                           equityDataFrame, indicatorDataFrame)
Esempio n. 14
0
def ta_detect(symbol):
    try:
        data = exchange.fetch_ohlcv(symbol.symbol, TA_TIME_FRAME)
        df = DataFrame(
            data, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
        df.set_index('time', inplace=True, drop=True)
        df['rsi'] = ta.RSI(df)
        df['adx'] = ta.ADX(df)
        df['plus_di'] = ta.PLUS_DI(df)
        df['minus_di'] = ta.MINUS_DI(df)
        df['fastd'] = ta.STOCHF(df)['fastd']
        df.loc[((df['rsi'] < 35) & (df['fastd'] < 35) & (df['adx'] > 30) &
                (df['plus_di'] > 0.5)) | ((df['adx'] > 65) &
                                          (df['plus_di'] > 0.5)), 'buy'] = 1
        df.loc[(((crossed_above(df['rsi'], 70)) |
                 (crossed_above(df['fastd'], 70))) & (df['adx'] > 10) &
                (df['minus_di'] > 0)) | ((df['adx'] > 70) &
                                         (df['minus_di'] > 0.5)), 'sell'] = 1
        buy_signal, sell_signal = df.iloc[-1]['buy'], df.iloc[-1]['sell']
        if buy_signal == 1:
            log('{} TA BUY'.format(symbol.symbol))
            rd.publish('ta_buy', symbol.symbol)
            return True
        elif sell_signal == 1:
            log('{} TA SELL'.format(symbol.symbol))
            rd.publish('ta_sell', symbol.symbol)
            return True
        return False
    except Exception as e:
        log('{} error: {}'.format(symbol.symbol, str(e)))
        time.sleep(30)
    return False
Esempio n. 15
0
def populate_indicators(dataframe: DataFrame) -> DataFrame:
    """
    Adds several different TA indicators to the given DataFrame
    """
    dataframe['sar'] = ta.SAR(dataframe)
    dataframe['adx'] = ta.ADX(dataframe)
    stoch = ta.STOCHF(dataframe)
    dataframe['fastd'] = stoch['fastd']
    dataframe['fastk'] = stoch['fastk']
    dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2,
                                    nbdevdn=2)['lowerband']
    dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
    dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
    dataframe['mfi'] = ta.MFI(dataframe)
    dataframe['cci'] = ta.CCI(dataframe)
    dataframe['rsi'] = ta.RSI(dataframe)
    dataframe['mom'] = ta.MOM(dataframe)
    dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
    dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
    dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
    dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
    dataframe['ao'] = awesome_oscillator(dataframe)
    macd = ta.MACD(dataframe)
    dataframe['macd'] = macd['macd']
    dataframe['macdsignal'] = macd['macdsignal']
    dataframe['macdhist'] = macd['macdhist']
    return dataframe
Esempio n. 16
0
 def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
     dataframe['adx'] = ta.ADX(dataframe, timeperiod=14)
     dataframe['plus_di'] = ta.PLUS_DI(dataframe, timeperiod=25)
     dataframe['minus_di'] = ta.MINUS_DI(dataframe, timeperiod=25)
     dataframe['sar'] = ta.SAR(dataframe)
     dataframe['mom'] = ta.MOM(dataframe, timeperiod=14)
     #print(f"\"{metadata['pair']}\"")
     return dataframe
Esempio n. 17
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # Populate/update the trade data if there is any, set trades to false if not live/dry
        self.custom_trade_info[metadata['pair']] = self.populate_trades(
            metadata['pair'])

        dataframe['rsi'] = np.nan_to_num(ta.RSI(dataframe, timeperiod=5))
        dataframe['emarsi'] = np.nan_to_num(
            ta.EMA(dataframe['rsi'], timeperiod=5))

        dataframe['adx'] = np.nan_to_num(ta.ADX(dataframe))

        dataframe['minusdi'] = np.nan_to_num(ta.MINUS_DI(dataframe))
        dataframe['minusdiema'] = np.nan_to_num(
            ta.EMA(dataframe['minusdi'], timeperiod=25))
        dataframe['plusdi'] = np.nan_to_num(ta.PLUS_DI(dataframe))
        dataframe['plusdiema'] = np.nan_to_num(
            ta.EMA(dataframe['plusdi'], timeperiod=5))

        dataframe['lowsma'] = np.nan_to_num(ta.EMA(dataframe, timeperiod=60))
        dataframe['highsma'] = np.nan_to_num(ta.EMA(dataframe, timeperiod=120))
        dataframe['fastsma'] = np.nan_to_num(ta.SMA(dataframe, timeperiod=120))
        dataframe['slowsma'] = np.nan_to_num(ta.SMA(dataframe, timeperiod=240))

        dataframe['bigup'] = dataframe['fastsma'].gt(dataframe['slowsma']) & (
            (dataframe['fastsma'] - dataframe['slowsma']) >
            dataframe['close'] / 300)
        dataframe['bigdown'] = ~dataframe['bigup']
        dataframe['trend'] = dataframe['fastsma'] - dataframe['slowsma']

        dataframe['preparechangetrend'] = dataframe['trend'].gt(
            dataframe['trend'].shift())
        dataframe['preparechangetrendconfirm'] = dataframe[
            'preparechangetrend'] & dataframe['trend'].shift().gt(
                dataframe['trend'].shift(2))
        dataframe['continueup'] = dataframe['slowsma'].gt(
            dataframe['slowsma'].shift()) & dataframe['slowsma'].shift().gt(
                dataframe['slowsma'].shift(2))

        dataframe['delta'] = dataframe['fastsma'] - dataframe['fastsma'].shift(
        )
        dataframe['slowingdown'] = dataframe['delta'].lt(
            dataframe['delta'].shift())

        dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5)
        dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4)

        dataframe['rmi-up'] = np.where(
            dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(), 1, 0)
        dataframe['rmi-dn'] = np.where(
            dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(), 1, 0)
        dataframe['rmi-up-trend'] = np.where(
            dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2, 1, 0)
        dataframe['rmi-dn-trend'] = np.where(
            dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2, 1, 0)

        return dataframe
Esempio n. 18
0
def populate_indicators(dataframe: DataFrame) -> DataFrame:
    """
    Adds several different TA indicators to the given DataFrame
    """

    # Log the dataframe
    dataframe.to_csv("dataframe.csv", sep='\t')

    #Determine Trend
    dataframe = indicators.TREND(dataframe)

    #Exponential Moving Average
    dataframe['ema'] = ta.EMA(dataframe, timeperiod=33)

    #Parabolic SAR
    dataframe['sar'] = ta.SAR(dataframe, 0.02, 0.22)

    #Average Directional Movement Index
    dataframe['adx'] = ta.ADX(dataframe)

    #MACD
    macd = ta.MACD(dataframe)
    dataframe['macd'] = macd['macd']
    dataframe['macds'] = macd['macdsignal']
    dataframe['macdh'] = macd['macdhist']

    #Relative Strength Index
    dataframe['rsi'] = ta.RSI(dataframe, 14)
    dataframe = indicators.RSI(dataframe)

    #Absolute Price Oscillator
    dataframe['apo'] = ta.APO(dataframe,
                              fastperiod=12,
                              slowperiod=26,
                              matype=0)

    #Momentum
    dataframe['mom'] = ta.MOM(dataframe, 10)

    #Bollinger Bands
    dataframe = indicators.BBANDS(20, dataframe, 2)

    # Stochcastic
    dataframe['K'] = indicators.STOK(dataframe, 14)
    dataframe['D'] = indicators.STOD(dataframe, 14)
    dataframe = indicators.STOCH(dataframe)

    # if Counter.counter < 30:
    #     print(dataframe)
    #     print (macd)
    #     print (dataframe ['adx'])
    #     Counter.counter = Counter.counter + 1

    # else:
    #     exit()

    return dataframe
Esempio n. 19
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        # RSI
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['rsi_84'] = ta.RSI(dataframe, timeperiod=84)
        dataframe['rsi_112'] = ta.RSI(dataframe, timeperiod=112)

        # Bollinger bands
        bollinger1 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=17,
                                             stds=1)
        dataframe['bb_lowerband'] = bollinger1['lower']
        dataframe['bb_middleband'] = bollinger1['mid']
        dataframe['bb_upperband'] = bollinger1['upper']

        # Close delta
        dataframe['closedelta'] = (dataframe['close'] -
                                   dataframe['close'].shift()).abs()

        # Dip Protection
        dataframe['tpct_change_0'] = top_percent_change(dataframe, 0)
        dataframe['tpct_change_1'] = top_percent_change(dataframe, 1)
        dataframe['tpct_change_2'] = top_percent_change(dataframe, 2)
        dataframe['tpct_change_4'] = top_percent_change(dataframe, 4)
        dataframe['tpct_change_5'] = top_percent_change(dataframe, 5)
        dataframe['tpct_change_9'] = top_percent_change(dataframe, 9)

        # SMA
        dataframe['sma_50'] = ta.SMA(dataframe['close'], timeperiod=50)
        dataframe['sma_200'] = ta.SMA(dataframe['close'], timeperiod=200)

        # CTI
        dataframe['cti'] = pta.cti(dataframe["close"], length=20)

        # ADX
        dataframe['adx'] = ta.ADX(dataframe)

        # %R
        dataframe['r_14'] = williams_r(dataframe, period=14)
        dataframe['r_96'] = williams_r(dataframe, period=96)

        # MAMA / FAMA
        dataframe['hl2'] = (dataframe['high'] + dataframe['low']) / 2
        dataframe['mama'], dataframe['fama'] = ta.MAMA(dataframe['hl2'], 0.5,
                                                       0.05)
        dataframe['mama_diff'] = ((dataframe['mama'] - dataframe['fama']) /
                                  dataframe['hl2'])

        # CRSI (3, 2, 100)
        crsi_closechange = dataframe['close'] / dataframe['close'].shift(1)
        crsi_updown = np.where(crsi_closechange.gt(1), 1.0,
                               np.where(crsi_closechange.lt(1), -1.0, 0.0))
        dataframe['crsi'] = (ta.RSI(dataframe['close'], timeperiod=3) + ta.RSI(
            crsi_updown, timeperiod=2) + ta.ROC(dataframe['close'], 100)) / 3

        return dataframe
Esempio n. 20
0
 def adx(self):
     adx = tb.ADX(self.dataframe, timeperiod=14)
     value = adx[len(adx) - 1]
     if value > adxLimit:
         return "strong"
     elif value < adxLimit:
         return "weak"
     else:
         return "neutral"
Esempio n. 21
0
def apply_indicators(df: pd.DataFrame):

    # ADX
    df['adx'] = ta.ADX(df)

    # EMA
    df['ema_5'] = ta.EMA(df, 5)
    df['ema_10'] = ta.EMA(df, 10)
    df['ema_20'] = ta.EMA(df, 20)
    df['ema_50'] = ta.EMA(df, 50)
    df['ema_100'] = ta.EMA(df, 100)
    df['ema_200'] = ta.EMA(df, 200)

    # MACD
    macd = ta.MACD(df)
    df['macd'] = macd['macd']
    df['macdsignal'] = macd['macdsignal']
    df['macdhist'] = macd['macdhist']

    # inverse Fisher rsi/ RSI
    df['rsi'] = ta.RSI(df)
    rsi = 0.1 - (df['rsi'] - 50)
    df['i_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)

    # Stoch fast
    stoch_fast = ta.STOCHF(df)
    df['fastd'] = stoch_fast['fastd']
    df['fastk'] = stoch_fast['fastk']

    # Stock slow
    stoch_slow = ta.STOCH(df)
    df['slowd'] = stoch_slow['slowd']
    df['slowk'] = stoch_slow['slowk']

    # Bollinger bands
    bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(df),
                                        window=20,
                                        stds=2)
    df['bb_lowerband'] = bollinger['lower']
    df['bb_middleband'] = bollinger['mid']
    df['bb_upperband'] = bollinger['upper']

    # ROC
    df['roc'] = ta.ROC(df, 10)

    # CCI
    df['cci'] = ta.CCI(df, 14)

    # on balance volume
    df['obv'] = ta.OBV(df)

    # Average True Range
    df['atr'] = ta.ATR(df, 14)

    df = ichimoku(df)

    return df
Esempio n. 22
0
def populate_indicators(dataframe: DataFrame) -> DataFrame:
    """
    Adds several different TA indicators to the given DataFrame
    """
    dataframe['ema'] = ta.EMA(dataframe, timeperiod=33)
    dataframe['sar'] = ta.SAR(dataframe, 0.02, 0.22)
    dataframe['adx'] = ta.ADX(dataframe)

    return dataframe
def generate_indicators(dataset,
                        timeperiod=5,
                        generate_target=True,
                        reset_index=False):

    # To avoid changes from original dataset
    df = pd.DataFrame(dataset).copy()

    # To prevent index from being Date
    if (reset_index):
        df = df.reset_index()

    df.columns = df.columns.str.lower()

    # check the given dataset has necessary_columns
    __check_columns(df)

    df = df[necessary_columns]

    # df_indicators has all columns except date, this is for talib to produces other indicators
    df_indicators = df.iloc[:, 1:]

    # Produce other indicators
    RSI = abstract.RSI(df_indicators.close, timeperiod)
    RSI = pd.DataFrame({'RSI': RSI})

    MOM = abstract.MOM(df_indicators.close, timeperiod)
    MOM = pd.DataFrame({'MOM': MOM})

    KD = abstract.STOCH(df_indicators)
    KD = pd.DataFrame(KD)  # KD has slowd and slowk

    MACD = abstract.MACD(df_indicators)
    MACD = pd.DataFrame(MACD)  # MACD has its own column names

    ADX = abstract.ADX(df_indicators)
    ADX = pd.DataFrame({'ADX': ADX})

    SMA = abstract.SMA(df_indicators.close)
    SMA = pd.DataFrame({'SMA': SMA})

    upper, middle, lower = talib.BBANDS(df_indicators.close, matype=MA_Type.T3)
    bb_df = pd.DataFrame({ \
        'upper_bb' : upper,
        'middel_bb' : middle,
        'lower_bb' : lower})

    # Combine all metrix
    frames = [df, RSI, MOM, KD, MACD, ADX, SMA, bb_df]
    combined = pd.concat(frames, axis=1)

    if (generate_target):
        target_name = 'next_' + str(timeperiod) + 'day_trend'
        combined[target_name] = np.where(
            combined.close.shift(-timeperiod) > combined.close, 1, 0)

    return combined
Esempio n. 24
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe["adx"] = ta.ADX(dataframe, timeperiod=14)
        dataframe["plus_di"] = ta.PLUS_DI(dataframe, timeperiod=25)
        dataframe["minus_di"] = ta.MINUS_DI(dataframe, timeperiod=25)
        dataframe["sar"] = ta.SAR(dataframe)
        dataframe["mom"] = ta.MOM(dataframe, timeperiod=14)

        return dataframe
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        dataframe['adx'] = ta.ADX(dataframe, timeperiod=14)
        dataframe['ao'] = qtpylib.awesome_oscillator(dataframe)

        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        return dataframe
Esempio n. 26
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        dataframe['adx'] = ta.ADX(dataframe, timeperiod=90)  #90
        aroon = ta.AROON(dataframe, timeperiod=60)  #60

        dataframe['aroon-down'] = aroon['aroondown']
        dataframe['aroon-up'] = aroon['aroonup']

        return dataframe
Esempio n. 27
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        stoch_fast = ta.STOCHF(dataframe, 5.0, 3.0, 0.0, 3.0, 0.0)
        dataframe['fastd'] = stoch_fast['fastd']
        dataframe['fastk'] = stoch_fast['fastk']
        dataframe['ema_high'] = ta.EMA(dataframe, timeperiod=5, price='high')
        dataframe['ema_close'] = ta.EMA(dataframe, timeperiod=5, price='close')
        dataframe['ema_low'] = ta.EMA(dataframe, timeperiod=5, price='low')
        dataframe['adx'] = ta.ADX(dataframe)

        return dataframe
Esempio n. 28
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        stoch_fast = ta.STOCHF(dataframe, 5, 3, 0, 3, 0)
        dataframe["fastd"] = stoch_fast["fastd"]
        dataframe["fastk"] = stoch_fast["fastk"]
        dataframe["ema_high"] = ta.EMA(dataframe, timeperiod=5, price="high")
        dataframe["ema_close"] = ta.EMA(dataframe, timeperiod=5, price="close")
        dataframe["ema_low"] = ta.EMA(dataframe, timeperiod=5, price="low")
        dataframe["adx"] = ta.ADX(dataframe)

        return dataframe
Esempio n. 29
0
 def ADX(self):
     ADX = tb.ADX(self.dataframe, timeperiod=14)
     value = ADX[len(ADX) - 1]
     if (value > adxLimit):
         #print("ADX: " + str(value) + " sell")
         return "strong"
     elif (value < adxLimit):
         #print("ADX: " + str(value) + " buy")
         return "weak"
     else:
         #print("ADX: " + str(value) + " neutral")
         return "neutral"
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        """
        Adds several different TA indicators to the given DataFrame

        Performance Note: For the best performance be frugal on the number of indicators
        you are using. Let uncomment only the indicator you are using in your strategies
        or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
        :param dataframe: Dataframe with data from the exchange
        :param metadata: Additional information, like the currently traded pair
        :return: a Dataframe with all mandatory indicators for the strategies
        """

        # Momentum Indicators (timeperiod is expressed in candles)
        # -------------------

        # ADX - Average Directional Index (The Trend Strength Indicator)
        dataframe['adx'] = ta.ADX(
            dataframe, timeperiod=14)  # 14 timeperiods is usually used for ADX

        # +DM (Positive Directional Indicator) = current high - previous high
        dataframe['plus_di'] = ta.PLUS_DI(dataframe, timeperiod=25)
        # -DM (Negative Directional Indicator) = previous low - current low
        dataframe['minus_di'] = ta.MINUS_DI(dataframe, timeperiod=25)

        # RSI - Relative Strength Index (Under bought / Over sold & Over bought / Under sold indicator Indicator)
        dataframe['rsi'] = ta.RSI(dataframe)

        # MACD - Moving Average Convergence Divergence
        macd = ta.MACD(dataframe)
        dataframe['macd'] = macd[
            'macd']  # MACD - Blue TradingView Line (Bullish if on top)
        dataframe['macdsignal'] = macd[
            'macdsignal']  # Signal - Orange TradingView Line (Bearish if on top)

        # Initialize total signal variables (should be 0 = false by default)
        dataframe['total_buy_signal_strength'] = dataframe[
            'total_sell_signal_strength'] = 0

        #divergences
        dataframe = self.divergences(dataframe)

        #get trend
        dataframe.loc[(dataframe['adx'] > 20) &
                      (dataframe['plus_di'] < dataframe['minus_di']),
                      'trend'] = 'downwards'
        dataframe.loc[dataframe['adx'] < 20, 'trend'] = 'sideways'
        dataframe.loc[(dataframe['adx'] > 20) &
                      (dataframe['plus_di'] > dataframe['minus_di']),
                      'trend'] = 'upwards'

        return dataframe