Python talib.SAR Examples

The following are 15 code examples of talib.SAR(). 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: ta.py    From dash-technical-charting with MIT License 8 votes vote down vote up
def add_SAR(self, acceleration=0.02, maximum=0.20,
            type='scatter', color='tertiary', **kwargs):
    """Parabolic SAR."""

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

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

    name = 'SAR({},{})'.format(str(acceleration), str(maximum))
    self.pri[name] = dict(type=type, color=color)
    self.ind[name] = talib.SAR(self.df[self.hi].values,
                               self.df[self.lo].values,
                               acceleration, maximum) 
Example #2
Source File: talib_indicators.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def SAR(DataFrame, acceleration=0, maximum=0):
    res = talib.SAR(DataFrame.high.values, DataFrame.low.values, acceleration, maximum)
    return pd.DataFrame({'SAR': res}, index=DataFrame.index) 
Example #3
Source File: ta.py    From dash-technical-charting with MIT License 6 votes vote down vote up
def add_SAREXT(self, startvalue=0, offsetonreverse=0,
               accelerationinitlong=0.02, accelerationlong=0.02,
               accelerationmaxlong=0.20, accelerationinitshort=0.02,
               accelerationshort=0.02, accelerationmaxshort=0.20,
               type='scatter', color='tertiary', **kwargs):
    """Parabolic SAR Extended."""

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

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

    name = ('SAREXT({},{},{},{},'
            '{},{},{},{})'.format(str(startvalue), str(offsetonreverse),
                                  str(accelerationinitlong),
                                  str(accelerationlong),
                                  str(accelerationmaxlong),
                                  str(accelerationinitshort),
                                  str(accelerationshort),
                                  str(accelerationmaxshort)))
    self.pri[name] = dict(type=type, color=color)
    self.ind[name] = talib.SAREXT(self.df[self.hi].values,
                                  self.df[self.lo].values,
                                  startvalue, offsetonreverse,
                                  accelerationinitlong,
                                  accelerationlong,
                                  accelerationmaxlong,
                                  accelerationinitshort,
                                  accelerationshort,
                                  accelerationmaxshort)
    self.ind[name] = self.ind[name].abs()  # Bug right now with negative value


