Python talib.STOCH Examples

The following are 13 code examples of talib.STOCH(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module talib , or try the search function .
Example #1
Source File: stochastic.py    From jesse with MIT License 9 votes vote down vote up
def stoch(candles: np.ndarray, fastk_period=14, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0,
          sequential=False) -> Stochastic:
    """
    The Stochastic Oscillator

    :param candles: np.ndarray
    :param period: int - default=14
    :param sequential: bool - default=False

    :return: Stochastic(k, d)
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    k, d = talib.STOCH(
        candles[:, 3],
        candles[:, 4],
        candles[:, 2],
        fastk_period=fastk_period,
        slowk_period=slowk_period,
        slowk_matype=slowk_matype,
        slowd_period=slowd_period,
        slowd_matype=slowd_matype
    )

    if sequential:
        return Stochastic(k, d)
    else:
        return Stochastic(k[-1], d[-1]) 
Example #2
Source File: talib_indicators.py    From QUANTAXIS with MIT License 7 votes vote down vote up
def STOCH(DataFrame, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0):
    slowk, slowd = talib.STOCH(DataFrame.high.values, DataFrame.low.values, DataFrame.close.values,
                               fastk_period, slowk_period, slowk_matype, slowd_period, slowd_matype)
    return pd.DataFrame({'STOCH_SLOWK': slowk, 'STOCH_SLOWD': slowd}, index=DataFrame.index) 
Example #3
Source File: talib_numpy.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def TA_KDJ(high:np.ndarray, 
           low:np.ndarray, 
           close:np.ndarray, 
           fastk_period:int=9, 
           slowk_matype:int=0, 
           slowk_period:int=3, 
           slowd_period:int=3) -> np.ndarray:
    '''
    参数设置:
        fastk_period = 9
        lowk_matype = 0, 
        slowk_period = 3, 
        slowd_period = 3

    返回: K, D, J
    '''
    K, D = talib.STOCH(high, 
                       low, 
                       close, 
                       fastk_period=fastk_period, 
                       slowk_matype=slowk_matype, 
                       slowk_period=slowk_period, 
                       slowd_period=slowd_period)
    J = 3 * K - 2 * D
    delta = np.r_[np.nan, np.diff(J)]
    return np.c_[K, D, J, delta] 
Example #4
Source File: IndicatorSubsystem.py    From cbpro-trader with GNU General Public License v3.0 5 votes vote down vote up
def calculate_stoch(self, period_name, closing_prices):
        slowk, slowd = talib.STOCH(self.highs, self.lows, closing_prices, fastk_period=14, slowk_period=2, slowk_matype=0, slowd_period=3, slowd_matype=0)
        self.current_indicators[period_name]['stoch_slowk'] = slowk[-1]
        self.current_indicators[period_name]['stoch_slowd'] = slowd[-1] 
Example #5
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def kdj(self, sym, frequency, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0):
        if not self.kbars_ready(sym, frequency):
            return [], []

        highs = self.high(sym, frequency)
        lows = self.low(sym, frequency)
        closes = self.close(sym, frequency)

        slowk, slowd = ta.STOCH(high=highs,
                                low=lows,
                                fastk_period=fastk_period,
                                close=closes,
                                slowk_period=slowk_period,
                                slowk_matype=slowk_matype,
                                slowd_period=slowd_period,
                                slowd_matype=slowd_matype)
        return slowk, slowd 
Example #6
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def __str__(self):
        return 'STOCH(symbol=%s, fast_k_period=%s, slow_k_period=%s, \
                      slow_k_ma_type=%s, slow_d_period=%s, self_d_ma_type=%s)' \
                      %(self.symbol, self.fast_k_period, self.slow_k_period, \
                      self.slow_k_ma_type, self.slow_d_period, self.slow_d_ma_type) 
Example #7
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def results(self, data_frame):
        try:
            slowk, slowd = talib.STOCH(data_frame['%s_High' %self.symbol].values,
                                       data_frame['%s_Low' %self.symbol].values,
                                       data_frame['%s_Close' %self.symbol].values,
                                       self.fast_k_period, self.slow_k_period,
                                       self.slow_k_ma_type, self.slow_d_period,
                                       self.slow_d_ma_type)
            data_frame[self.slowk] = slowk
            data_frame[self.slowd] = slowd
        except KeyError:
            data_frame[self.slowk] = np.nan
            data_frame[self.slowd] = np.nan 
Example #8
Source File: ta.py    From dash-technical-charting with MIT License 5 votes vote down vote up
def add_STOCH(self, fastk_period=5, slowk_period=3,
              slowk_matype=0, slowd_period=3, slowd_matype=0,
              types=['line', 'line'],
              colors=['primary', 'tertiary'],
              **kwargs):
    """Slow Stochastic Oscillator.

    Note that the first argument of types and colors refers to Slow Stoch %K,
    while second argument refers to Slow Stoch %D
    (signal line of %K obtained by MA).

    """
    if not (self.has_high and self.has_low and self.has_close):
        raise Exception()

    utils.kwargs_check(kwargs, VALID_TA_KWARGS)
    if 'kind' in kwargs:
        kwargs['type'] = kwargs['kind']
    if 'kinds' in kwargs:
        types = kwargs['type']

    if 'type' in kwargs:
        types = [kwargs['type']] * 2
    if 'color' in kwargs:
        colors = [kwargs['color']] * 2

    name = 'STOCH({},{},{})'.format(str(fastk_period),
                                    str(slowk_period),
                                    str(slowd_period))
    slowk = name + r'[%k]'
    slowd = name + r'[%d]'
    self.sec[slowk] = dict(type=types[0], color=colors[0])
    self.sec[slowd] = dict(type=types[1], color=colors[1], on=slowk)
    self.ind[slowk], self.ind[slowd] = talib.STOCH(self.df[self.hi].values,
                                                   self.df[self.lo].values,
                                                   self.df[self.cl].values,
                                                   fastk_period, slowk_period,
                                                   slowk_matype, slowd_period,
                                                   slowd_matype) 
Example #9
Source File: test_reg.py    From finta with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stoch():
    """test TA.STOCH"""

    stoch = TA.STOCH(ohlc, 9)
    talib_stoch = talib.STOCH(ohlc["high"], ohlc["low"], ohlc["close"], 9)

    #  talib_stoch[0] is "slowk"
    # assert talib_stoch[0][-1] == stoch.values[-1]
    # assert 76.27794470586021 == 80.7982311922445
    pass  # close enough 
Example #10
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def STOCH(frame, fastk=5, slowk=3, slowk_matype=0, slowd=3, slowd_matype=0, high_col='high', low_col='low',
          close_col='close'):
    return _frame_to_frame(frame, [high_col, low_col, close_col], ['SlowK', 'SlowD'], talib.STOCH, fastk, slowk,
                           slowk_matype, slowd, slowd_matype) 
Example #11
Source File: test_indicator_momentum.py    From pandas-ta with MIT License 5 votes vote down vote up
def test_stoch(self):
        result = pandas_ta.stoch(self.high, self.low, self.close, fast_k=14, slow_k=14, slow_d=14)
        self.assertIsInstance(result, DataFrame)
        self.assertEqual(result.name, 'STOCH_14_14_14')
        self.assertEqual(len(result.columns), 4)

        result = pandas_ta.stoch(self.high, self.low, self.close)
        self.assertIsInstance(result, DataFrame)
        self.assertEqual(result.name, 'STOCH_14_5_3')

        try:
            tal_stochf = tal.STOCHF(self.high, self.low, self.close)
            tal_stoch = tal.STOCH(self.high, self.low, self.close)
            tal_stochdf = DataFrame({'STOCHF_14': tal_stochf[0], 'STOCHF_3': tal_stochf[1], 'STOCH_5': tal_stoch[0], 'STOCH_3': tal_stoch[1]})
            pdt.assert_frame_equal(result, tal_stochdf)
        except AssertionError as ae:
            try:
                stochfk_corr = pandas_ta.utils.df_error_analysis(result.iloc[:,0], tal_stochdf.iloc[:,0], col=CORRELATION)
                self.assertGreater(stochfk_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:,0], CORRELATION, ex)

            try:
                stochfd_corr = pandas_ta.utils.df_error_analysis(result.iloc[:,1], tal_stochdf.iloc[:,1], col=CORRELATION)
                self.assertGreater(stochfd_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:,1], CORRELATION, ex, newline=False)

            try:
                stochsk_corr = pandas_ta.utils.df_error_analysis(result.iloc[:,2], tal_stochdf.iloc[:,2], col=CORRELATION)
                self.assertGreater(stochsk_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:,2], CORRELATION, ex, newline=False)

            try:
                stochsd_corr = pandas_ta.utils.df_error_analysis(result.iloc[:,3], tal_stochdf.iloc[:,3], col=CORRELATION)
                self.assertGreater(stochsd_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:,3], CORRELATION, ex, newline=False) 
Example #12
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def STOCH(data, **kwargs):
    _check_talib_presence()
    _, phigh, plow, pclose, _ = _extract_ohlc(data)
    return talib.STOCH(phigh, plow, pclose, **kwargs) 
Example #13
Source File: kdj_stock.py    From strategy with Apache License 2.0 4 votes vote down vote up
def on_bar(self, bar):
        if self.cls_mode == gm.MD_MODE_PLAYBACK:
            if bar.strtime[0:10] != self.cur_date[0:10]:
                self.cur_date = bar.strtime[0:10] + ' 08:00:00'
                # 新的交易日
                self.init_data_newday()

        symbol = bar.exchange + '.' + bar.sec_id

        self.movement_stop_profit_loss(bar)
        self.fixation_stop_profit_loss(bar)

        pos = self.get_position(bar.exchange, bar.sec_id, OrderSide_Bid)

        # 补充当天价格
        if symbol in self.dict_price:
            if self.dict_price[symbol][0][-1] < bar.high:
                self.dict_price[symbol][0][-1] = bar.high

            if self.dict_price[symbol][1][-1] > bar.low:
                self.dict_price[symbol][1][-1] = bar.low

            self.dict_price[symbol][2][-1] = bar.close

        if self.dict_open_close_signal[symbol] is False:
            # 当天未有对该代码开、平仓
            if symbol in self.dict_price:
                slowk, slowd = talib.STOCH(high=self.dict_price[symbol][0],
                                           low=self.dict_price[symbol][1],
                                           close=self.dict_price[symbol][2],
                                           fastk_period=self.fastk_period,
                                           slowk_period=self.slowk_period,
                                           slowk_matype=self.slowk_matype,
                                           slowd_period=self.slowd_period,
                                           slowd_matype=self.slowd_matype)

                if pos is None and symbol not in self.dict_open_cum_days \
                        and (slowk[-1] < self.slowk_bid or slowd[-1] < self.slowd_bid):
                    # 有开仓机会则设置已开仓的交易天数
                    self.dict_open_cum_days[symbol] = 0

                    cash = self.get_cash()
                    cur_open_vol = self.open_vol
                    if cash.available / bar.close > self.open_vol:
                        cur_open_vol = self.open_vol
                    else:
                        cur_open_vol = int(cash.available / bar.close / 100) * 100

                    if cur_open_vol == 0:
                        print('no available cash to buy, available cash: %.2f' % cash.available)
                    else:
                        self.open_long(bar.exchange, bar.sec_id, bar.close, cur_open_vol)
                        self.dict_open_close_signal[symbol] = True
                        logging.info('open long, symbol:%s, time:%s, price:%.2f' % (symbol, bar.strtime, bar.close))
                elif pos is not None and (slowk[-1] > self.slowk_sell or slowd[-1] > self.slowd_sell):
                    vol = pos.volume - pos.volume_today
                    if vol > 0:
                        self.close_long(bar.exchange, bar.sec_id, bar.close, vol)
                        self.dict_open_close_signal[symbol] = True
                        logging.info('close long, symbol:%s, time:%s, price:%.2f' % (symbol, bar.strtime, bar.close))