def onBar(self, bar): """收到Bar推送(必须由用户继承实现)""" # 撤销之前发出的尚未成交的委托(包括限价单和停止单) 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.atrLength)[-1] self.atrArray[0:self.bufferSize - 1] = self.atrArray[1:self.bufferSize] self.atrArray[-1] = self.atrValue self.atrCount += 1 if self.atrCount < self.bufferSize: return self.atrMa = talib.MA(self.atrArray, self.atrMaLength)[-1] self.rsiValue = talib.RSI(self.closeArray, self.rsiLength)[-1] # 判断是否要进行交易 # 当前无仓位 if self.pos == 0: self.intraTradeHigh = bar.high self.intraTradeLow = bar.low # ATR数值上穿其移动平均线,说明行情短期内波动加大 # 即处于趋势的概率较大,适合CTA开仓 if self.atrValue > self.atrMa: # 使用RSI指标的趋势行情时,会在超买超卖区钝化特征,作为开仓信号 if self.rsiValue > self.rsiBuy: # 这里为了保证成交,选择超价5个整指数点下单 self.buy(bar.close + 5, self.fixedSize) elif self.rsiValue < self.rsiSell: self.short(bar.close - 5, self.fixedSize) # 持有多头仓位 elif self.pos > 0: # 计算多头持有期内的最高价,以及重置最低价 self.intraTradeHigh = max(self.intraTradeHigh, bar.high) self.intraTradeLow = bar.low # 计算多头移动止损 longStop = self.intraTradeHigh * (1 - self.trailingPercent / 100) # 发出本地止损委托,并且把委托号记录下来,用于后续撤单 orderID = self.sell(longStop, abs(self.pos), stop=True) self.orderList.append(orderID) # 持有空头仓位 elif self.pos < 0: self.intraTradeLow = min(self.intraTradeLow, bar.low) self.intraTradeHigh = bar.high shortStop = self.intraTradeLow * (1 + self.trailingPercent / 100) orderID = self.cover(shortStop, abs(self.pos), stop=True) self.orderList.append(orderID) # 发出状态更新事件 self.putEvent()
def total(self, df0, scale=1, period=60): uid = self.uidKey % (self.mCodes[0], str(period), str(scale), self.klinePeriod, str(self.widthDeltaLine)) df0["rel_price"] = close = df0["close"] df0["datetime"] = df0.index p_l = close + self.shift p_h = close - self.shift num = len(df0) ma = ta.MA(close[0:num], timeperiod=period) df0["rel_std"] = sd = ta.STDDEV(close, timeperiod=period, nbdev=1) # 上下柜 top, lower = ma + scale * sd, ma - scale * sd #self.shift[0] = sd.values[-1] / close.values[-1] # bullWidth df0["bullwidth"] = width = 4 * sd / sd.mean() df0["delta"] = delta = (self.shift /sd).fillna(0) # 近三分钟width变动 df0["widthdelta"] = widthdelta=ta.MA(width - width.shift(1), timeperiod = 3).fillna(0) #df0["widthdelta"] = widthdelta = (width - width.shift(1)).fillna(0) widthdelta2 = widthdelta - widthdelta.shift(1) w2 = widthdelta2 * widthdelta2.shift(1) isOpen, preDate, prePrice = 0, None, 0 doc, docs = {}, [] self.index = uuid.uuid1() for i in range(num): isRun = False c_datetime = df0.index[i] if i < period and np.isnan(ma[i]): continue # 开仓 if isOpen == 0: # 开市前分钟不再开仓 if delta[i] > self.deltaLine : continue if self.widthDeltaLine != -1: cond1 = (widthdelta[i] > self.widthDeltaLine) or ( widthdelta2[i] > (self.widthDeltaLine / 2)) else: cond1 = False # 大于上线轨迹 if ((p_l[i] > top[i]) and not cond1) : isOpen = -1 isRun = True elif ((p_h[i] < lower[i]) and not cond1) : isOpen = 1 isRun = True elif cond1 and w2[i] < 0 and (p_h[i] > top[i]) : isOpen = -2 isRun = True elif (cond1 and w2[i] < 0) and (p_l[i] < lower[i]): isOpen = 2 isRun = True # 平仓 else: # 回归ma则平仓 或 超过24分钟 或到收盘时间 强制平仓 if (isOpen * ((p_h[i] if isOpen>0 else p_l[i]) - ma[i])) >= 0: isOpen = 0 isRun = True # 止损 #elif ((isOpen==2) and (p_l[i] < top[i])) or ((isOpen==-2) and (p_h[i] > lower[i])): #elif (abs(isOpen)==2) and (w2[i] < 0) : # isOpen = 0 # isRun = True if isRun: doc = self.order(df0.iloc[i], isOpen) if doc: doc["uid"] =uid docs.append(doc) res = pd.DataFrame(docs) if self.saveDetail: print(abs(widthdelta).mean(), sd.mean()) self.Train.insertAll(docs) if len(res) > 0: return { "scale": scale, "period": period, "count": len(res), "amount": (doc["price"] * doc["vol"]) if doc is not None else 0 , "income": res["income"].sum(), "uid": uid, #"delta":(self.shift/sd).mean(), "shift": widthdelta.mean() , "std": sd.mean(), "createdate": public.getDatetime() } else: return None
def cal_ma_ta_param(df, param, n): temp_serise = talib.MA(df[param], timeperiod=n) temp_serise.dropna(inplace=True) ma_serise = temp_serise.reset_index(drop=True) return ma_serise
def myStrategy(dailyOhlcvFile, minutelyOhlcvFile, currentPrice): import numpy as np import talib pastPriceVec = (dailyOhlcvFile['open'] + dailyOhlcvFile['close']) / 2 pastPriceVec = np.array(pastPriceVec) action = 0 # actions=1(buy), -1(sell), 0(hold), with 0 as the default actions param = [5, 20, 30, 85, 100] shortWindow = param[0] longWindow = param[1] rsiAlpha = param[2] rsiBeta = param[3] maAlpha = param[4] collectMA = [] for window in range(5, 201, 5): collectMA.append(talib.EMA(pastPriceVec, window)[-1]) shortMA = talib.MA(pastPriceVec, shortWindow)[-1] longMA = talib.MA(pastPriceVec, longWindow)[-1] dataLen = len(pastPriceVec) # Length of the data vector if dataLen <= param[0]: return action longrsi = None U = pastPriceVec[-shortWindow:] - pastPriceVec[-shortWindow - 1:-1] # Up D = -U # Down for i in range(0, shortWindow): if U[i] < 0: U[i] = 0 else: D[i] = 0 sumU = np.sum(U) sumD = np.sum(D) rsi = (sumU / (sumU + sumD)) * 100 U = [] D = [] if (longWindow < len(pastPriceVec)): U = pastPriceVec[-longWindow:] - pastPriceVec[-longWindow - 1:-1] # Up D = -U # Down else: U = pastPriceVec[1:len(pastPriceVec)] - pastPriceVec[ 0:len(pastPriceVec) - 1] # Up D = -U for i in range(0, len(U)): if U[i] < 0: U[i] = 0 else: D[i] = 0 sumU = np.sum(U) sumD = np.sum(D) longrsi = (sumU / (sumU + sumD)) * 100 voteBuy = 0 voteSale = 0 for i in range(len(collectMA)): if (currentPrice >= collectMA[i]): voteBuy += 1 elif (currentPrice < collectMA[i]): voteSale += 1 print(rsi, longrsi) if (rsi < rsiAlpha): action = 1 elif (rsi > rsiBeta): action = -1 elif (longrsi): if (rsi > longrsi and (voteSale < voteBuy or currentPrice - longMA < -maAlpha)): action = 1 elif (rsi < longrsi and (voteSale > voteBuy or currentPrice - longMA > maAlpha)): action = -1 return action
def get_datasets(asset, currency, granularity, datapoints, df_train_size=0.75): """Fetch the API and precess the desired pair Arguments: asset {str} -- First pair currency {str} -- Second pair granularity {str ['day', 'hour']} -- Granularity datapoints {int [100 - 2000]} -- [description] Returns: pandas.Dataframe -- The OHLCV and indicators dataframe """ df_train_path = 'datasets/bot_train_{}_{}_{}.csv'.format( asset + currency, datapoints, granularity) df_rollout_path = 'datasets/bot_rollout_{}_{}_{}.csv'.format( asset + currency, datapoints, granularity) asset_icon = '₿' if asset == 'BTC' else asset currency_icon = '₿' if currency == 'BTC' else currency if not os.path.exists(df_rollout_path): headers = { 'User-Agent': 'Mozilla/5.0', 'authorization': 'Apikey 3d7d3e9e6006669ac00584978342451c95c3c78421268ff7aeef69995f9a09ce' } url = 'https://min-api.cryptocompare.com/data/histo{}?fsym={}&tsym={}&limit={}'.format( granularity, asset, currency, datapoints) with yaspin(text='Downloading datasets') as sp: response = requests.get(url, headers=headers) sp.hide() print_formatted_text(HTML( u'<b>></b> <msg>{}/{}</msg> <sub-msg>download complete</sub-msg>' .format(asset_icon, currency_icon)), style=style) sp.show() json_response = response.json() status = json_response['Response'] if status == "Error": print(colored('=== {} ==='.format(json_response['Message']), 'red')) raise AssertionError() result = json_response['Data'] df = pd.DataFrame(result) # print(df.tail()) df['Date'] = pd.to_datetime(df['time'], utc=True, unit='s') df.drop('time', axis=1, inplace=True) # indicators # https://github.com/mrjbq7/ta-lib/blob/master/docs/func.md open_price, high, low, close = np.array(df['open']), np.array( df['high']), np.array(df['low']), np.array(df['close']) volume = np.array(df['volumefrom']) # cycle indicators df.loc[:, 'HT_DCPERIOD'] = talib.HT_DCPERIOD(close) df.loc[:, 'HT_DCPHASE'] = talib.HT_DCPHASE(close) df.loc[:, 'HT_PHASOR_inphase'], df.loc[:, 'HT_PHASOR_quadrature'] = talib.HT_PHASOR( close) df.loc[:, 'HT_SINE_sine'], df.loc[:, 'HT_SINE_leadsine'] = talib.HT_SINE( close) df.loc[:, 'HT_TRENDMODE'] = talib.HT_TRENDMODE(close) # momemtum indicators df.loc[:, 'ADX'] = talib.ADX(high, low, close, timeperiod=12) df.loc[:, 'ADXR'] = talib.ADXR(high, low, close, timeperiod=13) df.loc[:, 'APO'] = talib.APO(close, fastperiod=5, slowperiod=10, matype=0) df.loc[:, 'AROON_down'], df.loc[:, 'AROON_up'] = talib.AROON(high, low, timeperiod=15) df.loc[:, 'AROONOSC'] = talib.AROONOSC(high, low, timeperiod=13) df.loc[:, 'BOP'] = talib.BOP(open_price, high, low, close) df.loc[:, 'CCI'] = talib.CCI(high, low, close, timeperiod=13) df.loc[:, 'CMO'] = talib.CMO(close, timeperiod=14) df.loc[:, 'DX'] = talib.DX(high, low, close, timeperiod=10) df['MACD'], df['MACD_signal'], df['MACD_hist'] = talib.MACD( close, fastperiod=5, slowperiod=10, signalperiod=20) df.loc[:, 'MFI'] = talib.MFI(high, low, close, volume, timeperiod=12) df.loc[:, 'MINUS_DI'] = talib.MINUS_DI(high, low, close, timeperiod=10) df.loc[:, 'MINUS_DM'] = talib.MINUS_DM(high, low, timeperiod=14) df.loc[:, 'MOM'] = talib.MOM(close, timeperiod=20) df.loc[:, 'PPO'] = talib.PPO(close, fastperiod=17, slowperiod=35, matype=2) df.loc[:, 'ROC'] = talib.ROC(close, timeperiod=12) df.loc[:, 'RSI'] = talib.RSI(close, timeperiod=25) df.loc[:, 'STOCH_k'], df.loc[:, 'STOCH_d'] = talib.STOCH(high, low, close, fastk_period=35, slowk_period=12, slowk_matype=0, slowd_period=7, slowd_matype=0) df.loc[:, 'STOCHF_k'], df.loc[:, 'STOCHF_d'] = talib.STOCHF(high, low, close, fastk_period=28, fastd_period=14, fastd_matype=0) df.loc[:, 'STOCHRSI_K'], df.loc[:, 'STOCHRSI_D'] = talib.STOCHRSI( close, timeperiod=35, fastk_period=12, fastd_period=10, fastd_matype=1) df.loc[:, 'TRIX'] = talib.TRIX(close, timeperiod=30) df.loc[:, 'ULTOSC'] = talib.ULTOSC(high, low, close, timeperiod1=14, timeperiod2=28, timeperiod3=35) df.loc[:, 'WILLR'] = talib.WILLR(high, low, close, timeperiod=35) # overlap studies df.loc[:, 'BBANDS_upper'], df.loc[:, 'BBANDS_middle'], df.loc[:, 'BBANDS_lower'] = talib.BBANDS( close, timeperiod= 12, nbdevup=2, nbdevdn=2, matype=0) df.loc[:, 'DEMA'] = talib.DEMA(close, timeperiod=30) df.loc[:, 'EMA'] = talib.EMA(close, timeperiod=7) df.loc[:, 'HT_TRENDLINE'] = talib.HT_TRENDLINE(close) df.loc[:, 'KAMA'] = talib.KAMA(close, timeperiod=5) df.loc[:, 'MA'] = talib.MA(close, timeperiod=5, matype=0) df.loc[:, 'MIDPOINT'] = talib.MIDPOINT(close, timeperiod=20) df.loc[:, 'WMA'] = talib.WMA(close, timeperiod=15) df.loc[:, 'SMA'] = talib.SMA(close) # pattern recoginition df.loc[:, 'CDL2CROWS'] = talib.CDL2CROWS(open_price, high, low, close) df.loc[:, 'CDL3BLACKCROWS'] = talib.CDL3BLACKCROWS( open_price, high, low, close) df.loc[:, 'CDL3INSIDE'] = talib.CDL3INSIDE(open_price, high, low, close) df.loc[:, 'CDL3LINESTRIKE'] = talib.CDL3LINESTRIKE( open_price, high, low, close) # price transform df.loc[:, 'WCLPRICE'] = talib.WCLPRICE(high, low, close) # statistic funcitons df.loc[:, 'BETA'] = talib.BETA(high, low, timeperiod=20) df.loc[:, 'CORREL'] = talib.CORREL(high, low, timeperiod=20) df.loc[:, 'STDDEV'] = talib.STDDEV(close, timeperiod=20, nbdev=1) df.loc[:, 'TSF'] = talib.TSF(close, timeperiod=20) df.loc[:, 'VAR'] = talib.VAR(close, timeperiod=20, nbdev=1) # volatility indicators df.loc[:, 'ATR'] = talib.ATR(high, low, close, timeperiod=7) df.loc[:, 'NATR'] = talib.NATR(high, low, close, timeperiod=20) df.loc[:, 'TRANGE'] = talib.TRANGE(high, low, close) # volume indicators df.loc[:, 'AD'] = talib.AD(high, low, close, volume) df.loc[:, 'ADOSC'] = talib.ADOSC(high, low, close, volume, fastperiod=10, slowperiod=20) df.loc[:, 'OBV'] = talib.OBV(close, volume) # df.fillna(df.mean(), inplace=True) df.dropna(inplace=True) df.set_index('Date', inplace=True) # print(colored('> caching' + asset + '/' + currency + ':)', 'cyan')) # 75% to train -> test with different value train_size = round(len(df) * df_train_size) df_train = df[:train_size] df_rollout = df[train_size:] df_train.to_csv(df_train_path) df_rollout.to_csv(df_rollout_path) # re-read to avoid indexing issue w/ Ray df_train = pd.read_csv(df_train_path) df_rollout = pd.read_csv(df_rollout_path) else: print_formatted_text(HTML( u'<b>></b> <msg>{}/{}</msg> <sub-msg>cached</sub-msg>'.format( asset_icon, currency_icon)), style=style) # print(colored('> feching ' + asset + '/' + currency + ' from cache :)', 'magenta')) df_train = pd.read_csv(df_train_path) df_rollout = pd.read_csv(df_rollout_path) # df_train.set_index('Date', inplace=True) # df_rollout.set_index('Date', inplace=True) return df_train, df_rollout
def onFiveBar(self, bar): """收到5分钟K线""" # 撤销之前发出的尚未成交的委托(包括限价单和停止单) for orderID in self.orderList: self.cancelOrder(orderID) #print bar.openInterestList #print bar.datetime.minute # 如果当前是一个15分钟走完 if (bar.datetime.minute + 1 * self.barBin) % self.barLongBin == 0: # 如果已经有聚合5分钟K线 if self.longCycleBar: # 将最新分钟的数据更新到目前5分钟线中 longCycleBar = self.longCycleBar longCycleBar.high = max(longCycleBar.high, bar.high) longCycleBar.low = min(longCycleBar.low, bar.low) longCycleBar.close = bar.close longCycleBar.volume += bar.volume longCycleBar.openInterest = bar.openInterest # 推送5分钟线数据 self.onLongCycle(longCycleBar) # 清空5分钟线数据缓存 # print preBarOpenInterest self.longCycleBar = None else: # 如果没有缓存则新建 if not self.longCycleBar: longCycleBar = VtBarData() longCycleBar.vtSymbol = bar.vtSymbol longCycleBar.symbol = bar.symbol longCycleBar.exchange = bar.exchange longCycleBar.open = bar.open longCycleBar.high = bar.high longCycleBar.low = bar.low longCycleBar.close = bar.close longCycleBar.volume = bar.volume longCycleBar.openInterest = bar.openInterest longCycleBar.date = bar.date longCycleBar.time = bar.time longCycleBar.datetime = bar.datetime self.longCycleBar = longCycleBar else: longCycleBar = self.longCycleBar longCycleBar.high = max(longCycleBar.high, bar.high) longCycleBar.low = min(longCycleBar.low, bar.low) longCycleBar.close = bar.close longCycleBar.volume += bar.volume longCycleBar.openInterest = bar.openInterest vArray1min = np.array(bar.volumeList) oArray1min = np.array(bar.openInterestList) barOpenRatioModi = ((np.sqrt(vArray1min) / np.sqrt(vArray1min).sum()) * ((oArray1min[1:] - \ oArray1min[:-1]) / vArray1min)).mean() #print barOpenRatioModi #print 'Volume Array:', vArray1min, '\n', 'OpenInterestArray:', oArray1min,'\n','OpenRatioMOdi:',barOpenRatioModi print 'Long cycle:', self.longCycleTradingFlag 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.volumeArray[0:self.bufferSize - 1] = self.volumeArray[1:self.bufferSize] self.openInterestArray[0:self.bufferSize - 1] = self.openInterestArray[1:self.bufferSize] self.openRatioModiArray[0:self.bufferSize - 1] = self.openRatioModiArray[1:self.bufferSize] self.closeArray[-1] = bar.close self.highArray[-1] = bar.high self.lowArray[-1] = bar.low self.volumeArray[-1] = bar.volume self.openInterestArray[-1] = bar.openInterest # 持仓量 self.openRatioModiArray[-1] = barOpenRatioModi # 开仓比例 #print self.volumeArray #print self.openInterestArray 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.kkDevUp self.kkDown = self.kkMid - self.atrValue * self.kkDevDown #self.obvArray = talib.OBV(self.closeArray, self.volumeArray) #self.shortMA = talib.MA(self.closeArray, self.shortMAperiod) #self.longMA = talib.MA(self.closeArray, self.longMAperiod) self.atrMa = talib.MA(self.atrArray, self.atrMaLength)[-1] #print self.vol # 量价指标 #self.changePerVolumeArray = np.abs(self.closeArray[1:] - self.closeArray[:-1]) / self.volumeArray[1:] #self.changePerVolumeArray = np.abs(self.highArray - self.lowArray) / self.volumeArray # 最高价最低价 # 成交量均值指标 #self.volumeMa = talib.MA(self.volumeArray, 6)[-1] self.openRatio = (self.openInterestArray[-1] - self.openInterestArray[-2]) / self.volumeArray[-1] # self.openRatioModi = self.openRatioModiArray[-1] # 开仓量指标 self.openRatioArray = ( self.openInterestArray[1:] - self.openInterestArray[:-1]) / self.volumeArray[1:] #self.openRatioMaArray = talib.EMA(self.openRatioArray, timeperiod=self.openRatioMaLength) self.hb = talib.HT_TRENDLINE(self.closeArray) #print self.closeArray #self.kamaArray = talib.KAMA(self.closeArray, timeperiod=30) #print self.openRatio #print self.kamaArray [-1],self.kamaArray [-2] #kdjLongCondition = slowk[-1] > slowd[-1] and slowk[-2] < slowd[-2] #kdjShortCondition = slowk[-1] < slowd[-1] and slowk[-2] > slowd[-2] conditionKKBuy = self.closeArray[-1] > self.kkUp conditionKKSell = self.closeArray[-1] < self.kkDown #conditionImpulseBuy = self.changePerVolumeArray[-1] > talib.MA(self.changePerVolumeArray, 6)[-1] #conditionVolume = self.volumeArray[-1] > self.volumeMa # 成交量指标 conditionHBBuy = self.closeArray[-1] > self.hb[-1] and self.closeArray[ -2] < self.hb[-2] conditionHBSell = self.closeArray[-1] < self.hb[ -1] and self.closeArray[-2] > self.hb[-2] #conditionOpenRatioBuy = self.openRatio > self.thresholdRatio #conditionOpenRatioSell = self.openRatio > self.thresholdRatio + 0.015 #conditionkamabuy = (self.kamaArray[-1] >= self.kamaArray[-2] >= self.kamaArray[-3]) #conditionkamasell = (self.kamaArray[-1] <= self.kamaArray[-2] <= self.kamaArray[-3]) conditionOpenRatioModiBuy = self.openRatioModi > 0.022 conditionOpenRatioModiSell = self.openRatioModi > 0.026 # 最好0.026 #conditionOpenRatio = self.openRatioMaArray[-1] > self.openRatioMaArray[-2] and \ # self.openRatioMaArray[-1] > 0.095 # 保存信号 if conditionHBBuy and conditionOpenRatioModiBuy: self.signalBuy.append(bar.datetime) elif conditionHBSell and conditionOpenRatioModiSell: self.signalSell.append(bar.datetime) # 判断是否要进行交易 # 当前无仓位, if self.pos == 0: #print len(self.buyCost) #self.svdArrayShort = getSVD(self.closeArray, self.ShapeNum, self.SVDShort) #self.svdArrayLong = getSVD(self.closeArray, self.ShapeNum, self.SVDLong) self.intraTradeHigh = bar.high self.intraTradeLow = bar.low if conditionKKBuy and conditionOpenRatioModiBuy and self.longCycleTradingFlag == 1: self.buy(bar.close + 5, self.fixedSize) self.buyCost.append(bar.close + 5) elif conditionKKSell and conditionOpenRatioModiSell and self.longCycleTradingFlag == -1: self.short(bar.close - 5, self.fixedSize) self.shortCost.append(bar.close - 5) # 持有多头仓位 elif self.pos > 0: self.intraTradeHigh = max(self.intraTradeHigh, bar.high) self.intraTradeLow = bar.low self.longStop = self.intraTradeHigh * (1 - self.trailingPrcnt / 100) orderID = self.sell(self.longStop, abs(self.pos), stop=True) self.buycutProfitList.append(orderID) self.writeCtaLog(u'多头止损价格:' + str(self.longStop)) self.orderList.append(orderID) # 持有空头仓位 elif self.pos < 0: self.intraTradeHigh = bar.high self.intraTradeLow = min(self.intraTradeLow, bar.low) self.shortStop = self.intraTradeLow * (1 + self.trailingPrcnt / 100) orderID = self.cover(self.shortStop, abs(self.pos), stop=True) self.sellcutProfitList.append(orderID) self.writeCtaLog(u'空头头止损价格:' + str(self.shortStop)) self.orderList.append(orderID) # 发出状态更新事件 self.putEvent()
training_set = dataset_train.iloc[:, :].values # close data training_set.shape #(1092470, 9) long = 1430 short = 1060 RSIt = 14 ATRt = 14 close_price = np.array([i[3] for i in training_set ]) # close_price[-1]/close_price[0] # 1.002 low_price = np.array([i[2] for i in training_set]) high_price = np.array([i[1] for i in training_set]) # append MA_long MA_long = talib.MA(close_price, timeperiod=long, matype=0) MA_long.shape # (801453,) MA_long = np.reshape(MA_long, (MA_long.shape[0], 1)) MA_long.shape # (801453, 1) training_set = np.append(training_set, MA_long, axis=1) training_set.shape #(801453, 10) # append MA_short MA_short = talib.MA(close_price, timeperiod=short, matype=0) MA_short.shape # (801453,) MA_short = np.reshape(MA_short, (MA_short.shape[0], 1)) training_set = np.append(training_set, MA_short, axis=1) training_set.shape #(801453, 11) # append ATR ATR = talib.ATR(high_price, low_price, close_price, timeperiod=ATRt)
def handle_bar(self): """根据数据判断是否有交易信号产生,并根据信号下单(日线级)""" is_unlock_trade = False is_fire_trade = False trade_sum = 0 while not is_fire_trade: if not self.trade_env and not is_unlock_trade: ret_code, ret_data = self.trade_ctx.unlock_trade( self.unlock_password) is_unlock_trade = (ret_code == 0) if not is_unlock_trade: print("请求交易解锁失败: {} 重试中...".format(ret_data)) sleep(1) continue ret_code, ret_data = self.quote_ctx.get_history_kline( self.code, start='2017-01-01') if ret_code == 0: close = np.array(ret_data['close']) else: print('k线数据获取异常, 重试中: {}'.format(ret_data)) sleep(1) continue if self.indicator_type.lower() == 'chg': # calculate change% chg_rate = (close[-1] - close[-2]) / close[-2] # open position if self.up_chg_signal and not self.holding.get( self.up_buy_code, 0): if chg_rate > self.up_chg_rate: ret, data = self.quote_ctx.get_market_snapshot( [self.up_buy_code]) up_lst_price = data.iloc[0][ 'last_price'] if ret == 0 else 0 up_lot_size = data.iloc[0][ 'lot_size'] if ret == 0 else 0 if up_lot_size == 0 or up_lst_price == 0.0: continue ret_code, ret_data = self.trade_ctx.place_order( price=up_lst_price, qty=up_lot_size, strcode=self.up_buy_code, orderside=0, ordertype=self.order_type, envtype=self.trade_env) if not ret_code: trade_sum += 1 print( 'up_ma_signal MAKE BUY ORDER\n\tcode = {} price = {} quantity = {}' .format(self.up_buy_code, up_lst_price, up_lot_size)) up_sell_date = datetime.datetime.now( ) + datetime.timedelta(days=self.up_hold_sell) self.holding[ self.up_buy_code] = up_sell_date.strftime( '%Y-%m-%d') else: print('up_ma_signal: MAKE BUY ORDER FAILURE!') if self.down_chg_signal and not self.holding.get( self.down_buy_code, 0): if chg_rate < self.down_chg_rate: ret, data = self.quote_ctx.get_market_snapshot( [self.down_buy_code]) down_lst_price = data.iloc[0][ 'last_price'] if ret == 0 else 0 down_lot_size = data.iloc[0][ 'lot_size'] if ret == 0 else 0 if down_lot_size == 0 or down_lst_price == 0.0: continue ret_code, ret_data = self.trade_ctx.place_order( price=down_lst_price, qty=down_lot_size, strcode=self.down_buy_code, orderside=0, ordertype=self.order_type, envtype=self.trade_env) if not ret_code: trade_sum += 1 print( 'down_ma_signal MAKE BUY ORDER\n\tcode = {} price = {} quantity = {}' .format(self.down_buy_code, down_lst_price, down_lot_size)) down_sell_date = datetime.datetime.now( ) + datetime.timedelta(days=self.down_hold_sell) self.holding[ self.down_buy_code] = down_sell_date.strftime( '%Y-%m-%d') else: print('down_ma_signal: MAKE BUY ORDER FAILURE!') elif self.indicator_type.lower() == 'ma': # calculate MA ma_short1 = ta.MA(close, timeperiod=self.gold_ma_short, matype=0) ma_long1 = ta.MA(close, timeperiod=self.gold_ma_long, matype=0) ma_short2 = ta.MA(close, timeperiod=self.dead_ma_short, matype=0) ma_long2 = ta.MA(close, timeperiod=self.dead_ma_long, matype=0) # open position if self.gold_ma_signal and not self.holding.get( self.gold_buy_code, 0): if ma_short1[-1] > ma_long1[-1]: ret, data = self.quote_ctx.get_market_snapshot( [self.gold_buy_code]) gold_lst_price = data.iloc[0][ 'last_price'] if ret == 0 else 0 gold_lot_size = data.iloc[0][ 'lot_size'] if ret == 0 else 0 if gold_lst_price == 0.0 or gold_lot_size == 0: continue ret_code, ret_data = self.trade_ctx.place_order( price=gold_lst_price, qty=gold_lot_size, strcode=self.gold_buy_code, orderside=0, ordertype=self.order_type, envtype=self.trade_env) if not ret_code: trade_sum += 1 print( 'gold_ma_signal: MAKE BUY ORDER\n\tcode = {} price = {} quantity = {}' .format(self.gold_buy_code, gold_lst_price, gold_lot_size)) gold_sell_date = datetime.datetime.now( ) + datetime.timedelta(days=self.gold_hold_sell) self.holding[ self.gold_buy_code] = gold_sell_date.strftime( '%Y-%m-%d') else: print('gold_ma_signal: MAKE BUY ORDER FAILURE!') if self.dead_ma_signal and not self.holding.get( self.dead_buy_code, 0): if ma_short2[-1] < ma_long2[-1]: ret, data = self.quote_ctx.get_market_snapshot( [self.dead_buy_code]) dead_lst_price = data.iloc[0][ 'last_price'] if ret == 0 else 0 dead_lot_size = data.iloc[0][ 'lot_size'] if ret == 0 else 0 if dead_lst_price == 0.0 or dead_lot_size == 0: continue ret_code, ret_data = self.trade_ctx.place_order( price=dead_lst_price, qty=dead_lot_size, strcode=self.dead_buy_code, orderside=0, ordertype=self.order_type, envtype=self.trade_env) if not ret_code: trade_sum += 1 print( 'dead_ma_signal: MAKE BUY ORDER\n\tcode = {} price = {} quantity = {}' .format(self.dead_buy_code, dead_lst_price, dead_lot_size)) dead_sell_date = datetime.datetime.now( ) + datetime.timedelta(days=self.dead_hold_sell) self.holding[ self.dead_buy_code] = dead_sell_date.strftime( '%Y-%m-%d') else: print('dead_ma_signal: MAKE BUY ORDER FAILURE!') else: raise 'indicator_type设置错误: {}'.format(self.indicator_type) # close position temp_hold = self.holding.copy() if len(temp_hold): for key, item in temp_hold.items(): if datetime.datetime.now().strftime('%Y-%m-%d') == item: ret, data = self.quote_ctx.get_market_snapshot([key]) lst_price = data.iloc[0][ 'last_price'] if ret == 0 else 0 lot_size = data.iloc[0]['lot_size'] if ret == 0 else 0 if lst_price == 0.0 or lot_size == 0: continue ret_code, ret_data = self.trade_ctx.place_order( price=lst_price, qty=lot_size, strcode=key, orderside=1, ordertype=self.order_type, envtype=self.trade_env) if not ret_code: print( 'close position: MAKE SELL ORDER\n\tcode = {} price = {} quantity = {}' .format(key, lst_price, lot_size)) del self.holding[key] else: print('close position MAKE SELL ORDER FAILURE!') if trade_sum > 0: # destroy obj self.quote_ctx.close() self.trade_ctx.close() is_fire_trade = True return self.holding
def MA(self, ndarray, timeperiod=5): x = np.array([talib.MA(ndarray.T[0], timeperiod)]) # print(x) return x.T
def technical(df): open = df['open'].values close = df['close'].values high = df['high'].values low = df['low'].values volume = df['volume'].values # define the technical analysis matrix retn = np.array([ tb.MA(close, timeperiod=60), # 1 tb.MA(close, timeperiod=120), # 2 tb.ADX(high, low, close, timeperiod=14), # 3 tb.ADXR(high, low, close, timeperiod=14), # 4 tb.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)[0], # 5 tb.RSI(close, timeperiod=14), # 6 tb.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0], # 7 tb.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1], # 8 tb.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2], # 9 tb.AD(high, low, close, volume), # 10 tb.ATR(high, low, close, timeperiod=14), # 11 tb.HT_DCPERIOD(close), # 12 tb.CDL2CROWS(open, high, low, close), # 13 tb.CDL3BLACKCROWS(open, high, low, close), # 14 tb.CDL3INSIDE(open, high, low, close), # 15 tb.CDL3LINESTRIKE(open, high, low, close), # 16 tb.CDL3OUTSIDE(open, high, low, close), # 17 tb.CDL3STARSINSOUTH(open, high, low, close), # 18 tb.CDL3WHITESOLDIERS(open, high, low, close), # 19 tb.CDLABANDONEDBABY(open, high, low, close, penetration=0), # 20 tb.CDLADVANCEBLOCK(open, high, low, close), # 21 tb.CDLBELTHOLD(open, high, low, close), # 22 tb.CDLBREAKAWAY(open, high, low, close), # 23 tb.CDLCLOSINGMARUBOZU(open, high, low, close), # 24 tb.CDLCONCEALBABYSWALL(open, high, low, close), # 25 tb.CDLCOUNTERATTACK(open, high, low, close), # 26 tb.CDLDARKCLOUDCOVER(open, high, low, close, penetration=0), # 27 tb.CDLDOJI(open, high, low, close), # 28 tb.CDLDOJISTAR(open, high, low, close), # 29 tb.CDLDRAGONFLYDOJI(open, high, low, close), # 30 tb.CDLENGULFING(open, high, low, close), # 31 tb.CDLEVENINGDOJISTAR(open, high, low, close, penetration=0), # 32 tb.CDLEVENINGSTAR(open, high, low, close, penetration=0), # 33 tb.CDLGAPSIDESIDEWHITE(open, high, low, close), # 34 tb.CDLGRAVESTONEDOJI(open, high, low, close), # 35 tb.CDLHAMMER(open, high, low, close), # 36 tb.CDLHANGINGMAN(open, high, low, close), # 37 tb.CDLHARAMI(open, high, low, close), # 38 tb.CDLHARAMICROSS(open, high, low, close), # 39 tb.CDLHIGHWAVE(open, high, low, close), # 40 tb.CDLHIKKAKE(open, high, low, close), # 41 tb.CDLHIKKAKEMOD(open, high, low, close), # 42 tb.CDLHOMINGPIGEON(open, high, low, close), # 43 tb.CDLIDENTICAL3CROWS(open, high, low, close), # 44 tb.CDLINNECK(open, high, low, close), # 45 tb.CDLINVERTEDHAMMER(open, high, low, close), # 46 tb.CDLKICKING(open, high, low, close), # 47 tb.CDLKICKINGBYLENGTH(open, high, low, close), # 48 tb.CDLLADDERBOTTOM(open, high, low, close), # 49 tb.CDLLONGLEGGEDDOJI(open, high, low, close), # 50 tb.CDLLONGLINE(open, high, low, close), # 51 tb.CDLMARUBOZU(open, high, low, close), # 52 tb.CDLMATCHINGLOW(open, high, low, close), # 53 tb.CDLMATHOLD(open, high, low, close, penetration=0), # 54 tb.CDLMORNINGDOJISTAR(open, high, low, close, penetration=0), # 55 tb.CDLMORNINGSTAR(open, high, low, close, penetration=0), # 56 tb.CDLONNECK(open, high, low, close), # 57 tb.CDLPIERCING(open, high, low, close), # 58 tb.CDLRICKSHAWMAN(open, high, low, close), # 59 tb.CDLRISEFALL3METHODS(open, high, low, close), # 60 tb.CDLSEPARATINGLINES(open, high, low, close), # 61 tb.CDLSHOOTINGSTAR(open, high, low, close), # 62 tb.CDLSHORTLINE(open, high, low, close), # 63 tb.CDLSPINNINGTOP(open, high, low, close), # 64 tb.CDLSTALLEDPATTERN(open, high, low, close), # 65 tb.CDLSTICKSANDWICH(open, high, low, close), # 66 tb.CDLTAKURI(open, high, low, close), # 67 tb.CDLTASUKIGAP(open, high, low, close), # 68 tb.CDLTHRUSTING(open, high, low, close), # 69 tb.CDLTRISTAR(open, high, low, close), # 70 tb.CDLUNIQUE3RIVER(open, high, low, close), # 71 tb.CDLUPSIDEGAP2CROWS(open, high, low, close), # 72 tb.CDLXSIDEGAP3METHODS(open, high, low, close) # 73 ]).T return retn
def on_bar(context, bars): for bar in bars: context.symbol = bar['symbol'] if context.first[stocks.index(context.symbol)] == 0: # 最开始配置仓位 # 需要保持的总仓位 order_volume(symbol=context.symbol, volume=context.total[stocks.index(context.symbol)], side=PositionSide_Long, order_type=OrderType_Market, position_effect=PositionEffect_Open) print(context.now, context.symbol, '以市价单开多仓', context.total[stocks.index(context.symbol)], '股') context.first[stocks.index(context.symbol)] = 1. context.day[stocks.index(context.symbol)][-1] = bar.bob.day context.day[stocks.index(context.symbol)][0] = bar.bob.day # 更新最新的日期 day = bar.bob.strftime('%Y-%m-%d %H:%M:%S') context.day[stocks.index(context.symbol)][-1] = bar.bob.day # 若为新的一天,获取可用于回转的昨仓 if str(context.day[stocks.index(context.symbol)][-1]) != str( context.day[stocks.index(context.symbol)][0]): context.ending[stocks.index(context.symbol)] = 0 context.turnaround[stocks.index(context.symbol)] = [0, 0] # 若有可用的昨仓则操作 if context.total[stocks.index(context.symbol)] >= 0 and str( context.ending[stocks.index(context.symbol)]) == str(0): # 获取时间序列数据 symbol = context.symbol recent_data = context.data(symbol=symbol, frequency='300s', count=35, fields='close') # 计算MACD线 # DIF组成的线叫做MACD线,DEA组成的线叫做Signal线,DIFF减DEA,得Hist macd, signal, hist = talib.MACD(recent_data['close'].values) ma_5 = talib.MA(recent_data['close'].values, 5) ma_10 = talib.MA(recent_data['close'].values, 10) # 金叉,且均线齐头排列,买入 if (macd[-2] < signal[-2] and macd[-1] > signal[-1] and ma_5[-1] > ma_10[-1]): # macd[-1]<0 and signal[-1]<0 and # 多空单向操作都不能超过昨仓位,否则最后无法调回原仓位 if context.turnaround[stocks.index(context.symbol)][0] + context.trade_n[stocks.index(context.symbol)] < \ context.total[stocks.index(context.symbol)]: # 计算累计仓位 context.turnaround[stocks.index( context.symbol)][0] += context.trade_n[stocks.index( context.symbol)] order_volume(symbol=context.symbol, volume=context.trade_n[stocks.index( context.symbol)], side=PositionSide_Long, order_type=OrderType_Market, position_effect=PositionEffect_Open) print(context.now, symbol, '市价单开多仓', context.trade_n[stocks.index(context.symbol)], '股') # 死叉,或者,或者,或者均线空排下降,卖出 elif macd[-1] > 0 and signal[-1] > 0 and macd[-2] > signal[-2] and macd[-1] < signal[-1] or ma_5[-1] < \ ma_10[-1]: # elif macd[-2] > signal[-2] and macd[-1] < signal[-1]: if context.turnaround[stocks.index(context.symbol)][1] + context.trade_n[stocks.index(context.symbol)] < \ context.total[stocks.index(context.symbol)]: context.turnaround[stocks.index( context.symbol)][1] += context.trade_n[stocks.index( context.symbol)] order_volume(symbol=context.symbol, volume=context.trade_n[stocks.index( context.symbol)], side=PositionSide_Short, order_type=OrderType_Market, position_effect=PositionEffect_Close) print(context.now, symbol, '市价单平多仓', context.trade_n[stocks.index(context.symbol)], '股') # 临近收盘时若仓位数不等于昨仓则回转所有仓位 if day[11:16] == '14:55' or day[11:16] == '14:57': position = context.account().position(symbol=context.symbol, side=PositionSide_Long) # 这个if应该是有问题的,但没自信深究了,最好不用if先跑,如果跑不动再研究 if (position != None): if position['volume'] != context.total[stocks.index( context.symbol)]: order_target_volume(symbol=context.symbol, volume=context.total[stocks.index( context.symbol)], order_type=OrderType_Market, position_side=PositionSide_Long) print(context.now, context.symbol, '市价单回转仓位操作...') context.ending[stocks.index(context.symbol)] = 1 # 更新过去的日期数据 context.day[stocks.index( context.symbol)][0] = context.day[stocks.index( context.symbol)][-1]
def generateTechnicalDataframe(coin_dataframe): """Param: coin_dataframe: Dataframe type, exact same format as output of getCoinData Returns: dataframe of technical data, with index representing dates and columns representing each technical indicator""" Low_df = coin_dataframe['Low'] High_df = coin_dataframe['High'] Price_df = coin_dataframe['Adj. Close'] LowList = Low_df.values.tolist() HighList = High_df.values.tolist() PriceList = Price_df.values.tolist() DateList = coin_dataframe.index.tolist() #converted to list z = 0 while z < len(LowList): if isinstance(LowList[z], str): LowList[z] = float(LowList[z].replace(',', '')) z = z + 1 y = 0 while y < len(HighList): if isinstance(HighList[y], str): HighList[y] = float(HighList[y].replace(',', '')) y = y + 1 x = 0 while x < len(PriceList): if isinstance(PriceList[x], str): PriceList[x] = float(PriceList[x].replace(',', '')) x = x + 1 #type conversions complete, string --> float Low = np.array(LowList) High = np.array(HighList) Close = np.array(PriceList) #Low, High, and Close converted to Array format (TA-Lib calls require Array) SARtoList = (talib.SAR(High, Low, acceleration = 0.2, maximum = 0.20)) BBandsArray = (talib.BBANDS(Close, timeperiod = 5, nbdevup = 2, nbdevdn = 2, matype = 0)) EMAList = talib.EMA(Close, timeperiod=30) KAMAList = talib.KAMA(Close, timeperiod=30) MAList = talib.MA(Close, timeperiod=30, matype=0) WMAList = talib.WMA(Close, timeperiod=30) TRIMAList = talib.TRIMA(Close, timeperiod=30) TEMAList = talib.TEMA(Close, timeperiod=30) HTList = talib.HT_TRENDLINE(Close) ADXList = talib.ADX(High, Low, Close, timeperiod=14) ADXRList = talib.ADXR(High, Low, Close, timeperiod=14) CMOList = talib.CMO(Close, timeperiod=14) DXList = talib.DX(High, Low, Close, timeperiod=14) MACDArray = talib.MACDFIX(Close, signalperiod=9) MINUS_DI_List = talib.MINUS_DI(High, Low, Close, timeperiod=14) PLUS_DI_List = talib.PLUS_DI(High, Low, Close, timeperiod=14) MOMList = talib.MOM(Close, timeperiod=10) RSIList = talib.RSI(Close, timeperiod=14) NATRList = talib.NATR(High, Low, Close, timeperiod=14) BETAList = talib.BETA(High, Low, timeperiod=5) ROCList = talib.ROC(Close, timeperiod=10) WILLRList = talib.WILLR(High, Low, Close, timeperiod=14) ULTOSCList = talib.ULTOSC(High, Low, Close, timeperiod1=7, timeperiod2=14, timeperiod3=28) #method calls to TA-Lib complete, results stored in SARtoList (list) and BBandsArray (array) toCombine = [] BBandsUpperDF = pd.DataFrame(BBandsArray[0], columns = ['Upper Band',]) toCombine.append(BBandsUpperDF) BBandsMiddleDF = pd.DataFrame(BBandsArray[1], columns = ['Middle Band',]) toCombine.append(BBandsMiddleDF) BBandsLowerDF = pd.DataFrame(BBandsArray[2], columns = ['Lower Band',]) toCombine.append(BBandsLowerDF) MACD_df = pd.DataFrame(MACDArray[0], columns = ['MACD',]) toCombine.append(MACD_df) MACD_Hist_df = pd.DataFrame(MACDArray[1], columns = ['MACD_Hist',]) toCombine.append(MACD_Hist_df) MACD_Sig_df = pd.DataFrame(MACDArray[2], columns = ['MACD_Sig',]) toCombine.append(MACD_Sig_df) DateDF = pd.DataFrame({'Date': DateList,}) toCombine.append(DateDF) SARdf = pd.DataFrame({'SAR': SARtoList,}) toCombine.append(SARdf) EMAdf = pd.DataFrame({'EMA': EMAList,}) toCombine.append(EMAdf) KAMAdf = pd.DataFrame({'KAMA': KAMAList,}) toCombine.append(KAMAdf) MAdf = pd.DataFrame({'MA': MAList,}) toCombine.append(MAdf) WMAdf = pd.DataFrame({'WMA': WMAList,}) toCombine.append(WMAdf) TRIMAdf = pd.DataFrame({'TRIMA': TRIMAList,}) toCombine.append(TRIMAdf) TEMAdf = pd.DataFrame({'TEMA': TEMAList,}) toCombine.append(TEMAdf) HTdf = pd.DataFrame({'HT Trendline': HTList,}) toCombine.append(HTdf) ADXdf = pd.DataFrame({'ADX': ADXList,}) toCombine.append(ADXdf) ADXRdf = pd.DataFrame({'ADXR': ADXRList,}) toCombine.append(ADXdf) CMOdf = pd.DataFrame({'CMO': CMOList,}) toCombine.append(CMOdf) MINUSDI_df = pd.DataFrame({'MINUSDI': MINUS_DI_List,}) toCombine.append(MINUSDI_df) PLUSDI_df = pd.DataFrame({'PLUSDI': PLUS_DI_List,}) toCombine.append(PLUSDI_df) MOMdf = pd.DataFrame({'MOM': MOMList,}) toCombine.append(MOMdf) RSIdf = pd.DataFrame({'RSI': RSIList,}) toCombine.append(RSIdf) NATRdf = pd.DataFrame({'NATR': NATRList,}) toCombine.append(NATRdf) BETAdf = pd.DataFrame({'BETA': BETAList,}) toCombine.append(BETAdf) ROCdf = pd.DataFrame({'ROC': ROCList,}) toCombine.append(ROCdf) WILLRdf = pd.DataFrame({'WILLR': WILLRList,}) toCombine.append(WILLRdf) ULTOSCdf = pd.DataFrame({'ULTOSC': ULTOSCList,}) toCombine.append(ULTOSCdf) #All data converted to DataFrame type TA_df = pd.concat(toCombine, axis = 1,) TA_df = TA_df.set_index('Date') return TA_df
df["index"] = range(len(df)) df["date_time"] = df.index df.index = df["index"] print(alpha) # 计算出资产组合对比指标 dataf = pd.read_csv("/Users/wuyong/alldata/original_data/BITMEX_.bxbt_4h_2018-06-20_2018-12-26.csv") dataf = dataf.head(1126) index_values = list(dataf["close"].values) # print(index_values) df["index"] = np.array(index_values) # print(df["index"]) # df["index"] = dataf["close"] # print(df["index"]) combine_value = pd.Series(np.zeros(len(df)), name="mid_value") for close in ["ethusdt_close", "btcusdt_close", "xrpusdt_close", "eosusdt_close", "trxusdt_close"]: df[close + str(25)] = ta.MA(df[close].values, timeperiod=25, matype=0) combine_value[df[close] > df[close + str(25)]] = combine_value+1 df["strength"] = combine_value # df["index"] = (df[symbols_close]/df[symbols_close].iloc[0]).sum(axis=1) # df["index_ma5"]=ta.MA(df["index"].values,timeperiod=5) # df["index_ma20"]=ta.MA(df["index"].values,timeperiod=20) # print(df[["index_ma5","index_ma20","date_time"]]) # logger = logging.getLogger(str(x)) # logging对象 # fh = logging.FileHandler('/Users/wuyong/alldata/factor_writedb/factor_stra_4h/' + alpha + "_max.log", mode="w") # 文件对象 # sh = logging.StreamHandler() # 输出流对象 # fm = logging.Formatter('%(asctime)s-%(filename)s[line%(lineno)d]-%(levelname)s-%(message)s') # 格式化对象 # fh.setFormatter(fm) # 设置格式 # sh.setFormatter(fm) # 设置格式 # logger.addHandler(fh) # logger添加文件输出流 # logger.addHandler(sh) # logger添加标准输出流(std out)
def handle_data(context): vol = talib.MA(Vol().astype(float), timeperiod=20, matype=0) PlotNumeric("VOL", vol[-1], main=False, color=RGB_Yellow()) LogInfo(Date(), Time(), TradeDate(), Q_UpdateTime(), Vol()[-1], context.dateTimeStamp())
close = data.close volume = data.vol high = data.high low = data.low import talib as ta # 中文文档:https://github.com/HuaRongSAO/talib-document # 中文文档:https://www.bookstack.cn/read/talib-zh/README.md # 英文文档:https://mrjbq7.github.io/ta-lib/ # K线形态识别:参考02.识别K线图的形态 # 移动平均线 # ta.MA(close,timeperiod=30,matype=0) # matype分别对应:0=SMA, 1=EMA, 2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3 (Default=SMA) sma10_talib = ta.MA(close, timeperiod = 10, matype = 0) # 异同移动平均线MACD #macd, macdsignal, macdhist = ta.MACD(close, fastperiod = 12, slowperiod = 26) macdDIFF, macdDEA, macd = ta.MACDEXT(close, fastperiod=12, fastmatype=1, slowperiod=26, slowmatype=1, signalperiod=9, signalmatype=1) macd = macd * 2 # 布林带 upper, middle, lower = ta.BBANDS(close, timeperiod = 20, nbdevup=2, nbdevdn=2, matype = 0) # 相对强弱指数RSI,采用RSI = 100 - 100 / (1 + RS)计算 rsi = ta.RSI(close, timeperiod = 6) # 计算收盘价的动量 m = ta.MOM(close, timeperiod = 5)
def check_low_increase(code_name, data, end_date=None, ma_short=30, ma_long=250, threshold=10): stock = code_name[0] name = code_name[1] if len(data) < ma_long: logging.debug("{0}:样本小于{1}天...\n".format(code_name, ma_long)) return False data['ma_short'] = pd.Series(tl.MA(data['close'].values, ma_short), index=data.index.values) data['ma_long'] = pd.Series(tl.MA(data['close'].values, ma_long), index=data.index.values) if end_date is not None: mask = (data['date_day'] <= end_date) data = data.loc[mask] data = data.tail(n=threshold) inc_days = 0 dec_days = 0 if len(data) < threshold: logging.debug("{0}:样本小于{1}天...\n".format(code_name, threshold)) return False # 区间最低点 lowest_row = data.iloc[-1] # 区间最高点 highest_row = data.iloc[-1] days_count = len(data) total_change = 0.0 for index, row in data.iterrows(): if 'p_change' in row: p_change = float(row['p_change']) if abs(p_change) > 0: total_change += abs(p_change) # if p_change < -7: # return False # if row['ma_short'] < row['ma_long']: # return False if p_change > 0: inc_days = inc_days + 1 if p_change < 0: dec_days = dec_days + 1 if row['close'] > highest_row['close']: highest_row = row if row['close'] < lowest_row['close']: lowest_row = row atr = total_change / days_count if atr > 10: return False ratio = (highest_row['close'] - lowest_row['close']) / lowest_row['close'] if ratio > 1.1: logging.debug( "股票:{0}({1}) 最低:{2}, 最高:{3}, 涨跌比率:{4} 上涨天数:{5}, 下跌天数:{6}". format(name, stock, lowest_row['date_day'], highest_row['date_day'], ratio, inc_days, dec_days)) return True return False
import numpy import talib import sys TEST_LEN = int(sys.argv[1]) if len(sys.argv) > 1 else 10000 data = numpy.random.random(TEST_LEN) import time t0 = time.time() for _ in range(1000): talib.MA(data) talib.BBANDS(data) talib.KAMA(data) t1 = time.time() print '%d' % TEST_LEN print '%.6f' % ((t1 - t0) / 1000.)
out = pd.concat(out) \ .assign(CGO=lambda df: (df.TCLOSE - df.rpt) / df.rpt) ratio = out.query("ENDDATE=='{date1}'".format(date1=max(out.ENDDATE))) ratio = ratio.dropna() ratio_list.append(len(ratio.query("CGO>0")) / len(ratio)) cgo2 = out.groupby('ENDDATE') \ .CGO \ .apply(f) \ .reset_index() res = pd.merge(res, cgo2, on='ENDDATE') res = res.rename(index=str, columns={'CGO': 'CGO_300'}) res = res.assign(macgo_50_20=lambda df: tb.MA(df.CGO_50.values, 15)) \ .assign(macgo_50_10=lambda df: tb.MA(df.CGO_50.values, 5)) \ .assign(macgo_500_20=lambda df: tb.MA(df.CGO_500.values, 15)) \ .assign(macgo_500_10=lambda df: tb.MA(df.CGO_500.values, 5)) \ .assign(macgo_300_10=lambda df: tb.MA(df.CGO_300.values, 5)) \ .assign(macgo_300_20=lambda df: tb.MA(df.CGO_300.values, 15)) # ============================================================================= # 邮件发送 # ============================================================================= # print('完成计算') # 整理数据 res.dropna(inplace=True) res = res.assign(sign2=[sign2(row) for idx, row in res.iterrows()]) row_ = res.query("ENDDATE=='{date1}'".format(date1=max(out.ENDDATE))) position = positon(row_) position_last = list()
def onLongCycle(self, bar): #print 'cycletime:', bar.datetime #print bar.datetime self.longCycleCloseArray[0:self.longCycleBufferSize - 1] = self.longCycleCloseArray[ 1:self.longCycleBufferSize] self.longCycleHighArray[0:self.longCycleBufferSize - 1] = self.longCycleHighArray[ 1:self.longCycleBufferSize] self.longCycleLowArray[0:self.longCycleBufferSize - 1] = self.longCycleLowArray[1:self. longCycleBufferSize] self.longCycleVolumeArray[0:self.longCycleBufferSize - 1] = self.longCycleVolumeArray[ 1:self.longCycleBufferSize] self.longCycleCloseArray[-1] = bar.close self.longCycleHighArray[-1] = bar.high self.longCycleLowArray[-1] = bar.low self.longCycleVolumeArray[-1] = bar.volume self.longCycleBufferCount += 1 if self.longCycleBufferCount < self.longCycleBufferSize: return self.longCycleMAlong = talib.MA(self.longCycleCloseArray, self.longMAperiod) self.longCycleMAshort = talib.MA(self.longCycleCloseArray, self.shortMAperiod) maLongCondition = self.longCycleMAshort[-1] > self.longCycleMAlong[-1] slowk, slowd = talib.STOCH(self.longCycleHighArray, self.longCycleLowArray, self.longCycleCloseArray, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) fastk, fastd = talib.STOCHF(self.longCycleHighArray, self.longCycleLowArray, self.longCycleCloseArray, fastk_period=5, fastd_period=3, fastd_matype=0) kdjLongCondition = slowk[-1] > slowd[-1] kdjShortCondition = slowk[-1] < slowd[-1] ta_adx = talib.ADX(self.longCycleHighArray, self.longCycleLowArray, self.longCycleCloseArray, 14) ta_ndi = talib.MINUS_DI(self.longCycleHighArray, self.longCycleLowArray, self.longCycleCloseArray, 14) ta_pdi = talib.PLUS_DI(self.longCycleHighArray, self.longCycleLowArray, self.longCycleCloseArray, 14) taLongCondition = ta_adx[-1] > 25 diLongCondition = ta_pdi[-1] > ta_ndi[-1] diShortCondition = ta_pdi[-1] < ta_ndi[-1] #maLongCondition = (self.longCycleMAshort[-2:] > self.longCycleMAlong[-2:]).all() #maShortCondition = (self.longCycleMAshort[-2:] < self.longCycleMAlong[-2:]).all() #self.MACD = talib.MACD(self.longCycleCloseArray,fastperiod=self.shortMAperiod,slowperiod=self.longMAperiod,signalperiod=9) #print self.MACD[-1] #MACDLongCondition = self.MACD[0][-1] > self.MACD[-1][-1] if maLongCondition: self.longCycleTradingFlag = 1 elif not maLongCondition: self.longCycleTradingFlag = -1
# self.cash = self.cash - float(amount * price) print('allowSell_symbol:', self.allowSell_symbol) for i in self.allowSell_symbol: self.used_cash -= float(self.allowSell_symbol[i]['price']) cash = float(self.allowSell_symbol[i]['amount']) * float( self.allowSell_symbol[i]['price']) * (1 - self.close_fee) print('扣除平仓手续后,退还金额:{}'.format(cash)) # 利润计算 profit = (float(price) - float(self.allowSell_symbol[i]['price']) ) * float(self.allowSell_symbol[i]['amount']) print('获得利润为{}'.format(profit)) self.balance += profit self.free_cash = self.balance - self.used_cash del self.allowSell_symbol[i] print('退还后的总余额:{}'.format(self.balance)) # self.every_balance.append(self.balance) # 不下单子时处理 余额 def every_handle_Balance(self, date_time): # self.every_balance.append(self.balance) pass if __name__ == '__main__': Account().get_history('a', 'a', 'a', 'a') l_data = [1.0, 2.0, 3.0, 4.0, 5.0] a = talib.MA(np.array(l_data), timeperiod=5) Account().handle_data()
def ma(close): ma5 = talib.MA(close, timeperiod=5) ma10 = talib.MA(close, timeperiod=10) ma20 = talib.MA(close, timeperiod=20) ma60 = talib.MA(close, timeperiod=60) return ma5, ma10, ma20, ma60
# Created by ZS @ Ricequant 07/06/2017 # Purpose: Create an optimization class import talib close = np.array([1.1,2.1,3.1,4,5,6,7]) SMA = talib.MA(close,3,matype=0)[-1] SMA # plot('SMA',SMA) # import modules import rqdatac from rqdatac import * rqdatac.init("ricequant", "8ricequant8") import datetime as dt import itertools import matplotlib.pyplot as plt import numpy as np import scipy.optimize as sc_opt from math import * import pandas as pd import scipy.spatial as scsp
def strategy_ma(code=CODE, interval=5): """计算均线策略""" # close = get_bars(code, interval) stock = stbase.TradeManager().getStock(code) bars = stock.get_hist_bars('m{}'.format(interval), limit=30) close = map(lambda _: _.Close, bars) close = np.array(close) stbase.print_line('size:%s' % len(close)) # if not close: # print 'error: close is null.' print close.tolist() stbase.print_line(close.tolist()) print 'to ma calculating...' ma5 = ta.MA(close, 5) ma10 = ta.MA(close, 10) a, b = ma5[-2:] c, d = ma10[-2:] strategy_name = 'strategy_ma' # print 'ma5:',ma5 # print 'ma10:',ma10 stbase.print_line('=={}=={}=='.format(code, interval)) stbase.print_line('(strategy_ma) ma5:{}'.format(ma5.tolist()), stdout=False) stbase.print_line('(strategy_ma) ma10:{}'.format(ma10.tolist()), stdout=False) stbase.print_line('(strategy_ma)a:{} b:{} c:{} d:{}'.format(a, b, c, d), stdout=False) last_price = stbase.TradeManager().getStock(code).last_price if b >= d and a < c: num = 100 # stbase.print_line('-*'*20,stdout=False) # stbase.print_line('strategy_ma signal occur. (b >= d and a< c)',stdout=False) # stbase.print_line('a:{} b:{} c:{} d:{}'.format(a,b,c,d),stdout=False) stbase.record_signal(code, '-*' * 20) stbase.record_signal(code, '=={}=={}=='.format(code, interval)) stbase.record_signal(code, 'strategy_ma signal occur. (b >= d and a< c)') stbase.record_signal(code, 'a:{} b:{} c:{} d:{}'.format(a, b, c, d)) amount = stbase.TradeManager().xy_proxy.get_stock_amount_useable() cost = last_price * num if cost <= amount * 0.1: stbase.record_signal( code, 'do buy: {} , {} , {}'.format(code, last_price, num)) stbase.TradeManager().xy_proxy.buy(code, last_price, num) if b <= d and a > c: num = 100 # stbase.print_line('-*' * 20, stdout=False) # stbase.print_line('strategy_ma signal occur. (b <=d and a > c)',stdout=False) # stbase.print_line('a:{} b:{} c:{} d:{}'.format(a, b, c, d),stdout=False) stbase.record_signal(code, '-*' * 20) stbase.record_signal(code, '=={}=={}=='.format(code, interval)) stbase.record_signal(code, 'strategy_ma signal occur. (b <=d and a > c)') stbase.record_signal(code, 'a:{} b:{} c:{} d:{}'.format(a, b, c, d)) if num <= stbase.TradeManager().getStock(code).pos.net_yd: stbase.record_signal( code, 'do sell: {} ,{}, {}'.format(code, last_price, num)) stbase.TradeManager().xy_proxy.sell(code, last_price, num)
# Double Exponential Moving Average period = 30 df['DEMA'] = talib.DEMA(df["Close"], timeperiod=period) # Exponential Moving Average period = 30 df['EMA'] = talib.EMA(df["Close"], timeperiod=period) # HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline df['HT_TRENDLINE'] = talib.HT_TRENDLINE(df["Close"]) # KAMA - Kaufman Adaptive Moving Average period = 30 df['KAMA'] = talib.KAMA(df["Close"], timeperiod=period) # MA - Moving average period = 30 print('Time #5 batch TI: ' + str(time.time() - start_time) + ' seconds') start_time = time.time() df['MA'] = talib.MA(df["Close"], timeperiod=period, matype=0) # MIDPOINT - MidPoint over period period = 14 df['MIDPOINT'] = talib.MIDPOINT(df["Close"], timeperiod=period) # MIDPRICE - Midpoint Price over period period = 14 df['MIDPOINT'] = talib.MIDPRICE(df["High"], df["Low"], timeperiod=period) # SAR - Parabolic SAR df['SAR'] = talib.SAR(df["High"], df["Low"], acceleration=0, maximum=0) # SAREXT - Parabolic SAR - Extended df['SAREXT'] = talib.SAREXT(df["High"], df["Low"], startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0,
def func_example(): odata = talib.MA(idata) upper, middle, lower = talib.BBANDS(idata) kama = talib.KAMA(idata) plot(odata, upper, middle, lower, kama)
#print DATA.ix[:20].to_string() #DATA.plot(subplots=True) DATA = pandas.DataFrame({'AAPL': AAPL['bid'], 'GOOG': GOOG['bid']}) # Compute OHLC data with pandas from raw tick data DATA_15MIN = pandas.Panel({ 'AAPL': DATA.AAPL.resample('15min', how='ohlc', fill_method='backfill'), 'GOOG': DATA.GOOG.resample('15min', how='ohlc', fill_method='backfill') }) # Technical Analysis for n in DATA_15MIN: DATA_15MIN[n]['SMA'] = talib.MA(DATA_15MIN[n].close, 50) DATA_15MIN[n]['FMA'] = talib.MA(DATA_15MIN[n].close, 20) # Plot fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) ax1.set_ylabel('AAPL', size=20) ax2.set_ylabel('GOOG', size=20) DATA_15MIN.AAPL.close.plot(ax=ax1, lw=2) DATA_15MIN.AAPL.SMA.plot(ax=ax1, c='g') DATA_15MIN.AAPL.FMA.plot(ax=ax1, c='r') DATA_15MIN.GOOG.close.plot(ax=ax2, lw=2) DATA_15MIN.GOOG.SMA.plot(ax=ax2, c='g') DATA_15MIN.GOOG.FMA.plot(ax=ax2, c='r') plt.plot()
def cal_ma_ta_vol(df, n): temp_serise = talib.MA(df['vol'], timeperiod=n) temp_serise.dropna(inplace=True) ma_serise = temp_serise.reset_index(drop=True) return ma_serise
def plot_ma(ax, data): """This function plots ############ MA - Moving average - Overlap Studies Functions ################### A Moving Average is an indicator that shows the average value of a security's price over a period of time. When calculating a moving average, a mathematical analysis of the security's average value over a predetermined time period is made. As the security's price changes, its average price moves up or down. Identifying trends is one of the key functions of moving averages, which are used by most traders who seek to "make the trend their friend". Moving averages are lagging indicators, which means that they do not predict new trends, but confirm trends once they have been established. The moving average (MA) is a simple technical analysis tool that smooths out price data by creating a constantly updated average price. The average is taken over a specific period of time, like 10 days, 20 minutes, 30 weeks or any time period the trader chooses. There are advantages to using a moving average in your trading, as well as options on what type of moving average to use. Moving average strategies are also popular and can be tailored to any time frame, suiting both long-term investors and short-term traders. A moving average helps cut down the amount of "noise" on a price chart. Look at the direction of the moving average to get a basic idea of which way the price is moving. If it is angled up, the price is moving up (or was recently) overall; angled down, and the price is moving down overall; moving sideways, and the price is likely in a range. As a general guideline, if the price is above a moving average, the trend is up. If the price is below a moving average, the trend is down. However, moving averages can have different lengths (discussed shortly), so one MA may indicate an uptrend while another MA indicates a downtrend. An MA with a short time frame will react much quicker to price changes than an MA with a long look back period. Crossovers are one of the main moving average strategies. The first type is a price crossover, which is when the price crosses above or below a moving average to signal a potential change in trend. Another strategy is to apply two moving averages to a chart: one longer and one shorter. When the shorter-term MA crosses above the longer-term MA, it's a buy signal, as it indicates that the trend is shifting up. This is known as a "golden cross.""" ma_indicator30 = talib.MA(data['Adj_Close'], timeperiod=30, matype=0) ma_indicator200 = talib.MA(data['Adj_Close'], timeperiod=200, matype=0) ax.plot(data["Date"], ma_indicator30, label="Moving Average 30 days period", color="lime") ax.plot(data["Date"], ma_indicator200, label="Moving Average 200 days period", color="orchid") ax.fill_between(data["Date"], ma_indicator30, ma_indicator200, where=(ma_indicator30 <= ma_indicator200), facecolor='r', edgecolor='r', alpha=0.2) ax.fill_between(data["Date"], ma_indicator30, ma_indicator200, where=(ma_indicator30 >= ma_indicator200), facecolor='gold', edgecolor='gold', alpha=0.2)
start = datetime(2010, 1, 1) end = datetime(2019, 12, 31) stock_list = ["TWII", "GSPC", "HSI", "N225", "DJI"] dir_path = 'D:/Time_Series_Research/new_data/新增資料夾/' for name in stock_list: data = web.DataReader("^" + name, 'yahoo', start, end) data.reset_index(inplace=True) data.dropna(axis=0, how='any', inplace=True) data = data.reset_index(drop=True) close = data['Close'] day = len(close) # Moving average data['MA_5'] = ta.MA(close, 5) data["MA_20"] = ta.MA(close, 20) # Bollinger Bands (Ma20) data["BBands_up"], middleband, data["BBands_down"] = ta.BBANDS(close, 20, 2, 2, matype=0) # Relative Strength Index def getRSI(Close, period=6): # 整理資料 import pandas as pd Chg = Close - Close.shift(1) Chg_pos = pd.Series(index=Chg.index, data=Chg[Chg > 0])
def OnTick(): df = rmt_srv.get_kline_pd() ''' orders = pd.DataFrame(rmt_srv.get_open_orders()) print('open orders: \n',orders) trades = pd.DataFrame(rmt_srv.get_my_trades()) print(' trades: \n',trades) ''' ''' account = rmt_srv.get_account() account = pd.DataFrame(account) account['free'] = account['free'].apply(pd.to_numeric) account['locked'] = account['locked'].apply(pd.to_numeric) print(account[account['free']>0]) print(account[account['locked']>0]) ''' balance_base = rmt_srv.balance(arg_dict['base_coin']) logging.info('base coin: %s; balance: %s', arg_dict['base_coin'], balance_base) balance_target = rmt_srv.balance(arg_dict['target_coin']) logging.info('target coin: %s; balance: %s', arg_dict['target_coin'], balance_target) close = [float(x) for x in df['close']] # 调用talib计算10日移动平均线的值 df['MA10_talib'] = talib.MA(np.array(close), timeperiod=10) # 调用talib计算MACD指标 df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(np.array(close), fastperiod=12, slowperiod=26, signalperiod=9) # df['close'] = pd.Series(close) #print(df['close']) df['open'] = pd.Series([float(x) for x in df['open']]) df['high'] = pd.Series([float(x) for x in df['high']]) df['low'] = pd.Series([float(x) for x in df['low']]) # 指标计算 #MACD(df) ''' high = [float(x) for x in df['high']] low = [float(x) for x in df['low']] df['KDJ_K'],df['KDJ_D']=talib.STOCH(np.array(high),np.array(low),np.array(close), fastk_period=9,slowk_period=3,slowk_matype=0,slowd_period=3,slowd_matype=0) ''' indicator.KDJ(df) ''' df['open_time'] = [(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x/1000))) for x in df['open_time']] df['close_time'] = [(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x/1000))) for x in df['close_time']] del df['quote_asset_volume'] del df['number_of_trades'] del df['taker_buy_base_asset_volume'] del df['taker_buy_quote_asset_volume'] del df['ignore'] print(df) ''' kdj_k_cur = df['kdj_k'].values[-1] kdj_d_cur = df['kdj_d'].values[-1] kdj_j_cur = df['kdj_j'].values[-1] cur_price = close[-1] logging.info('current price: %f; kdj_k: %f; kdj_d: %f; kdj: %f', cur_price, kdj_k_cur, kdj_d_cur, kdj_j_cur) target_free_count = float(balance_target['free']) target_frozen_count = float(balance_target['frozen']) if kdj_j_cur > kdj_k_cur + 1: if kdj_k_cur > kdj_d_cur + 1: # j>k>d 买入信号 logging.info('j>k>d') if target_free_count > 0: # 持仓 pass else: # 空仓 cost_base_amount = min(float(balance_base['free']), base_coin_limit) logging.info('cost_base_amount: %f', cost_base_amount) if cost_base_amount > 0: # buy_target_amount = reserve_float( cost_base_amount / cur_price, int(args.a)) logging.info('buy target coin amount: %f', buy_target_amount) limit_buy_price = reserve_float(cur_price * 1.1, int(args.p)) order_id = rmt_srv.buy(limit_buy_price, buy_target_amount) logging.info( 'current price: %f; limit buy price: %f; order_id: %f ', cur_price, limit_buy_price, order_id) # send_report(orders, accounts, args.r, subject='Coin Trade - %s' % pair) else: pass else: # j>k<d pass elif kdj_j_cur < kdj_k_cur - 1: if kdj_k_cur < kdj_d_cur - 1: # j<k<d 卖出信号 logging.info('j<k<d') if target_frozen_count > 0: # 有挂单 logging.info('target_frozen_count: %f', target_frozen_count) else: # 无挂单 if target_free_count > 0: # 持仓 logging.info('sell target coin num: %f', target_free_count) limit_sell_price = reserve_float(cur_price * 0.9, int(args.p)) sell_target_amount = reserve_float(target_free_count, int(args.a)) order_id = rmt_srv.sell(limit_sell_price, sell_target_amount) logging.info( 'current price: %f; limit sell price: %f; order_id: %f', cur_price, limit_sell_price, order_id) else: # 空仓 pass else: # j<k>d pass