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(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(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
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
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # RSI dataframe['rsi'] = ta.RSI(dataframe) dataframe['mfi'] = ta.MFI(dataframe) # Bollinger Bands 1,2,3 and 4 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
def do_populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Adds multiple TA indicators to MoniGoMani's DataFrame per pair. Should be called with 'informative_pair' (1h candles) during backtesting/hyperopting with TimeFrame-Zoom! Performance Note: For the best performance be frugal on the number of indicators you are using. Only add in indicators that you are using in your weighted signal configuration for MoniGoMani, otherwise you will waste your memory and CPU usage. :param dataframe: (DataFrame) DataFrame with data from the exchange :param metadata: (dict) Additional information, like the currently traded pair :return DataFrame: DataFrame for MoniGoMani with all mandatory indicator data populated """ # Momentum Indicators (timeperiod is expressed in candles) # ------------------- # Parabolic SAR dataframe['sar'] = ta.SAR(dataframe) # Stochastic Slow stoch = ta.STOCH(dataframe) dataframe['slowk'] = stoch['slowk'] # 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) # MFI - Money Flow Index (Under bought / Over sold & Over bought / Under sold / volume Indicator) dataframe['mfi'] = ta.MFI(dataframe) # Overlap Studies # --------------- # Bollinger Bands bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) dataframe['bb_middleband'] = bollinger['mid'] # SMA's & EMA's are trend following tools (Should not be used when line goes sideways) # SMA - Simple Moving Average (Moves slower compared to EMA, price trend over X periods) dataframe['sma9'] = ta.SMA(dataframe, timeperiod=9) dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200) # TEMA - Triple Exponential Moving Average dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) # Volume Indicators # ----------------- # Rolling VWAP - Volume Weighted Average Price dataframe['rolling_vwap'] = qtpylib.rolling_vwap(dataframe) return dataframe
def analyze(self, historical_data, period_count=14, signal=['mfi'], hot_thresh=None, cold_thresh=None): """Performs MFI analysis on the historical data Args: historical_data (list): A matrix of historical OHCLV data. period_count (int, optional): Defaults to 14. The number of data points to consider for our MFI. signal (list, optional): Defaults to mfi. The indicator line to check hot/cold against. 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: pandas.DataFrame: A dataframe containing the indicators and hot/cold values. """ dataframe = self.convert_to_dataframe(historical_data) mfi_values = abstract.MFI(dataframe, period_count).to_frame() mfi_values.dropna(how='all', inplace=True) mfi_values.rename(columns={0: 'mfi'}, inplace=True) if mfi_values[signal[0]].shape[0]: mfi_values['is_hot'] = mfi_values[signal[0]] > hot_thresh mfi_values['is_cold'] = mfi_values[signal[0]] < cold_thresh return mfi_values
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 = 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
def add_indicators(self, df: pd.DataFrame = None) -> pd.DataFrame: """Add indicators.""" cols = ['high', 'low', 'open', 'close', 'volume'] HLOCV = {key: df[key].values for key in df if key in cols} try: df['volume'] = df['volumeto'] except: pass # Moving Averages df['sma'] = abstract_ta.SMA(df, timeperiod=25) df['ema20'] = abstract_ta.EMA(df, timeperiod=20) df['ema50'] = abstract_ta.EMA(df, timeperiod=50) df['ema100'] = abstract_ta.EMA(df, timeperiod=100) df['ema200'] = abstract_ta.EMA(df, timeperiod=200) df['ema300'] = abstract_ta.EMA(df, timeperiod=300) # Bollinger Bands u, m, l = abstract_ta.BBANDS(HLOCV, timeperiod=24, nbdevup=2.5, nbdevdn=2.5, matype=MA_Type.T3) df['upper'] = u df['middle'] = m df['lower'] = l # Stochastic # uses high, low, close (default) slowk, slowd = abstract_ta.STOCH(HLOCV, 5, 3, 0, 3, 0) # uses high, low, close by default df['slowk'] = slowk df['slowd'] = slowd df['slow_stoch'] = (slowk + slowd) / 2 df['slow_stoch_sma14'] = df.slow_stoch.rolling(window=14).mean() df['slow_stoch_sma26'] = df.slow_stoch.rolling(window=26).mean() # Relative Strength Index rsi = abstract_ta.RSI(df, timeperiod=14) df['rsi'] = rsi # Money Flow Index mfi = abstract_ta.MFI(df, timeperiod=14) df['mfi'] = mfi # Medivh Relative Flow Index mrfi_df = MRFI(df) df['mrfi'] = mrfi_df['mrfi'].astype(float) df['smrfi'] = mrfi_df['smrfi'].astype(float) df['mrfi_basis'] = mrfi_df['mrfi_basis'].astype(float) df['mrfi_inverse'] = mrfi_df['mrfi_inverse'].astype(float) return df
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: bollinger = qtpylib.bollinger_bands(dataframe['close'], window=20, stds=2) dataframe['bb_lowerband'] = bollinger['lower'] dataframe['bb_middleband'] = bollinger['mid'] dataframe['bb_upperband'] = bollinger['upper'] dataframe['bb_width'] = ( (dataframe['bb_upperband'] - dataframe['bb_lowerband']) / dataframe['bb_middleband']) dataframe['bb_bottom_cross'] = qtpylib.crossed_below( dataframe['close'], dataframe['bb_lowerband']).astype('int') dataframe['rsi'] = ta.RSI(dataframe, timeperiod=10) dataframe['plus_di'] = ta.PLUS_DI(dataframe) dataframe['minus_di'] = ta.MINUS_DI(dataframe) dataframe['cci'] = ta.CCI(dataframe, 30) dataframe['mfi'] = ta.MFI(dataframe, timeperiod=14) dataframe['cmf'] = chaikin_mf(dataframe) dataframe['rmi'] = RMI(dataframe, length=8, mom=4) stoch = ta.STOCHRSI(dataframe, 15, 20, 2, 2) dataframe['srsi_fk'] = stoch['fastk'] dataframe['srsi_fd'] = stoch['fastd'] dataframe['fastEMA'] = ta.EMA(dataframe['volume'], timeperiod=12) dataframe['slowEMA'] = ta.EMA(dataframe['volume'], timeperiod=26) dataframe['pvo'] = ((dataframe['fastEMA'] - dataframe['slowEMA']) / dataframe['slowEMA']) * 100 dataframe['is_dip'] = ((dataframe['rmi'] < 20) & (dataframe['cci'] <= -150) & (dataframe['srsi_fk'] < 20) # Maybe comment mfi and cmf to make more trades & (dataframe['mfi'] < 25) & (dataframe['cmf'] <= -0.1)).astype('int') dataframe['is_break'] = ( (dataframe['bb_width'] > 0.025) & (dataframe['bb_bottom_cross'].rolling(10).sum() > 1) & (dataframe['close'] < 0.99 * dataframe['bb_lowerband']) ).astype('int') dataframe['buy_signal'] = ((dataframe['is_dip'] > 0) & (dataframe['is_break'] > 0)).astype('int') return dataframe
def analyze(self, historical_data, signal=['bbp'], hot_thresh=0, cold_thresh=0.8, period_count=20, std_dev=2): """Check when close price cross the Upper/Lower bands. Args: historical_data (list): A matrix of historical OHCLV data. period_count (int, optional): Defaults to 20. The number of data points to consider for the BB bands indicator. signal (list, optional): Defaults bbp value. hot_thresh (float, optional): Defaults to 0. The threshold at which this might be good to purchase. cold_thresh (float, optional): Defaults to 0.8. The threshold at which this might be good to sell. std_dev (int, optional): number of std dev to use. Common values are 2 or 1 Returns: pandas.DataFrame: A dataframe containing the indicator and hot/cold values. """ dataframe = self.convert_to_dataframe(historical_data) mfi = abstract.MFI(dataframe, period_count=14) # Required to avoid getting same values for low, middle, up dataframe['close_10k'] = dataframe['close'] * 10000 up_band, mid_band, low_band = BBANDS(dataframe['close_10k'], timeperiod=period_count, nbdevup=std_dev, nbdevdn=std_dev, matype=0) bbp = (dataframe['close_10k'] - low_band) / (up_band - low_band) bollinger = pandas.concat([dataframe, bbp, mfi], axis=1) bollinger.rename(columns={0: 'bbp', 1: 'mfi'}, inplace=True) bollinger['is_hot'] = False bollinger['is_cold'] = False bollinger['is_hot'].iloc[ -1] = bollinger['bbp'].iloc[-2] <= hot_thresh and bollinger[ 'bbp'].iloc[-2] < bollinger['bbp'].iloc[-1] bollinger['is_cold'].iloc[ -1] = bollinger['bbp'].iloc[-1] >= cold_thresh return bollinger
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) return dataframe
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['adx'] = ta.ADX(dataframe) macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['mfi'] = ta.MFI(dataframe) dataframe['rsi'] = ta.RSI(dataframe) stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] 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'] dataframe['sar'] = ta.SAR(dataframe) return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe = self.resample(dataframe, self.ticker_interval, self.resample_factor) ################################################################################## # buy and sell indicators dataframe['ema_{}'.format(self.EMA_SHORT_TERM)] = ta.EMA( dataframe, timeperiod=self.EMA_SHORT_TERM) dataframe['ema_{}'.format(self.EMA_MEDIUM_TERM)] = ta.EMA( dataframe, timeperiod=self.EMA_MEDIUM_TERM) dataframe['ema_{}'.format(self.EMA_LONG_TERM)] = ta.EMA( dataframe, timeperiod=self.EMA_LONG_TERM) 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['min'] = ta.MIN(dataframe, timeperiod=self.EMA_MEDIUM_TERM) dataframe['max'] = ta.MAX(dataframe, timeperiod=self.EMA_MEDIUM_TERM) dataframe['cci'] = ta.CCI(dataframe) dataframe['mfi'] = ta.MFI(dataframe) dataframe['rsi'] = ta.RSI(dataframe, timeperiod=7) dataframe['average'] = (dataframe['close'] + dataframe['open'] + dataframe['high'] + dataframe['low']) / 4 ################################################################################## # 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'] return dataframe
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 # ------------------------------------ dataframe['adx'] = ta.ADX(dataframe) dataframe['sar'] = ta.SAR(dataframe) # RSI dataframe['rsi'] = ta.RSI(dataframe) dataframe['mfi'] = ta.MFI(dataframe) stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] # 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'] # 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'] # 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'] macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] return dataframe
def populate_indicators(self, dataframe: DataFrame) -> DataFrame: dataframe = self.resample(dataframe, self.ticker_interval, 5) dataframe['cci_one'] = ta.CCI(dataframe, timeperiod=170) dataframe['cci_two'] = ta.CCI(dataframe, timeperiod=34) dataframe['rsi'] = ta.RSI(dataframe) dataframe['mfi'] = ta.MFI(dataframe) dataframe['cmf'] = self.chaikin_mf(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: """ 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. """ # MFI dataframe['mfi'] = ta.MFI(dataframe) # Stoch fast stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] dataframe['fastk'] = stoch_fast['fastk'] # 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'] # EMA - Exponential Moving Average 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) # SAR Parabol dataframe['sar'] = ta.SAR(dataframe) # SMA - Simple Moving Average dataframe['sma'] = ta.SMA(dataframe, timeperiod=40) return dataframe
def populate_indicators(dataframe: DataFrame, metadata: dict) -> DataFrame: """ This method can also be loaded from the strategy, if it doesn't exist in the hyperopt class. """ dataframe['adx'] = ta.ADX(dataframe) macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['mfi'] = ta.MFI(dataframe) dataframe['rsi'] = ta.RSI(dataframe) stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] 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'] dataframe['sar'] = ta.SAR(dataframe) 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. """ # Commodity Channel Index: values Oversold:<-100, Overbought:>100 dataframe['cci'] = ta.CCI(dataframe) # MFI dataframe['mfi'] = ta.MFI(dataframe) # CMO dataframe['cmo'] = ta.CMO(dataframe) return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe = self.resample(dataframe, self.timeframe, 5) dataframe["cci_one"] = ta.CCI(dataframe, timeperiod=170) dataframe["cci_two"] = ta.CCI(dataframe, timeperiod=34) dataframe["rsi"] = ta.RSI(dataframe) dataframe["mfi"] = ta.MFI(dataframe) dataframe["cmf"] = self.chaikin_mf(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 TKE(dataframe, *, length=14, emaperiod=5): """ Source: https://www.tradingview.com/script/Pcbvo0zG/ Author: Dr Yasar ERDINC The calculation is simple: TKE=(RSI+STOCHASTIC+ULTIMATE OSCILLATOR+MFI+WIILIAMS %R+MOMENTUM+CCI)/7 Buy signal: when TKE crosses above 20 value Oversold region: under 20 value Overbought region: over 80 value Another usage of TKE is with its EMA , the default value is defined as 5 bars of EMA of the TKE line, Go long: when TKE crosses above EMALine Go short: when TKE crosses below EMALine Usage: `dataframe['TKE'], dataframe['TKEema'] = TKE1(dataframe)` """ import talib.abstract as ta df = dataframe.copy() # TKE=(RSI+STOCHASTIC+ULTIMATE OSCILLATOR+MFI+WIILIAMS %R+MOMENTUM+CCI)/7 df["rsi"] = ta.RSI(df, timeperiod=length) df['stoch'] = (100 * (df['close'] - df['low'].rolling(window=length).min()) / (df['high'].rolling(window=length).max() - df['low'].rolling(window=length).min())) df["ultosc"] = ta.ULTOSC(df, timeperiod1=7, timeperiod2=14, timeperiod3=28) df["mfi"] = ta.MFI(df, timeperiod=length) df["willr"] = ta.WILLR(df, timeperiod=length) df["mom"] = ta.ROCR100(df, timeperiod=length) df["cci"] = ta.CCI(df, timeperiod=length) df['TKE'] = df[['rsi', 'stoch', 'ultosc', 'mfi', 'willr', 'mom', 'cci']].mean(axis='columns') df["TKEema"] = ta.EMA(df["TKE"], timeperiod=emaperiod) return df["TKE"], df["TKEema"]
def analyze(self, historical_data, period_count=14, hot_thresh=None, cold_thresh=None, all_data=False): """Performs MFI analysis on the historical data Args: historical_data (list): A matrix of historical OHCLV data. period_count (int, optional): Defaults to 14. The number of data points to consider for our simple moving average. 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. all_data (bool, optional): Defaults to False. If True, we return the momentum associated with each data point in our historical dataset. Otherwise just return the last one. Returns: dict: A dictionary containing a tuple of indicator values and booleans for buy / sell indication. """ dataframe = self.convert_to_dataframe(historical_data) mom_values = abstract.MFI(dataframe, period_count) analyzed_data = [(value, ) for value in mom_values] return self.analyze_results(analyzed_data, is_hot=lambda v: v > hot_thresh if hot_thresh else False, is_cold=lambda v: v < cold_thresh if cold_thresh else False, all_data=all_data)
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 # ------------------------------------ # momentum high = dataframe['high'] low = dataframe['low'] close = dataframe['close'] volume = dataframe['volume'] dataframe['mfi'] = ta.MFI(high, low, close, volume, 14) dataframe['signal'] = 0 dataframe.loc[((dataframe['mfi'] <= 20)), 'signal'] = 1 dataframe.loc[((dataframe['mfi'] >= 80)), 'signal'] = -1 dataframe['signal'] = dataframe['signal'].diff() dataframe.loc[((dataframe['mfi'] > 20) & (dataframe['mfi'] < 80)), 'signal'] = 0 #relative volume dataframe['rv'] = (volume / dataframe['volume'].rolling(14).max()) * 100 # ADX #dataframe['adx'] = ta.ADX(dataframe) # # Plus Directional Indicator / Movement # dataframe['plus_dm'] = ta.PLUS_DM(dataframe) # dataframe['plus_di'] = ta.PLUS_DI(dataframe) # # Minus Directional Indicator / Movement # dataframe['minus_dm'] = ta.MINUS_DM(dataframe) # dataframe['minus_di'] = ta.MINUS_DI(dataframe) # # Aroon, Aroon Oscillator # aroon = ta.AROON(dataframe) # dataframe['aroonup'] = aroon['aroonup'] # dataframe['aroondown'] = aroon['aroondown'] # dataframe['aroonosc'] = ta.AROONOSC(dataframe) # # Awesome Oscillator # dataframe['ao'] = qtpylib.awesome_oscillator(dataframe) # # Keltner Channel # keltner = qtpylib.keltner_channel(dataframe) # dataframe["kc_upperband"] = keltner["upper"] # dataframe["kc_lowerband"] = keltner["lower"] # dataframe["kc_middleband"] = keltner["mid"] # dataframe["kc_percent"] = ( # (dataframe["close"] - dataframe["kc_lowerband"]) / # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) # ) # dataframe["kc_width"] = ( # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"] # ) # # Ultimate Oscillator # dataframe['uo'] = ta.ULTOSC(dataframe) # # Commodity Channel Index: values [Oversold:-100, Overbought:100] # dataframe['cci'] = ta.CCI(dataframe) # 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'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) # # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy) # dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1) # # Stochastic Slow # stoch = ta.STOCH(dataframe) # dataframe['slowd'] = stoch['slowd'] # dataframe['slowk'] = stoch['slowk'] # Stochastic Fast #stoch_fast = ta.STOCHF(dataframe) #dataframe['fastd'] = stoch_fast['fastd'] #dataframe['fastk'] = stoch_fast['fastk'] # # Stochastic RSI # stoch_rsi = ta.STOCHRSI(dataframe) # dataframe['fastd_rsi'] = stoch_rsi['fastd'] # dataframe['fastk_rsi'] = stoch_rsi['fastk'] # MACD #macd = ta.MACD(dataframe) #dataframe['macd'] = macd['macd'] #dataframe['macdsignal'] = macd['macdsignal'] #dataframe['macdhist'] = macd['macdhist'] # MFI #dataframe['mfi'] = ta.MFI(dataframe) # # ROC # dataframe['roc'] = ta.ROC(dataframe) # Overlap Studies # ------------------------------------ # 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"] #) # Bollinger Bands - Weighted (EMA based instead of SMA) # weighted_bollinger = qtpylib.weighted_bollinger_bands( # qtpylib.typical_price(dataframe), window=20, stds=2 # ) # dataframe["wbb_upperband"] = weighted_bollinger["upper"] # dataframe["wbb_lowerband"] = weighted_bollinger["lower"] # dataframe["wbb_middleband"] = weighted_bollinger["mid"] # dataframe["wbb_percent"] = ( # (dataframe["close"] - dataframe["wbb_lowerband"]) / # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) # ) # dataframe["wbb_width"] = ( # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / dataframe["wbb_middleband"] # ) # # EMA - Exponential Moving Average # dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3) # dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) # dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) # dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21) # dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) # dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) # # SMA - Simple Moving Average # dataframe['sma3'] = ta.SMA(dataframe, timeperiod=3) dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5) # dataframe['sma10'] = ta.SMA(dataframe, timeperiod=10) dataframe['sma34'] = ta.SMA(dataframe, timeperiod=34) # dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) # dataframe['sma100'] = ta.SMA(dataframe, timeperiod=100) # Parabolic SAR #dataframe['sar'] = ta.SAR(dataframe) # TEMA - Triple Exponential Moving Average #dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) # Cycle Indicator # ------------------------------------ # Hilbert Transform Indicator - SineWave #hilbert = ta.HT_SINE(dataframe) #dataframe['htsine'] = hilbert['sine'] #dataframe['htleadsine'] = hilbert['leadsine'] # Pattern Recognition - Bullish candlestick patterns # ------------------------------------ # # Hammer: values [0, 100] # dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) # # Inverted Hammer: values [0, 100] # dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe) # # Dragonfly Doji: values [0, 100] # dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) # # Piercing Line: values [0, 100] # dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100] # # Morningstar: values [0, 100] # dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100] # # Three White Soldiers: values [0, 100] # dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100] # Pattern Recognition - Bearish candlestick patterns # ------------------------------------ # # Hanging Man: values [0, 100] # dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe) # # Shooting Star: values [0, 100] # dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe) # # Gravestone Doji: values [0, 100] # dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe) # # Dark Cloud Cover: values [0, 100] # dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe) # # Evening Doji Star: values [0, 100] # dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe) # # Evening Star: values [0, 100] # dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe) # Pattern Recognition - Bullish/Bearish candlestick patterns # ------------------------------------ # # Three Line Strike: values [0, -100, 100] # dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) # # Spinning Top: values [0, -100, 100] # dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100] # # Engulfing: values [0, -100, 100] # dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100] # # Harami: values [0, -100, 100] # dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100] # # Three Outside Up/Down: values [0, -100, 100] # dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100] # # Three Inside Up/Down: values [0, -100, 100] # dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100] # # Chart type # # ------------------------------------ # # Heikin Ashi Strategy # heikinashi = qtpylib.heikinashi(dataframe) # dataframe['ha_open'] = heikinashi['open'] # dataframe['ha_close'] = heikinashi['close'] # dataframe['ha_high'] = heikinashi['high'] # dataframe['ha_low'] = heikinashi['low'] # Retrieve best bid and best ask from the orderbook # ------------------------------------ """ # first check if dataprovider is available if self.dp: if self.dp.runmode in ('live', 'dry_run'): ob = self.dp.orderbook(metadata['pair'], 1) dataframe['best_bid'] = ob['bids'][0][0] dataframe['best_ask'] = ob['asks'][0][0] """ return dataframe
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 # ------------------------------------ # ADX dataframe['adx'] = ta.ADX(dataframe) # RSI dataframe['rsi'] = ta.RSI(dataframe) # Stochastic Fast stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] dataframe['fastk'] = stoch_fast['fastk'] # MACD macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] # MFI dataframe['mfi'] = ta.MFI(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"]) # Parabolic SAR dataframe['sar'] = ta.SAR(dataframe) # TEMA - Triple Exponential Moving Average dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) # Cycle Indicator # ------------------------------------ # Hilbert Transform Indicator - SineWave hilbert = ta.HT_SINE(dataframe) dataframe['htsine'] = hilbert['sine'] dataframe['htleadsine'] = hilbert['leadsine'] """ # first check if dataprovider is available if self.dp: if self.dp.runmode in ('live', 'dry_run'): ob = self.dp.orderbook(metadata['pair'], 1) dataframe['best_bid'] = ob['bids'][0][0] dataframe['best_ask'] = ob['asks'][0][0] """ return dataframe
def populate_indicators(self, dataframe: DataFrame) -> DataFrame: # resampled dataframe to establish if we are in an uptrend, downtrend or sideways trend dataframe = StrategyHelper.resample(dataframe, self.ticker_interval, self.resample_factor) ################################################################################## # required for entry and exit # CCI dataframe['cci'] = ta.CCI(dataframe, timeperiod=20) dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) dataframe['adx'] = ta.ADX(dataframe) dataframe['mfi'] = ta.MFI(dataframe) dataframe['mfi_smooth'] = ta.EMA(dataframe, timeperiod=11, price='mfi') dataframe['cci_smooth'] = ta.EMA(dataframe, timeperiod=11, price='cci') dataframe['rsi_smooth'] = ta.EMA(dataframe, timeperiod=11, price='rsi') ################################################################################## # 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 macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] ################################################################################## # required for entry bollinger = qtpylib.bollinger_bands(dataframe['close'], window=20, stds=1.6) dataframe['entry_bb_lowerband'] = bollinger['lower'] dataframe['entry_bb_upperband'] = bollinger['upper'] dataframe['entry_bb_middleband'] = bollinger['mid'] dataframe['bpercent'] = (dataframe['close'] - dataframe['bb_lowerband']) / ( dataframe['bb_upperband'] - dataframe['bb_lowerband']) * 100 dataframe['bsharp'] = (dataframe['bb_upperband'] - dataframe['bb_lowerband']) / ( dataframe['bb_middleband']) # these seem to be kind useful to measure when bands widen # but than they are directly based on the moving average dataframe['bsharp_slow'] = ta.SMA(dataframe, price='bsharp', timeperiod=11) dataframe['bsharp_medium'] = ta.SMA(dataframe, price='bsharp', timeperiod=8) dataframe['bsharp_fast'] = ta.SMA(dataframe, price='bsharp', timeperiod=5) ################################################################################## # rsi and mfi are slightly weighted dataframe['mfi_rsi_cci_smooth'] = (dataframe['rsi_smooth'] * 1.125 + dataframe['mfi_smooth'] * 1.125 + dataframe[ 'cci_smooth']) / 3 dataframe['mfi_rsi_cci_smooth'] = ta.TEMA(dataframe, timeperiod=21, price='mfi_rsi_cci_smooth') # playgound dataframe['candle_size'] = (dataframe['close'] - dataframe['open']) * ( dataframe['close'] - dataframe['open']) / 2 # helps with pattern recognition dataframe['average'] = (dataframe['close'] + dataframe['open'] + dataframe['high'] + dataframe['low']) / 4 dataframe['sma_slow'] = ta.SMA(dataframe, timeperiod=200, price='close') dataframe['sma_medium'] = ta.SMA(dataframe, timeperiod=100, price='close') dataframe['sma_fast'] = ta.SMA(dataframe, timeperiod=50, price='close') return dataframe
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: Raw data from the exchange and parsed by parse_ticker_dataframe() :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) # ADX dataframe['adx'] = ta.ADX(dataframe) # # Aroon, Aroon Oscillator # aroon = ta.AROON(dataframe) # dataframe['aroonup'] = aroon['aroonup'] # dataframe['aroondown'] = aroon['aroondown'] # dataframe['aroonosc'] = ta.AROONOSC(dataframe) # # Awesome oscillator # dataframe['ao'] = qtpylib.awesome_oscillator(dataframe) # # Commodity Channel Index: values Oversold:<-100, Overbought:>100 # dataframe['cci'] = ta.CCI(dataframe) # MACD macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] # MFI dataframe['mfi'] = ta.MFI(dataframe) # # Minus Directional Indicator / Movement # dataframe['minus_dm'] = ta.MINUS_DM(dataframe) # dataframe['minus_di'] = ta.MINUS_DI(dataframe) # # Plus Directional Indicator / Movement # dataframe['plus_dm'] = ta.PLUS_DM(dataframe) # dataframe['plus_di'] = ta.PLUS_DI(dataframe) # dataframe['minus_di'] = ta.MINUS_DI(dataframe) # # ROC # dataframe['roc'] = ta.ROC(dataframe) # # 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) # # Inverse Fisher transform on RSI normalized, value [0.0, 100.0] (https://goo.gl/2JGGoy) # dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1) # # Stoch # stoch = ta.STOCH(dataframe) # dataframe['slowd'] = stoch['slowd'] # dataframe['slowk'] = stoch['slowk'] # Stoch fast stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] dataframe['fastk'] = stoch_fast['fastk'] # # Stoch RSI # stoch_rsi = ta.STOCHRSI(dataframe) # dataframe['fastd_rsi'] = stoch_rsi['fastd'] # dataframe['fastk_rsi'] = stoch_rsi['fastk'] # Overlap Studies # ------------------------------------ # 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'] # # EMA - Exponential Moving Average # dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3) # 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) # # SMA - Simple Moving Average # dataframe['sma'] = ta.SMA(dataframe, timeperiod=40) # SAR Parabol dataframe['sar'] = ta.SAR(dataframe) # TEMA - Triple Exponential Moving Average dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) # Cycle Indicator # ------------------------------------ # Hilbert Transform Indicator - SineWave hilbert = ta.HT_SINE(dataframe) dataframe['htsine'] = hilbert['sine'] dataframe['htleadsine'] = hilbert['leadsine'] # Pattern Recognition - Bullish candlestick patterns # ------------------------------------ # # Hammer: values [0, 100] # dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) # # Inverted Hammer: values [0, 100] # dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe) # # Dragonfly Doji: values [0, 100] # dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) # # Piercing Line: values [0, 100] # dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100] # # Morningstar: values [0, 100] # dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100] # # Three White Soldiers: values [0, 100] # dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100] # Pattern Recognition - Bearish candlestick patterns # ------------------------------------ # # Hanging Man: values [0, 100] # dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe) # # Shooting Star: values [0, 100] # dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe) # # Gravestone Doji: values [0, 100] # dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe) # # Dark Cloud Cover: values [0, 100] # dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe) # # Evening Doji Star: values [0, 100] # dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe) # # Evening Star: values [0, 100] # dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe) # Pattern Recognition - Bullish/Bearish candlestick patterns # ------------------------------------ # # Three Line Strike: values [0, -100, 100] # dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) # # Spinning Top: values [0, -100, 100] # dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100] # # Engulfing: values [0, -100, 100] # dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100] # # Harami: values [0, -100, 100] # dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100] # # Three Outside Up/Down: values [0, -100, 100] # dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100] # # Three Inside Up/Down: values [0, -100, 100] # dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100] # # Chart type # # ------------------------------------ # # Heikinashi stategy # heikinashi = qtpylib.heikinashi(dataframe) # dataframe['ha_open'] = heikinashi['open'] # dataframe['ha_close'] = heikinashi['close'] # dataframe['ha_high'] = heikinashi['high'] # dataframe['ha_low'] = heikinashi['low'] # Retrieve best bid and best ask from the orderbook # ------------------------------------ """ # first check if dataprovider is available if self.dp: if self.dp.runmode in ('live', 'dry_run'): ob = self.dp.orderbook(metadata['pair'], 1) dataframe['best_bid'] = ob['bids'][0][0] dataframe['best_ask'] = ob['asks'][0][0] """ return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Momentum Indicators # ------------------------------------ # ADX dataframe['adx'] = ta.ADX(dataframe) # Plus Directional Indicator / Movement dataframe['plus_dm'] = ta.PLUS_DM(dataframe) dataframe['plus_di'] = ta.PLUS_DI(dataframe) # # Minus Directional Indicator / Movement dataframe['minus_dm'] = ta.MINUS_DM(dataframe) dataframe['minus_di'] = ta.MINUS_DI(dataframe) # Aroon, Aroon Oscillator aroon = ta.AROON(dataframe) dataframe['aroonup'] = aroon['aroonup'] dataframe['aroondown'] = aroon['aroondown'] dataframe['aroonosc'] = ta.AROONOSC(dataframe) # Awesome Oscillator dataframe['ao'] = qtpylib.awesome_oscillator(dataframe) # # Keltner Channel # keltner = qtpylib.keltner_channel(dataframe) # dataframe["kc_upperband"] = keltner["upper"] # dataframe["kc_lowerband"] = keltner["lower"] # dataframe["kc_middleband"] = keltner["mid"] # dataframe["kc_percent"] = ( # (dataframe["close"] - dataframe["kc_lowerband"]) / # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) # ) # dataframe["kc_width"] = ( # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"] # ) # Ultimate Oscillator dataframe['uo'] = ta.ULTOSC(dataframe) # Commodity Channel Index: values [Oversold:-100, Overbought:100] dataframe['cci'] = ta.CCI(dataframe) # 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'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy) dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1) # Stochastic Slow stoch = ta.STOCH(dataframe) dataframe['slowd'] = stoch['slowd'] dataframe['slowk'] = stoch['slowk'] # Stochastic Fast stoch_fast = ta.STOCHF(dataframe) dataframe['fastd'] = stoch_fast['fastd'] dataframe['fastk'] = stoch_fast['fastk'] # Stochastic RSI stoch_rsi = ta.STOCHRSI(dataframe) dataframe['fastd_rsi'] = stoch_rsi['fastd'] dataframe['fastk_rsi'] = stoch_rsi['fastk'] # MACD macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] # MFI dataframe['mfi'] = ta.MFI(dataframe) # # ROC dataframe['roc'] = ta.ROC(dataframe) # Overlap Studies # ------------------------------------ # # 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"] # ) # # Bollinger Bands - Weighted (EMA based instead of SMA) # weighted_bollinger = qtpylib.weighted_bollinger_bands( # qtpylib.typical_price(dataframe), window=20, stds=2 # ) # dataframe["wbb_upperband"] = weighted_bollinger["upper"] # dataframe["wbb_lowerband"] = weighted_bollinger["lower"] # dataframe["wbb_middleband"] = weighted_bollinger["mid"] # dataframe["wbb_percent"] = ( # (dataframe["close"] - dataframe["wbb_lowerband"]) / # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) # ) # dataframe["wbb_width"] = ( # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / # dataframe["wbb_middleband"] # ) # # EMA - Exponential Moving Average # dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3) # dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) # dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) # dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21) # dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) # dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) # # SMA - Simple Moving Average # dataframe['sma3'] = ta.SMA(dataframe, timeperiod=3) # dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5) # dataframe['sma10'] = ta.SMA(dataframe, timeperiod=10) # dataframe['sma21'] = ta.SMA(dataframe, timeperiod=21) # dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) # dataframe['sma100'] = ta.SMA(dataframe, timeperiod=100) # Parabolic SAR # dataframe['sar'] = ta.SAR(dataframe) # TEMA - Triple Exponential Moving Average # dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) # # Cycle Indicator # # ------------------------------------ # # Hilbert Transform Indicator - SineWave # hilbert = ta.HT_SINE(dataframe) # dataframe['htsine'] = hilbert['sine'] # dataframe['htleadsine'] = hilbert['leadsine'] # # Pattern Recognition - Bullish candlestick patterns # # ------------------------------------ # # Hammer: values [0, 100] # dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) # # Inverted Hammer: values [0, 100] # dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe) # # Dragonfly Doji: values [0, 100] # dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) # # Piercing Line: values [0, 100] # dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100] # # Morningstar: values [0, 100] # dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100] # # Three White Soldiers: values [0, 100] # dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100] # # Pattern Recognition - Bearish candlestick patterns # # ------------------------------------ # # Hanging Man: values [0, 100] # dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe) # # Shooting Star: values [0, 100] # dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe) # # Gravestone Doji: values [0, 100] # dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe) # # Dark Cloud Cover: values [0, 100] # dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe) # # Evening Doji Star: values [0, 100] # dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe) # # Evening Star: values [0, 100] # dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe) # # Pattern Recognition - Bullish/Bearish candlestick patterns # # ------------------------------------ # # Three Line Strike: values [0, -100, 100] # dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) # # Spinning Top: values [0, -100, 100] # dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100] # # Engulfing: values [0, -100, 100] # dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100] # # Harami: values [0, -100, 100] # dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100] # # Three Outside Up/Down: values [0, -100, 100] # dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100] # # Three Inside Up/Down: values [0, -100, 100] # dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100] # # Chart type # # ------------------------------------ # # Heikin Ashi Strategy # heikinashi = qtpylib.heikinashi(dataframe) # dataframe['ha_open'] = heikinashi['open'] # dataframe['ha_close'] = heikinashi['close'] # dataframe['ha_high'] = heikinashi['high'] # dataframe['ha_low'] = heikinashi['low'] # Retrieve best bid and best ask from the orderbook # ------------------------------------ """ # first check if dataprovider is available if self.dp: if self.dp.runmode in ('live', 'dry_run'): ob = self.dp.orderbook(metadata['pair'], 1) dataframe['best_bid'] = ob['bids'][0][0] dataframe['best_ask'] = ob['asks'][0][0] """ return dataframe
def _build_indicators(self, df): if not self.realtime: inputs = df.to_dict(orient="list") for col in inputs: inputs[col] = np.array(inputs[col]) c = df["close"] for n in range(2, 40): inputs["bband_u_" + str(n)], inputs["bband_m_" + str(n)], inputs["bband_l_" + str(n)] = ta.BBANDS( inputs, n) inputs["sma_" + str(n)] = ta.SMA(inputs, timeperiod=n) inputs["adx_" + str(n)] = ta.ADX(inputs, timeperiod=n) # fast_ema = c.ewm(span = n, adjust = False).mean() # slow_ema = c.ewm(span = n*2, adjust = False).mean() # macd1 = fast_ema - slow_ema # macd2 = macd1.ewm(span = int(n*2/3), adjust = False).mean() # macd3 = macd1 - macd2 # inputs["macd_"+str(n)] = macd1.values # inputs["macdsignal_"+str(n)] = macd2.values # inputs["macdhist_"+str(n)] = macd3.values if n != 2: inputs["macd_" + str(n)], inputs["macdsignal_" + str(n)], inputs["macdhist_" + str(n)] = ta.MACD( inputs, n, n * 2, int(n * 2 / 3)) else: inputs["macd_" + str(n)], inputs["macdsignal_" + str(n)], inputs["macdhist_" + str(n)] = ta.MACD( inputs, n, n * 2, 1) # macd = [macd1.values, macd2.values, macd3.values] # for idx, i in enumerate(["macd_"+str(n), "macdsignal_"+str(n), "macdhist_"+str(n)]): # for day in zip(inputs[i], macd[idx]): # print("Type: %s N: %d PD: %.3f TA: %.3f, " % (i, n, day[1], day[0])) inputs["mfi_" + str(n)] = ta.MFI(inputs, n) inputs["ult_" + str(n)] = ta.ULTOSC(inputs, n, n * 2, n * 4) inputs["willr_" + str(n)] = ta.WILLR(inputs, n) inputs["slowk"], inputs["slowd"] = ta.STOCH(inputs) inputs["mom_" + str(n)] = ta.MOM(inputs, n) inputs["volume"] = list(map(lambda x: x / 10000, inputs["volume"])) df = pd.DataFrame().from_dict(inputs) # df = df.ix[100:] # print(df.tail(5)["macd_3"], df.tail(5)["macdsignal_3"], df.tail(5)["macdhist_3"]) return df else: # Build data one-by-one, as if it's coming in one at a time output = pd.DataFrame() sliding_window = pd.DataFrame() for idx, day in df.iterrows(): print("\rNow building day", str(idx), end="", flush=True) day = copy.deepcopy(day) # Avoid reference vs copy bullshit sliding_window = sliding_window.append(day, ignore_index=True) # print(day, type(day)) day_out = {} # print(sliding_window) o = sliding_window["open"].values h = sliding_window["high"].values l = sliding_window["low"].values c_series = sliding_window["close"] c = sliding_window["close"].values # print("----") # print(c) v = sliding_window["volume"].values for t in ["open", "high", "low", "close"]: day_out[t] = sliding_window[t].values[-1] for n in range(2, 40): # time.sleep(0.1) day_out["bband_u_" + str(n)], day_out["bband_m_" + str(n)], day_out[ "bband_l_" + str(n)] = stream.BBANDS(c, n) day_out["sma_" + str(n)] = stream.SMA(c, timeperiod=n) day_out["adx_" + str(n)] = stream.ADX(h, l, c, timeperiod=n) fast_ema = c_series.ewm(span=n, adjust=False).mean() slow_ema = c_series.ewm(span=n * 2, adjust=False).mean() macd1 = fast_ema - slow_ema macd2 = macd1.ewm(span=int(n * 2 / 3), adjust=False).mean() macd3 = macd1 - macd2 day_out["macd_" + str(n)] = macd1.values[-1] day_out["macdsignal_" + str(n)] = macd2.values[-1] day_out["macdhist_" + str(n)] = macd3.values[-1] # if n != 2: # day_out["macd_"+str(n)], day_out["macdsignal_"+str(n)], day_out["macdhist_"+str(n)] = stream.MACD(c, n, n*2, int(n*2/3)) # elif idx > 100: # macd = ta.MACD({"close":c}, n, n*2, 1) # day_out["macd_2"], day_out["macdsignal_2"], day_out["macdhist_2"] = (x[-1] for x in macd) # else: # day_out["macd_2"], day_out["macdsignal_2"], day_out["macdhist_2"] = None, None, None # macd = [macd1.values, macd2.values, macd3.values] # for idx, i in enumerate(["macd_"+str(n), "macdsignal_"+str(n), "macdhist_"+str(n)]): # for day in zip(inputs[i], macd[idx]): # print("Type: %s N: %d PD: %.3f TA: %.3f, " % (i, n, day[1], day[0])) day_out["mfi_" + str(n)] = stream.MFI(h, l, c, v, n) day_out["ult_" + str(n)] = stream.ULTOSC( h, l, c, n, n * 2, n * 4) day_out["willr_" + str(n)] = stream.WILLR(h, l, c, n) day_out["slowk"], day_out["slowd"] = stream.STOCH(h, l, c) day_out["mom_" + str(n)] = stream.MOM(c, n) day_out["volume"] = v[-1] / 10000 # print(day_out["macd_2"], day_out["macdsignal_2"], day_out["macdhist_2"]) output = output.append(day_out, ignore_index=True) # print(output.tail(5)["macd_3"], output.tail(5)["macdsignal_3"], output.tail(5)["macdhist_3"]) return output
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'] # add volatility indicators dataframe['natr'] = ta.NATR(dataframe) # add volume indicators dataframe['obv'] = ta.OBV(dataframe) # add more momentum indicators dataframe['rocp'] = ta.ROCP(dataframe) # add some pattern recognition dataframe['CDL2CROWS'] = ta.CDL2CROWS(dataframe) dataframe['CDL3BLACKCROWS'] = ta.CDL3BLACKCROWS(dataframe) dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) dataframe['CDL3STARSINSOUTH'] = ta.CDL3STARSINSOUTH(dataframe) dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) dataframe['CDLADVANCEBLOCK'] = ta.CDLADVANCEBLOCK(dataframe) dataframe['CDLBELTHOLD'] = ta.CDLBELTHOLD(dataframe) dataframe['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(dataframe) dataframe['CDLDOJI'] = ta.CDLDOJI(dataframe) dataframe['CDLDOJISTAR'] = ta.CDLDOJISTAR(dataframe) dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) dataframe['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(dataframe) dataframe['CDLBREAKAWAY'] = ta.CDLBREAKAWAY(dataframe) # enter categorical time hour = datetime.strptime(str(dataframe['date'][len(dataframe) - 1]), "%Y-%m-%d %H:%M:%S").hour for h in range(24): dataframe['hour_{0:02}'.format(h)] = int(h == hour) return dataframe