Beispiel #1
0
def add_volatility_indicators(data_list):
    # (volatility) Indicators common for all Time-frames
    for data in data_list:

        # 1) ATR - Average True Range
        real = talib.ATR(data.High, data.Low, data.Close, timeperiod=14)
        data['ATR_14'] = real

        # 2) NATR - Normalized Average True Range
        real = talib.NATR(data.High, data.Low, data.Close, timeperiod=14)
        data['NATR_14'] = real

        # 3) TRANGE - True Range
        real = talib.TRANGE(data.High, data.Low, data.Close)
        data['TRANGE'] = real

    data_weekly = data_list[6]
    data_monthly = data_list[7]
    data_15min = data_list[2]
    data_daily = data_list[5]
    data_60min = data_list[4]
    data_1min = data_list[0]
    data_5min = data_list[1]
    data_30min = data_list[3]

    # Create (volatility) indicators for a only to a particular timeframe here..

    return data_list
Beispiel #2
0
def test_tr():
    '''test TA.TR'''

    tr = TA.TR(ohlc)
    talib_tr = talib.TRANGE(ohlc['high'], ohlc['low'], ohlc['close'])

    assert round(talib_tr[-1], 5) == round(tr.values[-1], 5)
Beispiel #3
0
def get_atr(context, data, s='000016.SH', barcount=5):
    highs = get_symb_data(data, s, 'high', barcount, '1d')
    lows = get_symb_data(data, s, 'low', barcount, '1d')
    closes = get_symb_data(data, s, 'high', barcount, '1d')
    vol = ta.TRANGE(np.array(highs), np.array(lows),
                    np.array(closes))[-1] if ATR_ENABLED else closes.std()
    return vol
Beispiel #4
0
def trange(client,
           symbol,
           range="6m",
           highcol="high",
           lowcol="low",
           closecol="close"):
    """This will return a dataframe of true range for the given symbol across
    the given range

    Args:
        client (pyEX.Client): Client
        symbol (string): Ticker
        range (string): range to use, for pyEX.chart
        highcol (string): column to use to calculate
        lowcol (string): column to use to calculate
        closecol (string): column to use to calculate

    Returns:
        DataFrame: result
    """
    df = client.chartDF(symbol, range)
    trange = t.TRANGE(
        df[highcol].values.astype(float),
        df[lowcol].values.astype(float),
        df[closecol].values.astype(float),
    )
    return pd.DataFrame({
        highcol: df[highcol].values,
        lowcol: df[lowcol].values,
        closecol: df[closecol].values,
        "trange": trange,
    })
Beispiel #5
0
 def eval(self, environment, gene, date1, date2):
     date1 = environment.shift_date(date1, -1, -1)
     high = gene.next_value(environment, date1, date2)
     low = gene.next_value(environment, date1, date2)
     close = gene.next_value(environment, date1, date2)
     res = high.apply(lambda x: talib.TRANGE(x.values, low[x.name].values, close[x.name].values))
     return res.iloc[1:]
def tr(vm=None):
    if vm is None:
        return None
    high = np.array(vm.market.high(), dtype='f8')
    low = np.array(vm.market.low(), dtype='f8')
    close = np.array(vm.market.close(), dtype='f8')
    return series_np(ta.TRANGE(high, low, close))
def handle_volatility_indicators(args, axes, i, klines_df, close_times,
                                 display_count):
    # talib
    if args.ATR:
        name = 'ATR'
        real = talib.ATR(klines_df["high"],
                         klines_df["low"],
                         klines_df["close"],
                         timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.NATR:
        name = 'NATR'
        real = talib.NATR(klines_df["high"],
                          klines_df["low"],
                          klines_df["close"],
                          timeperiod=14)
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)

    if args.TRANGE:
        name = 'TRANGE'
        real = talib.TRANGE(klines_df["high"], klines_df["low"],
                            klines_df["close"])
        i += 1
        axes[i].set_ylabel(name)
        axes[i].grid(True)
        axes[i].plot(close_times, real[-display_count:], "y:", label=name)
