Python talib.BBANDS Examples

The following are 30 code examples of talib.BBANDS(). 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: data_preprocessing.py    From StarTrader with MIT License 22 votes vote down vote up
def technical_indicators_df(self, daily_data):
        """
        Assemble a dataframe of technical indicator series for a single stock
        """
        o = daily_data['Open'].values
        c = daily_data['Close'].values
        h = daily_data['High'].values
        l = daily_data['Low'].values
        v = daily_data['Volume'].astype(float).values
        # define the technical analysis matrix

        # Most data series are normalized by their series' mean
        ta = pd.DataFrame()
        ta['MA5'] = tb.MA(c, timeperiod=5) / tb.MA(c, timeperiod=5).mean()
        ta['MA10'] = tb.MA(c, timeperiod=10) / tb.MA(c, timeperiod=10).mean()
        ta['MA20'] = tb.MA(c, timeperiod=20) / tb.MA(c, timeperiod=20).mean()
        ta['MA60'] = tb.MA(c, timeperiod=60) / tb.MA(c, timeperiod=60).mean()
        ta['MA120'] = tb.MA(c, timeperiod=120) / tb.MA(c, timeperiod=120).mean()
        ta['MA5'] = tb.MA(v, timeperiod=5) / tb.MA(v, timeperiod=5).mean()
        ta['MA10'] = tb.MA(v, timeperiod=10) / tb.MA(v, timeperiod=10).mean()
        ta['MA20'] = tb.MA(v, timeperiod=20) / tb.MA(v, timeperiod=20).mean()
        ta['ADX'] = tb.ADX(h, l, c, timeperiod=14) / tb.ADX(h, l, c, timeperiod=14).mean()
        ta['ADXR'] = tb.ADXR(h, l, c, timeperiod=14) / tb.ADXR(h, l, c, timeperiod=14).mean()
        ta['MACD'] = tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0] / \
                     tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0].mean()
        ta['RSI'] = tb.RSI(c, timeperiod=14) / tb.RSI(c, timeperiod=14).mean()
        ta['BBANDS_U'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0].mean()
        ta['BBANDS_M'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1].mean()
        ta['BBANDS_L'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2].mean()
        ta['AD'] = tb.AD(h, l, c, v) / tb.AD(h, l, c, v).mean()
        ta['ATR'] = tb.ATR(h, l, c, timeperiod=14) / tb.ATR(h, l, c, timeperiod=14).mean()
        ta['HT_DC'] = tb.HT_DCPERIOD(c) / tb.HT_DCPERIOD(c).mean()
        ta["High/Open"] = h / o
        ta["Low/Open"] = l / o
        ta["Close/Open"] = c / o

        self.ta = ta 
Example #2
Source File: DyStockDataUtility.py    From DevilYuan with MIT License 10 votes vote down vote up
def getBBands(df, period=10, stdNbr=2):
        try:
            close = df['close']
        except Exception as ex:
            return None

        try:
            upper, middle, lower = talib.BBANDS(
                                close.values, 
                                timeperiod=period,
                                # number of non-biased standard deviations from the mean
                                nbdevup=stdNbr,
                                nbdevdn=stdNbr,
                                # Moving average type: simple moving average here
                                matype=0)
        except Exception as ex:
            return None

        data = dict(upper=upper, middle=middle, lower=lower)
        df = pd.DataFrame(data, index=df.index, columns=['upper', 'middle', 'lower']).dropna()

        return df 
Example #3
Source File: DySS_BBands.py    From DevilYuan with MIT License 7 votes vote down vote up
def _bbands(self, df):
        try:
            close = df['close']
        except Exception as ex:
            return None, None, None

        if close.shape[0] != self._forwardNDays:
            return None, None, None

        try:
            upper, middle, lower = talib.BBANDS(
                                close.values, 
                                timeperiod=self._forwardNDays,
                                # number of non-biased standard deviations from the mean
                                nbdevup=1,
                                nbdevdn=1,
                                # Moving average type: simple moving average here
                                matype=0)
        except Exception as ex:
            return None, None, None

        return upper, middle, lower 
Example #4
Source File: __init__.py    From ebisu with MIT License 7 votes vote down vote up
def bbands(source, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0):
    return talib.BBANDS(source, timeperiod, nbdevup, nbdevdn, matype) 
