예제 #1
0
def test_adx():
    """test TA.ADX"""

    adx = TA.ADX(ohlc).round(decimals=8)

    assert isinstance(adx, series.Series)
    assert adx.values[-1] == 46.43950615
예제 #2
0
파일: test_unit.py 프로젝트: zbclove/finta
def test_adx():
    """test TA.ADX"""

    adx = TA.ADX(ohlc)

    assert isinstance(adx, series.Series)
    assert adx.values[-1] == 54.21179329188816
예제 #3
0
def test_adx():
    """test TA.ADX"""

    adx = TA.ADX(ohlc)

    assert isinstance(adx, series.Series)
    assert adx.values[-1] == 54.781005617031234
예제 #4
0
    def technicalA(df):

        df['4_ema'] = TA.EMA(df, 4)
        df['9_ema'] = TA.EMA(df, 9)
        df['10_ema'] = TA.EMA(df, 10)
        df['18_ema'] = TA.EMA(df, 18)

        #MACD
        dfMACD = TA.MACD(df)
        dfMACD["HIST"] = dfMACD["MACD"] - dfMACD["SIGNAL"]
        df["MACD"] = dfMACD["MACD"]
        df["SIGNAL"] = dfMACD["SIGNAL"]
        df["HIST"] = dfMACD["HIST"]

        #DMI
        dfDMI = TA.DMI(df)
        df["DI-"] = dfDMI["DI-"]
        df["DI-"] = df["DI-"].fillna(0)

        df["DI+"] = dfDMI["DI+"]
        df["DI+"] = df["DI+"].fillna(0)

        #ADX
        df["ADX"] = TA.ADX(df)
        df["ADX"] = df["ADX"].fillna(0)

        return df
예제 #5
0
 def pre_backtest_calculations(self, value):
     self.ema = TA.EMA(value)
     self.adx = TA.ADX(value)
     self.rsi = TA.RSI(value)
     self.bbands = TA.BBANDS(value)
     self.lower_bband = self.bbands["BB_UPPER"]
     self.upper_bband = self.bbands["BB_LOWER"]
예제 #6
0
def test_adx():
    '''test TA.ADX'''

    adx = TA.ADX(ohlc, period=12)
    ta_adx = talib.ADX(ohlc["high"], ohlc["low"], ohlc["close"], timeperiod=12)

    assert int(ta_adx[-1]) == int(adx.values[-1])
예제 #7
0
def test_adx():
    """test TA.ADX"""

    adx = TA.ADX(ohlc)

    assert isinstance(adx, series.Series)
    assert adx.values[-1] == 46.43950615435351
예제 #8
0
def test_adx():
    """test TA.ADX"""

    adx = TA.ADX(ohlc)

    assert isinstance(adx, series.Series)
    assert adx.values[-1] == 66.589993072391422
예제 #9
0
    def pre_backtest_calculations(self, value):
        self.ema = TA.EMA(value)
        self.adx = TA.ADX(value)
        self.rsi = TA.RSI(value)

        self.rsi_low = 20
        self.rsi_high = 70
        self.adx_threshold = 25
예제 #10
0
    def get_adx(data):

        if data is None:
            raise ValueError("Invalid data value")

        result = TA.ADX(data)
        if result is None:
            raise IndicatorException
        return result