Beispiel #8
0
def checkOne(code_str):
    df = base.getOneStockData(code_str)
    df['MINUS_DM_' + str(adx_timeperiod)] = ta.MINUS_DM(
        np.array(df['high']), np.array(df['low']), timeperiod=adx_timeperiod)
    df['PLUS_DM_' + str(adx_timeperiod)] = ta.PLUS_DM(
        np.array(df['high']), np.array(df['low']), timeperiod=adx_timeperiod)
    df['TR_' + str(adx_timeperiod)] = ta.TRANGE(np.array(df['high']),
                                                np.array(df['low']),
                                                np.array(df['close']))
    df['MINUS_DI_' + str(adx_timeperiod)] = ta.MINUS_DI(
        np.array(df['high']),
        np.array(df['low']),
        np.array(df['close']),
        timeperiod=adx_timeperiod)
    df['PLUS_DI_' + str(adx_timeperiod)] = ta.PLUS_DI(
        np.array(df['high']),
        np.array(df['low']),
        np.array(df['close']),
        timeperiod=adx_timeperiod)
    df['ADX_' + str(adx_timeperiod)] = ta.ADX(np.array(df['high']),
                                              np.array(df['low']),
                                              np.array(df['close']),
                                              timeperiod=adx_timeperiod)
    df['ADXR_' + str(adx_timeperiod)] = ta.ADXR(np.array(df['high']),
                                                np.array(df['low']),
                                                np.array(df['close']),
                                                timeperiod=adx_timeperiod)

    df.to_csv(ADX_DIR + code_str + '.csv')
Beispiel #9
0
def get_volatility_indicators(df_price):

    df_local = df_price.copy()
    df_nonna_idxs = df_local[~df_local.Close.isna()].Close.index

    np_adj_close = df_local.Adj_Close.values
    np_close = df_local.Close.values
    np_open = df_local.Open.values
    np_high = df_local.High.values
    np_low = df_local.Low.values
    np_volume = df_local.Volume.values

    np_nan_indices = np.isnan(np_close)

    #ATR-Average True Range
    ATR = pd.Series(ta.ATR(np_high[~np_nan_indices], np_low[~np_nan_indices],
                           np_adj_close[~np_nan_indices]),
                    index=df_nonna_idxs)
    df_local['ATR'] = ATR

    #NATR-Normalized Average True Range
    NATR = pd.Series(ta.NATR(np_high[~np_nan_indices], np_low[~np_nan_indices],
                             np_adj_close[~np_nan_indices]),
                     index=df_nonna_idxs)
    df_local['NATR'] = NATR

    #TRANGE-True Range
    TRANGE = pd.Series(ta.TRANGE(np_high[~np_nan_indices],
                                 np_low[~np_nan_indices],
                                 np_adj_close[~np_nan_indices]),
                       index=df_nonna_idxs)
    df_local['TRANGE'] = TRANGE

    return df_local
Beispiel #10
0
 def trange(self, array=False):
     """
     TRANGE.
     """
     result = talib.TRANGE(self.high, self.low, self.close)
     if array:
         return result
     return result[-1]
Beispiel #11
0
    def evaluate(self, kite_fetcher, instrument):
        df = self.get_large_data(kite_fetcher=kite_fetcher,
                                 instrument=instrument)

        result = talib.TRANGE(high=df['high'],
                              low=df['low'],
                              close=df['close'])
        return np.round(result.iloc[-1], 4)
Beispiel #12
0
 def trange(self, array: bool = False) -> Union[float, np.ndarray]:
     """
     TRANGE.
     """
     result = talib.TRANGE(self.high, self.low, self.close)
     if array:
         return result
     return result[-1]
Beispiel #13
0
 def calculate(self, tagged):
     data = pd.DataFrame()
     #data['Date'] = df['Date']
     data['values'] = talib.TRANGE(df['High'], df['Low'],
                                   df['Close']) / df['Low']
     df[self.name()] = data['values']
     if tagged:
         data['tag'] = df['tag']
     return data
def Volatility_test():
    #真实波动幅度
    data_table["TRANGE"] = talib.TRANGE(data_table.high, data_table.low,
                                        data_table.close)
    #真实波动幅度均值
    data_table["ATR"] = talib.ATR(data_table.high,
                                  data_table.low,
                                  data_table.close,
                                  timeperiod=14)
    print(data_table["ATR"])
Beispiel #15
0
def TRANGE(high, low, close):
    ''' True Range 真正的范围

    分组: Volatility Indicator 波动率指标

    简介:

    real = TRANGE(high, low, close)
    '''
    return talib.TRANGE(high, low, close)