Example #5
Source File: ABuNDBoll.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def _calc_boll_from_ta(prices, time_period=20, nb_dev=2):
    """
    使用talib计算boll, 即透传talib.BBANDS计算结果
    :param prices: 收盘价格序列,pd.Series或者np.array
    :param time_period: boll的N值默认值20,int
    :param nb_dev: boll的nb_dev值默认值2,int
    :return: tuple(upper, middle, lower)
    """
    import talib
    if isinstance(prices, pd.Series):
        prices = prices.values

    upper, middle, lower = talib.BBANDS(
        prices,
        timeperiod=time_period,
        nbdevup=nb_dev,
        nbdevdn=nb_dev,
        matype=0)

    return upper, middle, lower 
Example #6
Source File: talib_numpy.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def TA_BBANDS(prices:np.ndarray, 
              timeperiod:int=5, 
              nbdevup:int=2, 
              nbdevdn:int=2, 
              matype:int=0) -> np.ndarray:
    '''
    参数设置:
        timeperiod = 5
        nbdevup = 2
        nbdevdn = 2

    返回: up, middle, low
    '''
    up, middle, low = talib.BBANDS(prices, 
                                   timeperiod, 
                                   nbdevup, 
                                   nbdevdn, 
                                   matype)
    ch = (up - low) / middle
    delta = np.r_[np.nan, np.diff(ch)]
    return np.c_[up, middle, low, ch, delta] 
Example #7
Source File: DyStockDataUtility.py    From DevilYuan with MIT License 6 votes vote down vote up
def getBBands(df, period=10, stdNbr=2):
        try:
            close = df['close']
        except Exception as ex:
            return None

        try:
            upper, middle, lower = talib.BBANDS(
                                close.values, 
                                timeperiod=period,
                                # number of non-biased standard deviations from the mean
                                nbdevup=stdNbr,
                                nbdevdn=stdNbr,
                                # Moving average type: simple moving average here
                                matype=0)
        except Exception as ex:
            return None

        data = dict(upper=upper, middle=middle, lower=lower)
        df = pd.DataFrame(data, index=df.index, columns=['upper', 'middle', 'lower']).dropna()

        return df 
Example #8
Source File: DySS_BBands.py    From DevilYuan with MIT License 6 votes vote down vote up
def _bbands(self, df):
        try:
            close = df['close']
        except Exception as ex:
            return None, None, None

        if close.shape[0] != self._forwardNDays:
            return None, None, None

        try:
            upper, middle, lower = talib.BBANDS(
                                close.values, 
                                timeperiod=self._forwardNDays,
                                # number of non-biased standard deviations from the mean
                                nbdevup=1,
                                nbdevdn=1,
                                # Moving average type: simple moving average here
                                matype=0)
        except Exception as ex:
            return None, None, None

        return upper, middle, lower 
Example #9
Source File: technical_indicator.py    From NowTrade with MIT License 6 votes vote down vote up
def __str__(self):
        return 'BBANDS(data=%s, period=%s, devup=%s, devdown=%s, ma_type=%s)' \
                %(self.data, self.period, self.devup, self.devdown, self.ma_type) 
Example #10
Source File: boll.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def handle_data(context):  
    # 等待数据就绪,否则计算果结为异常值
    if len(Close()) < p:
        return
  
    # 计算布林带高中低点
    upp, mid, low = talib.BBANDS(Close(), p, 2, 2)
    
    # 低买高卖
    if MarketPosition() != 1 and Open()[-1] < low[-1]: 
        Buy(qty, Open()[-1])
    elif MarketPosition() != -1 and Open()[-1] > upp[-1]:
        SellShort(qty, Open()[-1])

    # 绘制布林带曲线
    PlotNumeric('upp', upp[-1], RGB_Red())
    PlotNumeric('mid', mid[-1], RGB_Blue())
    PlotNumeric('low', low[-1], RGB_Green())
    # 绘制盈亏曲线
    PlotNumeric("profit", NetProfit() + FloatProfit() - TradeCost(), 0xFF00FF, False) 
