示例#1
0
    def ADX5_AROON(self, df):
        adx5_exLevel = 95
        adx5_brLevel = 10

        df.drop(df.last_valid_index(), axis=0, inplace=True)

        df['PLUS_DI'] = talib.PLUS_DI(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=5)
        df['MINUS_DI'] = talib.MINUS_DI(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=5)
        df['ADX5'] = talib.ADX(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=5)
        df['ARDN'], df['ARUP'] = talib.AROON(df['High'].values, df['Low'].values, timeperiod=10)

        df['ADX5SHIFTED'] = df['ADX5'].shift(1)
        df['ARDNSHIFTED'] = df['ARDN'].shift(1)
        df['ARUPSHIFTED'] = df['ARUP'].shift(1)

        columns = ['PLUS_DI', 'MINUS_DI', 'ADX5', 'AROONDN', 'AROONUP', 'ADX5SHIFTED', 'ARDNSHIFTED', 'ARUPSHIFTED']

        def adx5_aroon_cond(row, columns):
            df1_adx5_cond = (row['ADX5'] > row['ADX5SHIFTED']) & (row['ADX5'] > adx5_brLevel) & (
                        row['ADX5'] < adx5_exLevel)
            arbuy = (row['ARUPSHIFTED'] < 5) & (row['ARUP'] > 85) & (row['ARUP'] > row['ARDN'])
            arsell = (row['ARDNSHIFTED'] < 5) & (row['ARDN'] > 85) & (row['ARUP'] < row['ARDN'])
            buy = (row['PLUS_DI'] > row['MINUS_DI']) & df1_adx5_cond & arbuy
            sell = (row['PLUS_DI'] < row['MINUS_DI']) & df1_adx5_cond & arsell
            return buy, sell

        df['BUY'], df['SELL'] = zip(*df.apply(lambda row: adx5_aroon_cond(row, columns), axis=1))

        df2 = df.tail(self.withinBars)
        df2['BUY'].any()
        df2['SELL'].any()

        #return [df['SELL'].iloc[-1], df['BUY'].iloc[-1], df['normal_time']]
        return [df2['SELL'].any(), df2['BUY'].any(), df['normal_time']]
示例#2
0
def add_AROON(self,
              timeperiod=14,
              types=['line', 'line'],
              colors=['increasing', 'decreasing'],
              **kwargs):
    """Aroon indicators.

    Note that the first argument of types and colors refers to Aroon up while
    the second argument refers to Aroon down.

    """
    if not (self.has_high and self.has_low):
        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 = 'AROON({})'.format(str(timeperiod))
    uaroon = name + ' [Up]'
    daroon = name + ' [Dn]'
    self.sec[uaroon] = dict(type=types[0], color=colors[0])
    self.sec[daroon] = dict(type=types[1], color=colors[1], on=uaroon)
    self.ind[uaroon], self.ind[daroon] = talib.AROON(self.df[self.hi].values,
                                                     self.df[self.lo].values,
                                                     timeperiod)
示例#3
0
def getMomentumIndicators(df):

    high = df['High']
    low = df['Low']
    close = df['Close']
    open = df['Open']
    volume = df['Volume']
    df['ADX'] = ta.ADX(high, low, close, timeperiod=14)
    df['SMA'] = ta.ADXR(high, low, close, timeperiod=14)
    df['APO'] = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
    df['AROONDOWN'], df['AROOONUP'] = ta.AROON(high, low, timeperiod=14)
    df['AROONOSC'] = ta.AROONOSC(high, low, timeperiod=14)
    df['BOP'] = ta.BOP(open, high, low, close)
    df['CCI'] = ta.CCI(high, low, close, timeperiod=14)
    df['CMO'] = ta.CMO(close, timeperiod=14)
    df['DX'] = ta.DX(high, low, close, timeperiod=14)
    df['MACD'], df['MACDSIGNAL'], df['MACDHIST'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
    df['MFI'] = ta.MFI(high, low, close, volume, timeperiod=14)
    df['MINUS_DI'] = ta.MINUS_DI(high, low, close, timeperiod=14)
    df['MINUS_DM']= ta.MINUS_DM(high, low, timeperiod=14)
    df['MOM'] = ta.MOM(close, timeperiod=10)
    df['PLUS_DM'] =ta.PLUS_DM(high, low, timeperiod=14)
    df['PPO'] = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
    df['ROC'] = ta.ROC(close, timeperiod=10)
    df['ROCP'] = ta.ROCP(close, timeperiod=10)
    df['ROCR'] = ta.ROCR(close, timeperiod=10)
    df['ROCR100'] = ta.ROCR100(close, timeperiod=10)
    df['RSI'] = ta.RSI(close, timeperiod=14)
    df['SLOWK'], df['SLOWD'] = ta.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
    df['FASTK'], df['FASTD'] = ta.STOCHF(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0)
    df['FASTK2'], df['FASTD2'] = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
    df['TRIX'] = ta.TRIX(close, timeperiod=30)
    df['ULTOSC'] = ta.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28)
    df['WILLR'] = ta.WILLR(high, low, close, timeperiod=14)
