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
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close']) dataframe['EVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close']) dataframe['ABANDONEDBABY'] = ta.CDLEVENINGSTAR(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close']) dataframe['HARAMI'] = ta.CDLHARAMI(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close']) dataframe['INVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER( dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close']) dataframe['ENGULFING'] = ta.CDLENGULFING(dataframe['open'], dataframe['high'], dataframe['low'], dataframe['close']) dataframe['hclose'] = (dataframe['open'] + dataframe['high'] + dataframe['low'] + dataframe['close']) / 4 dataframe['hopen'] = ( (dataframe['open'].shift(2) + dataframe['close'].shift(2)) / 2) dataframe['hhigh'] = dataframe[['open', 'close', 'high']].max(axis=1) dataframe['hlow'] = dataframe[['open', 'close', 'low']].min(axis=1) dataframe['emac'] = ta.SMA(dataframe['hclose'], timeperiod=6) dataframe['emao'] = ta.SMA(dataframe['hopen'], timeperiod=6) return dataframe
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: dataframe['adx'] = ta.ADX(dataframe, timeperiod=14) dataframe['short'] = ta.SMA(dataframe, timeperiod=3) dataframe['long'] = ta.SMA(dataframe, timeperiod=6) return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # SMA - Simple Moving Average dataframe['fastMA'] = ta.SMA(dataframe, timeperiod=13) dataframe['slowMA'] = ta.SMA(dataframe, timeperiod=25) dataframe['mom'] = ta.MOM(dataframe, timeperiod=21) return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['rsi'] = numpy.nan_to_num(ta.RSI(dataframe, timeperiod=5)) dataframe['emarsi'] = numpy.nan_to_num(ta.EMA(dataframe['rsi'], timeperiod=5)) dataframe['adx'] = numpy.nan_to_num(ta.ADX(dataframe)) dataframe['minusdi'] = numpy.nan_to_num(ta.MINUS_DI(dataframe)) dataframe['minusdiema'] = numpy.nan_to_num(ta.EMA(dataframe['minusdi'], timeperiod=25)) dataframe['plusdi'] = numpy.nan_to_num(ta.PLUS_DI(dataframe)) dataframe['plusdiema'] = numpy.nan_to_num(ta.EMA(dataframe['plusdi'], timeperiod=5)) dataframe['lowsma'] = numpy.nan_to_num(ta.EMA(dataframe, timeperiod=60)) dataframe['highsma'] = numpy.nan_to_num(ta.EMA(dataframe, timeperiod=120)) dataframe['fastsma'] = numpy.nan_to_num(ta.SMA(dataframe, timeperiod=120)) dataframe['slowsma'] = numpy.nan_to_num(ta.SMA(dataframe, timeperiod=240)) dataframe['bigup'] = dataframe['fastsma'].gt(dataframe['slowsma']) & ((dataframe['fastsma'] - dataframe['slowsma']) > dataframe['close'] / 300) dataframe['bigdown'] = ~dataframe['bigup'] dataframe['trend'] = dataframe['fastsma'] - dataframe['slowsma'] dataframe['preparechangetrend'] = dataframe['trend'].gt(dataframe['trend'].shift()) dataframe['preparechangetrendconfirm'] = dataframe['preparechangetrend'] & dataframe['trend'].shift().gt(dataframe['trend'].shift(2)) dataframe['continueup'] = dataframe['slowsma'].gt(dataframe['slowsma'].shift()) & dataframe['slowsma'].shift().gt(dataframe['slowsma'].shift(2)) dataframe['delta'] = dataframe['fastsma'] - dataframe['fastsma'].shift() dataframe['slowingdown'] = dataframe['delta'].lt(dataframe['delta'].shift()) return dataframe
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 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)
def init_state(self, X, test): ''' Initializes state space for reinforcement learning ''' data = [] close = [] for i, s in enumerate(self.symbols): # Process data using technical analysis library close.append(X[s]['close']) diff = np.diff(close[i]) diff = np.insert(diff, 0, 0) sma15 = ta.SMA(X[s], timeperiod=14) sma60 = ta.SMA(X[s], timeperiod=56) rsi = ta.RSI(X[s], timeperiod=14) atr = ta.ATR(X[s], timeperiod=14) data.append( np.nan_to_num( np.vstack((close[i], diff, sma15, close[i] - sma15, sma15 - sma60, rsi, atr)))) data[i] = np.expand_dims(data[i], axis=1) data = np.hstack(data).T close = np.vstack(close) state = data[0:1, :, :] if test: self.data_test = data else: self.data = data return state, close
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
def normal_tf_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: bb_40 = qtpylib.bollinger_bands(dataframe['close'], window=40, stds=2) dataframe['lower'] = bb_40['lower'] dataframe['mid'] = bb_40['mid'] dataframe['bbdelta'] = (bb_40['mid'] - dataframe['lower']).abs() dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs() dataframe['tail'] = (dataframe['close'] - dataframe['low']).abs() 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['ema_slow'] = ta.EMA(dataframe, timeperiod=50) dataframe['volume_mean_slow'] = dataframe['volume'].rolling( window=30).mean() # EMA dataframe['ema_50'] = ta.EMA(dataframe, timeperiod=50) dataframe['ema_200'] = ta.EMA(dataframe, timeperiod=200) # SMA dataframe['sma_5'] = ta.SMA(dataframe, timeperiod=5) dataframe['sma_9'] = ta.SMA(dataframe, timeperiod=9) # RSI dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) return dataframe
def CalculateTech(self): self.m_dfTX_Data['PCT_Close'] = ( self.m_dfTX_Data['close'].pct_change() * 100) self.m_dfTX_Data['Close_SMA5'] = abstract.SMA( self.m_dfTX_Data['close'], timeperiod=5) self.m_dfTX_Data['Close_SMA20'] = abstract.SMA( self.m_dfTX_Data['close'], timeperiod=20) # MACD self.m_dfTX_Data['MACD_DIF'], self.m_dfTX_Data[ 'MACD_DEM'], self.m_dfTX_Data['MACD_OSC'] = talib.MACD( self.m_dfTX_Data['close'], fastperiod=12, slowperiod=26, signalperiod=6) # KD self.m_dfTX_Data['KD_K'], self.m_dfTX_Data['KD_D'] = talib.STOCH( self.m_dfTX_Data['high'], self.m_dfTX_Data['low'], self.m_dfTX_Data['close'], fastk_period=27, slowk_period=3, slowd_period=2) self.m_dfTX_Data['KD_J'] = 3 * \ self.m_dfTX_Data['KD_K']-2*self.m_dfTX_Data['KD_D']
def parse_data(self, response): """Parse data.""" data = json.loads(response.text) date = response.meta['date'] if data['hits']['total']['value'] == 0: stock_ids = [] self.logger.info(f'{date} doesn\'t have data') else: stock_ids = [ hit['_source']['stock_id'] for hit in data['hits']['hits'] ] for stock_id in stock_ids: df = self.get_history_pirce_by_id(stock_id, date) s_item = items.TechnicalIndexItem() s_item['date'] = date s_item['stock_id'] = stock_id sma5 = self.filter_nan(abstract.SMA(df, timeperiod=5)[0]) if sma5 is not None: s_item['sma5'] = sma5 sma10 = self.filter_nan(abstract.SMA(df, timeperiod=10)[0]) if sma10 is not None: s_item['sma10'] = sma10 sma20 = self.filter_nan(abstract.SMA(df, timeperiod=20)[0]) if sma20 is not None: s_item['sma20'] = sma20 sma60 = self.filter_nan(abstract.SMA(df, timeperiod=60)[0]) if sma60 is not None: s_item['sma60'] = sma60 sma100 = self.filter_nan(abstract.SMA(df, timeperiod=100)[0]) if sma100 is not None: s_item['sma100'] = sma100 rsi = self.filter_nan(abstract.RSI(df, timeperiod=14)[0]) if rsi is not None: s_item['rsi'] = rsi stoch_df = abstract.STOCH(df) slowk = self.filter_nan(stoch_df['slowk'][0]) if slowk is not None: s_item['slowk'] = slowk slowd = self.filter_nan(stoch_df['slowd'][0]) if slowd is not None: s_item['slowd'] = slowd if df.shape[0] >= 2: s_item['double_volume'] = df['trade_volume'][0] > ( df['trade_volume'][1] * 2) s_item['triple_volume'] = df['trade_volume'][0] > ( df['trade_volume'][1] * 3) if df['close'][1] != 0: quote_change = (df['close'][0] - df['close'][1]) / df['close'][1] * 100 # TODO: 取小數後兩位 s_item['quote_change'] = float( '{:.2f}'.format(quote_change)) s_item['id'] = f"{s_item['date']}-{s_item['stock_id']}" yield s_item self.logger.info(f'complete crawl \"{date}\"')
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # SMA - ex Moving Average dataframe['buy-fastMA'] = ta.SMA(dataframe, timeperiod=FTF) dataframe['buy-slowMA'] = ta.SMA(dataframe, timeperiod=STF) dataframe['sell-fastMA'] = ta.SMA(dataframe, timeperiod=FTF) dataframe['sell-slowMA'] = ta.SMA(dataframe, timeperiod=STF) return dataframe
def analyze_crossover(self, historical_data, hot_thresh=None, cold_thresh=None, period_count=(15, 21), all_data=False): """Performs a SMA crossover analysis on the historical data Args: historical_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. period_count (tuple of (2) ints, optional): Defaults to (15, 21). Each number in the tuple contains the period count of an sma to be used in the crossover analysis all_data (bool, optional): Defaults to False. If True, we return the SMA 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) sma_one_values = abstract.SMA(dataframe, period_count[0]) sma_two_values = abstract.SMA(dataframe, period_count[1]) combined_data = pandas.concat( [dataframe, sma_one_values, sma_two_values], axis=1) combined_data.rename(columns={ 0: 'sma_value_one', 1: 'sma_value_two' }, inplace=True) rows = list(combined_data.iterrows()) # List of 4-tuples containing: (old_sma_one, old_sma_two, current_sma_one, current_sma_two) analyzed_data = [(math.nan, math.nan, rows[1][1]['sma_value_one'], rows[1][1]['sma_value_two'])] # We keep track of the old values as to assign a "hot" value when the first sma crosses over # the second one, and assign a "cold" value when the second sma crosses over the first for i in range(1, len(rows)): analyzed_data.append( (analyzed_data[i - 1][2], analyzed_data[i - 1][3], rows[i][1]['sma_value_one'], rows[i][1]['sma_value_two'])) return self.analyze_results( analyzed_data, is_hot=lambda o1, o2, c1, c2: o1 < o2 and c1 > c2 if hot_thresh else False, is_cold=lambda o1, o2, c1, c2: o1 > o2 and c1 < c2 if cold_thresh else False, all_data=all_data)
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
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Populate/update the trade data if there is any, set trades to false if not live/dry self.custom_trade_info[metadata['pair']] = self.populate_trades( metadata['pair']) dataframe['rsi'] = np.nan_to_num(ta.RSI(dataframe, timeperiod=5)) dataframe['emarsi'] = np.nan_to_num( ta.EMA(dataframe['rsi'], timeperiod=5)) dataframe['adx'] = np.nan_to_num(ta.ADX(dataframe)) dataframe['minusdi'] = np.nan_to_num(ta.MINUS_DI(dataframe)) dataframe['minusdiema'] = np.nan_to_num( ta.EMA(dataframe['minusdi'], timeperiod=25)) dataframe['plusdi'] = np.nan_to_num(ta.PLUS_DI(dataframe)) dataframe['plusdiema'] = np.nan_to_num( ta.EMA(dataframe['plusdi'], timeperiod=5)) dataframe['lowsma'] = np.nan_to_num(ta.EMA(dataframe, timeperiod=60)) dataframe['highsma'] = np.nan_to_num(ta.EMA(dataframe, timeperiod=120)) dataframe['fastsma'] = np.nan_to_num(ta.SMA(dataframe, timeperiod=120)) dataframe['slowsma'] = np.nan_to_num(ta.SMA(dataframe, timeperiod=240)) dataframe['bigup'] = dataframe['fastsma'].gt(dataframe['slowsma']) & ( (dataframe['fastsma'] - dataframe['slowsma']) > dataframe['close'] / 300) dataframe['bigdown'] = ~dataframe['bigup'] dataframe['trend'] = dataframe['fastsma'] - dataframe['slowsma'] dataframe['preparechangetrend'] = dataframe['trend'].gt( dataframe['trend'].shift()) dataframe['preparechangetrendconfirm'] = dataframe[ 'preparechangetrend'] & dataframe['trend'].shift().gt( dataframe['trend'].shift(2)) dataframe['continueup'] = dataframe['slowsma'].gt( dataframe['slowsma'].shift()) & dataframe['slowsma'].shift().gt( dataframe['slowsma'].shift(2)) dataframe['delta'] = dataframe['fastsma'] - dataframe['fastsma'].shift( ) dataframe['slowingdown'] = dataframe['delta'].lt( dataframe['delta'].shift()) dataframe['rmi-slow'] = RMI(dataframe, length=21, mom=5) dataframe['rmi-fast'] = RMI(dataframe, length=8, mom=4) dataframe['rmi-up'] = np.where( dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(), 1, 0) dataframe['rmi-dn'] = np.where( dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(), 1, 0) dataframe['rmi-up-trend'] = np.where( dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2, 1, 0) dataframe['rmi-dn-trend'] = np.where( dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2, 1, 0) return dataframe
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Adding EMA's into the dataframe dataframe["s1_ema_xs"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xs) dataframe["s1_ema_sm"] = ta.EMA(dataframe, timeperiod=self.s1_ema_sm) dataframe["s1_ema_md"] = ta.EMA(dataframe, timeperiod=self.s1_ema_md) dataframe["s1_ema_xl"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xl) dataframe["s1_ema_xxl"] = ta.EMA(dataframe, timeperiod=self.s1_ema_xxl) s2_ema_value = ta.EMA(dataframe, timeperiod=self.s2_ema_input) s2_ema_xxl_value = ta.EMA(dataframe, timeperiod=200) dataframe[ "s2_ema"] = s2_ema_value - s2_ema_value * self.s2_ema_offset_input dataframe[ "s2_ema_xxl_off"] = s2_ema_xxl_value - s2_ema_xxl_value * self.s2_fib_lower_value dataframe["s2_ema_xxl"] = ta.EMA(dataframe, timeperiod=200) s2_bb_sma_value = ta.SMA(dataframe, timeperiod=self.s2_bb_sma_length) s2_bb_std_dev_value = ta.STDDEV(dataframe, self.s2_bb_std_dev_length) dataframe["s2_bb_std_dev_value"] = s2_bb_std_dev_value dataframe["s2_bb_lower_band"] = s2_bb_sma_value - ( s2_bb_std_dev_value * self.s2_bb_lower_offset) s2_fib_atr_value = ta.ATR(dataframe, timeframe=self.s2_fib_atr_len) s2_fib_sma_value = ta.SMA(dataframe, timeperiod=self.s2_fib_sma_len) dataframe[ "s2_fib_lower_band"] = s2_fib_sma_value - s2_fib_atr_value * self.s2_fib_lower_value s3_bollinger = qtpylib.bollinger_bands( qtpylib.typical_price(dataframe), window=20, stds=3) dataframe["s3_bb_lowerband"] = s3_bollinger["lower"] dataframe["s3_ema_long"] = ta.EMA(dataframe, timeperiod=self.s3_ema_long) dataframe["s3_ema_short"] = ta.EMA(dataframe, timeperiod=self.s3_ema_short) dataframe["s3_fast_ma"] = ta.EMA( dataframe["volume"] * dataframe["close"], self.s3_ma_fast) / ta.EMA(dataframe["volume"], self.s3_ma_fast) dataframe["s3_slow_ma"] = ta.EMA( dataframe["volume"] * dataframe["close"], self.s3_ma_slow) / ta.EMA(dataframe["volume"], self.s3_ma_slow) # Volume weighted MACD dataframe["fastMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], 12) / ta.EMA(dataframe["volume"], 12) dataframe["slowMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], 26) / ta.EMA(dataframe["volume"], 26) dataframe["vwmacd"] = dataframe["fastMA"] - dataframe["slowMA"] dataframe["signal"] = ta.EMA(dataframe["vwmacd"], 9) dataframe["hist"] = dataframe["vwmacd"] - dataframe["signal"] return dataframe
def test_call_first_exception(): inputs = {'close': np.array([np.nan, np.nan, np.nan])} with pytest.raises(Exception, match="inputs are all NaN"): abstract.SMA(inputs, timeperiod=2) inputs = {'close': np.array([1.0, 2.0, 3.0])} output = abstract.SMA(inputs, timeperiod=2) expected = np.array([np.nan, 1.5, 2.5]) assert_np_arrays_equal(expected, output)
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # SMA - Simple Moving Average for i in range(1, self.buy_params['buy-ma-count']): dataframe[f'buy-ma-{i}'] = ta.SMA( dataframe, timeperiod=int(i * self.buy_params['buy-ma-gap'])) for i in range(1, self.sell_params['sell-ma-count']): dataframe[f'sell-ma-{i}'] = ta.SMA( dataframe, timeperiod=int(i * self.sell_params['sell-ma-gap'])) return dataframe
def analyze(self, historical_data, signal=['close'], hot_thresh=None, cold_thresh=None, exponential=True, ma_fast=10, ma_slow=50): """Performs an analysis about the increase in volumen on the historical data Args: historical_data (list): A matrix of historical OHCLV data. signal (list, optional): Defaults to close. Unused in this indicator exponential (boolean): flag to indicate is EMA is used ma_fast (integer): periods to use to calculate the fast MA ma_slow (integer): periods to use to calculate the slow MA Returns: pandas.DataFrame: A dataframe containing the indicator and hot/cold values. """ dataframe = self.convert_to_dataframe(historical_data) if exponential == True: ma_fast_values = abstract.EMA(dataframe, ma_fast) ma_slow_values = abstract.EMA(dataframe, ma_slow) else: ma_fast_values = abstract.SMA(dataframe, ma_fast) ma_slow_values = abstract.SMA(dataframe, ma_slow) ma_crossover = pandas.concat( [dataframe, ma_fast_values, ma_slow_values], axis=1) ma_crossover.rename(columns={ 0: 'fast_values', 1: 'slow_values' }, inplace=True) previous_fast, previous_slow = ma_crossover.iloc[-2][ 'fast_values'], ma_crossover.iloc[-2]['slow_values'] current_fast, current_slow = ma_crossover.iloc[-1][ 'fast_values'], ma_crossover.iloc[-1]['slow_values'] ma_crossover['is_hot'] = False ma_crossover['is_cold'] = False ma_crossover['is_hot'].iloc[ -1] = previous_fast < previous_slow and current_fast > current_slow ma_crossover['is_cold'].iloc[ -1] = previous_fast > previous_slow and current_fast < current_slow return ma_crossover
def signal(self): ma14 = tb.SMA(self.dataframe, 14) ma30 = tb.SMA(self.dataframe, 30) ma14current = ma14[len(ma14) - 1] ma30current = ma30[len(ma30) - 1] if ma14current > ma30current: return 1 elif ma14current < ma30current: return -1 else: return 0
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe['hclose'] = (dataframe['open'] + dataframe['high'] + dataframe['low'] + dataframe['close']) / 4 dataframe['hopen'] = ( (dataframe['open'].shift(2) + dataframe['close'].shift(2)) / 2 ) #it is not the same as real heikin ashi since I found that this is better. dataframe['hhigh'] = dataframe[['open', 'close', 'high']].max(axis=1) dataframe['hlow'] = dataframe[['open', 'close', 'low']].min(axis=1) dataframe['emac'] = ta.SMA( dataframe['hclose'], timeperiod=6) #to smooth out the data and thus less noise. dataframe['emao'] = ta.SMA(dataframe['hopen'], timeperiod=6) return dataframe
def market_cipher(self, dataframe) -> DataFrame: self.n1 = 10 #WT Channel Length self.n2 = 21 #WT Average Length dataframe['ap'] = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3 dataframe['esa'] = ta.EMA(dataframe['ap'], self.n1) dataframe['d'] = ta.EMA((dataframe['ap'] - dataframe['esa']).abs(), self.n1) dataframe['ci'] = (dataframe['ap'] - dataframe['esa']) / (0.015 * dataframe['d']) dataframe['tci'] = ta.EMA(dataframe['ci'], self.n2) dataframe['wt1'] = dataframe['tci'] dataframe['wt2'] = ta.SMA(dataframe['wt1'], 4) dataframe['wtVwap'] = dataframe['wt1'] - dataframe['wt2'] dataframe['wtCrossUp'] = dataframe['wt2'] - dataframe['wt1'] <= 0 dataframe['wtCrossDown'] = dataframe['wt2'] - dataframe['wt1'] >= 0 dataframe['crossed_above'] = qtpylib.crossed_above( dataframe['wt2'], dataframe['wt1']) dataframe['crossed_below'] = qtpylib.crossed_below( dataframe['wt2'], dataframe['wt1']) 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 """ df = dataframe df["entry-bis"] = ((df["high"].iloc[-3] < df["low"]) & (df["low"] < df["high"].iloc[-1]) & (df["high"] < df["high"].iloc[-2]) & (df["high"].iloc[-1] < df["high"].iloc[-2])) df["exit-bis"] = ((df["low"].iloc[-3] > df["high"]) & (df["high"] > df["low"].iloc[-1]) & (df["low"] > df["low"].iloc[-2]) & (df["low"].iloc[-1] > df["low"].iloc[-2])) dataframe['sma'] = ta.SMA(dataframe, timeperiod=40) return df
def test_SMA(): expected = func.SMA(ford_2012['close'], 10) assert_np_arrays_equal(expected, abstract.Function('sma', ford_2012, 10).outputs) assert_np_arrays_equal( expected, abstract.Function('sma')(ford_2012, 10, price='close')) assert_np_arrays_equal(expected, abstract.Function('sma')(ford_2012, timeperiod=10)) expected = func.SMA(ford_2012['open'], 10) assert_np_arrays_equal( expected, abstract.Function('sma', ford_2012, 10, price='open').outputs) assert_np_arrays_equal( expected, abstract.Function('sma', price='low')(ford_2012, 10, price='open')) assert_np_arrays_not_equal( expected, abstract.Function('sma', ford_2012, 10, price='open')(timeperiod=20)) assert_np_arrays_not_equal( expected, abstract.Function('sma', ford_2012)(10, price='close')) assert_np_arrays_not_equal( expected, abstract.Function('sma', 10)(ford_2012, price='high')) assert_np_arrays_not_equal( expected, abstract.Function('sma', price='low')(ford_2012, 10)) input_arrays = {'foobarbaz': ford_2012['open']} assert_np_arrays_equal(expected, abstract.SMA(input_arrays, 10, price='foobarbaz'))
def analyze_sma(self, historial_data, hot_thresh=None, cold_thresh=None): """Performs a SMA 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 = 15 dataframe = self.__convert_to_dataframe(historial_data) sma_value = abstract.SMA(dataframe, period_count).iloc[-1] is_hot = False if not hot_thresh is None: is_hot = sma_value >= hot_thresh is_cold = False if not cold_thresh is None: is_cold = sma_value <= cold_thresh sma_data = { 'values': (sma_value, ), 'is_hot': is_hot, 'is_cold': is_cold } return sma_data
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: # WAVETREND try: ap = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3 esa = ta.EMA(ap, 10) d = ta.EMA((ap - esa).abs(), 10) ci = (ap - esa).div(0.0015 * d) tci = ta.EMA(ci, 21) wt1 = tci wt2 = ta.SMA(np.nan_to_num(wt1), 4) dataframe['wt1'], dataframe['wt2'] = wt1, wt2 stoch = ta.STOCH(dataframe, 14) slowk = stoch['slowk'] dataframe['slowk'] = slowk # print(dataframe.iloc[:, 6:].keys()) x = dataframe.iloc[:, 6:].values # returns a numpy array min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) dataframe.iloc[:, 6:] = pd.DataFrame(x_scaled) # print('wt:\t', dataframe['wt'].min(), dataframe['wt'].max()) # print('stoch:\t', dataframe['stoch'].min(), dataframe['stoch'].max()) dataframe['def'] = dataframe['slowk'] - dataframe['wt1'] # print('def:\t', dataframe['def'].min(), "\t", dataframe['def'].max()) except: dataframe['wt1'], dataframe['wt2'], dataframe['def'], dataframe[ 'slowk'] = 0, 10, 100, 1000 return dataframe
def market_cipher(self, dataframe) -> DataFrame: #dataframe['volume_rolling'] = dataframe['volume'].shift(14).rolling(14).mean() # osLevel = -60 obLevel = 30 dataframe['ap'] = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3 dataframe['esa'] = ta.EMA(dataframe['ap'], self.n1) dataframe['d'] = ta.EMA((dataframe['ap'] - dataframe['esa']).abs(), self.n1) dataframe['ci'] = (dataframe['ap'] - dataframe['esa']) / (0.015 * dataframe['d']) dataframe['tci'] = ta.EMA(dataframe['ci'], self.n2) dataframe['wt1'] = dataframe['tci'] dataframe['wt2'] = ta.SMA(dataframe['wt1'], 4) dataframe['wtVwap'] = dataframe['wt1'] - dataframe['wt2'] dataframe['wtOversold'] = dataframe['wt2'] <= osLevel dataframe['wtOverbought'] = dataframe['wt2'] >= obLevel dataframe['wtCrossUp'] = dataframe['wt2'] - dataframe['wt1'] <= 0 dataframe['wtCrossDown'] = dataframe['wt2'] - dataframe['wt1'] >= 0 dataframe['crossed_above'] = qtpylib.crossed_above( dataframe['wt2'], dataframe['wt1']) dataframe['crossed_below'] = qtpylib.crossed_below( dataframe['wt2'], dataframe['wt1']) return dataframe