Example #11
Source File: two-classifiers.py    From quantopian-ensemble-methods with MIT License 5 votes vote down vote up
def create_model(context, data):
    X = []
    Y = [] 
    
    for S in context.training_stocks:
        recent_prices = history(context.history_range, '1d', 'price')[S].values
        recent_lows   = history(context.history_range, '1d', 'low')[S].values
        recent_highs  = history(context.history_range, '1d', 'high')[S].values
        recent_closes = history(context.history_range, '1d', 'close_price')[S].values

        atr = talib.ATR(recent_highs, recent_lows, recent_closes, timeperiod=14)
        prev_close = np.roll(recent_closes, 2)
        upside_signal = (recent_prices - (prev_close + atr)).tolist()
        downside_signal = (prev_close - (recent_prices + atr)).tolist()
        price_changes = np.diff(recent_prices).tolist()
        upper, middle, lower = talib.BBANDS(recent_prices,timeperiod=10,nbdevup=2,nbdevdn=2,matype=1)
        upper = upper.tolist()
        middle = middle.tolist()
        lower = lower.tolist()
   
        for i in range(15, context.history_range-context.lookback-1):
            Z = price_changes[i:i+context.lookback] + upside_signal[i:i+context.lookback] + downside_signal[i:i+context.lookback] +\
                upper[i:i+context.lookback] + middle[i:i+context.lookback] + lower[i:i+context.lookback] 
                
            if (np.any(np.isnan(Z)) or not np.all(np.isfinite(Z))): continue

            X.append(Z)

            if abs(price_changes[i+context.lookback]) > abs(price_changes[i]*(1+context.percentage_change)):
                if price_changes[i+context.lookback] > 0:
                    Y.append(+1)
                else:
                    Y.append(-1)
            else:
                Y.append(0)

    context.model1.fit(X, Y) 
    context.model2.fit(X, Y) 
