def create_features(df): period = 14 bid_df = df[['bid']] ask_df = df[['ask']] bid_df['dema_bid'] = talib.DEMA(df.bid.values, timeperiod=period) ask_df['dema_ask'] = talib.DEMA(df.ask.values, timeperiod=period) bid_df['ema_bid'] = talib.EMA(df.bid.values, timeperiod=period) ask_df['ema_ask'] = talib.EMA(df.ask.values, timeperiod=period) bid_df['ht_trendline_bid'] = talib.HT_TRENDLINE(df.bid.values) ask_df['ht_trendline_ask'] = talib.HT_TRENDLINE(df.ask.values) bid_df['ma_bid'] = talib.MA(df.bid.values, timeperiod=period, matype=0) ask_df['ma_ask'] = talib.MA(df.ask.values, timeperiod=period, matype=0) bid_df['sma_bid'] = talib.SMA(df.bid.values, timeperiod=period) ask_df['sma_ask'] = talib.SMA(df.ask.values, timeperiod=period) bid_df['tema_bid'] = talib.TEMA(df.bid.values, timeperiod=period) ask_df['tema_ask'] = talib.TEMA(df.ask.values, timeperiod=period) bid_df['wma_bid'] = talib.WMA(df.bid.values, timeperiod=period) ask_df['wma_ask'] = talib.WMA(df.ask.values, timeperiod=period) bid_df['kama_bid'] = talib.KAMA(df.bid.values, timeperiod=period) ask_df['kama_ask'] = talib.KAMA(df.ask.values, timeperiod=period) bid_df = bid_df.fillna(method='bfill') ask_df = ask_df.fillna(method='bfill') return bid_df, ask_df
def onTick(): ama_short = 2 ama_long = 30 exchange.SetContractType('rb000') bar_arr = exchange.GetRecords() if len(bar_arr) < ama_long: return close_arr = get_close(bar_arr) np_close_arr = np.array(close_arr) ama1 = talib.KAMA(np_close_arr, ama_short).tolist() ama2 = talib.KAMA(np_close_arr, ama_long).tolist() last_close = close_arr[-1] global mp # open long if mp == 0 and is_up_cross(ama1, ama2) and is_up(ama2): exchange.SetDirection('buy') exchange.Buy(last_close, 1) mp = 1 # open short if mp == 0 and is_down_cross(ama1, ama2) and is_down(ama2): exchange.SetDirection('sell') exchange.Sell(last_close - 1, 1) mp = -1 # close long if mp == 1 and (is_down_cross(ama1, ama2) or is_down(ama1)): exchange.SetDirection('closebuy') exchange.Sell(last_close, -1, 1) mp = 0 # close short if mp == -1 and (is_up_cross(ama1, ama2) or is_up(ama1)): exchange.SetDirection('closesell') exchange.Buy(last_close, 1) mp = 0
def computeDKAMA(self): skama = talib.KAMA(self.prices, timeperiod=self.slowPeriod) fkama = talib.KAMA(self.prices, timeperiod=self.fastPeriod) dkama = fkama - skama self.removeNullID(dkama) self.rawFeatures['KAMA'] = dkama return
def Bollsignal_ntrend(self, am, paraDict): BOLL_MID_MA = paraDict["BOLL_MID_MA_ntrend"] BOLL_SD = paraDict["BOLL_SD_ntrend"]/10 MA_Short_period = paraDict["MA_Short_period"] MA_Long_period = paraDict["MA_Long_period"] highma = ta.KAMA(am.high, BOLL_MID_MA) lowma = ta.KAMA(am.low, BOLL_MID_MA) Bollmid = ta.KAMA(am.close, BOLL_MID_MA) STD = (ta.VAR(am.close, BOLL_MID_MA) ** 0.5) Bollup = Bollmid + STD * BOLL_SD Bolldown = Bollmid - STD * BOLL_SD MA_Short = ta.KAMA(am.close, MA_Short_period) MA_Long = ta.KAMA(am.close, MA_Long_period) ATRvalue = ta.ATR(am.high, am.low, am.close, BOLL_MID_MA) if (am.close[-1] > Bolldown[-1]) and (am.close[-2] <= Bolldown[-2]) and (MA_Short[-1] > MA_Long[-1]): BollSignal = 3 elif (am.close[-1] < Bollup[-1]) and (am.close[-2] >= Bollup[-2]) and (MA_Short[-1] < MA_Long[-1]): BollSignal = -3 else: BollSignal = 0 return BollSignal, ATRvalue[-1]
def _get_signal(self, date_now): index = self.times.index(date_now) + 1 diff_step = 20 # 量能 amt_5 = np.array(self.amt[index - 5 - diff_step:index]) amt_Long = np.array(self.amt[index - self.Long - diff_step:index]) amt_5 = talib.KAMA(amt_5, timeperiod=5)[-1] amt_Long = talib.KAMA(amt_Long, timeperiod=self.Long)[-1] amt_index = amt_5 / amt_Long # 价能 close_today = np.array(self.close[index - self.L - diff_step:index]) close_today_n = np.array(self.close[index - self.N - self.L - diff_step:index - self.N]) _, close_today, _ = talib.BBANDS(close_today, timeperiod=self.L) _, close_today_n, _ = talib.BBANDS(close_today_n, timeperiod=self.L) close_today = close_today[-1] close_today_n = close_today_n[-1] close_index = close_today / close_today_n # 返回指标值 all_index = amt_index * close_index # 牛熊指标 ma_5 = np.array(self.close[index - 5 - diff_step:index]) ma_90 = np.array(self.close[index - 90 - diff_step:index]) ma_5 = talib.MA(ma_5, timeperiod=5)[-1] ma_90 = talib.MA(ma_90, timeperiod=90)[-1] if ma_5 > ma_90: bull_bear = 1 else: bull_bear = -1 return (all_index, bull_bear)
def KAMA(self, length, *args, kline=None): """ 适应性移动平均线 :param length: 长度参数 :param args: 不定长参数,可传入多个值计算 :param kline: 回测时传入指定k线数据 :return: 返回一个一维数组 """ if kline: records = kline else: records = self.__platform.get_kline(self.__time_frame) records.reverse() kline_length = len(records) close_array = np.zeros(kline_length) t = 0 for item in records: close_array[t] = item[4] t += 1 if len(args) < 1: # 如果无别的参数 result = talib.KAMA(close_array, length) else: result = [talib.KAMA(close_array, length)] for x in args: result.append(talib.KAMA(close_array, x)) return result
def Bollsignal_wtrend(self, am, paraDict): BOLL_MID_MA = paraDict["BOLL_MID_MA_wtrend"] BOLL_SD = paraDict["BOLL_SD_wtrend"] / 10 ATR_period = paraDict["ATR_period"] ATR_threshold = paraDict["ATR_threshold"] ROC_Period = paraDict["ROC_Period"] ROC_MA_Period = paraDict["ROC_MA_Period"] highma = ta.KAMA(am.high, BOLL_MID_MA) lowma = ta.KAMA(am.low, BOLL_MID_MA) Bollmid = ta.KAMA(am.close, BOLL_MID_MA) STD = (ta.VAR(am.close, BOLL_MID_MA)**0.5) Bollup = Bollmid + STD * BOLL_SD Bolldown = Bollmid - STD * BOLL_SD UpValue = (highma + Bollmid) / 2 + STD LowValue = (lowma + Bollmid) / 2 - STD highmax = ta.MAX(am.high, BOLL_MID_MA) lowmin = ta.MIN(am.low, BOLL_MID_MA) ATRvalue = ta.ATR(am.high, am.low, am.close, ATR_period) ATRsignal = np.abs(am.close[-1] - am.close[-ATR_period]) / ATRvalue[-1] ROCvalue = ta.ROC(am.close, ROC_Period) rocMA = ta.MA(ROCvalue, ROC_MA_Period) if (ROCvalue[-1] > rocMA[-1]): ROCsignal = 1 else: ROCsignal = 0 Up_upper = (am.close[-1] > Bollup[-1]) and ( ATRsignal > ATR_threshold) and (ROCsignal == 1) Down_lower = (am.close[-1] < Bolldown[-1]) and ( ATRsignal > ATR_threshold) and (ROCsignal == 1) if Up_upper: BollSignal = 2 elif Down_lower: BollSignal = -2 else: BollSignal = 0 #出场准备 if Bollup[-1] >= UpValue[-1]: LongExitValue = UpValue[-1] else: LongExitValue = Bollup[-1] if Bolldown[-1] <= LowValue[-1]: ShortExitValue = LowValue[-1] else: ShortExitValue = Bolldown[-1] ExitValue = (LongExitValue, ShortExitValue) return BollSignal, ExitValue
def kama(df, time_id, slk = 3, llk = 9): Log(LOG_INFO) << "Computing kama with %d, %d" %(slk, llk) prices = df[OPEN_KEY].values kma_s = talib.KAMA(prices, slk) kma_l = talib.KAMA(prices, llk) dif_s = prices[time_id] - kma_s[time_id] dif_l = prices[time_id] - kma_l[time_id] dkma = kma_s[time_id] - kma_l[time_id] return np.hstack((dif_s.reshape(-1, 1), dif_l.reshape(-1,1), dkma.reshape(-1, 1)))
def bs(stk, opt): sql = ''' select trdate,v_close cl,trunc(trdate,'d')+7 ww from idx_td_t where stkcode='%s' order by 1 ''' dd = pd.read_sql(sql % stk, db, index_col='TRDATE') dw = dd.resample('W', how='last').dropna() ma = cur.execute('''select d,w from mv_tu_idx where stkcode='%s' ''' % stk).fetchone() dd['ma1'] = ta.KAMA(np.array(dd['CL'], dtype='f8'), timeperiod=ma[0]) dw['ma3'] = ta.KAMA(np.array(dw['CL'], dtype='f8'), timeperiod=ma[1]) data = pd.merge(dd, dw, on='WW') data.columns = ['CL', 'WW', 'ma1', 'CLW', 'ma3'] data.loc[data[data['CL'] >= data['ma1']].index, 'b'] = 1 data.loc[data[data['CL'] < data['ma1']].index, 'b'] = 0 data.loc[data[data['CLW'] >= data['ma3']].index, 'bw'] = 1 data.loc[data[data['CLW'] < data['ma3']].index, 'bw'] = 0 # 标记买卖点 data['b1'] = data['b'].shift(1) data.loc[data[(data['b'] == 1) & (data['b1'] == 0)].index, 'bs'] = 1 # buy data.loc[data[(data['b'] == 1) & (data['b1'] == 1)].index, 'bs'] = 2 # 持股 data.loc[data[(data['b'] == 0) & (data['b1'] == 1)].index, 'bs'] = -1 # sale data.loc[data[(data['b'] == 0) & (data['b1'] == 0)].index, 'bs'] = -2 # 持币 data['bw1'] = data['bw'].shift(1) data.loc[data[(data['bw'] == 1) & (data['bw1'] == 0)].index, 'bsw'] = 1 # buy data.loc[data[(data['bw'] == 1) & (data['bw1'] == 1)].index, 'bsw'] = 2 # 持股 data.loc[data[(data['bw'] == 0) & (data['bw1'] == 1)].index, 'bsw'] = -1 # sale data.loc[data[(data['bw'] == 0) & (data['bw1'] == 0)].index, 'bsw'] = -2 # 持币 data = data.fillna(0) dd.reset_index(inplace=True) data['TRDATE'] = dd['TRDATE'] sql = '''insert into bs_idx_t values ('%s',%s,to_date('%s','yyyymmdd'))''' if opt == 9: for v in data.values: if v[8] in (1, -1): cur.execute(sql % (stk[0], v[8], v[11].strftime('%Y%m%d'))) else: v = data.values[-1] if v[8] in (1, -1): cur.execute(sql % (stk[0], v[8], v[11].strftime('%Y%m%d'))) cur.execute( '''update idx_t set status=%s, stdate=sysdate, sw=%s where stkcode='%s' ''' % (v[8], v[10], stk[0])) db.commit()
def TA_KAMA(close, timeperiod=30): """ 请直接用 talib.KAMA(close, timeperiod) KAMA - Kaufman Adaptive Moving Average """ real = talib.KAMA(close, timeperiod=timeperiod) return np.c_[real]
def plot_kaufman(ax, data): """This function plots ################ KAMA - Kaufman Adaptive Moving Average ######################## Kaufman's Adaptive Moving Average (KAMA) is an intelligent moving average that was developed by Perry Kaufman. The powerful trend-following indicator is based on the Exponential Moving Average (EMA) and is responsive to both trend and volatility. It closely follows price when noise is low and smooths out the noise when price fluctuates. Like all moving averages, the KAMA can be used to visualize the trend. Price crossing it indicates a directional change. Price can also bounce off the KAMA, which can act as dynamic support and resistance. It is often used in combination with other signals and analysis techniques.""" kaufman_ind = talib.KAMA(data['Adj_Close'], timeperiod=30) ax.plot(data["Date"], kaufman_ind, label="Kaufman Adaptive Moving Average", color="coral") ema_indicator = talib.EMA(data['Adj_Close'], timeperiod=30) ax.plot(data["Date"], ema_indicator, label='Exponential Moving Average', color="aqua")
def get_kama_single(context,security): period= g.kama_days*4*6 close_long = get_price(security, end_date=context.current_dt, frequency='10m', fields=['close'], count= period +2*4*6 )['close'].values; #close_short = get_price(g.security, end_date=context.previous_date, frequency='1d', fields=['close'], count= short_days+10 )['close'].values; kama_long = tb.KAMA(close_long,timeperiod= period); #kama_short = tb.KAMA(close_short,timeperiod= short_days); # if( (kama_short[-1] > kama_long[-1]) & (kama_short[-2] <= kama_long[-2]) & (kama_short[-1] > kama_short[-2])): # return 1 # if(( kama_short[-1] < kama_long[-1]) & (kama_short[-2] >= kama_long[-2]) & (kama_short[-1] < kama_short[-2])): # return 0 #std = np.std(kama_long[long_days:]); #sell if ((kama_long[-1] / kama_long[-2])< g.return_radio ): #or ((close_short[-1]/close_short[-2])<=0.93): return -1; # if ((close_long[-1] / close_long[-2])<= 0.97 ): #or ((close_short[-1]/close_short[-2])<=0.93): # return -1; #attribute_history if(kama_long[-1]/kama_long[-2] >1.01): return 1; # if kama_short[-1] < kama_long[-1] and kama_short[-2] > kama_long[-2]: # #sell # return 0; # if kama_short[-1] > kama_long[-1] and kama_short[-2] < kama_long[-2]: # #buy # return 1 return 0;
def kama(self, n, array=False): """考夫曼的自适应移动平均线""" result = talib.KAMA(self.close, n) if array: return result return result
def kama(close_ts, timeperiod=30): import talib close_np = close_ts.cpu().detach().numpy() close_df = pd.DataFrame(close_np) kama = close_df.apply(lambda x: talib.KAMA(x, timeperiod=30)) kama_ts = torch.tensor(kama.values, dtype=close_ts.dtype, device=close_ts.device) return kama_ts
def alert1(self, _indata): # 冲击均线策略 db = Session() try: temp = list(np.array(self.Seq)[-30:, 1]) temp.append(_indata.price) current_KAMA = talib.KAMA(np.array(temp).astype(float), 20)[-1] if np.all([_indata.price - self.KAMASeries[-1] < -0.2, _indata.price >= current_KAMA - 0.1, _indata.price < current_KAMA - 0.06]): temp_buy_order = Order(_indata.Times, 1, _indata.Codes, _indata.price + 0.01, 1) if temp_buy_order not in self.OrderList and self.PositionList.__len__() <= 10: print(temp_buy_order) db.add(temp_buy_order) self.OrderList.append(deepcopy(temp_buy_order)) temp_sell_order = Order(_indata.Times, 0, _indata.Codes, _indata.price + 0.02, 1) if temp_sell_order not in self.OrderList: print(temp_sell_order) db.add(temp_sell_order) self.OrderList.append(deepcopy(temp_sell_order)) temp_buy_order = Order(_indata.Times, 1, _indata.Codes, round(self.KAMASeries[-1] - 0.28, 3), 2) if temp_buy_order not in self.OrderList and self.PositionList.__len__() <= 10: print(temp_buy_order) db.add(temp_buy_order) self.OrderList.append(deepcopy(temp_buy_order)) except Exception as e: print(e) finally: db.commit() db.close()
def loop(): global total while total < LOOPS: total += 1 talib.MA(data) talib.BBANDS(data) talib.KAMA(data) talib.CDLMORNINGDOJISTAR(data, data, data, data)
def compKAMA(self): kama = talib.KAMA(self.close,timeperiod=self.lookback) self.removeNullID(kama) self.rawFeatures['KAMA'] = kama FEATURE_SIZE_DICT['KAMA'] = 1 return
def kama(self, n: int, array: bool = False) -> Union[float, np.ndarray]: """ KAMA. """ result = talib.KAMA(self.close, n) if array: return result return result[-1]
def get_up_down(security, end_date, kama_windows=21): start_date = get_security_info(security).start_date price = get_price(security, start_date=start_date, end_date=end_date) price['kama'] = tb.KAMA(price.close, timeperiod=kama_windows) price['log_rate'] = np.log(price['kama'] / price['kama'].shift(1)) price.dropna(inplace=True) describe = price.describe() return describe['log_rate']['25%'], describe['log_rate']['75%']
def kama(self, n, array=False): """ KAMA. """ result = talib.KAMA(self.close, n) if array: return result return result[-1]
def market_open(context): # 以下是主循环 for ins in g.instruments: # 过滤空主力合约品种 if g.MappingReal[ins] != '': IndexFuture = g.MappingIndex[ins] RealFuture = g.MappingReal[ins] # 获取当月合约交割日期 end_date = get_CCFX_end_date(RealFuture) # 当月合约交割日当天不开仓 if (context.current_dt.date() == end_date): return else: g.LastRealPrice[RealFuture] = attribute_history(RealFuture,1,'1d',['close'])['close'][-1] # 获取价格list g.PriceArray[IndexFuture] = attribute_history(IndexFuture,50,'1d',['close','open','high','low']) g.CurrentPrice = g.PriceArray[IndexFuture]['close'][-1] g.ClosePrice = g.PriceArray[IndexFuture]['close'] # 如果没有数据,返回 if len(g.PriceArray[IndexFuture]) < 50: return else: close = np.array(g.PriceArray[IndexFuture]['close']) high = np.array(g.PriceArray[IndexFuture]['high']) low = np.array(g.PriceArray[IndexFuture]['low']) # 计算AMA,仅传入一个参数g.Window g.AMA[IndexFuture] = talib.KAMA(close,g.Window) # 计算ATR g.ATR[IndexFuture] = talib.ATR(high,low,close, g.Window)[-1] if not isnan(g.AMA[IndexFuture][-1]) : g.Filter[IndexFuture] = talib.STDDEV(g.AMA[IndexFuture][-g.Window:],g.Window)[-1] #判断AMA两日差值,是否大于标准差过滤器 if g.AMA[IndexFuture][-1]-g.AMA[IndexFuture][-2] > g.Filter[IndexFuture]*g.FilterTimes: g.Cross = 1 elif g.AMA[IndexFuture][-2]-g.AMA[IndexFuture][-1] > g.Filter[IndexFuture]*g.FilterTimes: g.Cross = -1 else: g.Cross = 0 #判断交易信号:均线交叉+可二次入场条件成立 if g.Cross == 1 and g.Reentry_long == False: g.Signal = 1 elif g.Cross == -1 and g.Reentry_short == False: g.Signal = -1 else: g.Signal = 0 # 执行交易 Trade(context,RealFuture,IndexFuture) # 运行防止充入模块 Re_entry(context,RealFuture) # 计数器+1 if RealFuture in g.Times.keys(): g.Times[RealFuture] += 1 else: g.Times[RealFuture] = 0
def overlap_process(event): print(event.widget.get()) overlap = event.widget.get() upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) fig, axes = plt.subplots(2, 1, sharex=True) ax1, ax2 = axes[0], axes[1] axes[0].plot(close, 'rd-', markersize=3) axes[0].plot(upperband, 'y-') axes[0].plot(middleband, 'b-') axes[0].plot(lowerband, 'y-') axes[0].set_title(overlap, fontproperties="SimHei") if overlap == '布林线': pass elif overlap == '双指数移动平均线': real = ta.DEMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '指数移动平均线 ': real = ta.EMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '希尔伯特变换——瞬时趋势线': real = ta.HT_TRENDLINE(close) axes[1].plot(real, 'r-') elif overlap == '考夫曼自适应移动平均线': real = ta.KAMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '移动平均线': real = ta.MA(close, timeperiod=30, matype=0) axes[1].plot(real, 'r-') elif overlap == 'MESA自适应移动平均': mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0) axes[1].plot(mama, 'r-') axes[1].plot(fama, 'g-') elif overlap == '变周期移动平均线': real = ta.MAVP(close, periods, minperiod=2, maxperiod=30, matype=0) axes[1].plot(real, 'r-') elif overlap == '简单移动平均线': real = ta.SMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '三指数移动平均线(T3)': real = ta.T3(close, timeperiod=5, vfactor=0) axes[1].plot(real, 'r-') elif overlap == '三指数移动平均线': real = ta.TEMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '三角形加权法 ': real = ta.TRIMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '加权移动平均数': real = ta.WMA(close, timeperiod=30) axes[1].plot(real, 'r-') plt.show()
def test_kama(): '''test TA.KAMA''' ma = TA.KAMA(ohlc, period=30) talib_ma = talib.KAMA(ohlc['close'], timeperiod=30) # assert round(talib_ma[-1], 5) == round(ma.values[-1], 5) # assert 1519.60321 == 1524.26954 pass # close enough
def consume(self, from_name, value): if self.from_name != from_name: return None self.history_values.append(value) v = talib.KAMA(numpy.array(self.history_values, float), self.days)[-1] return None if numpy.isnan(v) else v
def get_ma_set_diff(self, df, period, default_col): # print(period) open_price = np.array(df['open'], dtype=float) high_price = np.array(df['high'], dtype=float) low_price = np.array(df['low'], dtype=float) close_price = np.array(df['close'], dtype=float) # volume = np.array(df['Volume'], dtype=float) target = close_price if default_col == "open": target = open_price elif default_col == "high": target = high_price elif default_col == "low": target = low_price # m # Simple Moving Average (SMA) sma_m = talib.SMA(target, timeperiod=period[0]) # Adaptive Moving Average (AMA) ama_m = talib.KAMA(target, timeperiod=period[0]) # Typical Price Moving Average (TPMA) typical_price_m = talib.TYPPRICE(high_price, low_price, close_price) tpma_m = talib.SMA(typical_price_m, timeperiod=period[0]) # Triangular Moving Average (TMA) tma_m = talib.TRIMA(target, timeperiod=period[0]) # n # Simple Moving Average (SMA) sma_n = talib.SMA(target, timeperiod=period[1]) # Adaptive Moving Average (AMA) ama_n = talib.KAMA(target, timeperiod=period[1]) # Typical Price Moving Average (TPMA) typical_price_n = talib.TYPPRICE(high_price, low_price, close_price) tpma_n = talib.SMA(typical_price_n, timeperiod=period[1]) # Triangular Moving Average (TMA) tma_n = talib.TRIMA(target, timeperiod=period[1]) sma_diff = sma_n - sma_m ama_diff = ama_n - ama_m tpma_diff = tpma_n - tpma_m tma_diff = tma_n - tma_m return sma_diff, ama_diff, tpma_diff, tma_diff
def KAMA(self): # 计算均线 try: if self.Seq.__len__() >= 30: temp = talib.KAMA(np.array(self.Seq)[-30:, 1].reshape(-1).astype(float), 20)[-1] if ~np.isnan(temp): self.KAMASeries.append(temp) else: print('Seq序列不足') except Exception as e: print(e)
def _get_signal(self, date_now): index = self.times.index(date_now) + 1 diff_step = 1 # 量能 amt_5 = np.array(self.amt[index-5-diff_step:index]) amt_Long = np.array(self.amt[index-self.Long-diff_step:index]) amt_5 = talib.KAMA(amt_5, timeperiod=5)[-1] amt_Long = talib.KAMA(amt_Long, timeperiod=self.Long)[-1] amt_index = amt_5 / amt_Long # 价能 close_today = np.array(self.close[index-self.L-diff_step:index]) close_today_n = np.array(self.close[index-self.N-self.L-diff_step:index-self.N]) _, close_today, _ = talib.BBANDS(close_today, timeperiod=self.L) _, close_today_n, _ = talib.BBANDS(close_today_n, timeperiod=self.L) close_today = close_today[-1] close_today_n = close_today_n[-1] close_index = close_today / close_today_n # 返回指标值 all_index = amt_index * close_index return all_index
def Overlap_test(): data_table["MA5"] = talib.MA(data_table.close, timeperiod=5) print(data_table["MA5"]) data_table["EMA"] = talib.EMA(data_table.close) print(data_table["EMA"]) #考夫曼的自适应移动平均线 data_table["KAMA"] = talib.KAMA(data_table.close, timeperiod=30) print(data_table["KAMA"]) #布林通道 data_table["BBANDS_upper"], data_table["BBANDS_middle"], data_table[ "BBANDS_lower"] = talib.BBANDS(data_table.close, matype=talib.MA_Type.T3)
def KAMA(self, length): """适应性移动平均线""" records = self.platform.get_kline(self.time_frame) records.reverse() 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.KAMA(close_array, length)) return result
def add_KAMA(self, timeperiod=20, type='line', color='secondary', **kwargs): """Kaufmann Adaptive Moving Average.""" if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: type = kwargs['kind'] name = 'KAMA({})'.format(str(timeperiod)) self.pri[name] = dict(type=type, color=color) self.ind[name] = talib.KAMA(self.df[self.cl].values, timeperiod)