Beispiel #16
0
def getVolatilityIndicators(df):
    high = df['High']
    low = df['Low']
    close = df['Close']
    open = df['Open']
    volume = df['Volume']

    df['ATR'] = ta.ATR(high, low, close, timeperiod=14)
    df['NATR'] = ta.NATR(high, low, close, timeperiod=14)
    df['TRANGE'] = ta.TRANGE(high, low, close)
Beispiel #17
0
def add_technical_indicators(dataframe):

    # Overlap Studies Functions
    dataframe["SMA"] = talib.SMA(dataframe["Close"])
    dataframe["BBANDS_up"], dataframe["BBANDS_md"], dataframe[
        "BBANDS_dw"] = talib.BBANDS(dataframe["Close"],
                                    timeperiod=5,
                                    nbdevup=2,
                                    nbdevdn=2,
                                    matype=0)
    dataframe["EMA"] = talib.EMA(dataframe["Close"], timeperiod=30)
    dataframe["HT_TRENDLINE"] = talib.HT_TRENDLINE(dataframe["Close"])
    dataframe["WMA"] = talib.WMA(dataframe["Close"], timeperiod=30)

    # Momentum Indicator Functions
    dataframe["ADX"] = talib.ADX(dataframe["High"],
                                 dataframe["Low"],
                                 dataframe["Close"],
                                 timeperiod=14)
    dataframe["MACD"], _, _ = talib.MACD(dataframe["Close"],
                                         fastperiod=12,
                                         slowperiod=26,
                                         signalperiod=9)
    dataframe["MOM"] = talib.MOM(dataframe["Close"], timeperiod=5)
    dataframe["RSI"] = talib.RSI(dataframe["Close"], timeperiod=14)

    # Volume Indicator Functions
    # dataframe["OBV"] = talib.OBV(dataframe["Close"], dataframe["Volume"])

    # Volatility Indicator Functions
    dataframe["ATR"] = talib.ATR(dataframe["High"],
                                 dataframe["Low"],
                                 dataframe["Close"],
                                 timeperiod=14)
    dataframe["TRANGE"] = talib.TRANGE(dataframe["High"], dataframe["Low"],
                                       dataframe["Close"])

    # Price Transform Functions
    dataframe["AVGPRICE"] = talib.AVGPRICE(dataframe["Open"],
                                           dataframe["High"], dataframe["Low"],
                                           dataframe["Close"])
    dataframe["MEDPRICE"] = talib.MEDPRICE(dataframe["High"], dataframe["Low"])
    dataframe["WCLPRICE"] = talib.WCLPRICE(dataframe["High"], dataframe["Low"],
                                           dataframe["Close"])

    # Statistic Functions
    dataframe["LINEARREG_SLOPE"] = talib.LINEARREG_SLOPE(dataframe["Close"],
                                                         timeperiod=14)
    dataframe["STDDEV"] = talib.STDDEV(dataframe["Close"],
                                       timeperiod=5,
                                       nbdev=1)

    dataframe = dataframe.dropna()
    return dataframe
Beispiel #18
0
def handle_bar(context, bar_dict):
    for stock in list(context.portfolio.positions.keys()):
        res = pd.Series(talib.TRANGE(get_data(stock, 'high'), get_data(stock, 'low'), get_data(stock, 'close')))
        try:
            if context.price_list[stock].iloc[-1] - context.price_list[stock].iloc[-2] < -0.95 * res.iloc[-2]:
                order_target_percent(stock, 0)
        except:
            if stock not in context.price_list.columns:
                order_target_percent(stock, 0)
    alias = weight_decide(context.chosen)
    for stock in alias:
        order_target_percent(stock[0], stock[1])