Example #12
Source File: bollinger_bands_width.py    From jesse with MIT License 5 votes vote down vote up
def bollinger_bands_width(candles: np.ndarray, period=20, devup=2, devdn=2, matype=0, source_type="close",
                          sequential=False) -> Union[float, np.ndarray]:
    """
    BBW - Bollinger Bands Width - Bollinger Bands Bandwidth

    :param candles: np.ndarray
    :param period: int - default: 20
    :param devup: float - default: 2
    :param devdn: float - default: 2
    :param matype: int - default: 0
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    source = get_candle_source(candles, source_type=source_type)
    upperbands, middlebands, lowerbands = talib.BBANDS(source, timeperiod=period, nbdevup=devup, nbdevdn=devdn,
                                                       matype=matype)

    if sequential:
        return (upperbands - lowerbands) / middlebands
    else:
        return (upperbands[-1] - lowerbands[-1]) / middlebands[-1] 
Example #13
Source File: one-classifier.py    From quantopian-ensemble-methods with MIT License 5 votes vote down vote up
def create_model(context, data):
    X = []
    Y = [] 
    
    for S in context.training_stocks:
        recent_prices = history(context.history_range, '1d', 'price')[S].values
        recent_lows   = history(context.history_range, '1d', 'low')[S].values
        recent_highs  = history(context.history_range, '1d', 'high')[S].values
        recent_closes = history(context.history_range, '1d', 'close_price')[S].values

        atr = talib.ATR(recent_highs, recent_lows, recent_closes, timeperiod=14)
        prev_close = np.roll(recent_closes, 2)
        upside_signal = (recent_prices - (prev_close + atr)).tolist()
        downside_signal = (prev_close - (recent_prices + atr)).tolist()
        price_changes = np.diff(recent_prices).tolist()
        upper, middle, lower = talib.BBANDS(recent_prices,timeperiod=10,nbdevup=2,nbdevdn=2,matype=1)
        upper = upper.tolist()
        middle = middle.tolist()
        lower = lower.tolist()
   
        for i in range(15, context.history_range-context.lookback-1):
            Z = price_changes[i:i+context.lookback] + upside_signal[i:i+context.lookback] + downside_signal[i:i+context.lookback] +\
                upper[i:i+context.lookback] + middle[i:i+context.lookback] + lower[i:i+context.lookback] 
                
            if (np.any(np.isnan(Z)) or not np.all(np.isfinite(Z))): continue

            X.append(Z)

            if abs(price_changes[i+context.lookback]) > abs(price_changes[i]*(1+context.percentage_change)):
                if price_changes[i+context.lookback] > 0:
                    Y.append(+1)
                else:
                    Y.append(-1)
            else:
                Y.append(0)

    context.model.fit(X, Y) 
Example #14
Source File: boll.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def handle_bar(context, bar_dict):
    prices = history_bars(context.algoInfo, context.SHORTPERIOD+1, '1d', 'close')
    max_price = max(prices)
    min_price = min(prices)

    print(type(prices))

    print(str(max_price) + ":" + str(min_price))

    upperband, middleband, lowerband = talib.BBANDS(prices, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)

    # plot("upperband", upperband[-1])
    # plot("middleband", middleband[-1])
    # plot("lowerband", lowerband[-1])
    # plot("close", prices[-1])

    cha = (max_price - min_price) / (upperband[-1] - lowerband[-1])
    plot("cha", cha)

    # cur_position = context.portfolio.positions[context.algoInfo].quantity
    #
    # shares = context.portfolio.cash/bar_dict[context.algoInfo].close
    #
    # if short_avg[-1] > prices[-1] and short_avg[-2] < prices[-2] and cur_position > 0:
    #     order_target_value(context.algoInfo, 0)
    #
    # if short_avg[-1] < prices[-1] > 0 and short_avg[-2] > prices[-2]:
    #     order_shares(context.algoInfo, shares) 
Example #15
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def BBANDS(series, n=5, devup=2., devdn=2., matype=0):
    return _series_to_frame(series, ['UpperBand', 'MiddleBand', 'LowerBand'], talib.BBANDS, n, devup, devdn, matype) 
Example #16
Source File: test_indicator_volatility.py    From pandas-ta with MIT License 5 votes vote down vote up
def test_bbands(self):
        result = pandas_ta.bbands(self.close)
        self.assertIsInstance(result, DataFrame)
        self.assertEqual(result.name, 'BBANDS_5')

        try:
            expected = tal.BBANDS(self.close)
            expecteddf = DataFrame({'BBL_5': expected[0], 'BBM_5': expected[1], 'BBU_5': expected[2]})
            pdt.assert_frame_equal(result, expecteddf)
        except AssertionError as ae:
            try:
                bbl_corr = pandas_ta.utils.df_error_analysis(result.iloc[:,0], expecteddf.iloc[:,0], col=CORRELATION)
                self.assertGreater(bbl_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:,0], CORRELATION, ex)

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

            try:
                bbu_corr = pandas_ta.utils.df_error_analysis(result.iloc[:,2], expecteddf.iloc[:,2], col=CORRELATION)
                self.assertGreater(bbu_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:,2], CORRELATION, ex, newline=False) 
Example #17
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def BBANDS(data, **kwargs):
    _check_talib_presence()
    prices = _extract_series(data)
    return talib.BBANDS(prices, **kwargs) 
Example #18
Source File: SpdTrade1.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def handle_data(context):
    prc_lst1 = Close(code1, bt, bi)
    prc_lst2 = Close(code2, bt, bi)
    if len(prc_lst1) == 0 or len(prc_lst2) == 0:
        return

    # 生成价差序列
    global spds
    spd_c = prc_lst1[-1] - prc_lst2[-1]
    if len(prc_lst1) > len(spds):
        spds.append(spd_c)
    else:
        spds[-1] = spd_c

    if len(spds) < p1:
        return
    
    # 计算价差布林通道
    upp, mid, low = talib.BBANDS(np.array(spds), p1, 2, 2)     

    # 突破追单
    if spd_c < upp[-1] and MarketPosition(code1) <= 0:
        Buy(qty, prc_lst1[-1], code1)
        SellShort(qty, prc_lst2[-1], code2)
    elif spd_c > low[-1] and MarketPosition(code1) >= 0:
        SellShort(qty, prc_lst1[-1], code1)
        Buy(qty, prc_lst2[-1], code2)
    
    # 绘制指标线
    PlotNumeric("prc", spd_c, 0x000000, False)
    PlotNumeric('upp', upp[-1], RGB_Red(), False)
    PlotNumeric('mid', mid[-1], RGB_Blue(), False)
    PlotNumeric('low', low[-1], RGB_Green(), False) 
    PlotNumeric("fit", NetProfit() - TradeCost(), RGB_Purple(), False, True) 
Example #19
Source File: features.py    From trading-server with GNU General Public License v3.0 5 votes vote down vote up
def BB(self, bars, period: int):
        """
        Return top, bottom and mid Bollinger Bands for n bars close price.

        It is assumed that:
        -- Bollinger Bands are desired at 2 standard deviation's from the mean.
        -- moving average used is a simple moving average
        """

        self.check_bars_type(bars)

        upperband, middleband, lowerband = ta.BBANDS(
            close, timeperiod=period, nbdevup=2, nbdevdn=2, matype=0)

        return upperband, middleband, lowerband 
Example #20
Source File: test_reg.py    From finta with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bbands():
    '''test TA.BBANDS'''

    bb = TA.BBANDS(ohlc, 20)
    talib_bb = talib.BBANDS(ohlc['close'], timeperiod=20)

    # assert int(bb['BB_UPPER'][-1]) == int(talib_bb[0].values[-1])
    # assert 8212 == 8184

    # assert int(bb['BB_LOWER'][-1]) == int(talib_bb[2].values[-1])
    # assert 6008 == 6036

    pass  # close enough 
Example #21
Source File: ctaLineBar.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def __recountBoll(self):
        """布林特线"""
        if self.inputBollLen < EMPTY_INT: return

        l = len(self.lineBar)

        if l < min(7, self.inputBollLen)+1:
            self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算Boll需要:{1}'.
                             format(len(self.lineBar), min(7, self.inputBollLen)+1))
            return

        if l < self.inputBollLen+2:
            bollLen = l-1
        else:
            bollLen = self.inputBollLen

        # 不包含当前最新的Bar
        listClose=[x.close for x in self.lineBar[-bollLen - 1:-1]]
        #
        upper, middle, lower = ta.BBANDS(numpy.array(listClose, dtype=float),
                                         timeperiod=bollLen, nbdevup=self.inputBollStdRate,
                                         nbdevdn=self.inputBollStdRate, matype=0)

        self.lineUpperBand.append(upper[-1])
        self.lineMiddleBand.append(middle[-1])
        self.lineLowerBand.append(lower[-1])


    # ---------------------------------------------------------------------- 
Example #22
Source File: test_technical.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def expected_bbands(self, window_length, k, closes):
        """Compute the expected data (without adjustments) for the given
        window, k, and closes array.

        This uses talib.BBANDS to generate the expected data.
        """
        lower_cols = []
        middle_cols = []
        upper_cols = []

        ndates, nassets = closes.shape

        for n in range(nassets):
            close_col = closes[:, n]
            if np.isnan(close_col).all():
                # ta-lib doesn't deal well with all nans.
                upper, middle, lower = [np.full(ndates, np.nan)] * 3
            else:
                upper, middle, lower = talib.BBANDS(
                    close_col,
                    window_length,
                    k,
                    k,
                )

            upper_cols.append(upper)
            middle_cols.append(middle)
            lower_cols.append(lower)

        # Stack all of our uppers, middles, lowers into three 2d arrays
        # whose columns are the sids. After that, slice off only the
        # rows we care about.
        where = np.s_[window_length - 1:]
        uppers = np.column_stack(upper_cols)[where]
        middles = np.column_stack(middle_cols)[where]
        lowers = np.column_stack(lower_cols)[where]
        return uppers, middles, lowers 
Example #23
Source File: bollinger_bands.py    From jesse with MIT License 5 votes vote down vote up
def bollinger_bands(candles: np.ndarray, period=20, devup=2, devdn=2, matype=0, source_type="close",
                    sequential=False) -> BollingerBands:
    """
    BBANDS - Bollinger Bands

    :param candles: np.ndarray
    :param period: int - default: 20
    :param devup: float - default: 2
    :param devdn: float - default: 2
    :param matype: int - default: 0
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

    :return: BollingerBands(upperband, middleband, lowerband)
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    source = get_candle_source(candles, source_type=source_type)
    upperbands, middlebands, lowerbands = talib.BBANDS(source, timeperiod=period, nbdevup=devup, nbdevdn=devdn,
                                                       matype=matype)

    if sequential:
        return BollingerBands(upperbands, middlebands, lowerbands)
    else:
        return BollingerBands(upperbands[-1], middlebands[-1], lowerbands[-1]) 
