Example #1
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5)
        dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)

        # resample our dataframes
        dataframe_short = resample_to_interval(dataframe,
                                               self.get_ticker_indicator() * 2)
        dataframe_long = resample_to_interval(dataframe,
                                              self.get_ticker_indicator() * 8)

        # compute our RSI's
        dataframe_short['rsi'] = ta.RSI(dataframe_short, timeperiod=14)
        dataframe_long['rsi'] = ta.RSI(dataframe_long, timeperiod=14)

        # merge dataframe back together
        dataframe = resampled_merge(dataframe, dataframe_short)
        dataframe = resampled_merge(dataframe, dataframe_long)

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

        dataframe.fillna(method='ffill', inplace=True)

        return dataframe
Example #2
0
    def get_main_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        dataframe['rsi_fast'] = ta.RSI(dataframe,
                                       timeperiod=int(
                                           self.rsi_fast_length.value))
        dataframe['rsi_slow'] = ta.RSI(dataframe,
                                       timeperiod=int(
                                           self.rsi_slow_length.value))
        dataframe['rsi_slow_descending'] = (
            dataframe['rsi_slow'] <
            dataframe['rsi_slow'].shift()).astype('int')

        dataframe['ma_lower'] = ta.SMA(
            dataframe, timeperiod=int(
                self.ma_lower_length.value)) * self.ma_lower_offset.value
        dataframe['ma_middle_1'] = ta.SMA(
            dataframe, timeperiod=int(
                self.ma_middle_1_length.value)) * self.ma_middle_1_offset.value
        dataframe['ma_upper'] = ta.SMA(
            dataframe, timeperiod=int(
                self.ma_upper_length.value)) * self.ma_upper_offset.value

        # drop NAN in hyperopt to fix "'<' not supported between instances of 'str' and 'int' error
        if self.config['runmode'].value == 'hyperopt':
            dataframe = dataframe.dropna()

        return dataframe
Example #3
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['rsi-buy'] = ta.RSI(dataframe)
        dataframe['rsi-sell'] = ta.RSI(dataframe)

        # Bollinger bands
        bollinger_1sd = qtpylib.bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=1)
        dataframe['bb_lowerband_1sd'] = bollinger_1sd['lower']
        dataframe['bb_middleband_1sd'] = bollinger_1sd['mid']
        dataframe['bb_upperband_1sd'] = bollinger_1sd['upper']

        bollinger_2sd = qtpylib.bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe['bb_lowerband_2sd'] = bollinger_2sd['lower']
        dataframe['bb_middleband_2sd'] = bollinger_2sd['mid']
        dataframe['bb_upperband_2sd'] = bollinger_2sd['upper']

        bollinger_3sd = qtpylib.bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=3)
        dataframe['bb_lowerband_3sd'] = bollinger_3sd['lower']
        dataframe['bb_middleband_3sd'] = bollinger_3sd['mid']
        dataframe['bb_upperband_3sd'] = bollinger_3sd['upper']

        bollinger_4sd = qtpylib.bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=4)
        dataframe['bb_lowerband_4sd'] = bollinger_4sd['lower']
        dataframe['bb_middleband_4sd'] = bollinger_4sd['mid']
        dataframe['bb_upperband_4sd'] = bollinger_4sd['upper']

        return dataframe
Example #4
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        from technical.util import resample_to_interval
        from technical.util import resampled_merge

        dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
        # EMA - Exponential Moving Average
        dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
        dataframe['ema200'] = ta.EMA(dataframe, timeperiod=200)
        # resample our dataframes
        dataframe_short = resample_to_interval(dataframe,
                                               self.get_ticker_indicator() * 3)
        dataframe_long = resample_to_interval(dataframe,
                                              self.get_ticker_indicator() * 7)

        # compute our RSI's
        dataframe_short['rsi'] = ta.RSI(dataframe_short, timeperiod=14)
        dataframe_long['rsi'] = ta.RSI(dataframe_long, timeperiod=14)

        # merge dataframe back together
        dataframe = resampled_merge(dataframe, dataframe_short)
        dataframe = resampled_merge(dataframe, dataframe_long)

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

        dataframe.fillna(method='ffill', inplace=True)
        #print("rsi - {:.2f}, rsi_15 - {:.2f}, rsi_35 - {:.2f}".format(dataframe['rsi'].iloc[-1], dataframe['rsi_x'].iloc[-1], dataframe['rsi_y'].iloc[-1]))
        #print(dataframe.iloc[-1])
        return dataframe
