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
def natr( client, symbol, timeframe="6m", highcol="high", lowcol="low", closecol="close", period=14, ): """This will return a dataframe of normalized average true range 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 closecol (string): column to use to calculate period (int): time period to calculate over Returns: DataFrame: result """ df = client.chartDF(symbol, timeframe) natr = t.NATR(df[highcol].values, df[lowcol].values, df[closecol].values, period) return pd.DataFrame({ highcol: df[highcol].values, lowcol: df[lowcol].values, closecol: df[closecol].values, "natr": natr, })
def technical(df, rsi_range=15, kd_range=9, v_range=30): df_day = df.groupby(['timestamp']) volume_day = np.array(df_day.sum()['Amount (BTC)']) h = l = c = price_day = np.array(df_day.mean()['USD price']) raw_date = list(df_day.groups.keys()) def iso_format(x): t = str(x) return t[:4]+'-'+t[4:6]+'-'+t[6:]+'T00:00:00Z' es_date = list(map(iso_format, list(df_day.groups.keys()))) rsi = talib.RSI(volume_day, timeperiod=rsi_range) k, d = talib.STOCH(high=volume_day, low=volume_day, close=volume_day, fastk_period=kd_range, slowk_period=3, slowd_period=3 ) volatility = talib.NATR(h, l, c, timeperiod=v_range) * sqrt(365) df_technical = pd.DataFrame(data = {'es_date':es_date, 'timestamp':raw_date, 'btc_volume':volume_day, 'btc_price':price_day, 'RSI_{}'.format(rsi_range):rsi, 'K_{}'.format(kd_range):k, 'D_{}'.format(kd_range):d, 'Vola_{}'.format(v_range): volatility }) for i in ['btc_volume', 'Vola_{}'.format(v_range), 'btc_price']: df_technical[i] = df_technical[i].apply(round, args=(3, )) df_technical.index = pd.to_datetime(df_technical['timestamp'], format='%Y%m%d', errors='ignore') return df_technical
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
def NATR(df): high = df['High'].as_matrix() low = df['Low'].as_matrix() close = df['Close'].as_matrix() real = ta.NATR(high, low, close, timeperiod=20) return real
def compNATR(self): natr = talib.NATR(self.high,self.low,self.close,timeperiod=self.lookback) self.removeNullID(natr) self.rawFeatures['NATR'] = natr FEATURE_SIZE_DICT['NATR'] = 1 return
def getData(code,start,end): data = pandasData.DataReader(code,'yahoo',start,end) # print len(data) f_ema = ta.EMA(data['Close'].values, timeperiod=30).tolist() # print f_ema f_ma = ta.MA(data['Close'].values, timeperiod=30, matype=0).tolist() f_wma = ta.WMA(data['Close'].values, timeperiod=30).tolist() f_momentum = ta.MOM(data['Close'].values, timeperiod=10).tolist() f_roc = ta.ROC(data['Close'].values, timeperiod=10).tolist() # f_cycle = ta.HT_DCPERIOD(data['Close'].values).tolist() f_price = ta.WCLPRICE(data['High'].values, data['Low'].values, data['Close'].values).tolist() f_natr = ta.NATR(data['High'].values, data['Low'].values, data['Close'].values, timeperiod=14).tolist() f_stddev = ta.STDDEV(data['Close'].values, timeperiod=5, nbdev=1).tolist() X = pd.DataFrame( pd.np.array([f_ema, f_ma, f_wma, f_momentum, f_roc, f_price, f_natr, f_stddev]).T[32:] ,columns=['f_ema','f_ma','f_wma','f_momentum','f_roc','f_price','f_natr','f_stddev']) # print X['f_ema'].size # print X data = data['Close'].tolist() finaldata = [[] for i in range(2)] for i in range(0, len(data) - 1): temp = (data[i + 1] - data[i]) / data[i] finaldata[0].append(temp) if (temp > 0): finaldata[1].append(1) else: finaldata[1].append(0) # print len(data) data = data[31:len(data) - 1] # print data Y = pd.DataFrame(pd.np.array(finaldata).T, columns=['change', 'label']) X = X.join(Y) return X
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)
def buildTAindicators(stock_df): stock_df['REDORGREEN'] = stock_df.loc[:, 'Open'].subtract( stock_df.loc[:, 'Close']).apply(lambda x: 1 if x > 0 else 0).values stock_df['CANDLE_HEIGHT'] = stock_df.loc[:, 'Open'].subtract( stock_df.loc[:, 'Close']).values stock_df['NATR'] = ta.NATR(stock_df.loc[:, 'High'].values, stock_df.loc[:, 'Low'].values, stock_df.loc[:, 'Close'].values, 5) close = stock_df.loc[:, 'Close'].values high = stock_df.loc[:, 'High'].values low = stock_df.loc[:, 'Low'].values volume = pd.Series.astype(stock_df.loc[:, 'Volume'], dtype='double').values adx = ta.ADX(high, low, close, timeperiod=14) macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) mfi = ta.MFI(high, low, close, volume, timeperiod=14) rsi = ta.RSI(close, timeperiod=14) beta = ta.BETA(high, low, timeperiod=5) stock_df['ADX'] = pd.Series(adx).values stock_df['MFI'] = pd.Series(mfi).values stock_df['RSI'] = pd.Series(rsi).values stock_df['MACD'] = pd.Series(macd).values stock_df['BETA'] = pd.Series(beta).values stock_df = stock_df.iloc[33:, :] return stock_df
def extract_features(data): high = data['High'] low = data['Low'] close = data['Close'] volume = data['Volume'] open_ = data['Open'] data['ADX'] = ta.ADX(high, low, close, timeperiod=19) data['CCI'] = ta.CCI(high, low, close, timeperiod=19) data['CMO'] = ta.CMO(close, timeperiod=14) data['MACD'], X, Y = ta.MACD(close, fastperiod=10, slowperiod=30, signalperiod=9) data['MFI'] = ta.MFI(high, low, close, volume, timeperiod=19) data['MOM'] = ta.MOM(close, timeperiod=9) data['ROCR'] = ta.ROCR(close, timeperiod=12) data['RSI'] = ta.RSI(close, timeperiod=19) data['STOCHSLOWK'], data['STOCHSLOWD'] = ta.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) data['TRIX'] = ta.TRIX(close, timeperiod=30) data['WILLR'] = ta.WILLR(high, low, close, timeperiod=14) data['OBV'] = ta.OBV(close, volume) data['TSF'] = ta.TSF(close, timeperiod=14) data['NATR'] = ta.NATR(high, low, close)#, timeperiod=14) data['ULTOSC'] = ta.ULTOSC(high, low, close) data['AROONOSC'] = ta.AROONOSC(high, low, timeperiod=14) data['BOP'] = ta.BOP(open_, high, low, close) data['LINEARREG'] = ta.LINEARREG(close) data['AP0'] = ta.APO(close, fastperiod=9, slowperiod=23, matype=1) data['TEMA'] = ta.TRIMA(close, 29) return data
def natr(self): # Normalized Average True Range (NATR) natr = talib.NATR(self.price.high, self.price.low, self.price.close, timeperiod=14) return natr[-analyzePeriod * 2:]
def natr(candles: np.ndarray, period: int = 14, sequential: bool = False) -> Union[float, np.ndarray]: """ NATR - Normalized Average True Range :param candles: np.ndarray :param period: int - default=14 :param sequential: bool - default=False :return: float | np.ndarray """ warmup_candles_num = get_config('env.data.warmup_candles_num', 240) if not sequential and len(candles) > warmup_candles_num: candles = candles[-warmup_candles_num:] res = talib.NATR(candles[:, 3], candles[:, 4], candles[:, 2], timeperiod=period) if sequential: return res else: return None if np.isnan(res[-1]) else res[-1]
def run_indicators(symbol, file): try: if os.path.exists(file): # read file df = np.genfromtxt(file, delimiter=',') # run talib indicators using dataframe # create additional columns in the datafarame closePrice = df[:, 4] openPrice = df[:, 1] highPrice = df[:, 2] lowPrice = df[:, 3] volume = df[:, 5] sma = talib.SMA(closePrice) atr = talib.ATR(highPrice, lowPrice, closePrice) natr = talib.NATR(highPrice, lowPrice, closePrice) adx = talib.ADX(highPrice, lowPrice, closePrice) mfi = talib.MFI(highPrice, lowPrice, closePrice, volume) ppo = talib.PPO(closePrice, fastperiod=12, slowperiod=26, matype=0) rsi = talib.RSI(closePrice) slowk, slowd = talib.STOCH(highPrice, lowPrice, closePrice, fastk_period=14, slowk_period=3, slowd_period=3) macd, macdsignal, macdhist = talib.MACD(closePrice, fastperiod=12, slowperiod=26, signalperiod=9) # get ticker current price client = Client(os.environ.get('BINANCE_API_KEY'), os.environ.get('BINANCE_SECRET_KEY'), {"timeout": 100}) closing_price = client.get_symbol_ticker(symbol=symbol) # create crypto object crypto = {} crypto['ticker'] = symbol crypto['price'] = closing_price['price'] crypto['SMA14'] = sma[-1] crypto['ATR'] = atr[-1] crypto['NATR'] = natr[-1] crypto['ADX'] = adx[-1] crypto['MFI'] = mfi[-1] crypto['RSI'] = rsi[-1] crypto['STO'] = slowk[-1], slowd[-1] crypto['MACD'] = macd[-1] crypto['PPO'] = ppo[-1] else: crypto = {} crypto['ticker'] = symbol return crypto except Exception as e: print(str(e))
def natr(self, n, array=False): """ NATR. """ result = talib.NATR(self.high, self.low, self.close, n) if array: return result return result[-1]
def natr(self, n: int, array: bool = False) -> Union[float, np.ndarray]: """ NATR. """ result = talib.NATR(self.high, self.low, self.close, n) if array: return result return result[-1]
def get_natr(ohlc): natr = ta.NATR(ohlc['2_high'], ohlc['3_low'], ohlc['4_close'], timeperiod=14) ohlc['natr'] = natr return ohlc
def natr(self, sym, frequency, period=14): if not self.kbars_ready(sym, frequency): return [] highs = self.high(sym, frequency) lows = self.low(sym, frequency) closes = self.close(sym, frequency) natr = ta.NATR(highs, lows, closes, timeperiod=period) return natr
def NATR(high, low, close, timeperiod=14): ''' Normalized Average True Range 归一化波动幅度均值 分组: Volatility Indicator 波动率指标 简介: real = NATR(high, low, close, timeperiod=14) ''' return talib.NATR(high, low, close, timeperiod)
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)
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
def eval(self, environment, gene, date1, date2): timeperiod = int(gene.next_value(environment, date1, date2)) date1_ = environment.shift_date(date1, -(self.window-1), -1) high = gene.next_value(environment, date1_, date2) low = gene.next_value(environment, date1_, date2) close = gene.next_value(environment, date1_, date2) res = pd.DataFrame(np.nan, index=high.ix[date1:date2].index, columns=high.columns) for i, j in product(range(res.shape[0]), range(res.shape[1])): res.iloc[i, j] = talib.NATR( high.values[i: i+self.window, j], low.values[i: i+self.window, j], close.values[i: i+self.window, j], timeperiod=timeperiod)[-1] return res
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_natr(self): result = pandas_ta.natr(self.high, self.low, self.close) self.assertIsInstance(result, Series) self.assertEqual(result.name, "NATR_14") try: expected = tal.NATR(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)
def getRequirementData(req: ReqParam, data, reqMap): stocks = getStocks() for count, ticker in enumerate(stocks): df = data.get(ticker) if req.condition == 1: if req.indicatorPeriod is None: raise ValueError('Need to provide indicator period') df['ADX'] = talib.ADX(df['High'].values, df['Low'].values, df['Close'].values, req.indicatorPeriod) reqMap[ticker + '_' + str(req.indicatorPeriod)] = removeNaN( df['ADX'].values) if req.condition == 2: if req.fastPeriod is None or req.slowPeriod is None: raise ValueError('Need to provide fastperiod or slowperiod') df['chaikin'] = talib.ADOSC(df['High'].values, df['Low'].values, df['Close'].values, df['Volume'].values, req.fastPeriod, req.slowPeriod) reqMap[ticker + '_' + str(req.fastPeriod) + '_' + str(req.slowPeriod)] = removeNaN(df['chaikin'].values) if req.condition == 3: if req.indicatorPeriod is None or req.fastPeriod is None or req.slowPeriod is None: raise ValueError( 'Need to provide indicatorPeriod, fastPeriod or slowPeriod' ) _, __, df['MACDHist'] = talib.MACD( df['Close'].values, fastperiod=req.fastPeriod, slowperiod=req.slowPeriod, signalperiod=req.indicatorPeriod) reqMap[ticker + '_' + str(req.indicatorPeriod) + '_' + str(req.fastPeriod) + '_' + str(req.slowPeriod)] = removeNaN(df['MACDHist'].values) if req.condition == 4: if req.rollingPeriod is None: raise ValueError('Need to provide rollingPeriod') df['vol'] = np.where( df['Volume'] > df['Volume'].rolling(req.rollingPeriod).mean()) reqMap[ticker + '_' + str(req.rollingPeriod)] = df['vol'].values if req.condition == 6: if req.indicatorPeriod is None: raise ValueError('Need to provide indicator period') df['NATR'] = talib.NATR(df['High'].values, df['Low'].values, df['Close'].values, req.indicatorPeriod) reqMap[ticker + '_' + str(req.indicatorPeriod)] = removeNaN( df['NATR'].values) return reqMap
def compute_features(data): close = data['close'] rsi_indicator = talib.RSI(data['close'], 14) rsi_indicator = talib.SMA(rsi_indicator, 10) rsi_indicator = rsi_indicator / 100 bbands_indicator = talib.BBANDS(close, 20, 2, 2) low = bbands_indicator[2] mid = bbands_indicator[1] high = bbands_indicator[0] width = (high - low) / mid * 100 m = mid - low h = high - mid c = talib.SMA(close, 10) - mid close_in_bb = c / h natr = talib.NATR(data['high'], data['low'], data['close'], timeperiod=14) vol_sma = talib.SMA(data['volume'], 5) def zscore(x, window): r = x.rolling(window=window) m = r.mean().shift(1) s = r.std(ddof=0).shift(1) z = (x - m) / s return z z = zscore(vol_sma, 60 * 24) z = z / 10 df = pd.DataFrame({ 'vol_z': z, 'rsi': rsi_indicator, 'bb_width': width, 'natr': natr, 'close_pct_change': talib.SMA(close, 10).pct_change() * 100, 'time': data['time'], 'trades_count': data['trades'] / 100 }) for c in data.columns: df[c] = data[c] df = df[60 * 24 + 100:] return df
def generate_tech_data_default(stock, open_name, close_name, high_name, low_name, volume_name='vol'): open_price = stock[open_name].values close_price = stock[close_name].values low_price = stock[low_name].values high_price = stock[high_name].values volume = stock[volume_name].values data = stock.copy() data['MOM'] = talib.MOM(close_price) data['HT_DCPERIOD'] = talib.HT_DCPERIOD(close_price) data['HT_DCPHASE'] = talib.HT_DCPHASE(close_price) data['sine'], data['leadsine'] = talib.HT_SINE(close_price) data['inphase'], data['quadrature'] = talib.HT_PHASOR(close_price) data['ADXR'] = talib.ADXR(high_price, low_price, close_price) data['APO'] = talib.APO(close_price) data['AROON_UP'], _ = talib.AROON(high_price, low_price) data['CCI'] = talib.CCI(high_price, low_price, close_price) data['PLUS_DI'] = talib.PLUS_DI(high_price, low_price, close_price) data['PPO'] = talib.PPO(close_price) data['macd'], data['macd_sig'], data['macd_hist'] = talib.MACD(close_price) data['CMO'] = talib.CMO(close_price) data['ROCP'] = talib.ROCP(close_price) data['fastk'], data['fastd'] = talib.STOCHF(high_price, low_price, close_price) data['TRIX'] = talib.TRIX(close_price) data['ULTOSC'] = talib.ULTOSC(high_price, low_price, close_price) data['WILLR'] = talib.WILLR(high_price, low_price, close_price) data['NATR'] = talib.NATR(high_price, low_price, close_price) data['MFI'] = talib.MFI(high_price, low_price, close_price, volume) data['RSI'] = talib.RSI(close_price) data['AD'] = talib.AD(high_price, low_price, close_price, volume) data['OBV'] = talib.OBV(close_price, volume) data['EMA'] = talib.EMA(close_price) data['SAREXT'] = talib.SAREXT(high_price, low_price) data['TEMA'] = talib.EMA(close_price) #data = data.drop([open_name, close_name, high_name, low_name, volume_name, 'amount', 'count'], axis=1) data = drop_columns(data, [ open_name, close_name, high_name, low_name, volume_name, 'amount', 'count' ]) data = data.dropna().astype(np.float32) return data
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)
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
def corr_rate_calc(code): df = pd.read_sql( 'select * from day_k_data where code="' + code + '" order by date asc;', engine) ma5 = talib.MA(df['close'].values, 5) ma10 = talib.MA(df['close'].values, 10) ma20 = talib.MA(df['close'].values, 20) ma30 = talib.MA(df['close'].values, 30) K, D = talib.STOCH(df['high'].values, df['low'].values, df['close'].values, fastk_period=9, slowk_period=3) J = K * 3 - D * 2 atr = talib.ATR(df['high'].values, df['low'].values, df['close'].values) natr = talib.NATR(df['high'].values, df['low'].values, df['close'].values) trange = talib.TRANGE(df['high'].values, df['low'].values, df['close'].values) cci = talib.CCI(df['high'].values, df['low'].values, df['close'].values, 14) dif, dea, bar = talib.MACDFIX(df['close'].values) bar = bar * 2 df = df.drop(['code', 'open', 'low', 'high'], axis=1).set_index('date') df.insert(0, 'ma5', ma5) df.insert(0, 'ma10', ma10) df.insert(0, 'ma20', ma20) df.insert(0, 'ma30', ma30) df.insert(0, 'K', K) df.insert(0, 'D', D) df.insert(0, 'J', J) df.insert(0, 'cci', cci) df.insert(0, 'bar', bar) df.insert(0, 'dif', dif) df.insert(0, 'dea', dea) df_yesterday = df.T index_c = df.index added = [0] * len(df.columns) df_yesterday.insert(0, len(df_yesterday.columns), added) df_yesterday = df_yesterday.T df_yesterday = df_yesterday.drop(df.index[len(df.index) - 1]) df_yesterday.insert(0, 'index_c', index_c) df_yesterday = df_yesterday.set_index('index_c') dfd = df - df_yesterday return dfd.corr()
def sig_macd(df): highs = df['high'].values lows = df['low'].values closes = df['close'].values df['ta_NATR_%d' % 14] = talib.NATR(highs, lows, closes, 14) df = df.join(pta.MACD(df, fast, slow)) df["cross_%d_%d" % (fast, slow)] = df["ta_MACD_%d_%d" % (fast, slow)] / df["ta_MACDsign_%d_%d" % (fast, slow)] df["ta_MACD_%d_%d_shift_1" % (fast, slow)] = df["ta_MACD_%d_%d" % (fast, slow)].shift(1) df["cross_%d_%dshift_1" % (fast, slow)] = df["cross_%d_%d" % (fast, slow)].shift(1) df["ta_macd_signal_%d_%d" % (fast, slow)] = df.apply( lambda row: adx_signal(row), axis=1) return df