Example #24
Source File: ctaLineBar.py    From chanlun with MIT License 5 votes vote down vote up
def __recountBoll(self):
        """布林特线"""
        if self.inputBollLen < EMPTY_INT: return

        l = len(self.lineBar)

        if l < min(7, self.inputBollLen)+1:
            self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算Boll需要:{1}'.
                             format(len(self.lineBar), min(7, self.inputBollLen)+1))
            return

        if l < self.inputBollLen+2:
            bollLen = l-1
        else:
            bollLen = self.inputBollLen

        # 不包含当前最新的Bar
        listClose=[x.close for x in self.lineBar[-bollLen - 1:-1]]
        #
        upper, middle, lower = ta.BBANDS(numpy.array(listClose, dtype=float),
                                         timeperiod=bollLen, nbdevup=self.inputBollStdRate,
                                         nbdevdn=self.inputBollStdRate, matype=0)

        self.lineUpperBand.append(upper[-1])
        self.lineMiddleBand.append(middle[-1])
        self.lineLowerBand.append(lower[-1])


    # ---------------------------------------------------------------------- 
Example #25
Source File: ta.py    From dash-technical-charting with MIT License 5 votes vote down vote up
def add_BBANDS(self, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0,
               types=['line_dashed_thin', 'line_dashed_thin'],
               colors=['tertiary', 'grey_strong'], **kwargs):
    """Bollinger Bands.

    Note that the first argument of types and colors refers to upper and lower
    bands while second argument refers to middle band. (Upper and lower are
    symmetrical arguments, hence only 2 needed.)

    """
    if not 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 = 'BBANDS({},{},{})'.format(str(timeperiod),
                                     str(nbdevup),
                                     str(nbdevdn))
    ubb = name + '[Upper]'
    bb = name
    lbb = name + '[Lower]'
    self.pri[ubb] = dict(type='line_' + types[0][5:],
                         color=colors[0])
    self.pri[bb] = dict(type='area_' + types[1][5:],
                        color=colors[1], fillcolor='fill')
    self.pri[lbb] = dict(type='area_' + types[0][5:],
                         color=colors[0], fillcolor='fill')
    (self.ind[ubb],
     self.ind[bb],
     self.ind[lbb]) = talib.BBANDS(self.df[self.cl].values,
                                   timeperiod, nbdevup, nbdevdn, matype) 
