def get_indicators(self): period = int(self.strategy_value['period']) slowing = int(self.strategy_value['slowing_period']) d_period = int(self.strategy_value['d_period']) stoch_k, stoch_d = ti.stoch(self.high, self.low, self.close, period, slowing, d_period) return stoch_k, stoch_d
def srsi(candles: np.ndarray, period=14, sequential=False) -> StochasticRSI: """ Stochastic RSI :param candles: np.ndarray :param period: int - default: 14 :param sequential: bool - default=False :return: StochasticRSI """ if not sequential and len(candles) > 240: candles = candles[-240:] rsi_np = talib.RSI(candles[:, 2], timeperiod=period) rsi_np = rsi_np[np.logical_not(np.isnan(rsi_np))] fast_k, fast_d = ti.stoch(rsi_np, rsi_np, rsi_np, 14, 3, 3) if sequential: fast_k = np.concatenate((np.full((17 + period), np.nan), fast_k), axis=0) fast_d = np.concatenate((np.full((17 + period), np.nan), fast_d), axis=0) return StochasticRSI(fast_k, fast_d) else: return StochasticRSI(fast_k[-1], fast_d[-1])
def srsi(candles: np.ndarray, period=14, source_type="close", sequential=False) -> StochasticRSI: """ Stochastic RSI :param candles: np.ndarray :param period: int - default: 14 :param source_type: str - default: "close" :param sequential: bool - default=False :return: StochasticRSI(k, d) """ if not sequential and len(candles) > 240: candles = candles[-240:] source = get_candle_source(candles, source_type=source_type) rsi_np = talib.RSI(source, timeperiod=period) rsi_np = rsi_np[np.logical_not(np.isnan(rsi_np))] fast_k, fast_d = ti.stoch(rsi_np, rsi_np, rsi_np, 14, 3, 3) if sequential: fast_k = np.concatenate((np.full( (candles.shape[0] - fast_k.shape[0]), np.nan), fast_k), axis=0) fast_d = np.concatenate((np.full( (candles.shape[0] - fast_d.shape[0]), np.nan), fast_d), axis=0) return StochasticRSI(fast_k, fast_d) else: return StochasticRSI(fast_k[-1], fast_d[-1])
async def eval_impl(self): self.eval_note = 0 # slowk --> fastest # slowd --> slowest pct_k_period = 14 pct_k_slowing_period = 3 pct_d_period = 3 if len(self.last_candle_data[PriceIndexes.IND_PRICE_HIGH.value] > pct_k_period): slowk, slowd = tulipy.stoch(self.last_candle_data[PriceIndexes.IND_PRICE_HIGH.value], self.last_candle_data[PriceIndexes.IND_PRICE_LOW.value], self.last_candle_data[PriceIndexes.IND_PRICE_CLOSE.value], pct_k_period, pct_k_slowing_period, pct_d_period) last_value = slowd[-1] if last_value > self.STOCH_INSTABILITY_THRESHOLD: self.eval_note = 1 if last_value < self.STOCH_STABILITY_THRESHOLD: self.eval_note = -1 if self.last_eval_note != self.eval_note: await self.notify_evaluator_task_managers(self.get_name()) self.last_eval_note = self.eval_note
def srsi(candles: np.ndarray, period: int = 14, period_stoch: int = 14, k: int = 3, d: int = 3, source_type: str = "close", sequential: bool = False) -> StochasticRSI: """ Stochastic RSI :param candles: np.ndarray :param period_rsi: int - default: 14 - RSI Length :param period_stoch: int - default: 14 - Stochastic Length :param k: int - default: 3 :param d: int - default: 3 :param source_type: str - default: "close" :param sequential: bool - default=False :return: StochasticRSI(k, d) """ candles = slice_candles(candles, sequential) source = get_candle_source(candles, source_type=source_type) rsi_np = talib.RSI(source, timeperiod=period) rsi_np = rsi_np[np.logical_not(np.isnan(rsi_np))] fast_k, fast_d = ti.stoch(rsi_np, rsi_np, rsi_np, period_stoch, k, d) if sequential: fast_k = same_length(candles, fast_k) fast_d = same_length(candles, fast_d) return StochasticRSI(fast_k, fast_d) else: return StochasticRSI(fast_k[-1], fast_d[-1])
def srsi(candles: np.ndarray, period: int = 14, period_stoch: int = 14, k: int = 3, d: int = 3, source_type: str = "close", sequential: bool = False) -> StochasticRSI: """ Stochastic RSI :param candles: np.ndarray :param period_rsi: int - default: 14 - RSI Length :param period_stoch: int - default: 14 - Stochastic Length :param k: int - default: 3 :param d: int - default: 3 :param source_type: str - default: "close" :param sequential: bool - default=False :return: StochasticRSI(k, d) """ warmup_candles_num = get_config('env.data.warmup_candles_num', 240) if not sequential and len(candles) > warmup_candles_num: candles = candles[-warmup_candles_num:] source = get_candle_source(candles, source_type=source_type) rsi_np = talib.RSI(source, timeperiod=period) rsi_np = rsi_np[np.logical_not(np.isnan(rsi_np))] fast_k, fast_d = ti.stoch(rsi_np, rsi_np, rsi_np, period_stoch, k, d) if sequential: fast_k = np.concatenate((np.full((candles.shape[0] - fast_k.shape[0]), np.nan), fast_k), axis=0) fast_d = np.concatenate((np.full((candles.shape[0] - fast_d.shape[0]), np.nan), fast_d), axis=0) return StochasticRSI(fast_k, fast_d) else: return StochasticRSI(fast_k[-1], fast_d[-1])
def add_stoch(df, K=5, period=3, D=3): l = len(df.close.values) (k, d) = ti.stoch( (df.high.values), (df.low.values), (df.close.values), K, period, D,) df[f'stochk_{K}{period}{D}'] = pad_left(k, l) df[f'stochd_{K}{period}{D}'] = pad_left(d, l)
def stoch(self, name='stoch', kp=14, ksp=3, d=3): if len(self.df_ohlc) > kp: self._add_column_to_ohlc( name, ti.stoch(self.df_ohlc.pricehigh.values, self.df_ohlc.pricelow.values, self.df_ohlc.priceclose.values, kp, ksp, d)) return True else: return False
def stoch_rsi(self, name='stoch_rsi', kp=14, ksp=3, d=3): if len(self.df_ohlc) > kp: if 'rsi' not in self.df_ohlc.columns: self._add_column_to_ohlc( "rsi", ti.rsi(self.df_ohlc.priceclose.values, kp)) v = self.df_ohlc.rsi.dropna().values self._add_column_to_ohlc(name, ti.stoch(v, v, v, kp, ksp, d)) return True else: return False
def stoch_rsi(self, name='stoch_rsi', kp=14, ksp=3, d=3): try: if 'rsi' not in self.df_ohlc.columns: self._add_column_to_ohlc( "rsi", ti.rsi(self.df_ohlc.priceclose.values, kp)) v = self.df_ohlc.rsi.dropna().values self._add_column_to_ohlc(name, ti.stoch(v, v, v, kp, ksp, d)) return True except Exception as err: print("stoch_rsi error>>>", err.__repr__()) return False
def get_stochastic(self, stock, direction, loadHist=False): # this function calculates the stochastic curves self._L.info('\n\n### STOCHASTIC TREND ANALYSIS (%s for %s) ###' % (stock.name, stock.direction)) try: while True: if loadHist: self.load_historical_data( stock, interval=gvars.fetchItval['little']) # càlculs stoch_k_full, stoch_d_full = ti.stoch( stock.df.high.values, stock.df.low.values, stock.df.close.values, 9, 6, 9) # parameters for the curves stoch_k = stoch_k_full[-1] stoch_d = stoch_d_full[-1] # look for a buying condition if ((direction == 'buy') and (stoch_k > stoch_d) and ((stoch_k <= gvars.limStoch['maxBuy']) and (stoch_d <= gvars.limStoch['maxBuy']))): self._L.info('OK: k is over d: (K,D)=(%.2f,%.2f)' % (stoch_k, stoch_d)) return True # look for a selling condition elif ((direction == 'sell') and (stoch_k < stoch_d) and ((stoch_d >= gvars.limStoch['minSell']) and (stoch_k >= gvars.limStoch['minSell']))): self._L.info('OK: k is under d: (K,D)=(%.2f,%.2f)' % (stoch_k, stoch_d)) return True else: self._L.info( 'NO: The stochastics are (K,D)=(%.2f,%.2f) for %s' % (stoch_k, stoch_d, direction)) self.timeout += gvars.sleepTimes['ST'] time.sleep(gvars.sleepTimes['ST']) return False except Exception as e: self._L.info('ERROR_GS: error when getting stochastics') self._L.info(stock.df) self._L.info(stock.direction) self._L.info(str(e)) return False
def test_stoch(data): arr_high = data["high"].to_numpy().astype(float) arr_low = data["low"].to_numpy().astype(float) arr_close = data["close"].to_numpy().astype(float) ti_percK, ti_percD = ti.stoch(arr_high, arr_low, arr_close, 14, 1, 3) stoch = indicator.Indicate(data).stochastic() percK = stoch['percK'].astype(float) percD = stoch['percD'].astype(float) assert np.allclose(ti_percK[-250:], percK[-250:], atol=1e-03, equal_nan=True) assert np.allclose(ti_percD[-250:], percD[-250:], atol=1e-03, equal_nan=True)
def inds(self): Indicators = {} for i in range(len(self.time)): #i/o? ''' 2 = High, 3 = Low, 4 = Close, 5 = Volume collects the needed market data into one list to push to the indicators''' close = self.time[i][4].values.copy(order='C') high = self.time[i][2].values.copy(order='C') low = self.time[i][3].values.copy(order='C') volume = self.time[i][5].values.copy(order='C') # !!!This needs to be changed. Each volume of the base time must be indexed up to the slice __time = self.time[i][6] # these are the indicators currently being used, and recored Indicators[i] = { 'stochrsi': ti.stochrsi(close, 5), 'rsi': ti.rsi(close, 5), # indicators that need to be doublechecked 'mfi': ti.mfi(high, low, close, volume, 5), 'sar': ti.psar(high, low, .2, 2), 'cci': ti.cci(high, low, close, 5), 'ema': ti.ema(close, 5) } # this one is good Indicators[i]['stoch_k'], Indicators[i]['stoch_d'] = ti.stoch( high, low, close, 5, 3, 3) # check on this, to see if it functions properly Indicators[i]['bbands_lower'], Indicators[i]['bbands_middle'], Indicators[i]['bbands_upper'] = ti.bbands(close, 5, 2) Indicators[i]['macd'], Indicators[i]['macd_signal'], Indicators[i]['macd_histogram'] = ti.macd(close, 12, 26, 9) Indicators[i]['time'] = __time Indicators[i]['close'] = close ''' below changes the length of each array to match the longest one, for a pandas df np.nan for the tail of the shorter ones''' Indicators[i] = to_pd(Indicator=Indicators[i]).dropna(how='all') return Indicators
def stoch(candlestickperiod, one, two, three): closeprices = [] lowprices = [] highprices = [] listoftime = [] stoch = candlestickinfo(11, candlestickperiod) for i in range(len(stoch['candles'])): if stoch['candles'][i]['complete'] == True: if stoch['candles'][i]['time'] not in listoftime: closeprices.append(float(stoch['candles'][i]['mid']['c'])) lowprices.append(float(stoch['candles'][i]['mid']['l'])) highprices.append(float(stoch['candles'][i]['mid']['h'])) listoftime.append(stoch['candles'][i]['time']) closearray = np.array(closeprices) lowarray = np.array(lowprices) higharray = np.array(highprices) stoch_k, stoch_d = ti.stoch(higharray, lowarray, closearray, one, two, three) print(stoch_k) print(stoch_d) return stoch_k, stoch_d
def eval_impl(self): self.eval_note = 0 # slowk --> fastest # slowd --> slowest slowk, slowd = tulipy.stoch( self.last_candle_data[PriceIndexes.IND_PRICE_HIGH.value], self.last_candle_data[PriceIndexes.IND_PRICE_LOW.value], self.last_candle_data[PriceIndexes.IND_PRICE_CLOSE.value], 14, 3, 3) last_value = slowd[-1] if last_value > self.STOCH_INSTABILITY_THRESHOLD: self.eval_note = 1 if last_value < self.STOCH_STABILITY_THRESHOLD: self.eval_note = -1 if self.last_eval_note != self.eval_note: self.notify_evaluator_thread_managers(self.__class__.__name__) self.last_eval_note = self.eval_note
def test_tulip_stoch(): ti.stoch(high_np, low_np, close_np, 5, 3, 3)
def srsi(values, rsi_length, stoch_length, k_period, d_period): rsi = ti.rsi(values, rsi_length) return ti.stoch(rsi, rsi, rsi, stoch_length, k_period, d_period)
def compute(self, data_dict): close = data_dict.get('close') high = data_dict.get('high') low = data_dict.get('low') return ti.stoch(high, low, close, 5, 3, 3)[0]
def compute(self, data_dict): close = data_dict.get('close') high = data_dict.get('high') low = data_dict.get('low') return ti.stoch(high, low, close, self.p1, self.p2, self.p3)[1]
df['MA'] = new_o['MA'] df['EMA'] = new_o['EMA'] df['RSI'] = new_o['RSI'] df = df.loc['2007-04-25':'2007-10-07'] #фильтр для детализации plt.plot(df.index, df['test'], label='test') plt.plot(df.index, df['MA'], label='MA', color='red') plt.plot(df.index, df['EMA'], label='EMA', color='green') plt.legend() plt.title('Microsoft') plt.ylabel('Price($)') plt.show() df.plot(y=['RSI']) df.plot(y=['Stochastic']) #Tulip Indicators stoch_k, stoch_d = ti.stoch(high, low, z, 5, 3, 3) sma = ti.sma(y, 5) rsi = ti.rsi(z, 14) ema = ti.ema(y, 5) print('MA: ', sma) print('EMA: ', ema) print('RSI: ', rsi) print('Stochastic: ', stoch_d) # In[44]: new_o # In[29]: df
def get_StochOsc(high, low, close, k_period, k_slow_period, d_period): stoch = np.zeros([2,len(close)]) stoch[:,k_period + max(k_slow_period,d_period) + 1:] = np.array(ti.stoch(high, low, close, k_period, k_slow_period, d_period)) return stoch