예제 #11
0
def ta(asset, timeframe, count, fig, ax):
    methods = ChartHelper()
    matplotlib.use('agg')
    matplotlib.pyplot.switch_backend('Agg')
    plt.style.use(theme)
    signal = f"{asset} {timeframe} ->"
    # https://github.com/matplotlib/matplotlib/issues/14304

    klines = app.klines(asset, timeframe, count)
    df = app.dataframe(klines)

    if ax[0]:
        close = df['close']
        ema50 = TA.EMA(df, period=50)
        vwma = TA.EVWMA(df)
        pd.concat([close, ema50, vwma],
                  axis=1).tail(chart_tail_count).plot(ax=ax[0],
                                                      figsize=figure_size)

    macd_resp = macd_x_over(df)
    buysell, lastTime = macd_resp['signal'], macd_resp['time']
    hoursAgo = int((time.time() - lastTime.timestamp()) / 60 / 60)
    signal = signal + f"\n {buysell}: at {lastTime}, {hoursAgo} hours ago"
    if ax[1]:
        macd_resp['plot'](ax[1])

    rsi_resp = rsi(df)
    signal = signal + f"\n {rsi_resp['signal']}: {rsi_resp['info']}"
    if ax[2]:
        rsi_resp['plot'](ax[2])

    # Prepare TA Hints
    # - SMA50
    sma = TA.SMA(df, period=20 if timeframe == '1d' else 50)
    current_ma_20 = app.floor(sum(sma.tail(1).values), 9)
    current_price = float(klines[-1][4])
    prc_from_ema20 = app.floor_new(
        (current_price - current_ma_20) * 100 / current_ma_20, 2)
    signal = signal + f"\n Price ovr SMA: {prc_from_ema20} "
    # min, max Bollinger lower band distance in last 4 bars

    # kama = TA.KAMA(df) # KAMA instead of SMA
    # , MA=kama
    bb_resp = bb(df)
    if ax[3]:
        bb_resp['plot'](ax[3])
    signal = signal + f"\n {bb_resp['signal']}: {bb_resp['info']}"

    # Average Directional Movement, Directional Movement Indicator
    adx = TA.ADX(df).tail(ta_hints_bars)
    dmi = TA.DMI(df).tail(ta_hints_bars)
    direction = "Buy" if (dmi['DI+'][-1] > dmi['DI-'][-1]) else "Sell"
    adxStr = getAdxIntensity(adx.values[-1])
    signal = signal + f"\n ADX/DMI: {adxStr} {direction}"
    return signal
예제 #12
0
    def pre_backtest_calculations(self, value):

        self.ema_range = 2
        self.ema = TA.EMA(value, period=self.ema_range)

        self.adx = TA.ADX(value)
        self.rsi = TA.RSI(value)
        self.rsi_high = 90
        self.rsi_low = 30

        self.adx_threshold = 25
예제 #13
0
    def sign(self, symbol: str, timeframe: str):
        """



    """

        df = self.exchange.GetSymbolKlines(symbol=symbol, interval=timeframe)
        #df = self.exchange.technicalA(df)

        df['3_ema'] = TA.EMA(df, 3)
        df['25_sma'] = TA.SMA(df, 25)
        #df['10_ema'] = TA.EMA(df, 10)
        #df['55_ema'] = TA.EMA(df, 55)

        #df2= TA.MACD(df = df, period_fast = 30, period_slow = 20, signal = 30)
        df2 = TA.MACD(df, period_fast=30, period_slow=20, signal=30)
        df2["HIST"] = df2["MACD"] - df2["SIGNAL"]
        df["MACD"] = df2["MACD"]
        df["SIGNAL"] = df2["SIGNAL"]
        df["HIST"] = df2["HIST"]
        df['HIST_ESMA'] = df['3_ema'] - df['25_sma']

        #ADX
        df["ADX"] = TA.ADX(df)
        df["ADX"] = df["ADX"].fillna(0)
        df["HIST_ESMA"] = df["HIST_ESMA"].fillna(0)

        self.slopCalculator(df)

        df.to_csv('./export.csv', sep='\t')
        print(df)
        exit()
        df["sign"] = ""
        entrypoint = 'off'
        for i in range(0, len(df['close']) - 1):
            #strategy_result = Strategies.marginTrade(df = df, step = i)
            strategy_result = Strategies.tlStrategy(df=df, step=i)

            if strategy_result['signal'] == 'BUY' and entrypoint == 'off':
                #print('buy: ',i)
                self.buy_signals.append([df['time'][i], df['low'][i]])
                df.loc[i, 'sign'] = 'buy'
                entrypoint = 'on'
            elif strategy_result['signal'] == 'SELL' and entrypoint == 'on':
                #print('sell: ',i)
                df.loc[i, 'sign'] = 'sell'
                self.sell_signals.append([df['time'][i], df['low'][i]])

                entrypoint = 'off'

        #print(self.sell_signals)
        self.chart.plotData(df, symbol, timeframe, self.param,
                            self.buy_signals, self.sell_signals)