Example #5
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Dynamic TA indicators
        Used so hyperopt can optimized around the period of various indicators
        """
        for rsip in range(rsiStart, (rsiEnd + 1)):
            dataframe[f'rsi({rsip})'] = ta.RSI(dataframe, timeperiod=rsip)

        for temap in range(temaStart, (temaEnd + 1)):
            dataframe[f'tema({temap})'] = ta.TEMA(dataframe, timeperiod=temap)

        """
        Static TA indicators.
        RSI and TEMA Only used when --spaces does not include buy or sell
        """
        # Stochastic Slow
        # fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
        stoch_slow = ta.STOCH(dataframe, fastk_period=fastkPeriod, slowk_period=slowkPeriod, slowd_period=slowdPeriod)
        dataframe['stoch-slowk'] = stoch_slow['slowk']
        dataframe['stoch-slowd'] = stoch_slow['slowd']

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

        # TEMA - Triple Exponential Moving Average
        dataframe['tema'] = ta.TEMA(dataframe)

        return dataframe
Example #6
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        # # Commodity Channel Index: values [Oversold:-100, Overbought:100]
        dataframe['buy-cci'] = ta.CCI(dataframe,
                                      timeperiod=self.buy_params['cci-period'])
        dataframe['sell-cci'] = ta.CCI(
            dataframe, timeperiod=self.sell_params['sell-cci-period'])

        # RSI
        dataframe['buy-rsi'] = ta.RSI(dataframe,
                                      timeperiod=self.buy_params['rsi-period'])
        dataframe['sell-rsi'] = ta.RSI(
            dataframe, timeperiod=self.sell_params['sell-rsi-period'])

        # KAMA - Kaufman Adaptive Moving Average
        dataframe['buy-kama-short'] = ta.KAMA(
            dataframe, timeperiod=self.buy_params['kama-short-period'])
        dataframe['buy-kama-long'] = ta.KAMA(
            dataframe, timeperiod=self.buy_params['kama-long-period'])
        dataframe['buy-kama-long-slope'] = (dataframe['buy-kama-long'] /
                                            dataframe['buy-kama-long'].shift())

        dataframe['sell-kama-short'] = ta.KAMA(
            dataframe, timeperiod=self.sell_params['sell-kama-short-period'])
        dataframe['sell-kama-long'] = ta.KAMA(
            dataframe, timeperiod=self.sell_params['sell-kama-long-period'])
        dataframe['sell-kama-long-slope'] = (
            dataframe['sell-kama-long'] / dataframe['sell-kama-long'].shift())

        return dataframe
Example #7
0
 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
     # ------------------------------------
     # RSI
     dataframe['rsi'] = ta.RSI(dataframe)
     dataframe['sell-rsi'] = ta.RSI(dataframe)
     # Bollinger Bands 1 STD
     bollinger1 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                          window=20,
                                          stds=1)
     dataframe['bb_lowerband1'] = bollinger1['lower']
     dataframe['bb_middleband1'] = bollinger1['mid']
     dataframe['bb_upperband1'] = bollinger1['upper']
     # Bollinger Bands 4 STD
     bollinger4 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                          window=20,
                                          stds=4)
     dataframe['bb_lowerband4'] = bollinger4['lower']
     dataframe['bb_middleband4'] = bollinger4['mid']
     dataframe['bb_upperband4'] = bollinger4['upper']
     return dataframe
Example #8
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        self.custom_trade_info[metadata['pair']] = self.populate_trades(
            metadata['pair'])

        dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5)
        dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4)
        dataframe['roc'] = ta.ROC(dataframe, timeperiod=6)
        dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6)

        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)

        informative = self.dp.get_pair_dataframe(pair=metadata['pair'],
                                                 timeframe=self.inf_timeframe)
        informative['rsi'] = ta.RSI(informative, timeperiod=14)
        informative['1d_high'] = informative['close'].rolling(24).max()
        informative['3d_low'] = informative['close'].rolling(72).min()
        informative['adr'] = informative['1d_high'] - informative['3d_low']

        dataframe = merge_informative_pair(dataframe,
                                           informative,
                                           self.timeframe,
                                           self.inf_timeframe,
                                           ffill=True)

        return dataframe
Example #9
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:

        dataframe['rsi'] = ta.RSI(dataframe)
        dataframe['sell-rsi'] = ta.RSI(dataframe)

        # Bollinger bands
        bollinger1 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=1)
        dataframe['bb_lowerband1'] = bollinger1['lower']
        dataframe['bb_middleband1'] = bollinger1['mid']
        dataframe['bb_upperband1'] = bollinger1['upper']

        bollinger2 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
        dataframe['bb_lowerband2'] = bollinger2['lower']
        dataframe['bb_middleband2'] = bollinger2['mid']
        dataframe['bb_upperband2'] = bollinger2['upper']

        bollinger3 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=3)
        dataframe['bb_lowerband3'] = bollinger3['lower']
        dataframe['bb_middleband3'] = bollinger3['mid']
        dataframe['bb_upperband3'] = bollinger3['upper']

        bollinger4 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=4)
        dataframe['bb_lowerband4'] = bollinger4['lower']
        dataframe['bb_middleband4'] = bollinger4['mid']
        dataframe['bb_upperband4'] = bollinger4['upper']

        return dataframe
Example #10
0
    def populate_indicators(self, dataframe: DataFrame) -> DataFrame:
        dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5)
        dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)

        # resample our dataframes
        dataframe_short = resample_to_interval(dataframe, self.get_ticker_indicator() * 2)
        dataframe_long = resample_to_interval(dataframe, self.get_ticker_indicator() * 8)

        # compute our RSI's
        dataframe_short['rsi'] = ta.RSI(dataframe_short, timeperiod=14)
        dataframe_long['rsi'] = ta.RSI(dataframe_long, timeperiod=14)
        dataframe_short['cmf'] = cmf(dataframe_short, 14)
        dataframe_long['cmf'] = cmf(dataframe_long, 14)

        dataframe_short['osc'] = osc(dataframe_short, 14)
        dataframe_long['osc'] = osc(dataframe_long, 14)

        # merge dataframe back together
        dataframe = resampled_merge(dataframe, dataframe_short)
        dataframe = resampled_merge(dataframe, dataframe_long)

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

        # fill NA values with previes
        dataframe.fillna(method='ffill', inplace=True)

        # Volume Flow Index: Add VFI, VFIMA, Histogram to DF
        dataframe['vfi'], dataframe['vfima'], dataframe['vfi_hist'] =  \
            vfi(dataframe, length=130, coef=0.2, vcoef=2.5, signalLength=5, smoothVFI=True)

        return dataframe
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        self.custom_trade_info[metadata['pair']] = self.populate_trades(
            metadata['pair'])

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

        # Momentum Pinball
        dataframe['roc'] = ta.ROC(dataframe, timeperiod=6)
        dataframe['mp'] = ta.RSI(dataframe['roc'], timeperiod=6)

        # Trend Calculations
        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)

        # Informative for STAKE/FIAT and COIN/FIAT on default timeframe, only relevant if stake currency is BTC or ETH
        if self.config['stake_currency'] in ('BTC', 'ETH'):
            coin, stake = metadata['pair'].split('/')
            fiat = self.custom_fiat
            coin_fiat = f"{coin}/{fiat}"
            stake_fiat = f"{stake}/{fiat}"

            # COIN/FIAT (e.g. XLM/USD) - timeframe
            coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat,
                                                      timeframe=self.timeframe)
            dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14)

            # STAKE/FIAT (e.g. BTC/USD) - inf_timeframe
            stake_fiat_tf = self.dp.get_pair_dataframe(
                pair=stake_fiat, timeframe=self.timeframe)
            stake_fiat_inf_tf = self.dp.get_pair_dataframe(
                pair=stake_fiat, timeframe=self.inf_timeframe)

            dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14)
            dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(
                stake_fiat_inf_tf, length=21, mom=5)

        # Informative indicators for current pair on inf_timeframe
        informative = self.dp.get_pair_dataframe(pair=metadata['pair'],
                                                 timeframe=self.inf_timeframe)
        informative['rsi'] = ta.RSI(informative, timeperiod=14)

        dataframe = merge_informative_pair(dataframe,
                                           informative,
                                           self.timeframe,
                                           self.inf_timeframe,
                                           ffill=True)

        return dataframe
    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
Example #13
0
    def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ema200'] = ta.EMA(dataframe, timeperiod=200)
        macd = ta.MACD(dataframe, fastperiod=24, slowperiod=56, signalperiod=6)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']

        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['sell-rsi'] = ta.RSI(dataframe, timeperiod=14)
        return dataframe
Example #14
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        # EMAs
        dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20)

        # RSI
        dataframe['rsi2'] = ta.RSI(dataframe, timeperiod=2)
        dataframe['rsi14'] = ta.RSI(dataframe, timeperiod=14)

        return dataframe
Example #15
0
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair'])
    
        # Base timeframe indicators
        dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5)
        dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4)

        # Momentum Pinball: 
        dataframe['roc'] = ta.ROC(dataframe, timeperiod=6)
        dataframe['mp']  = ta.RSI(dataframe['roc'], timeperiod=6)
  
        # RMI Trends and Peaks
        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)
        dataframe['rmi-max'] = dataframe['rmi-slow'].rolling(10, min_periods=1).max()

        # See: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L1059
        # matype = vidya, src = hl2
        dataframe = PMAX(dataframe, period=10, multiplier=3, length=10, MAtype=5, src=2)

        # Other stake specific informative indicators
        # TODO: Re-evaluate the value of these informative indicators
        if self.config['stake_currency'] in ('BTC', 'ETH'):
            coin, stake = metadata['pair'].split('/')
            fiat = self.custom_fiat
            coin_fiat = f"{coin}/{fiat}"
            stake_fiat = f"{stake}/{fiat}"

            coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe)
            dataframe[f"{fiat}_rsi"] = ta.RSI(coin_fiat_tf, timeperiod=14)

            stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe)
            stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe)

            dataframe[f"{stake}_rsi"] = ta.RSI(stake_fiat_tf, timeperiod=14)
            dataframe[f"{stake}_rmi_{self.inf_timeframe}"] = RMI(stake_fiat_inf_tf, length=21, mom=5)

        # Base pair informative timeframe indicators
        informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe)
        informative['rsi'] = ta.RSI(informative, timeperiod=14)
        
        # Get the "average day range" between the 1d high and 3d low to set up guards
        informative['1d_high'] = informative['close'].rolling(24).max()
        informative['3d_low'] = informative['close'].rolling(72).min()
        informative['adr'] = informative['1d_high'] - informative['3d_low']

        dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True)

        dataframe.to_csv('user_data/foo.csv')

        return dataframe
Example #16
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        dataframe['cci-' + str(cciBuyTP)] = ta.CCI(dataframe,
                                                   timeperiod=cciBuyTP)
        dataframe['cci-' + str(cciSellTP)] = ta.CCI(dataframe,
                                                    timeperiod=cciSellTP)

        dataframe['rsi-' + str(rsiBuyTP)] = ta.RSI(dataframe,
                                                   timeperiod=rsiBuyTP)
        dataframe['rsi-' + str(rsiSellTP)] = ta.RSI(dataframe,
                                                    timeperiod=rsiSellTP)

        return dataframe
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        for val in self.buy_cciTime.range:
            dataframe[f'cci-{val}'] = ta.CCI(dataframe, timeperiod=val)

        for val in self.sell_cciTime.range:
            dataframe[f'cci-sell-{val}'] = ta.CCI(dataframe, timeperiod=val)

        for val in self.buy_rsiTime.range:
            dataframe[f'rsi-{val}'] = ta.RSI(dataframe, timeperiod=val)

        for val in self.sell_rsiTime.range:
            dataframe[f'rsi-sell-{val}'] = ta.RSI(dataframe, timeperiod=val)

        return dataframe
Example #18
0
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        # Bollinger bands
        bollinger1 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=1)
        dataframe['bb1_lowerband'] = bollinger1['lower']
        dataframe['bb1_middleband'] = bollinger1['mid']
        dataframe['bb1_upperband'] = bollinger1['upper']
        bollinger2 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=2)
        dataframe['bb2_lowerband'] = bollinger2['lower']
        dataframe['bb2_middleband'] = bollinger2['mid']
        dataframe['bb2_upperband'] = bollinger2['upper']
        bollinger3 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=3)
        dataframe['bb3_lowerband'] = bollinger3['lower']
        dataframe['bb3_middleband'] = bollinger3['mid']
        dataframe['bb3_upperband'] = bollinger3['upper']
        bollinger4 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                             window=20,
                                             stds=4)
        dataframe['bb4_lowerband'] = bollinger4['lower']
        dataframe['bb4_middleband'] = bollinger4['mid']
        dataframe['bb4_upperband'] = bollinger4['upper']

        return dataframe
Example #19
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 generate_technical_indicators(pair_df):
    """
    Builds dataframe containing Time and indicators such as 10-day and 50-day EMAs,
    RSI, and A/D index. Also uses differencing to remove seasonality trends.

    Args:
        pair_df: Dataframe containing "Time" column and columns for ohlc data

    Returns:
        Dataframe containing technical indicator data for a specific currency pair
    """
    pair_df["EMA_10"] = pd.DataFrame(abstract.EMA(
        pair_df["Close"], timeperiod=10))  # 960))
    pair_df["EMA_50"] = pd.DataFrame(abstract.EMA(
        pair_df["Close"], timeperiod=50))  # 4800))
    pair_df["RSI"] = pd.DataFrame(
        abstract.RSI(pair_df["Close"], timeperiod=14))
    pair_df["A/D Index"] = pd.DataFrame(
        abstract.AD(
            pair_df["High"], pair_df["Low"], pair_df["Close"], pair_df["Volume"]
        )
    )
    # Take difference to remove trends
    pair_df["A/D Index"] = pair_df["A/D Index"] - pair_df["A/D Index"].shift(1)
    pair_df = stationary_log_returns(pair_df)
    return pair_df
Example #21
0
def get_dataset(test=False):
    df = pickle.load(open(p.file, "rb"))

    # Add features to dataframe
    # Typical Features: close/sma, bollinger band, holding stock, return since entry
    df['dr'] = df.close / df.close.shift(1) - 1  # daily return
    df['adr'] = ta.SMA(df, price='dr', timeperiod=p.adr_period)
    df['sma'] = ta.SMA(df, price='close', timeperiod=p.sma_period)
    df['dsma'] = df.sma / df.sma.shift(1) - 1
    df['rsma'] = df.close / df.sma
    df['rsi'] = ta.RSI(df, price='close', timeperiod=p.rsi_period)
    df['hh'] = df.high / ta.MAX(df, price='high', timeperiod=p.hh_period)
    df['ll'] = df.low / ta.MIN(df, price='low', timeperiod=p.ll_period)
    df['hhll'] = (df.high + df.low) / (df.high / df.hh + df.low / df.ll)
    df = df.dropna()
    # Map features to bins
    df = df.assign(binrsi=bin_feature(df.rsi))
    if p.version == 1:
        df = df.assign(binadr=bin_feature(df.adr))
        df = df.assign(binhh=bin_feature(df.hh))
        df = df.assign(binll=bin_feature(df.ll))
    elif p.version == 2:
        df = df.assign(bindsma=bin_feature(df.dsma))
        df = df.assign(binrsma=bin_feature(df.rsma))
        df = df.assign(binhhll=bin_feature(df.hhll))

    if p.max_bars > 0: df = df.tail(p.max_bars).reset_index(drop=True)
    # Separate Train / Test Datasets using train_pct number of rows
    if test:
        rows = int(len(df) * p.test_pct)
        return df.tail(rows).reset_index(drop=True)
    else:
        rows = int(len(df) * p.train_pct)
        return df.head(rows).reset_index(drop=True)
Example #22
0
    def analyze_rsi(self, historial_data, hot_thresh=None, cold_thresh=None):
        """Performs an RSI analysis on the historical data

        Args:
            historial_data (list): A matrix of historical OHCLV data.
            hot_thresh (float, optional): Defaults to None. The threshold at which this might be good
                to purchase.
            cold_thresh (float, optional): Defaults to None. The threshold at which this might be good
                to sell.

        Returns:
            dict: A dictionary containing a tuple of indicator values and booleans for buy / sell
                indication.
        """

        period_count = 14

        dataframe = self.__convert_to_dataframe(historial_data)
        rsi_value = abstract.RSI(dataframe, period_count).iloc[-1]

        is_hot = False
        if not hot_thresh is None:
            is_hot = rsi_value <= hot_thresh

        is_cold = False
        if not cold_thresh is None:
            is_cold = rsi_value >= cold_thresh

        rsi_data = {
            'values': (rsi_value, ),
            'is_cold': is_cold,
            'is_hot': is_hot
        }

        return rsi_data
    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
Example #24
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
    def populate_indicators(self, dataframe: DataFrame,
                            metadata: dict) -> DataFrame:

        dataframe['rsi_slow'] = ta.RSI(dataframe, timeperiod=10)
        dataframe['ema600'] = ta.EMA(dataframe, timeperiod=600)

        return dataframe
Example #26
0
    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.
        """
        dataframe['gap'] = dataframe['close'].shift(1) - (
            (dataframe['high'].shift(1) - dataframe['low'].shift(1)) * 0.1)
        dataframe['adx'] = ta.ADX(dataframe)
        # MFI
        dataframe['mfi'] = ta.MFI(dataframe)
        # RSI
        dataframe['rsi'] = ta.RSI(dataframe)
        # Stochastic Fast
        stoch_fast = ta.STOCH(dataframe)
        dataframe['slowd'] = stoch_fast['slowd']
        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_upperband'] = bollinger['upper']
        return dataframe
    def populate_indicators(self, dataframe: DataFrame) -> 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.
        """

        # Stoch
        stoch = ta.STOCH(dataframe)
        dataframe['slowk'] = stoch['slowk']

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

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

        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=2)
        dataframe['bb_lowerband'] = bollinger['lower']

        # SAR Parabol
        dataframe['sar'] = ta.SAR(dataframe)

        # Hammer: values [0, 100]
        dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe)

        return dataframe
Example #28
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
Example #29
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
Example #30
0
def technical(profile):
    """
    Updates profile with SMA, BB, and RSI calculations

    In: profile with basic ohlc price data
    Out: profile updated with studies merged with profile's price history
    """
    prices = {
        'open': np.array([record['o'] for record in profile.history]),
        'high': np.array([record['h'] for record in profile.history]),
        'low': np.array([record['l'] for record in profile.history]),
        'close': np.array([record['c'] for record in profile.history]),
        'volume': np.array([record['vol'] for record in profile.history])
    }
    # print(prices['open'])
    # print(prices)

    sma = ta.SMA(prices, timeperiod=200)
    profile.add_study("sma", [round(float(point), 2) for point in sma])

    bb_upper, bb_middle, bb_lower = ta.BBANDS(prices, 100, 2, 2)
    profile.add_study("bb_upper",
                      [round(float(point), 2) for point in bb_upper])
    profile.add_study("bb_middle",
                      [round(float(point), 2) for point in bb_middle])
    profile.add_study("bb_lower",
                      [round(float(point), 2) for point in bb_lower])

    rsi = ta.RSI(prices, timeperiod=14)
    profile.add_study("rsi", [round(float(point), 2) for point in rsi])