示例#4
0
def calculate_indicators(data):

    close = data['Close'].values
    high = data['High'].values
    low = data['Low'].values
    data['upB'], data['midB'], data['lowB'] = talib.BBANDS(close,
                                                           timeperiod=20,
                                                           nbdevup=2,
                                                           nbdevdn=2,
                                                           matype=0)
    data['RSI'] = talib.RSI(close, timeperiod=10)
    data['K'], d = talib.STOCH(high,
                               low,
                               close,
                               fastk_period=14,
                               slowk_period=14,
                               slowk_matype=0,
                               slowd_period=3,
                               slowd_matype=0)
    macd, macdsignal, data['MACD'] = talib.MACD(close,
                                                fastperiod=12,
                                                slowperiod=26,
                                                signalperiod=9)

    data['EMA'] = talib.EMA(close, timeperiod=30)
    data['ADX'] = talib.ADX(high, low, close, timeperiod=14)
    data['AroonUp'], data['AroonDown'] = talib.AROON(high, low, timeperiod=14)
    data['diff'] = data['High'] - data['Low']

    return data
示例#5
0
def get_stock_data(ticker, start_date, end_date):

    print(end_date, type(ticker))
    data = nse.get_history(symbol=ticker, start=start_date,
                           end= end_date)
    #data = nse.get_history(symbol= ticker, start=start_date, end= end_date)

    data = data.drop(['Prev Close','Symbol', 'Series', 'Deliverable Volume', '%Deliverble', 'Trades', 'Last'], axis = 1)

    close = data['Close'].values
    high = data['High'].values
    low = data['Low'].values

    #Computing technical indicators
    data['upB'], data['midB'], data['lowB'] = talib.BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
    data['RSI'] = talib.RSI(close, timeperiod=10)
    data['K'], d = talib.STOCH(high, low, close, fastk_period=14, slowk_period=14, slowk_matype=0, slowd_period=3,
                               slowd_matype=0)
    macd, macdsignal, data['MACD'] = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)

    data['EMA'] = talib.EMA(close, timeperiod=30)
    data['ADX'] = talib.ADX(high, low, close, timeperiod=14)
    data['AroonUp'], data['AroonDown'] = talib.AROON(high, low, timeperiod=14)
    data['diff'] = data['High'] - data['Low']
    data = data.dropna()


    #saving as a csv file
    data.to_csv('stock_prices' + str(ticker) + '.csv', index=False)