Beispiel #19
0
def ADX_MA(data, period=14, smooth=14, limit=18):
    """
    Moving Average ADX
    ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend

    Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/
    Translator: 阿财(Rgveda@github)(4910163#qq.com)

    Parameters
    ----------
    data : (N,) array_like
        传入 OHLC Kline 序列。
        The OHLC Kline.
    period : int or None, optional
        DI 统计周期 默认值为 14
        DI Length period. Default value is 10. 
    smooth : int or None, optional
        ADX 平滑周期 默认值为 14
        ADX smoothing length period. Default value is 10.
    limit : int or None, optional
        ADX 限制阈值 默认值为 18
        ADX MA Active limit threshold. Default value is 18.

    Returns
    -------
    adx, ADXm : ndarray
        ADXm 指标和趋势指示方向 (-1, 0, 1) 分别代表 (下跌, 无明显趋势, 上涨)
        ADXm indicator and thread directions sequence. (-1, 0, 1) means for (Neagtive, No Trend, Positive)

    """
    up = data.high.pct_change()
    down = data.low.pct_change() * -1

    trur = TA_HMA(
        talib.TRANGE(data.high.values, data.low.values, data.close.values),
        period)
    plus = 100 * TA_HMA(np.where(
        ((up > down) & (up > 0)), up, 0), period) / trur
    minus = 100 * TA_HMA(np.where(
        ((down > up) & (down > 0)), down, 0), period) / trur

    # 这里是dropna的替代解决办法,因为我觉得nparray的传递方式如果随便drop了可能会跟 data.index
    # 对不上,所以我选择补零替代dropna
    plus = np.r_[np.zeros(period + 2), plus[(period + 2):]]
    minus = np.r_[np.zeros(period + 2), minus[(period + 2):]]
    sum = plus + minus
    adx = 100 * TA_HMA(
        abs(plus - minus) / (np.where((sum == 0), 1, sum)), smooth)
    adx = np.r_[np.zeros(smooth + 2), adx[(smooth + 2):]]
    ADXm = np.where(((adx > limit) & (plus > minus)), 1,
                    np.where(((adx > limit) & (plus < minus)), -1, 0))
    return adx, ADXm
Beispiel #20
0
 def get_quota(self):
     #stock_amount = cral_CNstock_order_ana.main()
     close = self.__df['close']
     high_prices = self.__df['high'].values
     low_prices = self.__df['low'].values
     close_prices = close.values
     ma5 = talib.MA(close_prices,5)
     ma10 = talib.MA(close_prices,10)
     ma20 = talib.MA(close_prices,20)
     ma30 = talib.MA(close_prices,30)
     K, D = talib.STOCH(high_prices,low_prices,close_prices, fastk_period=9, slowk_period=3)
     J = K * 3 - D * 2
     sar = talib.SAR(high_prices, low_prices, acceleration=0.05, maximum=0.2)
     sar = pd.DataFrame(sar-close)
     sar.index = self.__df.date
     atr = talib.ATR(high_prices,low_prices,close_prices)
     natr = talib.NATR(high_prices,low_prices,close_prices)
     trange = talib.TRANGE(high_prices,low_prices,close_prices)
     cci = talib.CCI(high_prices,low_prices,close_prices,14)
     dif, dea, bar = talib.MACDFIX(close_prices)
     bar = bar * 2
     df_all = self.__df.drop(['code','open','low', 'high','volume'],axis=1).set_index('date')
     df_all.insert(0,'ma5',ma5)
     df_all.insert(0,'ma10',ma10)
     df_all.insert(0,'ma20',ma20)
     df_all.insert(0,'ma30',ma30)
     df_all.insert(0,'K',K)
     df_all.insert(0,'D',D)
     df_all.insert(0,'J',J)
     df_all.insert(0,'cci',cci)
     df_all.insert(0,'bar',bar)
     df_all.insert(0,'dif',dif)
     df_all.insert(0,'dea',dea)
     df_all.insert(0,'sar',sar)
     #df_all = pd.concat([df_all,stock_amount],axis=1)
     df_yesterday = df_all.T
     index_c = df_all.index
     added = [np.nan] * len(df_all.columns)
     df_yesterday.insert(0, len(df_yesterday.columns), added)
     df_yesterday = df_yesterday.T
     df_yesterday = df_yesterday.drop(df_all.index[len(df_all.index)-1])
     df_yesterday.insert(0, 'index_c', index_c)
     df_yesterday = df_yesterday.set_index('index_c')
     df_dif = df_all - df_yesterday
     df_dif_close_plus_one_day = df_dif.copy()
     for i in range(len(df_dif_close_plus_one_day['close'])-1):
         df_dif_close_plus_one_day['close'][i] = df_dif_close_plus_one_day['close'][i+1]
     df_dif_close_plus_one_day['close'][len(df_dif_close_plus_one_day['close'])-1] = np.nan
     df_dif = df_dif.dropna(axis=0,how='any')
     df_dif_close_plus_one_day = df_dif_close_plus_one_day.dropna(axis=0,how='any')
     return df_dif, df_dif_close_plus_one_day
    def test_true_range(self):
        result = pandas_ta.true_range(self.high, self.low, self.close)
        self.assertIsInstance(result, Series)
        self.assertEqual(result.name, "TRUERANGE_1")

        try:
            expected = tal.TRANGE(self.high, self.low, self.close)
            pdt.assert_series_equal(result, expected, check_names=False)
        except AssertionError as ae:
            try:
                corr = pandas_ta.utils.df_error_analysis(result, expected, col=CORRELATION)
                self.assertGreater(corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result, CORRELATION, ex)
