def preproc(self): self.dat = df = pd.read_csv(self.path) s = np.asanyarray(ta.stoch( df["High"], df["Low"], df["Close"], 14)).reshape( (-1, 1)) - np.asanyarray( ta.stoch_signal(df["High"], df["Low"], df["Close"], 14)).reshape((-1, 1)) m = np.asanyarray(ta.macd(df["Close"])).reshape( (-1, 1)) - np.asanyarray(ta.macd_signal(df["Close"])).reshape( (-1, 1)) trend3 = np.asanyarray(self.dat[["Close"]]) - np.asanyarray( ta.ema(self.dat["Close"], 20)).reshape((-1, 1)) cross1 = np.asanyarray(ta.ema(self.dat["Close"], 20)).reshape( (-1, 1)) - np.asanyarray(ta.ema(self.dat["Close"], 5)).reshape( (-1, 1)) y = np.asanyarray(self.dat[["Open"]]) x = np.concatenate([s, m, cross1], 1) gen = tf.keras.preprocessing.sequence.TimeseriesGenerator( x, y, self.window_size) self.x = [] self.y = [] for i in gen: self.x.extend(i[0].tolist()) self.y.extend(i[1].tolist()) self.x = np.asanyarray( self.x) #.reshape((-1, self.window_size, x.shape[-1])) self.y = np.asanyarray(self.y) self.df = self.x self.trend = self.y
def stoch(candles, window): """Stochastic Oscillator""" highs = util.filtership(candles, "max") lows = util.filtership(candles, "min") closes = util.filtership(candles, "close") result = ta.stoch(highs, lows, closes, window) return result
def _indicadores(self, df): ''' ESTA FUNCAO NAO E EXECUDA, ELA EXECUTA ATRAVES DA FUNCAO INDICADOR() ''' import warnings warnings.filterwarnings("ignore", message="divide by zero encountered in double_scalars") warnings.filterwarnings("ignore", message="invalid value encountered in double_scalars") db = pd.DataFrame() for i in df.asset.unique(): df1 = df[df['asset'] == i].copy() df1['PD_low'] = df1.low.shift(1) df1['PD_high'] = df1.high.shift(1) df1['Change%'] = df1.close.pct_change().round(4) df1['SMA20'] = df1.close.rolling(20).mean().round(5) df1['SMA200'] = df1.close.rolling(200).mean().round(5) df1['low60'] = df1.low.rolling(window=60).min() df1['low300'] = df1.low.rolling(window=300).min() df1['low1200'] = df1.low.rolling(window=1200).min() df1['high60'] = df1.high.rolling(window=60).max() df1['high300'] = df1.high.rolling(window=300).max() df1['high1200'] = df1.high.rolling(window=1200).max() df1['%60'] = ((df1.close - df1.low60) / (df1.high60 - df1.low60)).round(2) df1['%300'] = ((df1.close - df1.low300) / (df1.high300 - df1.low300)).round(2) df1['%1200'] = ((df1.close - df1.low1200) / (df1.high1200 - df1.low1200)).round(2) df1['ATR'] = ((df1.high - df1.low).rolling(10).mean() * 5 + (df1.high - df1.low).rolling(60).mean() * 3 + (df1.high - df1.low).rolling(1200).mean() * 2) / 10 df1['PW_low1'] = df1.low.shift(1).resample('W').min().reindex(df1.index, method='ffill') #FIXED df1['PW_open'] = df1.open.shift(1).resample('W').first().reindex(df1.index, method='ffill') #FIXED df1['PW_close'] = df1.close.shift(1).resample('W').last().reindex(df1.index, method='ffill') #FIXED df1['PW_high1'] = df1.high.shift(1).resample('W').max().reindex(df1.index, method='ffill') #FIXED df1['PM_low1'] = df1.low.resample('M').min().reindex(df1.index, method='ffill').shift(1) #FIXED df1['PM_open'] = df1.open.resample('M').first().reindex(df1.index, method='ffill').shift(1) #FIXED df1['PM_close'] = df1.close.resample('M').last().reindex(df1.index, method='ffill').shift(1) #FIXED df1['PM_high1'] = df1.high.resample('M').max().reindex(df1.index, method='ffill').shift(1) #FIXED df1['M1_low'] = df1.low.resample('30D').min().reindex(df1.index, method='ffill') df1['M1_high'] = df1.high.resample('30D').max().reindex(df1.index, method='ffill') df1['RSI_5K'] = ta.stoch(df.high, df.low, df.close, 5).round(0) #FIXED df1['RSI_5D'] = ta.stoch_signal(df.high, df.low, df.close, 5, 3).round(0) #FIXED df1['d30%'] = ((df1.close - df1.close.shift(30)) / df1.close).round(4) db = pd.concat([db, df1]) return db
def rsi(self, df, period=50): #UPGRADE df.columns = map(str.lower, df.columns) #UPGRADE df.sort_index(inplace=True) df = df.reset_index() #UPGRADE rsi_k = ta.stoch(df['high'], df['low'], df['close'], period) rsi_k = rsi_k.iloc[-1] rsi_d = ta.stoch_signal(df['high'], df['low'], df['close'], period, 3) rsi_d = rsi_d.iloc[-1] return rsi_d, rsi_k
def rsi(self, df, period=5): df.columns = map(str.lower, df.columns) df.sort_index(inplace = True) df = df.reset_index() rsi_k = ta.stoch(df['high'], df['low'], df['close'], period) rsi_k = rsi_k.iloc[-1] rsi_d = ta.stoch_signal(df['high'], df['low'], df['close'], period, 3) rsi_d = rsi_d.iloc[-1] return int(rsi_d), int(rsi_k)
def so(): so = ta.stoch(high, low, close, n=14, fillna=False) SO = (so[-1]) if SO <= 20: status3 = "Buy" elif SO <= 30: status3 = "Buy" elif SO >= 80: status3 = "Sell" elif SO >= 70: status3 = "Sell" else: status3 = "Hold" return status3
def do_ta(self, data_series): open = Series(data_series['open'].astype('float64')) high = Series(data_series['high'].astype('float64')) low = Series(data_series['low'].astype('float64')) close = Series(data_series['close'].astype('float64')) # Trend # ---------------- ema30 = ta.ema(series=close, periods=30) ema50 = ta.ema(series=close, periods=50) ema100 = ta.ema(series=close, periods=100) ema200 = ta.ema(series=close, periods=200) macd_diff = ta.macd_diff(close=close, n_fast=12, n_slow=26, n_sign=9) macd_signal = ta.macd_signal(close=close, n_fast=12, n_slow=26, n_sign=9) data_series['ema30'] = ema30 data_series['ema50'] = ema50 data_series['ema100'] = ema100 data_series['ema200'] = ema200 data_series['macd_diff'] = macd_diff data_series['macd_signal'] = macd_signal # Momentum # ---------------- rsi = ta.rsi(close=close) stochastic = ta.stoch(high=high, low=low, close=close) data_series['rsi'] = rsi data_series['stochastic'] = stochastic # Volatility # ---------------- bollinger_h = ta.bollinger_hband(close=close) bollinger_l = ta.bollinger_lband(close=close) bollinger_h_indicator = ta.bollinger_hband_indicator(close=close) bollinger_l_indicator = ta.bollinger_lband_indicator(close=close) data_series['bollinger_h'] = bollinger_h data_series['bollinger_l'] = bollinger_l data_series['bollinger_h_indicator'] = bollinger_h_indicator data_series['bollinger_l_indicator'] = bollinger_l_indicator data_series['last_candle_change'] = self.lcc(close=close) return data_series
def analyze(data): # Moving average (5, 20, 75 days) sma5 = data['close'].rolling(window=5).mean() sma20 = data['close'].rolling(window=20).mean() sma75 = data['close'].rolling(window=75).mean() # MACD (12, 26 days) macd12_26 = ta.macd(data['close'], n_fast=12, n_slow=26) macd12_26_sig = ta.macd_signal(data['close'], n_fast=12, n_slow=26, n_sign=9) # Stochastics (%K: 5(not used), 9(not used), 14 day, %D: 3 days) stoch14_k = ta.stoch(data['high'], data['low'], data['close'], n=14) stoch14_d = ta.stoch_signal(data['high'], data['low'], data['close'], n=14, d_n=3) # Bollinger band (+3 sigma ~ -3 sigma) bb20_h1 = ta.bollinger_hband(data['close'], n=20, ndev=1) bb20_h2 = ta.bollinger_hband(data['close'], n=20, ndev=2) bb20_h3 = ta.bollinger_hband(data['close'], n=20, ndev=3) bb20_l1 = ta.bollinger_lband(data['close'], n=20, ndev=1) bb20_l2 = ta.bollinger_lband(data['close'], n=20, ndev=2) bb20_l3 = ta.bollinger_lband(data['close'], n=20, ndev=3) # Concatenate analysis = pd.concat([ sma5, sma20, sma75, macd12_26, macd12_26_sig, stoch14_k, stoch14_d, bb20_h1, bb20_h2, bb20_h3, bb20_l1, bb20_l2, bb20_l3 ], axis=1) analysis.columns = [ '5-Day SMA', '20-Day SMA', '75-Day SMA', 'MACD (12-16)', 'MACD Signal (12-26-9)', 'Stochastics %K (14 Day)', 'Stochastics %D (14 Day)', 'BB +1sigma', 'BB +2sigma', 'BB +3sigma', 'BB -1sigma', 'BB -2sigma', 'BB -3sigma' ] return analysis
def preproc(self): self.dat = df = pd.read_csv(self.path) s = np.asanyarray(ta.stoch(df["High"],df["Low"],df["Close"],14)).reshape((-1, 1)) - np.asanyarray(ta.stoch_signal(df["High"],df["Low"],df["Close"],14)).reshape((-1, 1)) x = np.asanyarray(ta.daily_return(df["Close"])).reshape((-1,1)) m = np.asanyarray(ta.macd_diff(df["Close"])).reshape((-1,1)) cross1 = np.asanyarray(ta.ema(self.dat["Close"],20)).reshape((-1, 1)) - np.asanyarray(ta.ema(self.dat["Close"],5)).reshape((-1, 1)) x = np.concatenate([x], 1) y = np.asanyarray(self.dat[["Open"]]) gen = tf.keras.preprocessing.sequence.TimeseriesGenerator(x, y, self.window_size) self.x = [] self.y = [] for i in gen: self.x.extend(i[0].tolist()) self.y.extend(i[1].tolist()) self.x = np.asanyarray(self.x)[1000::] self.y = np.asanyarray(self.y)[1000::] self.df = self.x[-self.STEP_SIZE::] self.trend = self.y[-self.STEP_SIZE::]
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import ta df = pd.read_csv('./data/coinbase_daily.csv') df = df.dropna().reset_index().sort_values('Date') ta_df = pd.DataFrame() ta_df['RSI'] = ta.rsi(df["Close"]) ta_df['MFI'] = ta.money_flow_index( df["High"], df["Low"], df["Close"], df["Volume BTC"]) ta_df['TSI'] = ta.tsi(df["Close"]) ta_df['UO'] = ta.uo(df["High"], df["Low"], df["Close"]) ta_df['Stoch'] = ta.stoch(df["High"], df["Low"], df["Close"]) ta_df['Stoch_Signal'] = ta.stoch_signal(df["High"], df["Low"], df["Close"]) ta_df['WR'] = ta.wr(df["High"], df["Low"], df["Close"]) ta_df['AO'] = ta.ao(df["High"], df["Low"]) ta_df['MACD'] = ta.macd(df["Close"]) ta_df['MACD_signal'] = ta.macd_signal(df["Close"]) ta_df['MACD_diff'] = ta.macd_diff(df["Close"]) ta_df['EMA_fast'] = ta.ema_indicator(df["Close"]) ta_df['EMA_slow'] = ta.ema_indicator(df["Close"]) ta_df['Vortex_pos'] = ta.vortex_indicator_pos( df["High"], df["Low"], df["Close"]) ta_df['Vortex_neg'] = ta.vortex_indicator_neg( df["High"], df["Low"], df["Close"]) ta_df['Vortex_diff'] = abs( ta_df['Vortex_pos'] -
def get_data(context, data_, window): # Crear ventana de datos. h1 = data_.history( context.symbols, context.row_features, bar_count=window, frequency=str(context.bar_period) + "T", ) h1 = h1.swapaxes(2, 0) norm_data = [] close_prices = [] for i, asset in enumerate(context.assets): data = h1.iloc[i] close = h1.iloc[i].close if context.include_ha: ha = heikenashi(data) data = pd.concat((data, ha), axis=1) for period in [3, 6, 8, 10, 15, 20]: data["rsi" + str(period)] = ta.rsi(data.close, n=period, fillna=True) data["stoch" + str(period)] = ta.stoch(data.high, data.low, data.close, n=period, fillna=True) data["stoch_signal" + str(period)] = ta.stoch_signal( high=data.high, low=data.low, close=data.close, n=period, d_n=3, fillna=True) data["dpo" + str(period)] = ta.dpo(close=data.close, n=period, fillna=True) data["atr" + str(period)] = ta.average_true_range(high=data.high, low=data.low, close=data.close, n=period, fillna=True) for period in [6, 7, 8, 9, 10]: data["williams" + str(period)] = ta.wr(high=data.high, low=data.low, close=data.close, lbp=period, fillna=True) for period in [12, 13, 14, 15]: data["proc" + str(period)] = ta.trix(close=data.close, n=period, fillna=True) data["macd_diff"] = ta.macd_diff(close=data.close, n_fast=15, n_slow=30, n_sign=9, fillna=True) data["macd_signal"] = ta.macd_signal(close=data.close, n_fast=15, n_slow=30, n_sign=9, fillna=True) data["bb_high_indicator"] = ta.bollinger_hband_indicator( close=data.close, n=15, ndev=2, fillna=True) data["bb_low_indicator"] = ta.bollinger_lband_indicator( close=data.close, n=15, ndev=2, fillna=True) data["dc_high_indicator"] = ta.donchian_channel_hband_indicator( close=data.close, n=20, fillna=True) data["dc_low_indicator"] = ta.donchian_channel_lband_indicator( close=data.close, n=20, fillna=True) data["ichimoku_a"] = ta.ichimoku_a(high=data.high, low=data.low, n1=9, n2=26, fillna=True) data.fillna(method="bfill") # Normalizar los valores for feature in data.columns: norm_feature = preprocessing.normalize( data[feature].values.reshape(-1, 1), axis=0) data[feature] = pd.DataFrame(data=norm_feature, index=data.index, columns=[feature]) norm_data.append(data.values) close_prices.append(close) context.features = data.columns return np.array(norm_data), np.array(close_prices)
def get_trayectory(self, t_intervals): """ :param t_intervals: número de intervalos en cada trayectoria :return: Datos con características de la trayectoria sintética y precios de cierre en bruto de al misma """ trayectories = [] closes = [] p = True for i, asset in enumerate(self.context.assets): synthetic_return = np.exp( self.drift[i] + self.stdev[i] * norm.ppf(np.random.rand((t_intervals * self.frequency) + self.frequency, 1))) initial_close = self.close[i, -1] synthetic_close = np.zeros_like(synthetic_return) synthetic_close[0] = initial_close for t in range(1, synthetic_return.shape[0]): synthetic_close[t] = synthetic_close[t - 1] * synthetic_return[t] OHLC = [] for t in range(synthetic_return.shape[0]): if t % self.frequency == 0 and t > 0: open = synthetic_close[t - self.frequency] high = np.max(synthetic_close[t - self.frequency: t]) low = np.min(synthetic_close[t - self.frequency: t]) close = synthetic_close[t] OHLC.append([open, high, close, low]) data = pd.DataFrame(data=OHLC, columns=["open", "high", "low", "close"]) close = data.close if self.context.include_ha: ha = heikenashi(data) data = pd.concat((data, ha), axis=1) for period in [3, 6, 8, 10, 15, 20]: data["rsi" + str(period)] = ta.rsi(data.close, n=period, fillna=True) data["stoch" + str(period)] = ta.stoch(data.high, data.low, data.close, n=period, fillna=True) data["stoch_signal" + str(period)] = ta.stoch_signal(high=data.high, low=data.low, close=data.close, n=period, d_n=3, fillna=True) data["dpo" + str(period)] = ta.dpo(close=data.close, n=period, fillna=True) data["atr" + str(period)] = ta.average_true_range(high=data.high, low=data.low, close=data.close, n=period, fillna=True) for period in [6, 7, 8, 9, 10]: data["williams" + str(period)] = ta.wr(high=data.high, low=data.low, close=data.close, lbp=period, fillna=True) for period in [12, 13, 14, 15]: data["proc" + str(period)] = ta.trix(close=data.close, n=period, fillna=True) data["macd_diff"] = ta.macd_diff(close=data.close, n_fast=15, n_slow=30, n_sign=9, fillna=True) data["macd_signal"] = ta.macd_signal(close=data.close, n_fast=15, n_slow=30, n_sign=9, fillna=True) data["bb_high_indicator"] = ta.bollinger_hband_indicator(close=data.close, n=15, ndev=2, fillna=True) data["bb_low_indicator"] = ta.bollinger_lband_indicator(close=data.close, n=15, ndev=2, fillna=True) data["dc_high_indicator"] = ta.donchian_channel_hband_indicator(close=data.close, n=20, fillna=True) data["dc_low_indicator"] = ta.donchian_channel_lband_indicator(close=data.close, n=20, fillna=True) data["ichimoku_a"] = ta.ichimoku_a(high=data.high, low=data.low, n1=9, n2=26, fillna=True) data.fillna(method="bfill") # Normalizar los valores for feature in data.columns: norm_feature = preprocessing.normalize(data[feature].values.reshape(-1, 1), axis=0) data[feature] = pd.DataFrame(data=norm_feature, index=data.index, columns=[feature]) self.assets = data.columns trayectories.append(data.values) closes.append(close) return np.array(trayectories), np.array(closes)