示例#6
0
	def momentum(self):
		adx = talib.ADX(self.high,self.low,self.close,self.period)
		adxr = talib.ADXR(self.high,self.low,self.close,self.period)
		apo = talib.APO(self.high,self.low,self.close,self.period)
		aroondown, aroonup = talib.AROON(self.high, self.low, period)
		aroonosc = talib.AROONOSC(self.high,self.low,self.period)
		bop  = talib.BOP(self.opens,self.high,self.low,self.close)
		cci = talib.CCI(self.high,self.low,self.close,self.period)
		cmo = talib.CMO(self.close,self.period)
		dx = talib.DX(self.high,self.low,self.close,self.period)
		macd, macdsignal, macdhist = talib.MACD(self.close, fastperiod=period, slowperiod=period*5, signalperiod=period*2)
		macd1, macdsignal1, macdhist1 = talib.MACDEXT(self.close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
		macd2, macdsignal2, macdhist2 = talib.MACDFIX(self.close, signalperiod=9)
		mfi = talib.MFI(self.high, self.low, self.close, self.volume, timeperiod=14)
		minus_di = talib.MINUS_DI(self.high, self.low, self.close, timeperiod=14)
		minus_dm = talib.MINUS_DM(self.high, self.low, timeperiod=14)
		mom = talib.MOM(self.close, timeperiod=10)
		plus_di = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=14)
		plus_dm = talib.PLUS_DM(self.high, self.low, timeperiod=14)
		ppo  = talib.PPO(self.close, fastperiod=12, slowperiod=26, matype=0)
		roc  = talib.ROC(self.close, timeperiod=10)
		rocp = talib.ROCP(self.close, timeperiod=10)
		rocr = talib.ROCR(self.close, timeperiod=10)
		rocr100 = talib.ROCR100(self.close, timeperiod=10)
		rsi =  talib.RSI(self.close, timeperiod=14)
		slowk, slowd = talib.STOCH(self.high, self.low, self.close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
		fastk, fastd = talib.STOCHF(self.high, self.low, self.close, fastk_period=5, fastd_period=3, fastd_matype=0)
		fastk1, fastd1 = talib.STOCHRSI(self.close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
		trix = talib.TRIX(self.close, timeperiod=30)
		ultosc = talib.ULTOSC(self.high, self.low, self.close, timeperiod1=7, timeperiod2=14, timeperiod3=28)
		willr = talib.WILLR(self.high, self.low, self.close, timeperiod=14)
示例#7
0
文件: tbh.1.py 项目: tahmi123/trader
    def put(self):
        """Method to check put pattern."""
        logger = logging.getLogger("__main__")
        candles = self.candles

        if hasattr(candles, 'candles_array'):
            candel_array = candles.candles_array
            close = pd.Series([candle.candle_close for candle in candel_array])
            open = pd.Series([candle.candle_open for candle in candel_array])
            high = pd.Series([candle.candle_high for candle in candel_array])
            low = pd.Series([candle.candle_low for candle in candel_array])
            up, lw, MA = talib.BBANDS(close, matype=MA_Type.T3)
            rsi14 = talib.RSI(close, timeperiod=14)
            sigs = trendy.iterlines(close,
                                    open,
                                    high,
                                    low,
                                    window=1 / 3.0,
                                    charts=False)

            # K, D = self.stoc_occilator(candles=candles)
            aroon_up, aroon_down = talib.AROON(high, low, timeperiod=3)

            # loaded_model = pickle.load(open('finalized_model.sav', 'rb'))
            # predicted_price = loaded_model.predict([[up[26] - candles.first_candle.candle_close, lw[26] - candles.first_candle.candle_close, candles.first_candle.candle_height - candles.second_candle.candle_height, rsi14[28], K[28], D[28], aroon_up[29], aroon_down[29]]])

            if candles.current_candle.candle_close > candles.current_candle.candle_open:  #candles.current_candle.candle_close > MA[27] and candles.current_candle.candle_open < MA[27] and aroon_up[27]==0 and aroon_up[27]==0:

                return True
示例#8
0
    def on_bar(self, bars):
        high = self.source_preference + '_high'
        low = self.source_preference + '_low'

        bars['up'], bars['down'] = talib.AROON(bars[high].values,
                                               bars[low].values, self.period)
        return bars
示例#9
0
def AROON(DF,N=20):
    H = DF['high']
    L = DF['low']
    AD,AP = ta.AROON(H.values,L.values,N)
    AR = AP - AD
    VAR = pd.DataFrame({'AROON': AR, 'AROON_UP': AP, 'AROON_DOWN': AD}, index=H.index.values)
    return VAR
示例#10
0
文件: ta.py 项目: a1sc/py-quantmod
def add_AROON(
    self,
    timeperiod=14,
    types=["line", "line"],
    colors=["increasing", "decreasing"],
    **kwargs
):
    """Aroon indicators.

    Note that the first argument of types and colors refers to Aroon up while
    the second argument refers to Aroon down.

    """
    if not (self.has_high and self.has_low):
        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 = "AROON({})".format(str(timeperiod))
    uaroon = name + " [Up]"
    daroon = name + " [Dn]"
    self.sec[uaroon] = dict(type=types[0], color=colors[0])
    self.sec[daroon] = dict(type=types[1], color=colors[1], on=uaroon)
    self.ind[uaroon], self.ind[daroon] = talib.AROON(
        self.df[self.hi].values, self.df[self.lo].values, timeperiod
    )
def AROON(raw_df, timeperiod=14):
    # extract necessary data from raw dataframe (high, low)
    # this function returns two columns of data
    aroondown, aroonup = ta.AROON(raw_df.High.values, raw_df.Low.values,
                                  timeperiod)
    singleMerged = np.stack((aroondown, aroonup), axis=-1)
    return singleMerged.tolist()
示例#12
0
 def aroon():
     for i in range(len(ForexTraderSwitch.curr_pair_list)):
         high=(ForexTraderSwitch.curr_pair_history_data[i]['highAsk'].values+\
               ForexTraderSwitch.curr_pair_history_data[i]['highBid'].values)/2
         low=(ForexTraderSwitch.curr_pair_history_data[i]['lowAsk'].values+\
              ForexTraderSwitch.curr_pair_history_data[i]['lowBid'].values)/2
         #open=(history['openAsk']+history['openBid'])/2
         bull, bear = talib.AROON(high, low, timeperiod=14)
         #print("Bull %s Bear %s" % (bull[-1], bear[-1]))
         ForexTraderSwitch.signal[i, 2] = bear[-2]
         ForexTraderSwitch.signal[i, 3] = bear[-1]
         ForexTraderSwitch.signal[i, 4] = bull[-2]
         ForexTraderSwitch.signal[i, 5] = bull[-1]
         if (bull[-1] > 70 and bear[-1] < 30) or (bull[-2] < bear[-2]
                                                  and bull[-1] >= bear[-1]):
             #trader.create_buy_order(ticker,units)
             ForexTraderSwitch.order[i, 2, 1] = 1
         elif (bull[-1] < 30
               and bear[-1] > 70) or (bull[-2] >= bear[-2]
                                      and bull[-1] < bear[-1]):
             #trader.create_sell_order(ticker,units)
             ForexTraderSwitch.order[i, 2, 2] = 1
         else:
             #print('No trade made')
             ForexTraderSwitch.order[i, 2, 0] = 1
示例#13
0
def AROON(df, n):
    aroondown, aroonup = talib.AROON(df['high'].values,
                                     df['low'].values,
                                     timeperiod=n)
    aroon_dn = pd.Series(aroondown, index=df.index, name="AROONDN_%s" % str(n))
    aroon_up = pd.Series(aroonup, index=df.index, name="AROONUP_%s" % str(n))
    return pd.concat([aroon_up, aroon_dn], join='outer', axis=1)
示例#14
0
def aroon_analyse(ohlcv, period=14):
    high = ohlcv['high']
    low = ohlcv['low']
    adown, aup = talib.AROON(high, low, period)
    df = pd.DataFrame({'aroon_down': adown, 'aroon_up': aup})
    '''当 AroonUp大于AroonDown,并且AroonUp大于50,多头开仓;
    当 AroonUp小于AroonDown,或者AroonUp小于50,多头平仓;
    当 AroonDown大于AroonUp,并且AroonDown大于50,空头开仓;
    当 AroonDown小于AroonUp,或者AroonDown小于50,空头平仓;'''
    def aroon_row(row):
        res = []
        if row['aroon_up'] > row['aroon_down'] and row['aroon_up'] > 50:
            res.append('UP-STRONG')
        elif row['aroon_up'] < row['aroon_down'] or row['aroon_up'] < 50:
            res.append('DN-WEAK')
        elif row['aroon_up'] < row['aroon_down'] or row['aroon_down'] > 50:
            res.append('DN-STRONG')
        elif row['aroon_up'] > row['aroon_down'] or row['aroon_down'] < 50:
            res.append('UP-WEAK')
        else:
            res.append('UNKNOWN')
        return ' '.join(res)

    df['aroon_stage'] = df.apply(aroon_row, axis=1)
    return df
示例#15
0
def aroon(client,
          symbol,
          timeframe="6m",
          highcol="high",
          lowcol="low",
          period=14):
    """This will return a dataframe of
    Aroon
    for the given symbol across the given timeframe

    Args:
        client (pyEX.Client): Client
        symbol (string): Ticker
        timeframe (string): timeframe to use, for pyEX.chart
        highcol (string): column to use to calculate
        lowcol (string): column to use to calculate
        period (int): period to calculate across

    Returns:
        DataFrame: result
    """
    df = client.chartDF(symbol, timeframe)
    aroondown, aroonup = t.AROON(df[highcol].values.astype(float),
                                 df[lowcol].values.astype(float), period)
    return pd.DataFrame({
        highcol: df[highcol].values,
        lowcol: df[lowcol].values,
        "aroonup": aroonup,
        "aroondown": aroondown,
    })
示例#16
0
def add_indicators(df):
    high = df["HA_High"].values
    close = df["HA_Close"].values
    low = df["HA_Low"].values
    _open = df["HA_Open"].values
    volume = df["volume"].values.astype('uint32')

    df["APO"] = talib.APO(close, fastperiod=9, slowperiod=21, matype=0)
    df["APO"] = talib.APO(close, fastperiod=9, slowperiod=21, matype=0)
    df["aroondown"], df["aroonup"] = talib.AROON(high, low, timeperiod=14)
    df["BOP"] = talib.BOP(_open, high, low, close)
    df["CCI"] = talib.CCI(high, low, close, timeperiod=10)
    df["DX"] = talib.DX(high, low, close, timeperiod=10)
    df["MOM"] = talib.MOM(close, timeperiod=10)
    df["slowk"], df["slowd"] = talib.STOCH(high,
                                           low,
                                           close,
                                           fastk_period=5,
                                           slowk_period=3,
                                           slowk_matype=0,
                                           slowd_period=3,
                                           slowd_matype=0)
    df["OBV"] = talib.OBV(close, np.asarray(volume, dtype='float'))
    df["ADOSC"] = talib.ADOSC(high,
                              low,
                              close,
                              np.asarray(volume, dtype='float'),
                              fastperiod=3,
                              slowperiod=10)
    df["upperband"], df["middleband"], df["lowerband"] = talib.BBANDS(
        close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)

    return df
示例#17
0
    def test_aroon(self):
        result = pandas_ta.aroon(self.high, self.low)
        self.assertIsInstance(result, DataFrame)
        self.assertEqual(result.name, "AROON_14")

        try:
            expected = tal.AROON(self.high, self.low)
            expecteddf = DataFrame({
                "AROOND_14": expected[0],
                "AROONU_14": expected[1]
            })
            pdt.assert_frame_equal(result, expecteddf)
        except AssertionError as ae:
            try:
                aroond_corr = pandas_ta.utils.df_error_analysis(
                    result.iloc[:, 0], expecteddf.iloc[:, 0], col=CORRELATION)
                self.assertGreater(aroond_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:, 0], CORRELATION, ex)

            try:
                aroonu_corr = pandas_ta.utils.df_error_analysis(
                    result.iloc[:, 1], expecteddf.iloc[:, 1], col=CORRELATION)
                self.assertGreater(aroonu_corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result.iloc[:, 1],
                               CORRELATION,
                               ex,
                               newline=False)
示例#18
0
def SignalDetection(df, tick, *args):
    """
    This function downloads prices for desired quotes (those in the parameter)
    and then tries to catch signals for selected timeframe.
    Stocks for which we catched a signal are stored in variable "validsymbol"

    :param p1: dataframe of eod data
    :param p2: ticker
    :returns: df with signals
    """

    close = df["Close"].to_numpy()
    high = df["High"].to_numpy()
    low = df["Low"].to_numpy()

    # Aroon
    aroonDOWN, aroonUP = talib.AROON(high=high, low=low,
                                     timeperiod=Aroonval)  ####
    # RSI
    real = talib.RSI(close, timeperiod=14)

    df['RSI'] = real
    df['Aroon Down'] = aroonDOWN
    df['Aroon Up'] = aroonUP
    df['signal'] = pd.Series(np.zeros(len(df)))
    df['signal_aroon'] = pd.Series(np.zeros(len(df)))
    df = df.reset_index()

    # Moving averages
    df['short_mavg'] = df['Close'].rolling(window=short_window,
                                           min_periods=1,
                                           center=False).mean()
    df['long_mavg'] = df['Close'].rolling(window=long_window,
                                          min_periods=1,
                                          center=False).mean()

    # When 'Aroon Up' crosses 'Aroon Down' from below
    df["signal"][short_window:] = np.where(
        df['short_mavg'][short_window:] > df['long_mavg'][short_window:], 1, 0)
    df["signal_aroon"][short_window:] = np.where(
        df['Aroon Down'][short_window:] < df['Aroon Up'][short_window:], 1, 0)

    df['positions'] = df['signal'].diff()
    df['positions_aroon'] = df['signal_aroon'].diff()
    df['positions_aroon'].value_counts()

    # Trend reversal detection
    # Aroon alone doesn't give us enough information.
    # Too many false signals are given
    # We blend moving averages crossing strategy
    df['doubleSignal'] = np.where(
        (df["Aroon Up"] > df["Aroon Down"]) & (df['positions'] == 1) &
        (df["Aroon Down"] < 75) & (df["Aroon Up"] > 55), 1, 0)

    df['symbol'] = tick

    csvAppend(df)

    return df
 def aroon(self, n, array=False):
     """"""
     # Course code
     aroon_up, aroon_down = talib.AROON(self.high, self.low, n)
     if array:
         return aroon_up, aroon_down
     else:
         return aroon_up[-1], aroon_down[-1]
示例#20
0
 def aroon(self, n, array=False):
     """
     AROON.
     """
     aroon_up, aroon_down = talib.AROON(self.high, self.low, n)
     if array:
         return aroon_up, aroon_down
     return aroon_up[-1], aroon_down[-1]
示例#21
0
    def Aroon(self, timeperiod=14):

        aroon = pd.DataFrame()

        aroon['down'], aroon['up'] = ta.AROON(self.data.high,
                                              self.data.low,
                                              timeperiod=14)

        return aroon
示例#22
0
def extract_aroon(data):
    period = long_period
    data['aroon_down'], data['aroon_up'] = ta.AROON(data['high'].values,
                                                    data['low'].values,
                                                    timeperiod=period)
    data['aroon_osc'] = ta.AROONOSC(data['high'].values,
                                    data['low'].values,
                                    timeperiod=period)
    return data
示例#23
0
文件: func.py 项目: Bohr1005/repo
    def aroon(self, n: int, dev: float, array: bool = False):
        """
        Aroon indicator.
        """
        aroon_up, aroon_down = talib.AROON(self.high, self.low, n)

        if array:
            return aroon_up, aroon_down
        return aroon_up[-1], aroon_down[-1]
 def AROON(self, timeperiod=14):
     real_data = np.array([self.df.high, self.df.low], dtype='f8')
     # aroondown, aroonup = talib.AROON(real_data[0], real_data[1], timeperiod=timeperiod)
     # return go.Scatter(
     #     x=self.df.index,
     #     y=aroondown,
     #     name='AROON'
     # )
     return talib.AROON(real_data[0], real_data[1], timeperiod=timeperiod)
示例#25
0
    def aroon(self, sym, frequency, *args, **kwargs):
        if not self.kbars_ready(sym, frequency):
            return []

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

        v = ta.AROON(highs, lows, *args, **kwargs)

        return v
示例#26
0
 def add_indicators_and_disc(self):
     discretizing = 2
     self.data["ADL"] = ta.ADX(self.data["High"].values,
                               self.data["Low"].values,
                               self.data["Close"].values)
     self.data["AROON_1"] = ta.AROON(self.data["High"].values,
                                     self.data["Low"].values)[0]
     self.data["AROON_2"] = ta.AROON(self.data["High"].values,
                                     self.data["Low"].values)[1]
     self.data["MACD_1"] = ta.MACD(self.data["Close"].values)[0]
     self.data["MACD_2"] = ta.MACD(self.data["Close"].values)[1]
     self.data["MACD_3"] = ta.MACD(self.data["Close"].values)[2]
     self.data["RSI"] = ta.RSI(self.data["Close"].values)
     self.data["STOCHASTIC_1"] = ta.STOCH(self.data["High"].values,
                                          self.data["Low"].values,
                                          self.data["Close"].values)[0]
     self.data["STOCHASTIC_2"] = ta.STOCH(self.data["High"].values,
                                          self.data["Low"].values,
                                          self.data["Close"].values)[1]
     self.data = self.data.dropna().copy()
     self.data["1"] = pd.cut(self.data["ADL"], discretizing, labels=False)
     self.data["2"] = pd.cut(self.data["AROON_1"],
                             discretizing,
                             labels=False)
     self.data["3"] = pd.cut(self.data["AROON_2"],
                             discretizing,
                             labels=False)
     self.data["4"] = pd.cut(self.data["MACD_1"],
                             discretizing,
                             labels=False)
     self.data["5"] = pd.cut(self.data["MACD_2"],
                             discretizing,
                             labels=False)
     self.data["6"] = pd.cut(self.data["MACD_3"],
                             discretizing,
                             labels=False)
     self.data["7"] = pd.cut(self.data["RSI"], discretizing, labels=False)
     self.data["8"] = pd.cut(self.data["STOCHASTIC_1"],
                             discretizing,
                             labels=False)
     self.data["9"] = pd.cut(self.data["STOCHASTIC_2"],
                             discretizing,
                             labels=False)
示例#27
0
def aroon(high, low, n):
    try:
        aroondown, aroonup = talib.AROON(high, low, timeperiod=n)
        df = pd.DataFrame()
        df['aroondown'] = aroondown
        df['aroonup'] = aroonup
        df['aroon_oscillator'] = talib.AROONOSC(high, low, timeperiod=n)
        return df
    except Exception as e:
        raise (e)
示例#28
0
 def _get_indicators(security, open_name, close_name, high_name, low_name,
                     volume_name):
     """
     expand the features of the data through technical analysis across 26 different signals
     :param security: data which features are going to be expanded
     :param open_name: open price column name
     :param close_name: close price column name
     :param high_name: high price column name
     :param low_name: low price column name
     :param volume_name: traded volumn column name
     :return: expanded and extracted data
     """
     open_price = security[open_name].values
     close_price = security[close_name].values
     low_price = security[low_name].values
     high_price = security[high_name].values
     volume = security[volume_name].values if volume_name else None
     security['MOM'] = talib.MOM(close_price)
     security['HT_DCPERIOD'] = talib.HT_DCPERIOD(close_price)
     security['HT_DCPHASE'] = talib.HT_DCPHASE(close_price)
     security['SINE'], security['LEADSINE'] = talib.HT_SINE(close_price)
     security['INPHASE'], security['QUADRATURE'] = talib.HT_PHASOR(
         close_price)
     security['ADXR'] = talib.ADXR(high_price, low_price, close_price)
     security['APO'] = talib.APO(close_price)
     security['AROON_UP'], _ = talib.AROON(high_price, low_price)
     security['CCI'] = talib.CCI(high_price, low_price, close_price)
     security['PLUS_DI'] = talib.PLUS_DI(high_price, low_price, close_price)
     security['PPO'] = talib.PPO(close_price)
     security['MACD'], security['MACD_SIG'], security[
         'MACD_HIST'] = talib.MACD(close_price)
     security['CMO'] = talib.CMO(close_price)
     security['ROCP'] = talib.ROCP(close_price)
     security['FASTK'], security['FASTD'] = talib.STOCHF(
         high_price, low_price, close_price)
     security['TRIX'] = talib.TRIX(close_price)
     security['ULTOSC'] = talib.ULTOSC(high_price, low_price, close_price)
     security['WILLR'] = talib.WILLR(high_price, low_price, close_price)
     security['NATR'] = talib.NATR(high_price, low_price, close_price)
     security['RSI'] = talib.RSI(close_price)
     security['EMA'] = talib.EMA(close_price)
     security['SAREXT'] = talib.SAREXT(high_price, low_price)
     # security['TEMA'] = talib.EMA(close_price)
     security['RR'] = security[close_name] / security[close_name].shift(
         1).fillna(1)
     security['LOG_RR'] = np.log(security['RR'])
     if volume_name:
         security['MFI'] = talib.MFI(high_price, low_price, close_price,
                                     volume)
         # security['AD'] = talib.AD(high_price, low_price, close_price, volume)
         # security['OBV'] = talib.OBV(close_price, volume)
         security[volume_name] = np.log(security[volume_name])
     security.drop([open_name, close_name, high_name, low_name], axis=1)
     security = security.dropna().astype(np.float32)
     return security
示例#29
0
def AROON(high, low, timeperiod=14):
    ''' Aroon 阿隆指标

    分组: Momentum Indicator 动量指标

    简介: 该指标是通过计算自价格达到近期最高值和最低值以来所经过的期间数,
    阿隆指标帮助你预测价格趋势到趋势区域(或者反过来,从趋势区域到趋势)的变化。

    aroondown, aroonup = AROON(high, low, timeperiod=14)
    '''
    return talib.AROON(high, low, timeperiod)
示例#30
0
def factorMaker17(Data, parameter, pair):
    a = int(parameter['a'])
    b = int(parameter['b'])
    df = Data.copy()
    df['tmp'] = df['cp_adj_' + pair[0]] / df['cp_adj_' + pair[1]]
    df['tmp'] = df['tmp'].rolling(a).mean()
    df['up'], df['down'] = talib.AROON(df['tmp'].values, df['tmp'].values, b)
    factor = pd.Series(np.zeros(len(df['tmp'])))
    factor[(df['up'] > df['down'])] = 1
    factor[(df['up'] < df['down'])] = -1
    return factor