예제 #14
0
    def get_adx(data):
        """Calculate the ADX of given dataframe.

        :param data: a dataframe in OHLC format
        :return: a Pandas series
        """
        if data is None:
            raise EmptyDataError("[!] Invalid data value")

        result = TA.ADX(data)
        if result is None:
            raise IndicatorException
        return result
예제 #15
0
def tech_indictors(df):
    df['macd'] = TA.MACD(df).SIGNAL
    df['boll_ub'] = TA.BBANDS(df).BB_UPPER
    df['boll_lb'] = TA.BBANDS(df).BB_LOWER
    df['rsi_30'] = TA.RSI(df, period=30)
    df['dx_30'] = TA.ADX(df, period=30)
    df['close_30_sma'] = TA.SMA(df, period=30)
    df['close_60_sma'] = TA.SMA(df, period=60)

    #fill NaN to 0
    df = df.fillna(0)
    print(
        f'--------df head - tail ----------------\n{df.head(3)}\n{df.tail(3)}\n---------------------------------'
    )

    return df
예제 #16
0
    def calc_ta(self):
        ta = [
            TA.ER(self.ohlc),
            TA.PPO(self.ohlc)["HISTO"],
            TA.STOCHRSI(self.ohlc),
            TA.ADX(self.ohlc),
            TA.RSI(self.ohlc),
            TA.COPP(self.ohlc),
            TA.CCI(self.ohlc),
            TA.CHAIKIN(self.ohlc),
            TA.FISH(self.ohlc)
        ]

        ta = np.array(ta).transpose()
        ta[np.isnan(ta)] = 0
        ta[np.isinf(ta)] = 0

        # scale them to the same range
        self.scaler = StandardScaler()
        self.scaler.fit(ta)
        self.ta = self.scaler.transform(ta)
예제 #17
0
def technical_indicators(tiDF, usdflag):
    # tiDF 'date_time', 'Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Stock'

    ohlcv = tiDF[[
        'date_time', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume'
    ]]

    for i in ohlcv.columns:
        ohlcv = ohlcv.rename(columns={str(i): str(i.lower())})

    ohlcv.rename(columns={'date_time': 'Date', 'date': 'day'}, inplace=True)
    ohlcv.set_index('Date', inplace=True)

    ohlcv['sma2'] = TA.SMA(ohlcv, 2)
    ohlcv['sma3'] = TA.SMA(ohlcv, 3)
    ohlcv['sma4'] = TA.SMA(ohlcv, 4)
    ohlcv['sma5'] = TA.SMA(ohlcv, 5)
    ohlcv['sma6'] = TA.SMA(ohlcv, 6)
    ohlcv['sma7'] = TA.SMA(ohlcv, 7)

    ohlcv['rsi'] = TA.RSI(ohlcv)
    ohlcv['cci'] = TA.CCI(ohlcv)
    ohlcv['adx'] = TA.ADX(ohlcv)

    ohlcv['vpt'] = TA.VPT(ohlcv)
    ohlcv['efi'] = TA.EFI(ohlcv)
    ohlcv['wobv'] = TA.WOBV(ohlcv)
    ohlcv['vzo'] = TA.VZO(ohlcv)
    ohlcv['pzo'] = TA.PZO(ohlcv)
    ohlcv['tp'] = TA.TP(ohlcv)
    ohlcv['adl'] = TA.ADL(ohlcv)
    ohlcv['smma'] = TA.SMMA(ohlcv)
    ohlcv['tr'] = TA.TR(ohlcv)
    ohlcv['sar'] = TA.SAR(ohlcv)
    ohlcv['vwap'] = TA.VWAP(ohlcv)
    ohlcv['ssma'] = TA.SSMA(ohlcv)
    ohlcv['dema'] = TA.DEMA(ohlcv)
    ohlcv['tema'] = TA.TEMA(ohlcv)
    ohlcv['trix'] = TA.TRIX(ohlcv)

    stock = tiDF['Stock'].unique().tolist()[0]
    ohlcv['Stock'] = stock

    ohlcv = ohlcv.dropna()

    numTimes = ohlcv.groupby('day').count()
    shortDays = numTimes[numTimes.sma7 != 7].index.values
    ohlcv = ohlcv[~ohlcv['day'].isin(shortDays)]

    ohlcv = ohlcv.drop(['high', 'low', 'close', 'day'], axis=1)
    ohlcv.reset_index(level=0, inplace=True)
    for i in ohlcv.columns:
        ohlcv = ohlcv.rename(columns={str(i): str(i.capitalize())})

    ohlcv.rename(columns={'Date': 'date_time'}, inplace=True)

    pd.options.display.max_columns = None
    pd.options.display.max_rows = None

    if usdflag:
        totale = pd.read_csv("total.csv")
        totale['date_time'] = to_datetime(totale['date_time'],
                                          format="%Y-%m-%d %H:%M:%S")
        result = pd.merge(ohlcv, totale, how='inner', on=['date_time'])
    else:
        result = ohlcv.copy()

    print(result.info())
    print(result.head(5))
    return result