Example #26
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def results(self, data_frame):
        try:
            upper, middle, lower = talib.BBANDS(data_frame[self.data].values,
                                                self.period,
                                                self.devup,
                                                self.devdown,
                                                matype=self.ma_type)
            data_frame[self.upper] = upper
            data_frame[self.middle] = middle
            data_frame[self.lower] = lower
        except KeyError:
            data_frame[self.upper] = np.nan
            data_frame[self.middle] = np.nan
            data_frame[self.lower] = np.nan 
Example #27
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def boll(self, sym, frequency, period=5, nbdev_up=2, nbdev_down=2, ma_type=0):
        if not self.kbars_ready(sym, frequency):
            return [],[],[]

        closes = self.close(sym, frequency)

        upperband, middleband, lowerband = ta.BBANDS(closes, timeperiod=period,
                                                     nbdevup=nbdev_up, nbdevdn=nbdev_down, matype=ma_type)

        return upperband, middleband, lowerband 
Example #28
Source File: talib_series.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def BBANDS(Series, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0):
    up, middle, low = talib.BBANDS(
        Series.values, timeperiod, nbdevup, nbdevdn, matype)
    return pd.Series(up, index=Series.index), pd.Series(middle, index=Series.index), pd.Series(low, index=Series.index) 
Example #29
Source File: IndicatorSubsystem.py    From cbpro-trader with GNU General Public License v3.0 5 votes vote down vote up
def calculate_bbands(self, period_name, close):
        timeperiod = 20
        upperband_1, middleband_1, lowerband_1 = talib.BBANDS(close, timeperiod=timeperiod, nbdevup=1, nbdevdn=1, matype=0)

        self.current_indicators[period_name]['bband_upper_1'] = upperband_1[-1]
        self.current_indicators[period_name]['bband_lower_1'] = lowerband_1[-1]

        upperband_2, middleband_2, lowerband_2 = talib.BBANDS(close, timeperiod=timeperiod, nbdevup=2, nbdevdn=2, matype=0)

        self.current_indicators[period_name]['bband_upper_2'] = upperband_2[-1]
        self.current_indicators[period_name]['bband_lower_2'] = lowerband_2[-1] 
Example #30
Source File: ctaLineBar.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __recountBoll(self):
        """布林特线"""
        if self.inputBollLen < EMPTY_INT: return

        l = len(self.lineBar)

        if l < min(7, self.inputBollLen)+1:
            self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算Boll需要:{1}'.
                             format(len(self.lineBar), min(7, self.inputBollLen)+1))
            return

        if l < self.inputBollLen+2:
            bollLen = l-1
        else:
            bollLen = self.inputBollLen

        # 不包含当前最新的Bar
        listClose=[x.close for x in self.lineBar[-bollLen - 1:-1]]
        #
        upper, middle, lower = ta.BBANDS(numpy.array(listClose, dtype=float),
                                         timeperiod=bollLen, nbdevup=self.inputBollStdRate,
                                         nbdevdn=self.inputBollStdRate, matype=0)

        self.lineUpperBand.append(upper[-1])
        self.lineMiddleBand.append(middle[-1])
        self.lineLowerBand.append(lower[-1])


    # ----------------------------------------------------------------------