Beispiel #22
0
def trange(candles: np.ndarray, sequential: bool = False) -> Union[float, np.ndarray]:
    """
    TRANGE - True Range

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

    :return: float | np.ndarray
    """
    candles = slice_candles(candles, sequential)

    res = talib.TRANGE(candles[:, 3], candles[:, 4], candles[:, 2])

    return res if sequential else res[-1]
Beispiel #23
0
def _calc_tr(kl_df, *args):
    """
    计算真实波幅
    :param kl_df: 时间序列,dataFrame格式
    :return: ndarray或者series格式
    """
    high = kl_df['high'].values
    low = kl_df['low'].values
    close = kl_df['close'].values

    import talib

    tr = talib.TRANGE(high, low, close)

    return tr
Beispiel #24
0
 def test_TRANGE(self):
     self.env.add_operator('trange', {
         'operator': OperatorTRANGE,
     })
     string = 'trange(high, low, close)'
     gene = self.env.parse_string(string)
     self.assertRaises(IndexError, gene.eval, self.env, self.dates[0],
                       self.dates[-1])
     ser = gene.eval(self.env, self.dates[1], self.dates[1]).iloc[0]
     h = self.env.get_data_value('high').values
     l = self.env.get_data_value('low').values
     c = self.env.get_data_value('close').values
     res = []
     for i, val in ser.iteritems():
         res.append(talib.TRANGE(h[:2, i], l[:2, i], c[:2, i])[-1] == val)
     self.assertTrue(all(res))
Beispiel #25
0
    def updateIndicator(self, data, candles_visible):
        true_range = talib.TRANGE(data[2], data[3], data[4])
        firstNotNan = np.where(np.isnan(true_range))[0][-1] + 1
        true_range[:firstNotNan] = true_range[firstNotNan]

        true_range_avg = talib.ATR(data[2], data[3], data[4], timeperiod=14)
        firstNotNan = np.where(np.isnan(true_range_avg))[0][-1] + 1
        true_range_avg[:firstNotNan] = true_range_avg[firstNotNan]

        true_range = true_range[-candles_visible:]
        true_range_avg = true_range_avg[-candles_visible:]

        self.true_range_line.clear()
        self.true_range_avg.clear()
        for i in range(candles_visible):
            self.true_range_line.append(i + 0.5, true_range[i])
            self.true_range_avg.append(i + 0.5, true_range_avg[i])

        # detach and remove old axes
        for ax in self.true_range_line.attachedAxes():
            self.true_range_line.detachAxis(ax)
        for ax in self.true_range_avg.attachedAxes():
            self.true_range_avg.detachAxis(ax)
        for ax in self.axes():
            self.removeAxis(ax)

        # set x axes
        ax = QtChart.QValueAxis()
        ax.setRange(0, candles_visible)
        ax.hide()

        # set y axes
        ay = QtChart.QValueAxis()
        ay.setRange(0.0, abs(max(true_range)))
        ay.setGridLinePen(QtGui.QPen(QtGui.QColor(80, 80, 80), 0.5))
        ay.setLinePen(QtGui.QPen(QtGui.QColor(0, 0, 0), 0.5))
        ay.applyNiceNumbers()
        ay.setTickCount(3)

        # add and attach new axes
        self.addAxis(ax, QtCore.Qt.AlignBottom)
        self.addAxis(ay, QtCore.Qt.AlignRight)
        self.true_range_line.attachAxis(ax)
        self.true_range_line.attachAxis(ay)
        self.true_range_avg.attachAxis(ax)
        self.true_range_avg.attachAxis(ay)
