def __calculate_indicator(self): # Create RSI Series self.rsi = talib.RSI(self.numpy_array["close"], timeperiod=14) # Create Bollinger Bands bollinger_upper, bollinger_middle, bollinger_lower = talib.BBANDS( self.numpy_array["close"], timeperiod=20) self.bollinger_bandwidth = ( (bollinger_upper - bollinger_lower) / bollinger_middle) * 100 # Calculate Directional Indicators. minus_dmi = talib.MINUS_DI(high=self.numpy_array["high"], low=self.numpy_array["low"], close=self.numpy_array["close"]) plus_dmi = talib.PLUS_DI(high=self.numpy_array["high"], low=self.numpy_array["low"], close=self.numpy_array["close"]) # If Directional Indicator gives Upward Direction. self.dmi_difference = plus_dmi - minus_dmi # Slope Calculation : Throws error if value is yet NaN try: self.rsi_slope_angle = self.__slope_to_degrees( talib.LINEARREG_SLOPE(self.rsi, timeperiod=5)) self.bw_slope_angle = self.__slope_to_degrees( talib.LINEARREG_SLOPE(self.bollinger_bandwidth, timeperiod=5)) except Exception: #logging.info("Value of RSI and Bollinger is null") raise StrategyNotReady(1, "Value of RSI and Bollinger is null") return None
def getIndepIndicators(DF, rsi_n, bollinger_n): #get rsi df = DF.copy() df["rsi"] = talib.RSI(df["close"], timeperiod=rsi_n) #get ema df["ema50"] = df["ema50"] = talib.EMA(df['close'], timeperiod=50) df["ema100"] = df["ema100"] = talib.EMA(df['close'], timeperiod=100) df["ema150"] = df["ema150"] = talib.EMA(df['close'], timeperiod=150) #get bollingers upperband, middleband, lowerband = talib.BBANDS(df["close"], timeperiod=bollinger_n, nbdevup=2, nbdevdn=2, matype=0) df["BB_up"] = upperband df["BB_dn"] = upperband df["BB_range"] = upperband - middleband #obv df['obv'] = talib.OBV(df['close'], df['volume']) df.dropna(inplace=True) #angles df["angle50"] = talib.LINEARREG_SLOPE(df["ema50"], timeperiod=5) df["angle100"] = talib.LINEARREG_SLOPE(df["ema100"], timeperiod=5) df["angle150"] = talib.LINEARREG_SLOPE(df["ema150"], timeperiod=5) #future_close df["future_close"] = df["close"].shift(-1) df.dropna(inplace=True) return df
def do_algo(i, t=15): points = arr_ys[i - (t + 2):i + 1] slope = ta.LINEARREG_SLOPE(points, t)[-1] slope_5 = ta.LINEARREG_SLOPE(points, 5)[-1] # slope_prev = ta.LINEARREG_SLOPE(points,t)[-2] # slope_prev_2 = ta.LINEARREG_SLOPE(points,t)[-3] # print(str(slope_prev_2)) if slope > 0 and slope_5 > 0: return True else: return False
def getTrend(self, fastWindow=6, slowWindow=30): trendFastArray = talib.LINEARREG_SLOPE(self.close, fastWindow) trendSlowArray = talib.LINEARREG_SLOPE(self.close, slowWindow) if trendFastArray[-1] > trendSlowArray[-1] or trendFastArray[-1] > 0: Trend = 1 elif trendFastArray[-1] < trendSlowArray[-1] or trendSlowArray[-1] < 0: Trend = -1 else: Trend = 0 return Trend
def add_stock_index(self, df0, index_list=None): ktype, period, scale = self.klineType[: -1], self.timePeriods, self.scale close = df0["close"] df0["ma"] = ma = ta.MA(close, timeperiod=period) df0["std"] = std = ta.STDDEV(close, timeperiod=period, nbdev=1) # 上下柜 # bullWidth df0["bullwidth"] = width = (4 * std / ma * 100).fillna(0) # 近三分钟width变动 df0["widthDelta"] = self.stand(ta.LINEARREG_SLOPE(width, timeperiod=3)) df0["slope"] = self.stand( ta.LINEARREG_SLOPE(ta.MA(close, timeperiod=5), timeperiod=2)) df0["slope30"] = self.stand( ta.LINEARREG_SLOPE(ta.MA(close, timeperiod=period), timeperiod=3)) df0["rsi"] = rsi = ta.RSI(close, timeperiod=14) # SAR 顶点 sar = ta.SAR(df0["high"], df0["low"], acceleration=0.04, maximum=0.2) df0['sard'] = sard = close - sar df0['sarm'] = sard * sard.shift(1) df0['sarm'] = df0.apply( lambda row: self.turn(row['sarm'], row['sard'], 1), axis=1) # kdj顶点 kdjK, kdjD = ta.STOCH(df0["high"], df0["low"], close, fastk_period=4, slowk_period=3, slowk_matype=2, slowd_period=3, slowd_matype=2) df0["kdj_d2"] = kdj_d2 = kdjK - kdjD df0["kdjm"] = kdj_d2 * kdj_d2.shift(1) df0["kdjm"] = df0.apply( lambda row: self.turn(row['kdjm'], row['kdj_d2'], 1), axis=1) df0["top"], df0["lower"] = ma + (scale + 0.1) * std, ma - (scale - 0.1) * std df0["p_l"] = close * (1 + self.shift) df0["p_h"] = close * (1 - self.shift) df1 = df0.apply(lambda row: self.point(row, ktype), axis=1) for key in self.pointColumns: df0[key] = df1[key] return df0
def TripleScreen_extend_data(df, timeScaleSmall, timeScaleLarge): df_large = data_min_resample(df, timeScaleLarge) df_large['slope'] = talib.LINEARREG_SLOPE(df_large['close'], 13) df_large['dif'], df_large['dem'], df_large['histogram'] = talib.MACD( df_large['close'], fastperiod=12, slowperiod=26, signalperiod=9) df_large['histogram_pre'] = df_large.shift(1)['histogram'] df_large['macdTrade'] = df_large['histogram'] > df_large['histogram_pre'] df_large['firstSignal'] = 0 df_large.loc[(df_large['slope'] > 0) & (df_large['macdTrade']), 'firstSignal'] = True df_large.loc[(df_large['slope'] > 0) & (df_large['macdTrade'] == False), 'firstSignal'] = False df_small = data_min_resample(df, timeScaleSmall) df_small['fi'] = ta.volume.ForceIndexIndicator(close=df_small['close'], volume=df_small["volume"], n=2, fillna=False).force_index() df_small['fi_pre'] = df_small['fi'].shift() df_small.loc[(df_small['fi'] > 0) & (df_small['fi_pre'] < 0), 'secondSignal'] = True df_temp = df_large.resample("d", ).pad()['firstSignal'] res_df = pd.concat([df_small, df_temp], axis=1, join_axes=[df_small.index]) res_df['buyPoint'] = 0 res_df.loc[(res_df['secondSignal']) & (res_df['firstSignal']), 'buyPoint'] = True return res_df
def rsi(df, target_list): for target in target_list: value = talib.RSI(df[target], hp.timePeriodRSI) value = np.nan_to_num(value) rsiValueCorrect, pastVar = [], 50 for val in value: if (val == 0): rsiValueCorrect.append(float(pastVar)) else: rsiValueCorrect.append(float(val)) pastVar = val value = np.asarray(rsiValueCorrect) df['RSI_' + target] = value trend = talib.LINEARREG_SLOPE(value, hp.timePeriodRSI) df['RSI_TREND_' + target] = trend df['RSI_TREND_UP_' + target] = np.where(df['RSI_TREND_' + target] >= 0, 1, 0) df['RSI_OB_' + target] = np.where(df['RSI_' + target] >= 70, 1, 0) df['RSI_OS_' + target] = np.where(df['RSI_' + target] <= 30, 1, 0) return df
def test_LINEARREG_SLOPE(self): self.env.add_operator('linearreg', { 'operator': OperatorLINEARREG_SLOPE, }) string = 'linearreg(14, open)' gene = self.env.parse_string(string) self.assertRaises(IndexError, gene.eval, self.env, self.dates[12], self.dates[-1]) df = gene.eval(self.env, self.dates[13], self.dates[14]) ser0, ser1 = df.iloc[0], df.iloc[1] o = self.env.get_data_value('open').values res0, res1, res = [], [], [] for i in df.columns: res0.append(talib.LINEARREG_SLOPE(o[:14, i], timeperiod=14)[-1] == ser0[i]) res1.append(talib.LINEARREG_SLOPE(o[1:14+1, i], timeperiod=14)[-1] == ser1[i]) res.append(talib.LINEARREG_SLOPE(o[:14+1, i], timeperiod=14)[-1] == ser1[i]) self.assertTrue(all(res0) and all(res1) and all(res))
def eval(self, environment, gene, date1, date2): timeperiod = (gene.next_value(environment, date1, date2)) date1 = environment.shift_date(date1, -(timeperiod - 1), -1) df = gene.next_value(environment, date1, date2) res = df.apply(lambda x: pd.Series(talib.LINEARREG_SLOPE( x.values, timeperiod=timeperiod), index=df.index)) return res.iloc[timeperiod - 1:]
def ema_k(self, long_ema, short_ema, k_length): short = talib.EMA(self.close, timeperiod=short_ema) long = talib.EMA(short, timeperiod=long_ema) k = talib.LINEARREG_SLOPE(self.close, timeperiod=k_length) result = (long[-1] - short[-1]) * (long[-2] - short[-2]) if result < 0: jiaoyi = k[-1] * result return jiaoyi else: return 0
def cross_entry(i, t=15): points = arr_ys[i - (t + 2):i + 1] slope = ta.LINEARREG_SLOPE(points, t)[-1] # slope_prev = ta.LINEARREG_SLOPE(points,t)[-2] # slope_prev_2 = ta.LINEARREG_SLOPE(points,t)[-3] # print(str(slope_prev_2)) if slope > 0: return True else: return False
def buy(data): sma_data = ta.MA(data["close"], timeperiod=5, matype=0) slope = ta.LINEARREG_SLOPE(sma_data, timeperiod=11) if slope.iloc[-2] < 0 and slope.iloc[-1] > 0: buy_flag = True else: buy_flag = False return buy_flag
def LINEARREG_SLOPE(close, timeperiod=14): ''' Linear Regression Slope 线性回归斜率指标 分组: Statistic Functions 统计函数 简介: real = LINEARREG_SLOPE(close, timeperiod=14) ''' return talib.LINEARREG_SLOPE(close, timeperiod)
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
def test_DIY_signal(): # -------------------------------------------------------------------------------- # Step.1 load dataview dv = DataView() dv.load_dataview(dataview_folder) # 方法1:add_formula 基于dataview里已有的字段,通过表达式定义因子 dv.add_formula("momentum", "Return(close_adj, 20)", is_quarterly=False, add_data=True) # 方法2: append_df 构造一个因子表格(pandas.Dataframe),直接添加到dataview当中 import pandas as pd import talib as ta close = dv.get_ts("close_adj").dropna(how='all', axis=1) slope_df = pd.DataFrame( { sec_symbol: -ta.LINEARREG_SLOPE(value.values, 10) for sec_symbol, value in close.iteritems() }, index=close.index) dv.append_df(slope_df, 'slope') dv.get_ts("slope") # 定义事件 from jaqs_fxdayu.research.signaldigger import process Open = dv.get_ts("open_adj") High = dv.get_ts("high_adj") Low = dv.get_ts("low_adj") Close = dv.get_ts("close_adj") trade_status = dv.get_ts('trade_status') mask_sus = trade_status != 1 # 剔除掉停牌期的数据 再计算指标 open_masked = process._mask_df(Open, mask=mask_sus) high_masked = process._mask_df(High, mask=mask_sus) low_masked = process._mask_df(Low, mask=mask_sus) close_masked = process._mask_df(Close, mask=mask_sus) from jaqs_fxdayu.data import signal_function_mod as sfm MA5 = sfm.ta(ta_method='MA', ta_column=0, Open=open_masked, High=high_masked, Low=low_masked, Close=close_masked, Volume=None, timeperiod=10) MA10 = sfm.ta('MA', Close=close_masked, timeperiod=10) dv.append_df(MA5, 'MA5') dv.append_df(MA10, 'MA10') dv.add_formula("Cross", "(MA5>=MA10)&&(Delay(MA5<MA10, 1))", is_quarterly=False, add_data=True)
def getATRSlope(self, volatilityWindow=15): """取ATR斜率""" volatilityArray = talib.ATR(self.high, self.low, self.close, volatilityWindow) volatilityThreshold = talib.LINEARREG_SLOPE(volatilityArray, volatilityWindow) if volatilityThreshold[-1] > 0: return 1 elif volatilityThreshold[-1] <= 0: return -1 return 0
def parse(code_list): '''''process stock''' is_buy = 0 buy_val = [] buy_date = [] sell_val = [] sell_date = [] df = ts.get_hist_data(STOCK) df=df.sort_index(axis=0) ma20 = df[u'ma20'] close = df[u'close'] rate = 1.0 idx = len(ma20) angel=ta.EMA(df['close'].values,timeperiod=2) evel=ta.EMA((ta.LINEARREG_SLOPE(df['close'].values,21)*20+df['close'].values),timeperiod=42) idx=-len(evel) while idx < -1: idx += 1 close_val = close[idx] ma20_val = ma20[idx] if angel[idx] > evel[idx]: if is_buy == 0: is_buy = 1 buy_val.append(close_val) buy_date.append(close.keys()[idx]) elif angel[idx] < evel[idx]: if is_buy == 1: is_buy = 0 sell_val.append(close_val) sell_date.append(close.keys()[idx]) print "stock number: %s" %STOCK print "buy count : %d" %len(buy_val) print "sell count : %d" %len(sell_val) money=10000 for i in range(len(sell_val)): rate = rate * (sell_val[i] * (1 - 0.002) / buy_val[i]) yield1=(sell_val[i]-buy_val[i])/buy_val[i] money=money*(1+(sell_val[i]-buy_val[i])/buy_val[i]) print "buy date : %s, sell date: %s, buy price : %.2f,sell price: %.2f, money: %.2f, yield: %.2f%%" %(buy_date[i], sell_date[i],buy_val[i], sell_val[i],money,100*yield1) if len(sell_val)<len(buy_val): i+=1 print "buy date : %s, buy price : %.2f" %(buy_date[i], buy_val[i]) print "rate: %.2f" % rate
def _talib_LINEARREG_SLOPE(data, n): if n <= 1: value = np.zeros_like(data) else: try: value = talib.LINEARREG_SLOPE(data, timeperiod=n) ss = pd.Series(value).ffill().fillna(0) value = ss.values except Exception as e: raise Exception("[_talib_LINEARREG_SLOPE]", e) # print("[WARNING] _talib_LINEARREG_SLOPE: {}".format(e.args[0])) value = np.zeros_like(data) return value.astype(float)
def slope(self, context): lookback = self.kwargs['lookback'] ds = pd.Series(index=context.dp.minor_axis) for asset in context.dp.minor_axis: ds[asset] = talib.LINEARREG_SLOPE( context.dp[self.inputs[0]][asset].values, lookback)[-1] df = pd.DataFrame(0, index=context.dp.major_axis, columns=context.dp.minor_axis) df.iloc[-1] = ds return df
def lr_calc(self, df, print_log=True): for tmprd_lr in self.lr_tmprd_arr: for mult_lr in self.lr_mult_arr: postfix = '_' + processing.digit_to_text( tmprd_lr) + '_' + processing.digit_to_text(mult_lr) new_clmn_names = [ name + postfix for name in self.lr_base_clmn_names ] if print_log: print('new_clmn_names: ', new_clmn_names) tmprd_lr_1 = tmprd_lr df[new_clmn_names[0]] = tl.LINEARREG_SLOPE( df['open'].values, timeperiod=tmprd_lr_1) tmprd_lr_2 = int(tmprd_lr_1 * mult_lr) df[new_clmn_names[1]] = tl.LINEARREG_SLOPE( df['open'].values, timeperiod=tmprd_lr_2) inp = (df, new_clmn_names[0], new_clmn_names[1], 'lr_cmpr' + postfix) df = processing.clmn_compare(*inp) return df
def test_linreg_slope(self): result = self.overlap.linreg(self.close, slope=True) self.assertIsInstance(result, Series) self.assertEqual(result.name, 'LRm_14') try: expected = tal.LINEARREG_SLOPE(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 getStatFunctions(df): high = df['High'] low = df['Low'] close = df['Close'] open = df['Open'] volume = df['Volume'] df['BETA'] = ta.BETA(high, low, timeperiod=5) df['CORREL'] = ta.CORREL(high, low, timeperiod=30) df['LINREG'] = ta.LINEARREG(close, timeperiod=14) df['LINREGANGLE'] = ta.LINEARREG_ANGLE(close, timeperiod=14) df['LINREGINTERCEPT'] = ta.LINEARREG_INTERCEPT(close, timeperiod=14) df['LINREGSLOPE'] = ta.LINEARREG_SLOPE(close, timeperiod=14) df['STDDEV'] = ta.STDDEV(close, timeperiod=5, nbdev=1) df['TSF'] = ta.TSF(close, timeperiod=14) df['VAR'] = ta.VAR(close, timeperiod=5, nbdev=1)
def strategy(self): sma_data = ta.MA(self.data["close"], timeperiod=self.parameter["sma"], matype=0) slope = ta.LINEARREG_SLOPE(sma_data, timeperiod=self.parameter["slope"]) if slope.iloc[-2] < 0 and slope.iloc[-1] > 0: self.bs_flag = "B" self.args["period_max_point"] = max(self.data["close"].iloc[-40:]) elif self.amount: if slope.iloc[-2] > 0 and slope.iloc[-1] < 0: self.bs_flag = "S" elif (self.data["close"].iloc[-1] - self.args["period_max_point"]) / self.args["period_max_point"] > -0.02: if self.data["close"].iloc[-1] < self.data["close"].iloc[-2] < self.data["close"].iloc[-3] < self.data["close"].iloc[-4]: self.bs_flag = "S" else: pass
def sell(data): sma_data = ta.MA(data["close"], timeperiod=5, matype=0) slope = ta.LINEARREG_SLOPE(sma_data, timeperiod=11) if slope.iloc[-2] > 0 and slope.iloc[-1] < 0: sell_flag = True elif (data["close"].iloc[-1] - max(data["close"].iloc[-40:])) / max( data["close"].iloc[-40:]) > -0.02: if data["close"].iloc[-1] < data["close"].iloc[-2] < data[ "close"].iloc[-3] < data["close"].iloc[-4]: sell_flag = True else: sell_flag = False else: sell_flag = False return sell_flag
def handle_bar(context, bar_dict): price = history_bars(context.s1, context.PERIOD + 1, '1d', 'close') slope = talib.LINEARREG_SLOPE(price, context.PERIOD) intercept = talib.LINEARREG_INTERCEPT(price, context.PERIOD) prediction = slope * price + intercept cur_position = context.portfolio.positions[context.s1].quantity shares = context.portfolio.cash / bar_dict[context.s1].close if price[-1] < prediction[ -1] and cur_position > 0: #时间不对为何还能运行?这是因为引擎重新计算了各个值 order_target_value(context.s1, 0) if price[-1] > prediction[-1]: order_shares(context.s1, shares)
def linearreg_slope(client, symbol, timeframe="6m", closecol="close", period=14): """This will return a dataframe of linear regression slope 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 period (int): period to calculate adx across Returns: DataFrame: result """ df = client.chartDF(symbol, timeframe) linearreg = t.LINEARREG_SLOPE(df[closecol].values, period) return pd.DataFrame({closecol: df[closecol].values, "lineearreg_slope": linearreg})
def linearreg_slope(candles: np.ndarray, period: int = 14, source_type: str = "close", sequential: bool = False) -> \ Union[float, np.ndarray]: """ LINEARREG_SLOPE - Linear Regression Slope :param candles: np.ndarray :param period: int - default: 14 :param source_type: str - default: "close" :param sequential: bool - default=False :return: float | np.ndarray """ candles = slice_candles(candles, sequential) source = get_candle_source(candles, source_type=source_type) res = talib.LINEARREG_SLOPE(source, timeperiod=period) return res if sequential else res[-1]
def run_formula(dv, param=None): import pandas as pd import talib as ta default_param = {'t': 20} if not param: param = default_param t = param['t'] close = dv.get_ts("close_adj").dropna(how='all', axis=1) Alpha116 = pd.DataFrame( { sec_symbol: ta.LINEARREG_SLOPE(value.values, t) for sec_symbol, value in close.iteritems() }, index=close.index) dv.append_df(Alpha116, 'Alpha116') return dv.get_ts("Alpha116")
def handle_bar(context, bar_dict): price = history_bars(context.s1, context.PERIOD * 3, '1d', 'close') #注意时间context.PERIOD*3略有不同 slope = talib.LINEARREG_SLOPE(price, context.PERIOD) #计算斜率 intercept = talib.LINEARREG_INTERCEPT(price, context.PERIOD) #计算b值 prediction = slope * price + intercept #计算预测值 residual = (price - prediction) / price #计算残差 residual_MA = ta.MA(residual, 20) #计算20日残差均值 cur_position = context.portfolio.positions[context.s1].quantity shares = context.portfolio.cash / bar_dict[context.s1].close if residual[-1] < residual_MA[-1] and cur_position > 0: order_target_value(context.s1, 0) if residual[-1] > residual_MA[-1]: order_shares(context.s1, shares)
def linearreg_slope(candles: np.ndarray, period: int = 14, source_type: str = "close", sequential: bool = False) -> \ Union[float, np.ndarray]: """ LINEARREG_SLOPE - Linear Regression Slope :param candles: np.ndarray :param period: int - default: 14 :param source_type: str - default: "close" :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:] source = get_candle_source(candles, source_type=source_type) res = talib.LINEARREG_SLOPE(source, timeperiod=period) return res if sequential else res[-1]