我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用talib.MA。
def SVAPO(df, period = 8, cutoff = 1, stdev_h = 1.5, stdev_l = 1.3, stdev_period = 100): HA = HEIKEN_ASHI(df, 1) haCl = (HA.HAopen + HA.HAclose + HA.HAhigh + HA.HAlow)/4.0 haC = TEMA( haCl, 0.625 * period ) vave = MA(df, 5 * period, field = 'volume').shift(1) vc = pd.concat([df['volume'], vave*2], axis=1).min(axis=1) vtrend = TEMA(LINEAR_REG_SLOPE(df.volume, period), period) UpD = pd.Series(vc) DoD = pd.Series(-vc) UpD[(haC<=haC.shift(1)*(1+cutoff/1000.0))|(vtrend < vtrend.shift(1))] = 0 DoD[(haC>=haC.shift(1)*(1-cutoff/1000.0))|(vtrend > vtrend.shift(1))] = 0 delta_sum = pd.rolling_sum(UpD + DoD, period)/(vave+1) svapo = pd.Series(TEMA(delta_sum, period), name = 'SVAPO_%s' % period) svapo_std = pd.rolling_std(svapo, stdev_period) svapo_ub = pd.Series(svapo_std * stdev_h, name = 'SVAPO_UB%s' % period) svapo_lb = pd.Series(-svapo_std * stdev_l, name = 'SVAPO_LB%s' % period) return pd.concat([svapo, svapo_ub, svapo_lb], join='outer', axis=1)
def FOUR(closes, days = [5,10,20,60]): """????? return: fours""" closes = np.array(closes) avgs = [] for day in days: avgs.append(MA(closes, day=day)) max_day = max(days) #??????????????? dvs = np.zeros(len(closes[max_day:])) for i in range(len(avgs)): c = avgs[i][max_day:]/closes[max_day:] for j in range(i, len(avgs)): dvs += c - avgs[j][max_day:]/closes[max_day:] max_day = min(max_day, len(closes)) fours = np.zeros(max_day) fours = np.full(len(fours), np.nan) fours = agl.array_insert(fours, len(fours), np.array(dvs)) return fours
def __init__(self, selector): self.selector = selector self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"} self.feature = []
def ma_type_test(): #MA_Type: 0=SMA, 1=EMA, 2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3 (Default=SMA) df=ts.get_k_data('300580',start='2017-01-12',end='2017-05-26') closed=df['close'].values sma=talib.MA(closed,timeperiod=10,matype=0) ema=talib.MA(closed,timeperiod=10,matype=1) wma=talib.MA(closed,timeperiod=10,matype=2) dema=talib.MA(closed,timeperiod=10,matype=3) tema=talib.MA(closed,timeperiod=10,matype=4) trima=talib.MA(closed,timeperiod=10,matype=5) kma=talib.MA(closed,timeperiod=10,matype=6) mama=talib.MA(closed,timeperiod=10,matype=7) t3=talib.MA(closed,timeperiod=10,matype=8) #ouput=talib.MA(closed,timeperiod=5,matype=0) print closed plt.ylim([0,40]) plt.plot(sma,'r--') plt.plot(ema,'g-*') plt.plot(wma) plt.plot(dema) plt.plot(tema) plt.plot(trima) plt.plot(kma) plt.plot(mama) plt.plot(t3) plt.grid() plt.text(7,30,'BST') plt.show()
def pre_data(stick_code,ktype='D'): # ktype in ('D','W','M') 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>'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['volma20'] = ta.MA(df['vol'].values.astype('double'), 20); df['MA20'] = ta.MA(df['close'].values.astype('double'), 20) df['MA60'] = ta.MA(df['close'].values.astype('double'), 60) df['cwbili']=0 df['pricebili']=0 return df # draw
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 # draw
def pre_data(stick_code,ktype='D'): # ktype in ('D','W','M') 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>'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['volma20'] = ta.MA(df['vol'].values.astype('double'), 20); df['MA20'] = ta.MA(df['close'].values.astype('double'), 5) #print(df) #i= ta.CDLCONCEALBABYSWALL(df['open'].values.astype('double'),df['high'].values.astype('double'), # df['low'].values.astype('double'),df['close'].values.astype('double'),) #print(i) return df # draw
def MAEXT(df, n, field = 'close', ma_type = 0): return pd.Series(talib.MA(df[field].values, timeperiod = n, matype = ma_type), index = df.index, name = 'MA_' + field.upper() + str(n))
def maext(df, n, field = 'close', ma_type = 0): key = 'MA_' + field.upper() + '_' + str(n) ma_ts = talib.MA(df[field][-(n+1):].values, timeperiod = n, matype = ma_type) df[key][-1] = float(ma_ts[-1])
def MA(df, n, field = 'close'): return pd.Series(pd.rolling_mean(df[field], n), name = 'MA_' + field.upper() + '_' + str(n), index = df.index)
def SMAVAR(df, n, field = 'close'): ma_ts = MA(df, n, field) var_ts = pd.Series(pd.rolling_mean(df[field]**2, n) - ma_ts**2, name = 'SVAR_' + field.upper() + '_' + str(n)) return pd.concat([ma_ts, var_ts], join='outer', axis=1)
def BBANDS(df, n, k = 2): MA = pd.Series(pd.rolling_mean(df['close'], n)) MSD = pd.Series(pd.rolling_std(df['close'], n)) b1 = 2 * k * MSD / MA B1 = pd.Series(b1, name = 'BollingerB' + str(n)) b2 = (df['close'] - MA + k * MSD) / (2 * k * MSD) B2 = pd.Series(b2, name = 'Bollingerb' + str(n)) return pd.concat([B1,B2], join='outer', axis=1) #Pivot Points, Supports and Resistances
def add_MA(self, timeperiod=20, matype=0, type='line', color='secondary', **kwargs): """Moving Average (customizable).""" if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: type = kwargs['kind'] name = 'MA({})'.format(str(timeperiod)) self.pri[name] = dict(type=type, color=color) self.ind[name] = talib.MA(self.df[self.cl].values, timeperiod, matype)
def add_STOCH(self, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0, types=['line', 'line'], colors=['primary', 'tertiary'], **kwargs): """Slow Stochastic Oscillator. Note that the first argument of types and colors refers to Slow Stoch %K, while second argument refers to Slow Stoch %D (signal line of %K obtained by MA). """ if not (self.has_high and self.has_low and self.has_close): raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: kwargs['type'] = kwargs['kind'] if 'kinds' in kwargs: types = kwargs['type'] if 'type' in kwargs: types = [kwargs['type']] * 2 if 'color' in kwargs: colors = [kwargs['color']] * 2 name = 'STOCH({},{},{})'.format(str(fastk_period), str(slowk_period), str(slowd_period)) slowk = name + r'[%k]' slowd = name + r'[%d]' self.sec[slowk] = dict(type=types[0], color=colors[0]) self.sec[slowd] = dict(type=types[1], color=colors[1], on=slowk) self.ind[slowk], self.ind[slowd] = talib.STOCH(self.df[self.hi].values, self.df[self.lo].values, self.df[self.cl].values, fastk_period, slowk_period, slowk_matype, slowd_period, slowd_matype)
def add_STOCHF(self, fastk_period=5, fastd_period=3, fastd_matype=0, types=['line', 'line'], colors=['primary', 'tertiary'], **kwargs): """Fast Stochastic Oscillator. Note that the first argument of types and colors refers to Fast Stoch %K, while second argument refers to Fast Stoch %D (signal line of %K obtained by MA). """ if not (self.has_high and self.has_low and self.has_close): raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: kwargs['type'] = kwargs['kind'] if 'kinds' in kwargs: types = kwargs['type'] if 'type' in kwargs: types = [kwargs['type']] * 2 if 'color' in kwargs: colors = [kwargs['color']] * 2 name = 'STOCHF({},{})'.format(str(fastk_period), str(fastd_period)) fastk = name + r'[%k]' fastd = name + r'[%d]' self.sec[fastk] = dict(type=types[0], color=colors[0]) self.sec[fastd] = dict(type=types[1], color=colors[1], on=fastk) self.ind[fastk], self.ind[fastd] = talib.STOCHF(self.df[self.hi].values, self.df[self.lo].values, self.df[self.cl].values, fastk_period, fastd_period, fastd_matype)
def moving_average(data, tp=14): """ :param data: ndarray data for MA :param tp: int time period for MA """ return MA(data, timeperiod=tp)
def get_fit(codes, data): for code in codes: try: his = data.history(code, frequency='5min', length=21, fields='close') except Exception as e: print e continue fast = pd.Series(talib.MA(his.values, timeperiod=10), his.index) slow = pd.Series(talib.MA(his.values, timeperiod=20), his.index) if fast[-1] > slow[-1] and (fast[-2] < slow[-2]): yield code
def handle_data(context, data): # print data.history('000001', length=2) dc = data.history(context.s, fields="close", length=20).values context.ma10[0] = context.ma10[1] context.ma20[0] = context.ma20[1] context.ma10[1] = ta.MA(dc, 10)[-1] context.ma20[1] = ta.MA(dc, 20)[-1] if context.ma10[0] <= context.ma20[0] and context.ma10[1] > context.ma20[1]: print(context.ma10, context.ma20) order_target(context.security, 1) elif context.ma10[0] >= context.ma20[0] and context.ma10[1] < context.ma20[1]: print(context.ma10, context.ma20) order_target(context.security, -1) position = context.portfolio.positions.get(context.s, 0)
def entry(context, data, s, lot=LOT): def order_to(n): sod = context.stop_order.pop(s, None) # cancel_order(sod.id) if sod: o = get_order(sod) if o.is_open: o.cancel() n *= 2 order(s, n) # cancel former stop_order dc = data.history(s, fields="close", length=MA_SLOW_LEN).values ma_fast = context.ma_fast[s] ma_slow = context.ma_slow[s] ma_fast[0] = ma_fast[1] ma_slow[0] = ma_slow[1] try: ma_fast[1] = ta.MA(dc, MA_FAST_LEN)[-1] ma_slow[1] = ta.MA(dc, MA_SLOW_LEN)[-1] except: return if ma_fast[0] <= ma_slow[0] and ma_fast[1] > ma_slow[1]: order_to(lot) elif ma_fast[0] >= ma_slow[0] and ma_fast[1] < ma_slow[1]: order_to(-lot)
def calculate_ma(context, data): for ticker in context.tickers: if data.can_trade(ticker): context.ma[ticker] = { 'fast': talib.MA(data.history(ticker, fields='close', length=fast + 1).values, fast), 'slow': talib.MA(data.history(ticker, fields='close', length=slow + 1).values, slow) }
def MA_CN(close,timeperiod=5): return tl.MA(close, timeperiod, 0)
def MA(self): """""" closes = self.getCloses() return talib.MA(closes) # #----------------------------------------------------------------------
def MA(closes, day=5): """closes is close price, day = avg day""" return talib.MA(closes, day)
def TDX_BOLL(closes): """????TDX??????????? ????? closes: np.ndarray return: upper, middle, lower ??????BOLL-M {?? N: 2 250 20 } MID:=MA(C,N); #MID:=SMA(C,N,1); VART1:=POW((C-MID),2); VART2:=MA(VART1,N); VART3:=SQRT(VART2); UPPER:=MID+2*VART3; LOWER:=MID-2*VART3; BOLL:REF(MID,1),COLORFFFFFF; UB:REF(UPPER,1),COLOR00FFFF; LB:REF(LOWER,1),COLORFF00FF; """ closes = np.array(closes) assert(len(closes)>=20) n = 20 mid = talib.MA(closes, n) vart1 = np.zeros(len(closes)) for i, v in np.ndenumerate(closes): i = i[0] vart1[i] = pow(closes[i] - mid[i], 2) vart2 = talib.MA(vart1, n) vart3 = np.sqrt(vart2) upper = mid + 2*vart3 lower = mid - 2*vart3 return upper, mid, lower
def unittest_ma(): closes = Guider('600100').getCloses() print(MA(closes)) fours = FOUR(closes) print( len(closes), len(fours)) print(fours) rsi = RSI(closes) #rsi = rsi/100 - 0.5 rsi -= 50 fours *= 100 pl.figure #pl.plot(closes) pl.plot(fours,'r') pl.plot(rsi) pl.show()
def MA(security_list, timeperiod=5): # ???????????? if isinstance(security_list, str): security_list = [security_list] # ?? MA security_data = history(timeperiod * 2, '1d', 'close', security_list, df=False, skip_paused=True) ma = {} for stock in security_list: ma[stock] = talib.MA(security_data[stock], timeperiod) return ma # SMA
def MA_MONEY(security_list, timeperiod=5): # ???????????? if isinstance(security_list, str): security_list = [security_list] # ?? N ?????? security_data = history(timeperiod * 2, '1d', 'money', security_list, df=False, skip_paused=True) mamoney = {} for stock in security_list: x = security_data[stock] mamoney[stock] = talib.MA(security_data[stock], timeperiod) return mamoney # ?????
def MA_VOLUME(security_list, timeperiod=5): # ???????????? if isinstance(security_list, str): security_list = [security_list] # ?? N ?????? security_data = history(timeperiod * 2, '1d', 'volume', security_list, df=False, skip_paused=True) mavol = {} for stock in security_list: x = security_data[stock] mavol[stock] = talib.MA(security_data[stock], timeperiod) return mavol # BIAS
def ma(close, p = 30): return talib.MA(close, p)
def calculate_indicator(stock_df): periods = [3, 5, 10, 20, 30, 60] # MA for period in periods: stock_df['MA' + str(period)] = talib.MA(stock_df['close'].values, timeperiod=period) # EMA periods = [3, 5, 10, 20, 30, 60] for period in periods: stock_df['EMA' + str(period)] = talib.EMA(stock_df['close'].values, timeperiod=period) # AMTMA periods = [5, 10, 20] for period in periods: stock_df['AMTMA' + str(period)] = talib.MA(stock_df['amount'].values, timeperiod=period) # ATR periods = [5, 10, 20] for period in periods: stock_df['ATR' + str(period)] = talib.ATR(stock_df['high'].values, stock_df['low'].values, stock_df['close'].values, timeperiod=period) # ADX period = 14 stock_df['ADX' + str(period)] = talib.ADX(stock_df['high'].values, stock_df['low'].values, stock_df['close'].values, timeperiod=period) # MACD stock_df['MACD_DIFF'], stock_df['MACD_DEA'], stock_df['MACD_HIST'] = talib.MACD( stock_df['close'].values, fastperiod=12, slowperiod=26, signalperiod=9) # CCI period = 14 stock_df['CCI' + str(period)] = talib.CCI(stock_df['high'].values, stock_df['low'].values, stock_df['close'].values, timeperiod=period) # MFI period = 14 stock_df['MFI' + str(period)] = talib.MFI(stock_df['high'].values, stock_df['low'].values, stock_df['close'].values, stock_df['volume'].values, timeperiod=period) # ROCP periods = [5, 10, 20] for period in periods: stock_df['ROCP' + str(period)] = talib.ROCP(stock_df['close'].values, timeperiod=period)
def get_kdj(sorted_data): close,high,low,ma5,ma10,ma20 = get_case_data(sorted_data) slowk, slowd = ta.STOCH(high,low,close, fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) slowkMA5 = ta.MA(slowk, timeperiod=5, matype=0) slowkMA10 = ta.MA(slowk, timeperiod=10, matype=0) slowkMA20 = ta.MA(slowk, timeperiod=20, matype=0) slowdMA5 = ta.MA(slowd, timeperiod=5, matype=0) slowdMA10 = ta.MA(slowd, timeperiod=10, matype=0) slowdMA20 = ta.MA(slowd, timeperiod=20, matype=0) operator = '' #1.K???????——???90?????????10??????D??80???????????D??20??????????? if slowk[-1] >= 90: operator += 'S9' elif slowk[-1] <= 10: operator += 'B1' elif slowd[-1] >=80: operator += 'S8' elif slowd[-1] <= 20: operator += 'B2' #2.??????K???D??K?????D???????? if slowk[-1] > slowd[-1] and slowk[-2] <= slowd[-2]: operator += 'BX' elif slowk[-1] < slowd[-1] and slowk[-2] >= slowd[-2]: operator += 'SX' #3.??????????????????????? if ma5[-1] >= ma10[-1] and ma10[-1] >= ma20[-1]: #k??? if (slowkMA5[-1] <= slowkMA10[-1] and slowkMA10[-1] <= slowkMA20[-1]) or (slowdMA5[-1] <= slowdMA10[-1] and slowdMA10[-1] <= slowdMA20[-1]): operator += 'S><' elif ma5[-1] <= ma10[-1] and ma10[-1] <= ma20[-1]: #k??? if (slowkMA5[-1] >= slowkMA10[-1] and slowkMA10[-1] >= slowkMA20[-1]) or (slowdMA5[-1] >= slowdMA10[-1] and slowdMA10[-1] >= slowdMA20[-1]): operator += 'B><' return operator
def _get_ma_data(self, ori_data, periods): ret_data = {} float_data = [float(x) for x in ori_data] for period in periods: data = talib.MA(numpy.array(float_data), timeperiod = period) data_list = data.tolist() data_list = self._filter_data(data_list) ret_data["%d" % period] = data_list return ret_data
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 == u'???': pass elif overlap == u'????????': real = ta.DEMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == u'??????? ': real = ta.EMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == u'??????——?????': real = ta.HT_TRENDLINE(close) axes[1].plot(real, 'r-') elif overlap == u'???????????': real = ta.KAMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == u'?????': real = ta.MA(close, timeperiod=30, matype=0) axes[1].plot(real, 'r-') elif overlap == u'MESA???????': mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0) axes[1].plot(mama, 'r-') axes[1].plot(fama, 'g-') elif overlap == u'????????': real = ta.MAVP(close, periods, minperiod=2, maxperiod=30, matype=0) axes[1].plot(real, 'r-') elif overlap == u'???????': real = ta.SMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == u'????????(T3)': real = ta.T3(close, timeperiod=5, vfactor=0) axes[1].plot(real, 'r-') elif overlap == u'????????': real = ta.TEMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == u'?????? ': real = ta.TRIMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == u'???????': real = ta.WMA(close, timeperiod=30) axes[1].plot(real, 'r-') plt.show() # ????
def onFiveBar(self, bar): """??5??K?""" # ????????????????????????? for orderID in self.orderList: self.cancelOrder(orderID) self.orderList = [] # ??K??? self.closeArray[0:self.bufferSize-1] = self.closeArray[1:self.bufferSize] self.highArray[0:self.bufferSize-1] = self.highArray[1:self.bufferSize] self.lowArray[0:self.bufferSize-1] = self.lowArray[1:self.bufferSize] self.closeArray[-1] = bar.close self.highArray[-1] = bar.high self.lowArray[-1] = bar.low self.bufferCount += 1 if self.bufferCount < self.bufferSize: return # ?????? self.atrValue = talib.ATR(self.highArray, self.lowArray, self.closeArray, self.kkLength)[-1] self.kkMid = talib.MA(self.closeArray, self.kkLength)[-1] self.kkUp = self.kkMid + self.atrValue * self.kkDev self.kkDown = self.kkMid - self.atrValue * self.kkDev # ????????? # ????????OCO???? if self.pos == 0: self.intraTradeHigh = bar.high self.intraTradeLow = bar.low self.sendOcoOrder(self.kkUp, self.kkDown, self.fixedSize) # ?????? elif self.pos > 0: self.intraTradeHigh = max(self.intraTradeHigh, bar.high) self.intraTradeLow = bar.low orderID = self.sell(self.intraTradeHigh*(1-self.trailingPrcnt/100), abs(self.pos), True) self.orderList.append(orderID) # ?????? elif self.pos < 0: self.intraTradeHigh = bar.high self.intraTradeLow = min(self.intraTradeLow, bar.low) orderID = self.cover(self.intraTradeLow*(1+self.trailingPrcnt/100), abs(self.pos), True) self.orderList.append(orderID) # ???????? self.putEvent() #----------------------------------------------------------------------
def pre_data(self,stick_code, ktype='D', beginday='',endday=''): # ktype in ('D','W','M') # today='2010-01-01' if '' == beginday: begindaytmp = datetime.date.today() - datetime.timedelta(days=13) beginday = begindaytmp.strftime('%Y-%m-%d') if '' == endday: endday = datetime.date.today().strftime('%Y-%m-%d') df ='' print(beginday,endday) try: if ktype == 'D': df = self.get_data( "select * from t_stick_data_d \ where code = '" + stick_code + "' and date > '"+beginday+"' \ and date <='" + endday + "' order by date asc;") # and date>'2015-05-01' elif ktype == 'W': df = self.get_data( "select * from t_stick_data_w \ where code = '" + stick_code + "' and date > '"+beginday+"' \ and date <='" + endday + "' order by date asc;") # and date>'2015-05-01' elif ktype == 'M': df = self.get_data( "select * from t_stick_data_m \ where code = '" + stick_code + "' and date > '"+beginday+"' \ and date <='" + endday + "' order by date asc;") # 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['volma20'] = ta.MA(df['vol'].values.astype('double'), 20); df['MA20'] = ta.MA(df['close'].values.astype('double'), 20) df['MA60'] = ta.MA(df['close'].values.astype('double'), 60) df['cwbili'] = 0 df['pricebili'] = 0 return df # xx=m_db2(); # df=xx.pre_data('000157',ktype='W') # print(df) # xx.insert_data('t_stick_data_m_test',df.head(20).as_matrix()) # xx.commit()
def add_MACDEXT(self, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0, types=['line', 'line', 'histogram'], colors=['primary', 'tertiary', 'fill'], **kwargs): """Moving Average Convergence Divergence with Controllable MA Type. Note that the first argument of types and colors refers to MACD, the second argument refers to MACD signal line and the third argument refers to MACD histogram. """ if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: kwargs['type'] = kwargs['kind'] if 'kinds' in kwargs: types = kwargs['type'] if 'type' in kwargs: types = [kwargs['type']] * 3 if 'color' in kwargs: colors = [kwargs['color']] * 3 name = 'MACDEXT({},{},{})'.format(str(fastperiod), str(slowperiod), str(signalperiod)) macd = name smacd = name + '[Sign]' hmacd = name + '[Hist]' self.sec[macd] = dict(type=types[0], color=colors[0]) self.sec[smacd] = dict(type=types[1], color=colors[1], on=macd) self.sec[hmacd] = dict(type=types[2], color=colors[2], on=macd) (self.ind[macd], self.ind[smacd], self.ind[hmacd]) = talib.MACDEXT(self.df[self.cl].values, fastperiod, fastmatype, slowperiod, slowmatype, signalperiod, signalmatype)
def add_STOCHRSI(self, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0, types=['line', 'line'], colors=['primary', 'tertiary'], **kwargs): """Stochastic Relative Strength Index. Note that the first argument of types and colors refers to StochRSI %K while second argument refers to StochRSI %D (signal line of %K obtained by MA). """ if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: kwargs['type'] = kwargs['kind'] if 'kinds' in kwargs: types = kwargs['type'] if 'type' in kwargs: types = [kwargs['type']] * 2 if 'color' in kwargs: colors = [kwargs['color']] * 2 name = 'STOCHRSI({},{},{})'.format(str(timeperiod), str(fastk_period), str(fastd_period)) fastk = name + r'[%k]' fastd = name + r'[%d]' self.sec[fastk] = dict(type=types[0], color=colors[0]) self.sec[fastd] = dict(type=types[1], color=colors[1], on=fastk) self.ind[fastk], self.ind[fastd] = talib.STOCHRSI(self.df[self.cl].values, timeperiod, fastk_period, fastd_period, fastd_matype)
def get_macd(sorted_data): close,high,low,ma5,ma10,ma20 = get_case_data(sorted_data) macd, macdsignal, macdhist = ta.MACD(close, fastperiod=10, slowperiod=22, signalperiod=9) # macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) SignalMA5 = ta.MA(macdsignal, timeperiod=5, matype=0) SignalMA10 = ta.MA(macdsignal, timeperiod=10, matype=0) SignalMA20 = ta.MA(macdsignal, timeperiod=20, matype=0) #2??? 1.DIFF?DEA????DIFF????DEA?????? 2.DIFF?DEA????DIFF????DEA?????? operator = '' if macd[-1] > 0 and macdsignal[-1] > 0: if macd[-1] > macdsignal[-1] and macd[-2] <= macdsignal[-2]: operator += 'BX' #?? elif macd[-1] < 0 and macdsignal[-1] < 0: if macd[-1] <= macdsignal[-2]: operator += 'SX' #DEA??k???????????? if ma5[-1] >= ma10[-1] and ma10[-1] >= ma20[-1]: #k??? if SignalMA5[-1] <= SignalMA10[-1] and SignalMA10[-1] <= SignalMA20[-1]: #DEA?? operator += 'S><' if ma5[-1] <= ma10[-1] and ma10[-1] <= ma20[-1]: #k??? if SignalMA5[-1] >= SignalMA10[-1] and SignalMA10[-1] >= SignalMA20[-1]: #DEA?? operator += 'B><' if macd[-1] > 0 and macdhist[-1] >0: if macd[-1] > macd[-2] and macdhist[-1] > macdhist[-2]: operator += 'B^' elif macd[-1] < 0 and macdhist[-1] < 0: if macd[-1] < macd[-2] and macdhist[-1] > macdhist[-2]: operator += 'S^' #??MACD?????????????? if macdhist[-1] > 0: for i in range(1,7): if macdhist[-2] <= 0: operator += 'Bh' break if macdhist[-1] < 0: for i in range(1,7): if macdhist[-2] >= 0: operator += 'Sh' break return (operator) #??KDJ?????????
def Get_MACD(df): #??12,26,9 macd, macdsignal, macdhist = ta.MACD(np.array(df['close']), fastperiod=12, slowperiod=26, signalperiod=9) SignalMA5 = ta.MA(macdsignal, timeperiod=5, matype=0) SignalMA10 = ta.MA(macdsignal, timeperiod=10, matype=0) SignalMA20 = ta.MA(macdsignal, timeperiod=20, matype=0) #13-15 DIFF DEA DIFF-DEA df['macd']=pd.Series(macd,index=df.index) #DIFF df['macdsignal']=pd.Series(macdsignal,index=df.index)#DEA df['macdhist']=pd.Series(macdhist,index=df.index)#DIFF-DEA dflen = df.shape[0] MAlen = len(SignalMA5) operate = 0 #2??? 1.DIFF?DEA????DIFF????DEA?????? 2.DIFF?DEA????DIFF????DEA?????? #??? if df.iat[(dflen-1),13]>0: if df.iat[(dflen-1),14]>0: if df.iat[(dflen-1),13]>df.iat[(dflen-1),14] and df.iat[(dflen-2),13]<=df.iat[(dflen-2),14]: operate = operate + 10#?? else: if df.iat[(dflen-1),14]<0: if df.iat[(dflen-1),13]<=df.iat[(dflen-2),14]: operate = operate - 10#?? #3.DEA??K????????????? if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K??? if SignalMA5[MAlen-1]<=SignalMA10[MAlen-1] and SignalMA10[MAlen-1]<=SignalMA20[MAlen-1]: #DEA?? operate = operate - 1 elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K??? if SignalMA5[MAlen-1]>=SignalMA10[MAlen-1] and SignalMA10[MAlen-1]>=SignalMA20[MAlen-1]: #DEA?? operate = operate + 1 #4.??MACD?????????????? if df.iat[(dflen-1),15]>0 and dflen >30 : for i in range(1,26): if df.iat[(dflen-1-i),15]<=0:# operate = operate + 5 break #????????? if df.iat[(dflen-1),15]<0 and dflen >30 : for i in range(1,26): if df.iat[(dflen-1-i),15]>=0:# operate = operate - 5 break return (df,operate) #??KDJ??????
def Get_KDJ(df): #??9,3,3 slowk, slowd = ta.STOCH(np.array(df['high']), np.array(df['low']), np.array(df['close']), fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) slowkMA5 = ta.MA(slowk, timeperiod=5, matype=0) slowkMA10 = ta.MA(slowk, timeperiod=10, matype=0) slowkMA20 = ta.MA(slowk, timeperiod=20, matype=0) slowdMA5 = ta.MA(slowd, timeperiod=5, matype=0) slowdMA10 = ta.MA(slowd, timeperiod=10, matype=0) slowdMA20 = ta.MA(slowd, timeperiod=20, matype=0) #16-17 K,D df['slowk']=pd.Series(slowk,index=df.index) #K df['slowd']=pd.Series(slowd,index=df.index)#D dflen = df.shape[0] MAlen = len(slowkMA5) operate = 0 #1.K???????——???90?????????10??????D??80???????????D??20??????????? if df.iat[(dflen-1),16]>=90: operate = operate + 3 elif df.iat[(dflen-1),16]<=10: operate = operate - 3 if df.iat[(dflen-1),17]>=80: operate = operate + 3 elif df.iat[(dflen-1),17]<=20: operate = operate - 3 #2.??????K???D??K?????D?????????#??? if df.iat[(dflen-1),16]> df.iat[(dflen-1),17] and df.iat[(dflen-2),16]<=df.iat[(dflen-2),17]: operate = operate + 10 #??????K??D?K?????D?????????#??? elif df.iat[(dflen-1),16]< df.iat[(dflen-1),17] and df.iat[(dflen-2),16]>=df.iat[(dflen-2),17]: operate = operate - 10 #3.??????????????????????? if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K??? if (slowkMA5[MAlen-1]<=slowkMA10[MAlen-1] and slowkMA10[MAlen-1]<=slowkMA20[MAlen-1]) or \ (slowdMA5[MAlen-1]<=slowdMA10[MAlen-1] and slowdMA10[MAlen-1]<=slowdMA20[MAlen-1]): #K,D?? operate = operate - 1 elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K??? if (slowkMA5[MAlen-1]>=slowkMA10[MAlen-1] and slowkMA10[MAlen-1]>=slowkMA20[MAlen-1]) or \ (slowdMA5[MAlen-1]>=slowdMA10[MAlen-1] and slowdMA10[MAlen-1]>=slowdMA20[MAlen-1]): #K,D?? operate = operate + 1 return (df,operate) #??RSI??????
def Get_RSI(df): #??14,5 slowreal = ta.RSI(np.array(df['close']), timeperiod=14) fastreal = ta.RSI(np.array(df['close']), timeperiod=5) slowrealMA5 = ta.MA(slowreal, timeperiod=5, matype=0) slowrealMA10 = ta.MA(slowreal, timeperiod=10, matype=0) slowrealMA20 = ta.MA(slowreal, timeperiod=20, matype=0) fastrealMA5 = ta.MA(fastreal, timeperiod=5, matype=0) fastrealMA10 = ta.MA(fastreal, timeperiod=10, matype=0) fastrealMA20 = ta.MA(fastreal, timeperiod=20, matype=0) #18-19 ??real???real df['slowreal']=pd.Series(slowreal,index=df.index) #??real 18 df['fastreal']=pd.Series(fastreal,index=df.index)#??real 19 dflen = df.shape[0] MAlen = len(slowrealMA5) operate = 0 #RSI>80?????RSI<20???? if df.iat[(dflen-1),18]>80 or df.iat[(dflen-1),19]>80: operate = operate - 2 elif df.iat[(dflen-1),18]<20 or df.iat[(dflen-1),19]<20: operate = operate + 2 #RSI??50???????????50???????? if (df.iat[(dflen-2),18]<=50 and df.iat[(dflen-1),18]>50) or (df.iat[(dflen-2),19]<=50 and df.iat[(dflen-1),19]>50): operate = operate + 4 elif (df.iat[(dflen-2),18]>=50 and df.iat[(dflen-1),18]<50) or (df.iat[(dflen-2),19]>=50 and df.iat[(dflen-1),19]<50): operate = operate - 4 #RSI??????????RSI????????? if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K??? if (slowrealMA5[MAlen-1]<=slowrealMA10[MAlen-1] and slowrealMA10[MAlen-1]<=slowrealMA20[MAlen-1]) or \ (fastrealMA5[MAlen-1]<=fastrealMA10[MAlen-1] and fastrealMA10[MAlen-1]<=fastrealMA20[MAlen-1]): #RSI?? operate = operate - 1 elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K??? if (slowrealMA5[MAlen-1]>=slowrealMA10[MAlen-1] and slowrealMA10[MAlen-1]>=slowrealMA20[MAlen-1]) or \ (fastrealMA5[MAlen-1]>=fastrealMA10[MAlen-1] and fastrealMA10[MAlen-1]>=fastrealMA20[MAlen-1]): #RSI?? operate = operate + 1 #????????????????????????????????????????????????????????????????? if df.iat[(dflen-1),19]> df.iat[(dflen-1),18] and df.iat[(dflen-2),19]<=df.iat[(dflen-2),18]: operate = operate + 10 elif df.iat[(dflen-1),19]< df.iat[(dflen-1),18] and df.iat[(dflen-2),19]>=df.iat[(dflen-2),18]: operate = operate - 10 return (df,operate)