Beispiel #26
0
def get_additional_factors(open, high, low, close, volume):

    # Overlap Studies Functions
    mat = get_all_factors(open, high, low, close, volume)

    mat = np.column_stack((mat, talib.HT_TRENDLINE(close)))  ## close
    mat = np.column_stack((mat, talib.KAMA(close, timeperiod=30)))  ##close

    #Momentum Indicator Functions
    mat = np.column_stack((mat, talib.ADX(high, low, close, timeperiod=14)))
    mat = np.column_stack((mat, talib.ADXR(high, low, close, timeperiod=14)))
    mat = np.column_stack(
        (mat, talib.APO(close, fastperiod=12, slowperiod=26, matype=0)))
    mat = np.column_stack((mat, talib.AROONOSC(high, low, timeperiod=14)))
    mat = np.column_stack((mat, talib.BOP(open, high, low, close)))
    mat = np.column_stack((mat, talib.MOM(close, timeperiod=10)))

    #Volume Indicator Functions
    mat = np.column_stack((mat, talib.AD(high, low, close, volume)))
    mat = np.column_stack(
        (mat, talib.ADOSC(high,
                          low,
                          close,
                          volume,
                          fastperiod=3,
                          slowperiod=10)))
    mat = np.column_stack((mat, talib.OBV(close, volume)))

    #Volatility Indicator Functions
    mat = np.column_stack((mat, talib.NATR(high, low, close, timeperiod=14)))
    mat = np.column_stack((mat, talib.TRANGE(high, low, close)))

    #Price Transform Functions
    mat = np.column_stack((mat, talib.AVGPRICE(open, high, low, close)))
    mat = np.column_stack((mat, talib.MEDPRICE(high, low)))
    mat = np.column_stack((mat, talib.TYPPRICE(high, low, close)))
    mat = np.column_stack((mat, talib.WCLPRICE(high, low, close)))

    #Cycle Indicator Functions
    mat = np.column_stack((mat, talib.HT_DCPERIOD(close)))
    mat = np.column_stack((mat, talib.HT_DCPHASE(close)))
    mat = np.column_stack((mat, talib.HT_TRENDMODE(close)))

    # 20

    return mat
Beispiel #27
0
def main():
    # read csv file and transform it to datafeed (df):
    df = pd.read_csv(current_dir + "/" + base_dir + "/" + in_dir + "/" +
                     in_dir + '_' + stock_symbol + '.csv')

    # set numpy datafeed from df:
    df_numpy = {
        'Date': np.array(df['date']),
        'Open': np.array(df['open'], dtype='float'),
        'High': np.array(df['high'], dtype='float'),
        'Low': np.array(df['low'], dtype='float'),
        'Close': np.array(df['close'], dtype='float'),
        'Volume': np.array(df['volume'], dtype='float')
    }

    date = df_numpy['Date']
    openp = df_numpy['Open']
    high = df_numpy['High']
    low = df_numpy['Low']
    close = df_numpy['Close']
    volume = df_numpy['Volume']

    #########################################
    ###  Volatility Indicator Functions  ####
    #########################################

    #ATR - Average True Range
    atr = ta.ATR(high, low, close, timeperiod=14)

    #NATR - Normalized Average True Range
    natr = ta.NATR(high, low, close, timeperiod=14)

    #TRANGE - True Range
    trange = ta.TRANGE(high, low, close)

    df_save = pd.DataFrame(data={
        'date': np.array(df['date']),
        'atr': atr,
        'natr': natr,
        'trange': trange
    })

    df_save.to_csv(current_dir + "/" + base_dir + "/" + out_dir + '/' +
                   stock_symbol + "/" + out_dir + '_ta_volatility_indicator_' +
                   stock_symbol + '.csv',
                   index=False)