예제 #18
0
    def sell(self,
             period: int = 14,
             ema_period: int = 60,
             column: str = "close",
             adjust: bool = True,
             period2: int = 14,
             ema_period2: int = 60) -> np.bool_:
        """Bearish sell signal calculation based on volume zone oscillator (VZO).

        The flag is generated based on a number of conditional statements generated from technical indicators.
        The basic buy rule is to sell when a bearish crossover happens -- the VZO crossing below the 40% line

        Along with the bearish crossover, we can use a 14 period average directional index (ADX), directional
        movement index (DMI), and a 60 period EMA to confirm the trend. We do this by making sure the close
        price has crossed below the 60 day EMA and either an ADX less than 20 or a downward DMI (DI- > DI+).

        An example usage might look like:

        if vzo.sell() or difference(current_price, entry_price) == profit_target:
            execute_sell_order()

        :param period:
        :param ema_period:
        :param column:
        :param adjust:
        :param period2:
        :param ema_period2:
        :return:
        """
        try:
            # grab the indicators we need (VZO, ADX, DMI, EMA) for this signal
            vzo = TA.VZO(self.df, period, column, adjust)
            adx = TA.ADX(self.df, period, adjust)
            dmi = TA.DMI(self.df, period, adjust)
            ema = TA.EMA(self.df, ema_period, column, adjust)
        except TradeSignalException as error:
            raise error
        else:
            _vzo_bearish_cross = vzo.iloc[-1] < 40 and trending_down(vzo.iloc[:-2], period=int(period/2)).iloc[-1]
            _adx_trending = adx.iloc[-1] < 20
            _dmi_negative = dmi["DI-"].iloc[-1] > dmi["DI+"].iloc[-1]
            _ema_bearish_cross = self.df["close"].iloc[-1] < ema.iloc[-1] and \
                trending_down(self.df["close"].iloc[:-2], period=int(period/2)).iloc[-1]
            selling = _vzo_bearish_cross and (_adx_trending or _dmi_negative) and _ema_bearish_cross

            if SU.is_valid_dataframe(self.df2):
                try:
                    # grab the indicators we need (VZO, ADX, DMI, EMA) for this signal
                    vzo2 = TA.VZO(self.df2, period2, column, adjust)
                    adx2 = TA.ADX(self.df2, period2, adjust)
                    dmi2 = TA.DMI(self.df2, period2, adjust)
                    ema2 = TA.EMA(self.df2, ema_period2, column, adjust)
                except TradeSignalException as error:
                    raise error
                else:
                    _vzo_bearish_cross2 = vzo2.iloc[-1] < 40 and trending_down(vzo2.iloc[:-2], period=int(period2/2)).iloc[-1]
                    _adx_trending2 = adx2.iloc[-1] < 20
                    _dmi_negative2 = dmi2["DI-"].iloc[-1] > dmi2["DI+"].iloc[-1]
                    _ema_bearish_cross2 = self.df2["close"].iloc[-1] < ema2.iloc[-1] and \
                        trending_down(self.df2["close"].iloc[:-2], period=int(period2/2)).iloc[-1]
                    selling = selling and _vzo_bearish_cross2 and (_adx_trending2 or _dmi_negative2) and _ema_bearish_cross2

            return selling
    def do_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Stoch fast - mainly due to 5m timeframes
        stoch_fast = ta.STOCHF(dataframe)
        dataframe['fastd'] = stoch_fast['fastd']
        dataframe['fastk'] = stoch_fast['fastk']

        #StochRSI for double checking things
        period = 14
        smoothD = 3
        SmoothK = 3
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        stochrsi = (dataframe['rsi'] - dataframe['rsi'].rolling(period).min()
                    ) / (dataframe['rsi'].rolling(period).max() -
                         dataframe['rsi'].rolling(period).min())
        dataframe['srsi_k'] = stochrsi.rolling(SmoothK).mean() * 100
        dataframe['srsi_d'] = dataframe['srsi_k'].rolling(smoothD).mean()

        # Bollinger Bands because obviously
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe),
                                            window=20,
                                            stds=1)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_middleband'] = bollinger['mid']
        dataframe['bb_upperband'] = bollinger['upper']

        # SAR Parabol - probably don't need this
        dataframe['sar'] = ta.SAR(dataframe)

        ## confirm wideboi variance signal with bbw expansion
        dataframe["bb_width"] = (
            (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) /
            dataframe["bb_middleband"])
        dataframe['bbw_expansion'] = dataframe['bb_width'].rolling(
            window=4).apply(self.bbw_expansion)

        # confirm entry and exit on smoothed HA
        dataframe = self.HA(dataframe, 4)

        # thanks to Hansen_Khornelius for this idea that I apply to the 1hr informative
        # https://github.com/hansen1015/freqtrade_strategy
        hansencalc = self.hansen_HA(dataframe, 6)
        dataframe['emac'] = hansencalc['emac']
        dataframe['emao'] = hansencalc['emao']

        # money flow index (MFI) for in/outflow of money, like RSI adjusted for vol
        dataframe['mfi'] = fta.MFI(dataframe)

        ## sqzmi to detect quiet periods
        dataframe['sqzmi'] = fta.SQZMI(dataframe)  #, MA=hansencalc['emac'])

        # Volume Flow Indicator (MFI) for volume based on the direction of price movement
        dataframe['vfi'] = fta.VFI(dataframe, period=14)

        dmi = fta.DMI(dataframe, period=14)
        dataframe['dmi_plus'] = dmi['DI+']
        dataframe['dmi_minus'] = dmi['DI-']
        dataframe['adx'] = fta.ADX(dataframe, period=14)

        ## for stoploss - all from Solipsis4
        ## simple ATR and ROC for stoploss
        dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
        dataframe['roc'] = ta.ROC(dataframe, timeperiod=9)
        dataframe['rmi'] = RMI(dataframe, length=24, mom=5)
        ssldown, sslup = SSLChannels_ATR(dataframe, length=21)
        dataframe['sroc'] = SROC(dataframe, roclen=21, emalen=13, smooth=21)
        dataframe['ssl-dir'] = np.where(sslup > ssldown, 'up', 'down')
        dataframe['rmi-up'] = np.where(
            dataframe['rmi'] >= dataframe['rmi'].shift(), 1, 0)
        dataframe['rmi-up-trend'] = np.where(
            dataframe['rmi-up'].rolling(5).sum() >= 3, 1, 0)
        dataframe['candle-up'] = np.where(
            dataframe['close'] >= dataframe['close'].shift(), 1, 0)
        dataframe['candle-up-trend'] = np.where(
            dataframe['candle-up'].rolling(5).sum() >= 3, 1, 0)

        return dataframe
    prices["True Range"] = TA.TR(ohlc)
    prices["True Range Ave"] = TA.ATR(ohlc)

    # Stop and reverse indicator (trails prices and flips direction depending on market direction)
    # This is used to set suitable entry or exit points or trailing stop losses
    prices["SAR"] = TA.SAR(ohlc)
    prices["SAR-signal"] = prices["Adj Close"] - prices["SAR"]
    # Parabolic SAR indicator
    prices["PSAR"], prices["PSAR_bull"], prices["PSAR_bear"] = TA.PSAR(ohlc)

    # Directional movement indicator
    # Assesses price direction and strength - Allows the trader to differentiate between strong and weak trends
    prices["DMI_plus"], prices["DMI_minus"] = TA.DMI(ohlc)

    # Trend strength - below 20 is weak, above 40 is strong and above 50 is extremely strong
    prices["Trend_strength"] = TA.ADX(ohlc)

    # Stochastic oscillator
    prices["STOCH"] = TA.STOCH(ohlc)
    prices["STOCHD"] = TA.STOCHD(ohlc)
    prices["STOCHRSI"] = TA.STOCHRSI(ohlc)

    # Williams %R is a technical analysis oscillator
    prices["WR"] = TA.WILLIAMS(ohlc)

    # Awesome Oscillator - measures market momentum
    prices["awesome_oscil"] = TA.AO(ohlc)
    prices["ultimate_oscil"] = TA.UO(ohlc)

    # Mass index - measures high-low range expansion to identify trend reversals. Essentially volatility indicator
    prices["MI"] = TA.MI(ohlc)