# Momentum indicators 
Example #4
Source File: sar.py    From jesse with MIT License 6 votes vote down vote up
def sar(candles: np.ndarray, acceleration=0.02, maximum=0.2, sequential=False) -> Union[float, np.ndarray]:
    """
    SAR - Parabolic SAR

    :param candles: np.ndarray
    :param acceleration: float - default: 0.02
    :param maximum: float - default: 0.2
    :param sequential: bool - default=False

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

    res = talib.SAR(candles[:, 3], candles[:, 4], acceleration=acceleration, maximum=maximum)

    return res if sequential else res[-1] 
Example #5
Source File: ADXSAR.py    From Rqalpha-myquant-learning with Apache License 2.0 6 votes vote down vote up
def before_trading(context):
    prices = history_bars(context.s1, context.window, '1d', fields=['high', 'low', 'close', 'open'])
    highP = prices['high']
    lowP = prices['low']
    closeP = prices['close']
    openP = prices['open']

    context.ADX = ta.ADXR(highP, lowP, closeP, timeperiod=14)
    context.Pdi = ta.PLUS_DI(highP, lowP, closeP, timeperiod=14)
    context.Ndi = ta.MINUS_DI(highP, lowP, closeP, timeperiod=14)

    context.MA_tw = ta.MA(closeP, timeperiod=20)[-5:]
    context.MA_fi = ta.MA(closeP, timeperiod=50)[-5:]
    context.MA_fork = context.MA_tw > context.MA_fi

    context.SAR = ta.SAR(highP, lowP, acceleration=context.acceleration, maximum=0.2)

    # context.JQ_selOpen = (context.ADX[-1]>=20) #& (context.ADX[-2]>=20) & (context.ADX[-1]<=30) & (context.ADX[-2]<=30)
    context.JW_selOpen = (context.Pdi[-1] <= context.Ndi[-1]) & (context.Pdi[-2] >= context.Ndi[-2])
    context.JE_selOpen = (context.MA_fork[-1]) & (context.MA_fork[-2]) & (not context.MA_fork[-3])
    context.JR_selOpen = (context.SAR[-1] >= 0.95 * openP[-1]) & (context.SAR[-2] <= 1.05 * closeP[-2])
    context.J_selOpen = context.JQ_selOpen & context.JW_selOpen & context.JE_selOpen & context.JR_selOpen

    # context.JQ_buyOpen = context.JQ_selOpen
    context.JW_buyOpen = (context.Pdi[-1] >= context.Ndi[-1]) & (context.Pdi[-2] <= context.Ndi[-2])
    context.JE_buyOpen = (not context.MA_fork[-1]) & (not context.MA_fork[-2]) & (not context.MA_fork[-3])
    context.JR_buyOpen = (context.SAR[-2] >= 0.95 * openP[-2]) & (context.SAR[-1] <= 1.05 * closeP[-1])
    context.J_buyOpen = context.JQ_buyOpen & context.JW_buyOpen & context.JE_buyOpen & context.JR_buyOpen


# 你选择的期货数据更新将会触发此段逻辑,例如日线或分钟线更新 
Example #6
Source File: test_indicator_trend.py    From pandas-ta with MIT License 6 votes vote down vote up
def test_psar(self):
        result = pandas_ta.psar(self.high, self.low)
        self.assertIsInstance(result, DataFrame)
        self.assertEqual(result.name, 'PSAR_0.02_0.2')

        # Combine Long and Short SAR's into one SAR value
        psar = result[result.columns[:2]].fillna(0)
        psar = psar[psar.columns[0]] + psar[psar.columns[1]]
        psar.name = result.name

        try:
            expected = tal.SAR(self.high, self.low)
            pdt.assert_series_equal(psar, expected)
        except AssertionError as ae:
            try:
                psar_corr = pandas_ta.utils.df_error_analysis(psar, expected, col=CORRELATION)
                self.assertGreater(psar_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(psar, CORRELATION, ex) 
Example #7
Source File: TestSAR.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def handle_data(context):
    global mySAR, OParCl2,OParOp2,OPosition2,OTRansition2
    afStep  = runsVar / 100 
    afLimit = afStep  * 10
    sar = talib.SAR(High(), Low(), afStep,afLimit)

    OParCl, OParOp, OPosition, OTRansition = ParabolicSAR(High(), Low(), afStep, afLimit)

    #OParCl2[-1], OParOp2[-1], OPosition2[-1], OTRansition2[-1] = mySAR.U_SAR(High(), Low(), afStep, afLimit)
    OParCl3, OParOp3, OPosition3, OTRansition3 = mySAR.U_SAR(High(), Low(), afStep, afLimit)
    
    #LogInfo("SAR", Date(), Time(), sar[-1], OParCl[-1])
    PlotNumeric("SAR", sar[-1])
    PlotNumeric("ESAR", OParCl[-1], color=RGB_Blue())
    PlotNumeric("USAR", OParCl3, color=RGB_Green())
    #LogInfo("BBBB:", Date(), Time(), High()[-1], Low()[-1], sar[-1], OParCl[-1], OParCl3)
    #LogInfo("AAAA:", Date(), Time(), OParCl[-1], OParOp[-1], OPosition[-1], OTRansition[-1]) 
Example #8
Source File: IndicatorSubsystem.py    From cbpro-trader with GNU General Public License v3.0 5 votes vote down vote up
def calculate_sar(self, period_name, highs, lows):
        sar = talib.SAR(highs, lows)

        self.current_indicators[period_name]['sar'] = sar[-1] 
Example #9
Source File: talib_indicators.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def DX(DataFrame, N=14):
    res = talib.DX(DataFrame.high.values, DataFrame.low.values, DataFrame.close.values, N)
    return pd.DataFrame({'DX': res}, index=DataFrame.index)


# SAR - Parabolic SAR 
Example #10
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def sar(self, sym, frequency, *args, **kwargs):
        if not self.kbars_ready(sym, frequency):
            return []

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

        return ta.SAR(highs, lows, *args, **kwargs) 
Example #11
Source File: __init__.py    From ebisu with MIT License 5 votes vote down vote up
def sar(high, low, acceleration=0, maximum=0):
    return talib.SAR(high, low, acceleration, maximum) 
Example #12
Source File: test_reg.py    From finta with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_sar():
    """test TA.SAR"""

    sar = TA.SAR(ohlc)
    talib_sar = talib.SAR(ohlc.high, ohlc.low)

    # assert sar.values[-1] == talib_sar.values[-1]
    # 1466.88618052864 == 1468.3663877395456
    # close enough
    pass 
Example #13
Source File: ADXSAR.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def init(context):
    # context内引入全局变量:沪深主力连续合约(偷懒直接用米筐主力了。。。)
    context.s1 = "IF88"

    context.window = 80

    context.selOpen_Flag = False
    context.buyOpen_Flag = False

    # 据说SAR的使用需要根据势头改变大小哈,
    context.acceleration = 0.05

    # 初始化时订阅合约行情。订阅之后的合约行情会在handle_bar中进行更新。
    subscribe(context.s1)

    # 判断指标(搓键盘方便,无实际意义)
    context.JQ_selOpen = False
    context.JW_selOpen = False
    context.JE_selOpen = False
    context.JR_selOpen = False
    context.JQ_buyOpen = False
    context.JW_buyOpen = False
    context.JE_buyOpen = False
    context.JR_buyOpen = False
    context.JQ_selClos = False
    context.JW_selClos = False
    context.JE_selClos = False
    context.JR_selClos = False
    context.JQ_buyClos = False
    context.JW_buyClos = False
    context.JE_buyClos = False
    context.JR_buyClos = False

    scheduler.run_weekly(ADX, weekday=5) 
Example #14
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def SAR(frame, acc_fator=.02, max_acc_factor=.2, high_col='high', low_col='low'):
    return _frame_to_series(frame, [high_col, low_col], talib.SAR, acc_fator, max_acc_factor) 
Example #15
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def SAR(data, **kwargs):
    _check_talib_presence()
    _, phigh, plow, _, _ = _extract_ohlc(data)
    return talib.SAR(phigh, plow, **kwargs)