Beispiel #28
0
def TMA(open, high, low, close, atr=2, multiplier=1, cci=10):
    """Trend Moving Averaage
	"""
    df = pd.DataFrame()
    df['tr'] = talib.TRANGE(high, low, close)
    df['wma'] = talib.WMA(df.tr, timeperiod=atr)
    df['CCI'] = talib.CCI(close, close, close, timeperiod=cci)
    df['bufferDn'] = pd.Series(high + multiplier * df.wma)
    df['bufferUp'] = pd.Series(low - multiplier * df.wma)
    df.reset_index(inplace=True, drop=True)
    df.fillna(value=0, inplace=True)
    for i, v in df.iterrows():
        if i == 0:
            continue
        if df.at[i, 'CCI'] >= 0 and df.at[i - 1, 'CCI'] < 0:
            df.at[i, 'bufferUp'] = df.at[i - 1, 'bufferDn']
        if df.at[i, 'CCI'] <= 0 and df.at[i - 1, 'CCI'] > 0:
            df.at[i, 'bufferDn'] = df.at[i - 1, 'bufferUp']
        if df.at[i, 'CCI'] >= 0:
            if (df.at[i, 'bufferUp'] < df.at[i - 1, 'bufferUp']):
                df.at[i, 'bufferUp'] = df.at[i - 1, 'bufferUp']
        else:
            if df.at[i, 'CCI'] <= 0:
                if df.at[i, 'bufferDn'] > df.at[i - 1, 'bufferDn']:
                    df.at[i, 'bufferDn'] = df.at[i - 1, 'bufferDn']

    df['x'] = np.where(df.CCI >= 0, df.bufferUp, df.bufferDn)
    for i, v in df.iterrows():
        if i == 0:
            df.at[0, 'color'] = 100
            continue
        df.at[i, 'color'] = 100 if df.at[i, 'x'] > df.at[
            i - 1,
            'x'] else -100 if df.at[i, 'x'] < df.at[i - 1,
                                                    'x'] else df.at[i - 1,
                                                                    'color']
    for i, v in df.iterrows():
        if i == 0:
            df.at[0, 'ind'] = 100
            continue
        df.at[i, 'ind'] = 100 if df.at[i, 'color'] > df.at[
            i - 1, 'color'] else -100 if df.at[i,
                                               'color'] < df.at[i - 1,
                                                                'color'] else 0
    return df.ind.values, df.color.values
def init_state(indata, test=False):
    openn = indata['open'].values
    close = indata['close'].values
    high = indata['high'].values
    low = indata['low'].values
    volume = indata['volume'].values
    
    diff = np.diff(close)
    diff = np.insert(diff, 0, 0)
    
    sma30 = talib.SMA(close, 30)
    sma60 = talib.SMA(close, timeperiod=60)
    rsi = talib.RSI(close, timeperiod=14)
    atr = talib.ATR(high, low, close, timeperiod=14)
    trange = talib.TRANGE(high, low, close)
    macd, macdsignal, macdhist = talib.MACD(close, 12, 26, 9)
    upper, middle, lower = talib.BBANDS(close, 20, 2, 2)
    ema = talib.EMA(close, 30)
    ma = talib.MA(close, 30)
    wma = talib.WMA(close, timeperiod=30)
    tema = talib.TEMA(close, 30)
    obv = talib.OBV(close, np.asarray(volume, dtype='float'))
    adx = talib.ADX(high, low, close, 14)
    apo = talib.APO(close, 12, 2, 0)
    bop = talib.BOP(openn, high, low, close)
    mom = talib.MOM(close,10)
    ppo = talib.PPO(close, 12, 26, 0)
    slowk, slowd = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
    ad = talib.AD(high, low, close, np.asarray(volume, dtype='float'))
    wcl = talib.WCLPRICE(high, low, close)

    #--- Preprocess data
    xdata = np.column_stack((close, diff, sma30, sma60, rsi, atr, macd, macdsignal, macdhist, lower, middle, upper, ema, ma, wma, adx, apo, bop, mom, ppo, slowk, slowd, trange, wcl))
    
    xdata = np.nan_to_num(xdata)
    if test == False:
        scaler = preprocessing.StandardScaler()
        xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1)
        joblib.dump(scaler, 'data/scaler.pkl')
    elif test == True:
        scaler = joblib.load('data/scaler.pkl')
        xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1)
    state = xdata[0:1, 0:1, :]

    return state, xdata, close
Beispiel #30
0
def trange(candles: np.ndarray, sequential=False) -> Union[float, np.ndarray]:
    """
    TRANGE - True Range

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

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

    res = talib.TRANGE(candles[:, 3], candles[:, 4], candles[:, 2])

    if sequential:
        return res
    else:
        return None if np.isnan(res[-1]) else res[-1]