예제 #21
0
    def buy(self,
            period: int = 14,
            ema_period: int = 60,
            column: str = "close",
            adjust: bool = True,
            period2: int = 14,
            ema_period2: int = 60) -> np.bool_:
        """Bullish buy signal calculation based on volume zone oscillator (VZO).

        The flag is generated based on a number of conditional statements generated from technical indicators.
        The basic buy rule is to buy when a bullish crossover happens -- the VZO crossing over the -40% line

        Along with the bullish crossover, we can use a 14 period average directional index (ADX), directional
        movement index (DMI), and a 60 period EMA to confirm the trend. We do this by making sure the ADX is
        at least 20, the DMI is trending upward (DI+ > DI-) and that the close price has crossed over the 60 day EMA.

        An example usage might look like:

        if vzo.buy() and some_other_indicator():
            execute_buy_order()

        :param period:
        :param ema_period:
        :param column:
        :param adjust:
        :param period2:
        :param ema_period2:
        :return bool:
        """
        try:
            # grab the indicators we need (VZO, ADX, DMI, EMA) for this signal
            vzo = TA.VZO(self.df, period, column, adjust)
            adx = TA.ADX(self.df, period, adjust)
            dmi = TA.DMI(self.df, period, adjust)
            ema = TA.EMA(self.df, ema_period, column, adjust)
        except TradeSignalException as error:
            raise error
        else:
            _vzo_bullish_cross = vzo.iloc[-1] > -40 and trending_up(vzo.iloc[:-2], period=int(period/2)).iloc[-1]
            _adx_trending = adx.iloc[-1] > 20
            _dmi_positive = dmi["DI+"].iloc[-1] > dmi["DI-"].iloc[-1]
            _ema_bullish_cross = self.df["close"].iloc[-1] > ema.iloc[-1] and \
                trending_up(self.df["close"].iloc[:-2], period=int(period/2)).iloc[-1]
            buying = _vzo_bullish_cross and \
                (_adx_trending or _dmi_positive) and \
                _ema_bullish_cross

            if SU.is_valid_dataframe(self.df2):
                try:
                    # grab the indicators we need (VZO, ADX, DMI, EMA) for this signal
                    vzo2 = TA.VZO(self.df2, period2, column, adjust)
                    adx2 = TA.ADX(self.df2, period2, adjust)
                    dmi2 = TA.DMI(self.df2, period2, adjust)
                    ema2 = TA.EMA(self.df2, ema_period2, column, adjust)
                except TradeSignalException as error:
                    raise error
                else:
                    _vzo_bullish_cross2 = vzo2.iloc[-1] > -40 and trending_up(vzo2.iloc[:-2], period=int(period2/2)).iloc[-1]
                    _adx_trending2 = adx2.iloc[-1] > 20
                    _dmi_positive2 = dmi2["DI+"].iloc[-1] > dmi2["DI-"].iloc[-1]
                    _ema_bullish_cross2 = self.df2["close"].iloc[-1] > ema2.iloc[-1] and \
                        trending_up(self.df2["close"].iloc[:-2], period=int(period2/2)).iloc[-1]
                    buying = buying and _vzo_bullish_cross2 and (_adx_trending2 or _dmi_positive2) and _ema_bullish_cross2

            return buying