def OBV(ds1, volumeDs, count): """On Balance Volume""" data1 = value_ds_to_numpy(ds1, count) if data1 is None: return None data2 = value_ds_to_numpy(volumeDs, count) if data2 is None: return None return talib.OBV(data1, data2)
def calculate_features(df): """ Method which calculates and generates features """ close = df['close'].values high = df['high'].values low = df['low'].values volume = df['volume'].values last_row = df.tail(1).copy() # ************** Calc EMAs ema_periods = [2, 4, 8, 12, 16, 20] for ema_period in ema_periods: ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1] last_row['ema' + str(ema_period)] = ema # ************** Calc RSIs rsi_periods = [5] for rsi_period in rsi_periods: rsi = talib.RSI(close[-rsi_period:], timeperiod=rsi_period-1)[-1] last_row['rsi' + str(rsi_period)] = rsi last_row['rsi_above_50' + str(rsi_period)] = int(rsi > 50.0) # ************** Calc CCIs cci_periods = [5] for cci_period in cci_periods: cci = talib.CCI(high[-cci_period:], low[-cci_period:], close[-cci_period:], timeperiod=cci_period)[-1] last_row['cci' + str(cci_period)] = cci # ************** Calc MACD 1 macd_periods = [34] for macd_period in macd_periods: macd, macd_signal, _ = talib.MACD(close[-macd_period:], fastperiod=12, slowperiod=26, signalperiod=9) macd = macd[-1] signal_line = macd_signal[-1] last_row['macd_above_signal' + str(macd_period)] = int(macd > signal_line) last_row['macd_above_zero' + str(macd_period)] = int(macd > 0.0) # ************** Calc OBVs obv_periods = [2, 4, 8, 12, 16, 20] for obv_period in obv_periods: obv = talib.OBV(close[-obv_period:], volume[-obv_period:])[-1] last_row['obv' + str(obv_period)] = obv return last_row
def test_obv(self): result = pandas_ta.obv(self.close, self.volume_) self.assertIsInstance(result, Series) self.assertEqual(result.name, "OBV") try: expected = tal.OBV(self.close, self.volume_) 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 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'] ######################################### ###### Volume Indicator Functions ##### ######################################### #AD - Chaikin A/D Line ad = ta.AD(high, low, close, volume) #ADOSC - Chaikin A/D Oscillator adosc = ta.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10) #OBV - On Balance Volume obv = ta.OBV(close, volume) df_save = pd.DataFrame(data ={ 'date': np.array(df['date']), 'ad':ad, 'adosc':adosc, 'obv':obv }) df_save.to_csv(current_dir+"/"+base_dir+"/"+out_dir+'/'+stock_symbol+"/"+out_dir+'_ta_volume_indicator_'+stock_symbol+'.csv',index=False)
def pre_data(stick_code, ktype='D', today=''): # ktype in ('D','W','M') #today='2010-01-01' if '' == today: today = datetime.date.today().strftime('%Y-%m-%d') # begindate = datetime.date.today() - datetime.timedelta(days=13) global df db = m_db2() try: if ktype == 'D': df = db.get_data( "select * from t_stick_data_d where code = '" + stick_code + "' and date > '2015-09-01' and date <='" + today + "' order by date asc;") #and date>'2015-05-01' elif ktype == 'W': df = db.get_data("select * from t_stick_data_w where code = '" + stick_code + "' ;") #and date>'2015-05-01' elif ktype == 'M': df = db.get_data("select * from t_stick_data_m where code = '" + stick_code + "' ;") # and date>'2015-05-01' except Exception as e: #print('ERR:',e) return df['cci'] = ta.CCI(df['high'].values.astype('double'), df['low'].values.astype('double'), df['close'].values.astype('double')) df['diff'], df['dea'], df['macd'] = ta.MACD( df['close'].values.astype('double'), fastperiod=12, slowperiod=26, signalperiod=9) df['obv'] = ta.OBV(df['close'].values.astype('double'), df['vol'].values.astype('double')) df['volma5'] = ta.MA(df['vol'].values.astype('double'), 5) df['volma13'] = ta.MA(df['vol'].values.astype('double'), 13) df['volma20'] = ta.MA(df['vol'].values.astype('double'), 20) df['volma34'] = ta.MA(df['vol'].values.astype('double'), 34) df['MA20'] = ta.MA(df['close'].values.astype('double'), 20) df['MA60'] = ta.MA(df['close'].values.astype('double'), 60) df['MA5'] = ta.MA(df['close'].values.astype('double'), 5) df['MA13'] = ta.MA(df['close'].values.astype('double'), 13) df['MA34'] = ta.MA(df['close'].values.astype('double'), 34) df['MA89'] = ta.MA(df['close'].values.astype('double'), 89) df['MA144'] = ta.MA(df['close'].values.astype('double'), 144) df['cwbili'] = 0 df['pricebili'] = 0 return df
def getVolumeIndicators(df): high = df['High'] low = df['Low'] close = df['Close'] open = df['Open'] volume = df['Volume'] df['AD'] = ta.AD(high, low, close, volume) df['ADOSC'] = ta.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10) df['OBV'] = ta.OBV(close, volume)
def OBV(kline): """ OBV :param kline: 传入指定k线数据 :return: 返回一个一维数组 """ records = kline kline_length = len(records) close_array = np.zeros(kline_length) t = 0 for item in records: close_array[t] = item[4] t += 1 result = (talib.OBV(close_array, VOLUME(kline))) return result
def get_obv_talib_OBV(df): close_arr = df['close'].values vol_arr = df['vol'].values #倒置数组 日期升序 close_arr_reverse = close_arr[::-1] vol_arr_reverse = vol_arr[::-1] temp_arr = talib.OBV(close_arr_reverse, vol_arr_reverse) #倒置数组 日期降序 obv_arr = temp_arr[::-1] df['OBV'] = obv_arr temp_serise = df['OBV'].rolling(30).mean() temp_serise.dropna(inplace=True) maobv_serise = temp_serise.reset_index(drop=True) df['MAOBV'] = maobv_serise return df
def OnBar(self, bar): if self.bar_count >= 31: close = np.array(self.array.close) volume = np.array(self.array.volume, dtype='double') signal = ta.OBV(close, volume) if signal[-1] > 0 and self.pos == 0: self.buy(99999, 5000) elif signal[-1] < 0 and self.pos > 0: self.sell(1, self.pos) elif signal[-1] > 0 and self.pos < 0: self.buy_to_cover(99999, -self.pos) elif signal[-1] < 0 and self.pos == 0: self.sell_short(1, 5000) self.strategy_output(self.pos)
def obv(candles: np.ndarray, sequential: bool = False) -> Union[float, np.ndarray]: """ OBV - On Balance Volume :param candles: np.ndarray :param sequential: bool - default: False :return: float | np.ndarray """ candles = slice_candles(candles, sequential) res = talib.OBV(candles[:, 2], candles[:, 5]) return res if sequential else res[-1]
def OBV_EMA(self, timeperiod=20): """ Returns ------- TYPE DESCRIPTION. """ obv = ta.OBV(np.log(self.data.close), np.log(self.data.volume)) obv_ema = obv.ewm(com=timeperiod, adjust=True, min_periods=timeperiod).mean() return (obv - obv_ema) / obv
def add_ta_features(self): obv = talib.OBV(self.close, self.volume) obv_mv_avg = talib.MA(obv, timeperiod=10) obv_mv_avg[np.isnan(obv_mv_avg)] = obv[np.isnan(obv_mv_avg)] difference = obv - obv_mv_avg self.df['obv'] = obv self.df['obv_signal'] = difference self.df['obv_cheat'] = np.gradient(difference) upper, middle, lower = talib.BBANDS(self.close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) self.df['dn'] = lower self.df['mavg'] = middle self.df['up'] = upper self.df['pctB'] = (self.close - self.df.dn) / (self.df.up - self.df.dn) rsi14 = talib.RSI(self.close, 14) self.df['rsi14'] = rsi14 macd, macdsignal, macdhist = talib.MACD(self.close, 12, 26, 9) self.df['macd'] = macd self.df['signal'] = macdsignal ## addtional info self.df['adx'] = talib.ADX(self.high, self.low, self.close, timeperiod=14) self.df['cci'] = talib.CCI(self.high, self.low, self.close, timeperiod=14) ## maximum profit self.df['plus_di'] = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=14) ## lower_bound self.df['lower_bound'] = self.df['open'] - self.df['low'] + 1 ## ATR self.df['atr'] = talib.ATR(self.high, self.low, self.close, timeperiod=14) ## STOCH momentum self.df = ta.stochastic_oscillator_k(self.df) self.df = ta.stochastic_oscillator_d(self.df, n=10) ## TRIX self.df['trix'] = talib.TRIX(self.close, timeperiod=5) self.df['trix_signal'] = ta.moving_average(self.df['trix'], n=3) self.df['trix_hist'] = self.df['trix'] - self.df['trix_signal'] ## MFI self.df['mfi14'] = money_flow_index(self.df, 14)
def calculate(self, look_back, wallet): """ Main strategy logic (the meat of the strategy) """ (dataset_cnt, _) = common.get_dataset_count(look_back, self.group_by_field) # Wait until we have enough data if dataset_cnt < self.min_history_ticks: print('dataset_cnt:', dataset_cnt) return self.actions self.actions.clear() # Calculate indicators df = look_back.tail(self.min_history_ticks) close = df['close'].values volume = df['volume'].values new_action = TradeState.none close_price = self.get_price(TradeState.none, look_back, self.pair) # ************** OBV (On Balance Volume) obv = talib.OBV(close, volume)[-1] print('obv:', obv) if obv >= 100.0: new_action = TradeState.buy elif obv < 100.0: new_action = TradeState.sell # ************** Calc EMA ema_period = 6 ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1] if close_price <= ema: new_action = TradeState.sell if new_action == TradeState.none: return self.actions trade_price = self.get_price(new_action, df.tail(), self.pair) action = TradeAction(self.pair, new_action, amount=None, rate=trade_price, buy_sell_mode=self.buy_sell_mode) self.actions.append(action) return self.actions
def OBV(close, volume): ''' On Balance Volume 能量潮 分组: Volume Indicators 成交量指标 简介: Joe Granville提出,通过统计成交量变动的趋势推测股价趋势 计算公式:以某日为基期,逐日累计每日上市股票总成交量,若隔日指数或股票上涨 ,则基期OBV加上本日成交量为本日OBV。隔日指数或股票下跌, 则基期OBV减去本日成交量为本日OBV 研判: 1、以“N”字型为波动单位,一浪高于一浪称“上升潮”,下跌称“跌潮”;上升潮买进,跌潮卖出 2、须配合K线图走势 3、用多空比率净额法进行修正,但不知TA-Lib采用哪种方法 计算公式: 多空比率净额= [(收盘价-最低价)-(最高价-收盘价)] ÷( 最高价-最低价)×成交量 real = OBV(close, volume) ''' return talib.OBV(close, volume)
def btchart2_clicked(self): close = np.array(self.closes,dtype=float) high = np.array(self.highs,dtype=float) low = np.array(self.lows,dtype=float) vol = np.array(self.vols,dtype = float) self.macd, macdsignal,macdhist = talib.MACD(close) self.ema = talib.EMA(close) self.momentum = talib.MOM(close) self.slowk, self.slowd = talib.STOCH(high,low,close) self.roc = talib.ROC(close) self.willr = talib.WILLR(high,low,close) self.ad = talib.AD(high,low,close,vol) self.rsi = talib.RSI(close) self.obv = talib.OBV(close,vol) self.upband, middle, self.lowband = talib.BBANDS(close) print('지표계산 완료')
def stock_OBV(userstock): stock=TheConstructor(userstock) if type(stock) == str: return stock else: ret = pd.DataFrame(talib.OBV(stock['Close'], stock['Volume']), columns= ['OBV']) ret = pd.concat([ret,stock['Close']], axis=1) ### 開始畫圖 ### ret.plot(color=color, linestyle='dashed') ret['Close'].plot(secondary_y=True,color=color[5]) plt.title('On_Balance_Volume') # 標題設定 plt.grid(True,axis='y') plt.show() plt.savefig('On_Balance_Volume.png') #存檔 plt. close() # 刪除記憶體中的圖片 return Imgur.showImgur('On_Balance_Volume')
def get_feature_year(a,n,date1,date2): #1. data gathering & processing data = get_stock_data_year(a,date1,date2) data = data.replace(0, np.nan) data.dropna(inplace=True) #2. exponential smoothing S = X = np.array(data['Close']) alpha = 0.9 for i in range(1,len(S)): S[i] = alpha*X[i] + (1-alpha)*S[i-1] data['Close'] = S #3.data extraction macd, dea, bar = talib.MACD(data['Close'].values, fastperiod=12, slowperiod=26, signalperiod=9) fastk, fastd = talib.STOCHF(data['High'], data['Low'], data['Close'], fastk_period=14, fastd_period=3, fastd_matype=0) data['dif'] = data['Close'].diff(-n) data['MACD'] = macd data['STOCH'] = fastk data['WILLR'] = talib.WILLR(data['High'], data['Low'], data['Close'], timeperiod=14) data['OBV'] = talib.OBV(data['Close'], data['Volume']) data['RSI'] = talib.RSI(data['Close'], timeperiod=14) data['ATR'] = talib.ATR(data['High'],data['Low'],data['Close'], timeperiod=14) data = pd.DataFrame(data) data.dropna(inplace=True) #4. Labels are the values we want to predict diff = np.array(data['dif']) labels = np.zeros(len(diff)) sum = 0 for i in range(len(diff)): if diff[i] > 0: labels[i] = 1 sum += 1 # print (sum/len(diff)) #5. Remove the excess data from the features features = data[['STOCH']] #6. Saving feature names for later use feature_list = list(features.columns) return features, labels, feature_list
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 get_volumne_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) #AD-Chaikin A/D Line AD = pd.Series( ta.AD( np_high[~np_nan_indices], np_low[~np_nan_indices], np_close[~np_nan_indices], # np_volume[~np_nan_indices], np.asarray(np_volume[~np_nan_indices], dtype='float')), index=df_nonna_idxs) df_local['AD'] = AD #ADOSC-Chaikin A/D Oscillator ADOSC = pd.Series( ta.ADOSC( np_high[~np_nan_indices], np_low[~np_nan_indices], np_close[~np_nan_indices], #np_volume[~np_nan_indices], np.asarray(np_volume[~np_nan_indices], dtype='float')), index=df_nonna_idxs) df_local['ADOSC'] = ADOSC #OBV-On Balance Volume OBV = pd.Series( ta.OBV( np_close[~np_nan_indices], #np_volume[~np_nan_indices], np.asarray(np_volume[~np_nan_indices], dtype='float')), index=df_nonna_idxs) df_local['OBV'] = OBV return df_local
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 OBV(self, df): """On Balance Volume (OBV) measures buying and selling pressure as a cumulative indicator that adds volume on up days and subtracts volume on down days. Args: close: close of issue volume: volume of issue feature_dict: Dictionary of added features Return: onBalVol feature_dict """ col_name = 'OBV' current_feature['Latest'] = col_name feature_dict[col_name] = 'Keep' df[col_name] = ta.OBV(df.Close, df.Volume) return df
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
def obv(candles: np.ndarray, sequential=False) -> Union[float, np.ndarray]: """ OBV - On Balance Volume :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.OBV(candles[:, 2], candles[:, 5]) if sequential: return res else: return None if np.isnan(res[-1]) else res[-1]
def obv(client, symbol, timeframe="6m", closecol="close", volumecol="volume"): """This will return a dataframe of On Balance Volume for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): Ticker timeframe (string): timeframe to use, for pyEX.chart closecol (string): column to use to calculate volumecol (string): column to use to calculate Returns: DataFrame: result """ df = client.chartDF(symbol, timeframe) obv = t.OBV(df[closecol].values.astype(float), df[volumecol].values.astype(float)) return pd.DataFrame( {closecol: df[closecol].values, volumecol: df[volumecol].values, "obv": obv} )
def OBV(self, kline=None): """ OBV :param kline: 回测时传入指定k线数据 :return: 返回一个一维数组 """ if kline: records = kline else: records = self.__platform.get_kline(self.__time_frame) kline_length = len(records) close_array = np.zeros(kline_length) t = 0 for item in records: close_array[t] = item[4] t += 1 result = (talib.OBV(close_array, self.VOLUME())) return result
def tech_indicator(self) -> pd.DataFrame: cp = self.df.copy() close = cp.close.values open_price = cp.close.values high = cp.close.values low = cp.low.values volume = cp.volume.values cp['SMA_5'] = talib.SMA(close, 5) cp['upper'], cp['middle'], cp['low'] = talib.BBANDS(close, matype=MA_Type.T3) cp['slowk'], cp['slowd'] = talib.STOCH(high, low, close, fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) cp['slowk_slowd'] = cp['slowk'] - cp['slowd'] cp['CCI'] = talib.CCI(high, low, close, timeperoid=10) cp['DIF'], cp['DEA'], cp['HIST'] = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) cp['BAR'] = (cp['DIF'] - cp['DEA']) * 2 cp['macdext'], cp['signal_xt'], cp['hist_xt'] = talib.MACDFIX( close, signalperiod=9) cp['RSI'] = talib.RSI(close, timepriod=14) cp['AROON_DOWN'], cp['AROON_UP'] = talib.AROON(high, low, timeperiod=14) cp['upperband'], cp['middleband'], cp['lowerband'] = talib.BBANDS( close, timepriod=5, nbdevup=2, nbdevdn=2, matype=0) cp['AD'] = talib.AD(high, low, close, volume) cp['ADX'] = talib.ADX(high, low, close, timeperiod=14) cp['ADXR'] = talib.ADXR(high, low, close, timeperiod=14) cp['OBV'] = talib.OBV(close, volume) return cp
def Get_feature(df): df['Pre_high'] = df['high'].shift(1) df['Pre_low'] = df['low'].shift(1) df['Pre_close'] = df['close'].shift(1) df['Pre_volume'] = df['volume'].shift(1) feature_names = [ 'Volume_Change', 'Market_info', 'Market_info_2', 'Market_info_3', 'Market_info_4', 'MA5', 'MA120', 'MA20', 'RSI', 'Corr', 'SAR', 'ADX', 'ATR', 'OBV' ] df['Market_info'] = np.where( df.Pre_close > df.Pre_close.rolling(120).median(), 1, 0) df['Market_info_2'] = np.where( df.Pre_close < df.Pre_close.rolling(120).max() * 0.9, 1, 0) df['Market_info_3'] = np.where( df.Pre_close > df.Pre_close.rolling(120).min() * 1.1, 1, 0) df['Market_info_4'] = np.where( df.Pre_close.rolling(120).max() / df.Pre_close.rolling(120).min() > 1.2, 1, 0) df['Volume_Change'] = (df.volume / df.Pre_volume) - 1 df['MA20'] = df.Pre_close.rolling(window=20).mean() df['MA5'] = ta.MA(df.Pre_close, 5) df['MA120'] = ta.MA(df.Pre_close, 120) df['RSI'] = ta.RSI(df.Pre_close, timeperiod=14) df['Corr'] = df['MA20'].rolling(window=20).corr(df['Pre_close']) df['SAR'] = ta.SAR(np.array(df['Pre_high']), np.array(df['Pre_low']), 0.2, 0.2) df['ADX'] = ta.ADX(np.array(df['Pre_high']), np.array(df['Pre_low']), np.array(df['Pre_close']), timeperiod=14) df['ATR'] = ta.ATR(np.array(df['Pre_high']), np.array(df['Pre_low']), np.array(df['Pre_close']), timeperiod=14) df['OBV'] = ta.OBV(df.Pre_close, df.Pre_volume) df = df.loc[:, feature_names + ['symbol', 'Return', 'True_return']].replace( np.inf, 10000).replace(-np.inf, -10000) df = df.dropna() return df
def test_OBV(self): class MyOBV(OperatorOBV): def __init__(self, name, **kwargs): super(MyOBV, self).__init__(100, name, **kwargs) self.env.add_operator('obv', { 'operator': MyOBV, }) string = 'obv(high, volume)' gene = self.env.parse_string(string) self.assertRaises(IndexError, gene.eval, self.env, self.dates[98], self.dates[-1]) ser = gene.eval(self.env, self.dates[99], self.dates[99]).iloc[0] h = self.env.get_data_value('high').values v = self.env.get_data_value('volume').values res = [] for i, val in ser.iteritems(): res.append(talib.OBV(h[:100, i], v[:100, i])[-1] == val) self.assertTrue(all(res))
def handle_data(self, data): sid = self.sids[0] tmptop = [] for i in range(10): tmptop.append( (self.topsgetattr(data[sid], "top%d_buyvolume" % (i)) - getattr(data[sid], "top%d_sellvolume" % (i), self.tops[i]))) self.window.append(( # data data[sid].open, data[sid].high, data[sid].low, data[sid].close, data[sid].volume, # future data[sid].fopen, data[sid].fhigh, data[sid].flow, data[sid].fclose, data[sid].fvolume, # credit data[sid].financesellvolume, data[sid].financeused)) self.window[-1] += (tmptop[-1], ) if len(self.window) == self._buf_win: open, high, low, close, volume = [ np.array(i) for i in zip(*self.window) ] talib.EMA(close, timeperiod=5) talib.OBV(close, np.asarray(volume, dtype='float')) #talib.DMA if self._trend_up: close[-1] signals = { 'open': open[-1], }
def generate_indicator(self, name): if name == 'BBANDS_upper': se = talib.BBANDS(self.data_dict['close'])[0] elif name == 'BBANDS_middle': se = talib.BBANDS(self.data_dict['close'])[1] elif name == 'BBANDS_lower': se = talib.BBANDS(self.data_dict['close'])[2] elif name == 'MA': se = talib.MA(self.data_dict['close'], timeperiod=30) elif name == 'EMA': se = talib.EMA(self.data_dict['close'], timeperiod=30) elif name == 'SMA': se = talib.SMA(self.data_dict['close'], timeperiod=30) elif name == 'WMA': se = talib.WMA(self.data_dict['close'], timeperiod=30) if name == 'APO': se = talib.APO(self.data_dict['close']) elif name == 'MACD': se = talib.MACD(self.data_dict['close'])[0] elif name == 'MOM': se = talib.MOM(self.data_dict['close']) elif name == 'PPO': se = talib.PPO(self.data_dict['close']) elif name == 'RSI': se = talib.RSI(self.data_dict['close']) elif name == 'WILLR': se = talib.WILLR(self.data_dict['high'], self.data_dict['low'], self.data_dict['close']) if name == 'OBV': se = talib.OBV(self.data_dict['close'], self.data_dict['volume']) if name == 'ATR': se = talib.ATR(self.data_dict['high'], self.data_dict['low'], self.data_dict['close'], timeperiod=14) ans = pd.Series(se, index=self.datetime_index) ans.name = name return ans