def handle_data(context, data): portfolio = context.portfolio for ticker, position in portfolio.positions.items(): if not data.can_trade(ticker): continue ma_fast = abstract.MA(data.history(ticker, 'D', length=fast + 1), timeperiod=fast, price='close').dropna() ma_slow = abstract.MA(data.history(ticker, 'D', length=slow + 1), timeperiod=slow, price='close').dropna() if ma_slow[0] < ma_fast[0] and ma_slow[1] > ma_fast[1]: portfolio.send_order(ticker, -position['quantity']) for ticker in context.tickers: if not data.can_trade(ticker): continue ma_fast = abstract.MA(data.history(ticker, 'D', length=fast + 1), timeperiod=fast, price='close').dropna() ma_slow = abstract.MA(data.history(ticker, 'D', length=slow + 1), timeperiod=slow, price='close').dropna() if ma_slow[0] > ma_fast[0] and ma_slow[1] < ma_fast[1]: portfolio.send_order(ticker, 1000)
def handle_data(context, data): portfolio = context.portfolio for ticker in portfolio.positions.keys(): ticker = sid(ticker).symbol if not data.can_trade(ticker): continue ma_fast = abstract.MA(data.history(ticker, 'D', length=fast + 1), timeperiod=fast, price='close').dropna() ma_slow = abstract.MA(data.history(ticker, 'D', length=slow + 1), timeperiod=slow, price='close').dropna() if ma_slow[0] < ma_fast[0] and ma_slow[1] > ma_fast[1]: order(ticker, -1000) for ticker in context.tickers: ticker = symbol(ticker).symbol if not data.can_trade(ticker): continue ma_fast = abstract.MA(data.history(ticker, 'D', length=fast + 1), timeperiod=fast, price='close').dropna() ma_slow = abstract.MA(data.history(ticker, 'D', length=slow + 1), timeperiod=slow, price='close').dropna() if ma_slow[0] > ma_fast[0] and ma_slow[1] < ma_fast[1]: order(ticker, 1000)
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: macd = ta.MACD(dataframe) dataframe['maShort'] = ta.MA(dataframe, timeperiod=50) dataframe['maMedium'] = ta.MA(dataframe, timeperiod=200) return dataframe
def execute(self, pool, context, data): out = [] for code in pool: candle = data.history(code, frequency=self.frequency, length=self.slow + 1) try: fast = abstract.MA(candle, timeperiod=self.fast) slow = abstract.MA(candle, timeperiod=self.slow) if fast[-1] > slow[-1] and (fast[-2] < slow[-2]): out.append(code) except Exception as e: print e print candle print 'MA', out return out
def updateMA(Client, symbol, mas, interval, ma_type): if ma_type == MA_Type.SMA: folder = "ma" elif ma_type == MA_Type.WMA: folder = "wma" else: raise UnknownMATypeException() #check files and directories filename = f"{Client.MAIN_PATH}/data/candles/{interval}" filename2 = f"{Client.MAIN_PATH}/data/{folder}/{interval}" if not os.path.exists(filename): os.makedirs(filename) if not os.path.exists(filename2): os.makedirs(filename2) fn = f"{filename}/{symbol}.feather" fn2 = f"{filename2}/{symbol}.feather" if os.path.isfile(fn): df_cdl = feather.read_feather(fn) if not df_cdl["OpenTime"].empty: if os.path.isfile(fn2): df_ma = feather.read_feather(fn2) else: df_ma = pd.DataFrame(columns=["OpenTime","ClosePrice"]) feather.write_feather(df_ma, fn2) length_old = len(df_ma.index) if not df_ma.empty: if length_old >= mas[-1]: ma_lastDate = df_ma["OpenTime"].iloc[-(mas[-1] - 1)] length_old = mas[-1] - 1 else: ma_lastDate = df_ma["OpenTime"].iloc[0] else: ma_lastDate = 0 df_add = df_cdl.loc[df_cdl["OpenTime"] >= ma_lastDate, ["OpenTime", "ClosePrice"]] if not df_add.empty: for num in mas: name = f"MA{num}" df_add[name] = abstract.MA(df_add["ClosePrice"], timeperiod=num, matype=ma_type) df_add = df_add[length_old:] df_ma = df_ma.append(df_add, ignore_index=True) feather.write_feather(df_ma, fn2) else: print("Nothing to do") else: print("file is empty")
def signal(data): data['RSI'] = abstract.RSI(data.close,2) data['MA'] = abstract.MA(data.close, timeperiod=7, matype=0) #RVI #Nem = data.close-data.open + 2*(data.iloc[-1:,:].close - data.iloc[-1:,:].open) + 2*(data.iloc[-2:,:].close - data.iloc[-1:,:].open) + data.iloc[-3:,:].close - data.iloc[-3:,:].open Nem =(data.close-data.open)+2*(data.close.shift(1) - data.open.shift(1))+2*(data.close.shift(2) - data.open.shift(2))+(data.close.shift(3) - data.open.shift(3)) Dem =data.high-data.low+2*(data.high.shift(1) - data.low.shift(1)) +2*(data.high.shift(2) - data.low.shift(2)) +(data.high.shift(3) - data.low.shift(3)) #Dem = data.high-data.low + 2*(data.iloc[-1:,:].high - data.iloc[-1:,:].low) + 2*(data.iloc[-2:,:].high - data.iloc[-1:,:].low) + data.iloc[-3:,:].high - data.iloc[-3:,:].low data['RVI'] = RVI = (Nem/6)/(Dem/6) data['RVIR'] = (RVI + 2*RVI.shift(1) + 2*RVI.shift(2) + RVI.shift(3))/6 if data.iloc[-1:,:].RSI <=RSILo | data.iloc[-2:-1,:].RSI <=RSILo | data.iloc[-3:-2,:].RSI <=RSILo: if data.iloc[-1:,:].RVI >= data.iloc[-1:,:].RVIR & data.iloc[-2:-1,:].RVI <= data.iloc[-2:-1,:].RVIR: now = datetime.now() if (now > today930 and now < today11) or (now > today13 and now < today15): ret_code, info_data = trd_ctx.accinfo_query() #get ac info if info_data.cash > data.close[-1]*size: print('place order') buy() if size != 0: if data.iloc[-1:,:].RSI >=RSIHi | data.iloc[-2:-1,:].RSI <=RSIHi | data.iloc[-3:-1,:].RSI <=RSIHi: if data.iloc[-1:,:].RVI <= data.iloc[-1:,:].RVIR: if data.iloc[-1:,:].MA <= price: print('sell') sell()
def MA(ohlcv, kw): """ :return Moving Average (ma) """ params = {'timeperiod': 30, 'matype': 0} timeperiod, matype = _get_params(kw, params, ['timeperiod', 'matype']) result = talib.MA(ohlcv, timeperiod, matype) return { 'ma': result }
def KELCH(self, df, length, mult): ma = tb.MA(df, timeperiod=length) range = tb.TRANGE(df) rangema = talib.MA(np.array(range), timeperiod=length) upperKC = ma + rangema * mult lowerKC = ma - rangema * mult return upperKC[len(upperKC) - 1], lowerKC[len(lowerKC) - 1], upperKC[len(upperKC) - 2], lowerKC[ len(lowerKC) - 2]
def ma_200(self): ma_200 = abstract.MA(self.df, 200) self.df["ma_200"] = 0 for i in range(199, len(self.df)): try: ma = ma_200[i] close = self.df.iloc[i]['close'] #If Close pirce is higher tha MA200 if ma < close: self.df['ma_200'][i] = 1 except: pass return self.df
def _get_statistics(n=1, start_time=None, end_time=None): ohlc = _get_ohlc(3, start_time, end_time) # TODO: maybe handle nan differently limit = n * -1 stoch = np.nan_to_num(abstract.STOCH(ohlc)) macd = np.nan_to_num(abstract.MACD(ohlc)) output = dict( macd=macd[0][limit:].tolist(), macd_signal=macd[1][limit:].tolist(), macd_hist=macd[2][limit:].tolist(), stoch_slowk=stoch[0][limit:].tolist(), stoch_slowd=stoch[1][limit:].tolist(), vave=np.nan_to_num(abstract.MA(ohlc)[limit:]).tolist(), sma=np.nan_to_num(abstract.SMA(ohlc)[limit:]).tolist(), rsi=np.nan_to_num(abstract.RSI(ohlc)[limit:]).tolist(), stddev=np.nan_to_num(abstract.STDDEV(ohlc)[limit:]).tolist()) return output
print('data ok') else: print('error:', data) continue #get snap data ret, snapdata = quote_ctx.get_market_snapshot(['HK.' + code]) if ret == RET_OK: print('snap ok') else: print('error:', data) continue #check lot size and price per lot #print('lot_size') #print(snapdata.iloc[0].lot_size * snapdata.iloc[0].last_price) if snapdata.iloc[0].lot_size * snapdata.iloc[0].last_price > 10000: continue #calculate bias if len(data) == 0: continue MA = abstract.MA(data.close, timeperiod=12, matype=0) print('MA:' + str(MA)) bias = (data.iloc[-1].close - MA[len(MA)-1])/(MA[len(MA)-1]) if bias < 0: df = df.append({'Stock number':code}, ignore_index=True) sleep(15) quote_ctx.close() #close connection df.to_csv('filter.csv', encoding='utf-8', index=False)
def signal(data): global NumPos,openprice,indicator trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) #make connection data['RSI'] = abstract.RSI(data.close,RSIP) data['MA'] = abstract.MA(data.close, timeperiod=7, matype=0) #RVI #Nem = data.close-data.open + 2*(data.iloc[-1:,:].close - data.iloc[-1:,:].open) + 2*(data.iloc[-2:,:].close - data.iloc[-1:,:].open) + data.iloc[-3:,:].close - data.iloc[-3:,:].open data['Nem'] =((data.close-data.open)+2*(data.close.shift(1) - data.open.shift(1))+2*(data.close.shift(2) - data.open.shift(2))+(data.close.shift(3) - data.open.shift(3)))/6 data['Dem'] =((data.high-data.low)+2*(data.high.shift(1) - data.low.shift(1)) +2*(data.high.shift(2) - data.low.shift(2)) +(data.high.shift(3) - data.low.shift(3)))/6 #Dem = data.high-data.low + 2*(data.iloc[-1:,:].high - data.iloc[-1:,:].low) + 2*(data.iloc[-2:,:].high - data.iloc[-1:,:].low) + data.iloc[-3:,:].high - data.iloc[-3:,:].low for j in range(1,RVIper+3): #calculate RVI value maNEM = 0 maDEM = 0 for i in range (j,RVIper+j): maNEM = maNEM + data.iloc[-i].Nem maDEM = maDEM + data.iloc[-i].Dem #data.iloc[-j].at['RVI'] = (maNEM/RVIper)/(maDEM/RVIper) data.at[30-j,'RVI'] = (maNEM/RVIper)/(maDEM/RVIper) data.at[29,'RVIR'] = (data.iloc[-1].RVI + 2*data.iloc[-2].RVI + 2*data.iloc[-3].RVI + data.iloc[-4].RVI)/6 print(data.iloc[-3:]) #data['RVI'] = (maNEM/RVIper)/(maDEM/RVIper) #data.iloc[-1].RVI = (maNEM/RVIper)/(maDEM/RVIper) #new_row = {'RVI':'', 'RVIR':''} #indicator = indicator.append(new_row,ignore_index=True) #indicator.at[len(indicator)-1,'RVI'] = (maNEM/RVIper)/(maDEM/RVIper) #data['RVIR'] = (RVI + 2*RVI.shift(1) + 2*RVI.shift(2) + RVI.shift(3))/6 #data.iloc[-1].RVIR = (data.iloc[-1].RVI + 2*data.iloc[-2].RVI + 2*data.iloc[-3].RVI + data.iloc[-4].RVI)/6 #data.at[-1,'RVIR'] = (data.iloc[-1].RVI + 2*data.iloc[-2].RVI + 2*data.iloc[-3].RVI + data.iloc[-4].RVI)/6 #indicator.at[len(indicator)-1,'RVIR'] = (data.iloc[-1].RVI + 2*data.iloc[-2].RVI + 2*data.iloc[-3].RVI + data.iloc[-4].RVI)/6 #print(indicator) if (data.iloc[-1].RSI <=RSILo) | (data.iloc[-2].RSI <=RSILo) | (data.iloc[-3].RSI <=RSILo): print('RSI match') if (data.iloc[-1].RVI > data.iloc[-1].RVIR) & (data.iloc[-2].RVI < data.iloc[-2].RVIR): print('RVI match') print('-----buy signal-----') print(size) notify("AutoTrade.py", "!!!!!!!Buy Signal!!!!!!!") now = datetime.now() print(now) print(data.iloc[-4].time_key) time_object = datetime.strptime(data.iloc[-4].time_key, '%Y-%m-%d %H:%M:%S') print(time_object) if (time_object >= today930): if (now > today930 and now < today11) or (now > today13 and now < today15): ret_code, info_data = trd_ctx.accinfo_query(trd_env = TrdEnv.SIMULATE) #get ac info if ret_code == RET_OK: print('info data ok') else: while ret_code != RET_OK: ret_code, info_data = trd_ctx.accinfo_query(trd_env = TrdEnv.SIMULATE) if info_data.iloc[-1].cash > ((data.iloc[-1].close)*(size)): print('place order') buy(data.iloc[-1].close) #buy stock if NumPos > 0: print('RSI:') print(data.iloc[-1].RSI) print(data.iloc[-2].RSI) print(data.iloc[-3].RSI) print('RVI') print(data.iloc[-1].RVI - data.iloc[-1].RVIR) print('MA') print(data.iloc[-1].MA) print('close') print(data.iloc[-1].close) if (data.iloc[-1].RSI >=RSIHi) | (data.iloc[-2].RSI >=RSIHi) | (data.iloc[-3].RSI >=RSIHi): if (data.iloc[-1].RVI <= data.iloc[-1].RVIR): if data.iloc[-1].close <= data.iloc[-1].MA: notify("AutoTrade.py", "!!!!!!!SELL SELL SELL!!!!!!!") print('~~~sell~~~') #sell stock sell(data.iloc[-1].close) if data.iloc[-1].close >= openprice*1.1: #sell if profit >10% sell(data.iloc[-1].close) trd_ctx.close()
def set_ma(frame): close = pd.DataFrame(frame['close'].dropna(), dtype=numpy.float64) frame['ma'] = abstract.MA(close, timeperiod=50) return frame
def signal(data): global NumPos trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) #make connection data['RSI'] = abstract.RSI(data.close, 2) data['MA'] = abstract.MA(data.close, timeperiod=7, matype=0) #RVI data['Nem'] = ((data.close - data.open) + 2 * (data.close.shift(1) - data.open.shift(1)) + 2 * (data.close.shift(2) - data.open.shift(2)) + (data.close.shift(3) - data.open.shift(3))) / 6 data['Dem'] = (data.high - data.low + 2 * (data.high.shift(1) - data.low.shift(1)) + 2 * (data.high.shift(2) - data.low.shift(2)) + (data.high.shift(3) - data.low.shift(3))) / 6 maNEM = 0 maDEM = 0 for i in range(1, RVIper): maNEM = maNEM + data.iloc[-i].Nem maDEM = maDEM + data.iloc[-i].Dem data['RVI'] = RVI = (maNEM / RVIper) / (maDEM / RVIper) data['RVIR'] = (data.iloc[-1].RVI + 2 * data.iloc[-2].RVI + 2 * data.iloc[-3].RVI + data.iloc[-4].RVI) / 6 if (data.iloc[-1].RSI <= RSILo) | (data.iloc[-2].RSI <= RSILo) | (data.iloc[-3].RSI <= RSILo): print('RSI match') if (data.iloc[-1].RVI > data.iloc[-1].RVIR) & (data.iloc[-2].RVI < data.iloc[-2].RVIR): print('RVI match') print('-----buy signal-----') print(size) notify("AutoTrade.py", "!!!!!!!Buy Signal!!!!!!!") now = datetime.now() print(now) print(data.iloc[-4].time_key) time_object = datetime.strptime(data.iloc[-4].time_key, '%Y-%m-%d %H:%M:%S') print(time_object) if (time_object >= today930): if (now > today930 and now < today11) or (now > today13 and now < today15): ret_code, info_data = trd_ctx.accinfo_query( trd_env=TrdEnv.REAL) #get ac info if ret_code == RET_OK: print('info data ok') else: while ret_code != RET_OK: ret_code, info_data = trd_ctx.accinfo_query( trd_env=TrdEnv.REAL) if info_data.iloc[-1].cash > ((data.iloc[-1].close) * (size)): print('place order') buy(data.iloc[-1].close) #buy stock if NumPos > 0: print('RSI:') print(data.iloc[-1].RSI) print(data.iloc[-2].RSI) print(data.iloc[-3].RSI) print('RVI') print(data.iloc[-1].RVI) print(data.iloc[-1].RVIR) print(data.iloc[-1].RVI - data.iloc[-1].RVIR) print('MA') print(data.iloc[-1].MA) print('close') print(data.iloc[-1].close) if (data.iloc[-1].RSI >= RSIHi) | (data.iloc[-2].RSI >= RSIHi) | ( data.iloc[-3].RSI >= RSIHi): if (data.iloc[-1].RVI <= data.iloc[-1].RVIR): if data.iloc[-1].close <= data.iloc[-1].MA: notify("AutoTrade.py", "!!!!!!!SELL SELL SELL!!!!!!!") print('~~~sell~~~') #sell stock sell(data.iloc[-1].close) if data.iloc[-1].close >= openprice * 1.1: #sell if profit >10% sell(data.iloc[-1].close) trd_ctx.close()
def MA(data, period, interest, ma_type): ret = abstract.MA(data, timeperiod=period, price=interest, matype=ma_type) return ret
def signal(data): global NumPos, openprice, indicator trd_ctx = OpenHKTradeContext(host='127.0.0.1', port=11111) #make connection data['RSI'] = abstract.RSI(data.close, RSIP) data['MA'] = abstract.MA(data.close, timeperiod=7, matype=0) #RVI Original data['Nem_Ori'] = ((data.close - data.open) + 2 * (data.close.shift(1) - data.open.shift(1)) + 2 * (data.close.shift(2) - data.open.shift(2)) + (data.close.shift(3) - data.open.shift(3))) / 6 data['Dem_Ori'] = ((data.high - data.low) + 2 * (data.high.shift(1) - data.low.shift(1)) + 2 * (data.close.shift(2) - data.open.shift(2)) + (data.close.shift(3) - data.open.shift(3))) / 6 data['RVI_Ori'] = data.Nem_Ori / data.Dem_Ori data['RVIR_Ori'] = (data.RVI_Ori + 2 * data.shift(1).RVI_Ori + 2 * data.shift(2).RVI_Ori + data.shift(3).RVI_Ori) / 6 #RVI data['Nem'] = ((data.close - data.open) + 2 * (data.close.shift(1) - data.open.shift(1)) + 2 * (data.close.shift(2) - data.open.shift(2)) + (data.close.shift(3) - data.open.shift(3))) / 6 data['Dem'] = ((data.high - data.low) + 2 * (data.high.shift(1) - data.low.shift(1)) + 2 * (data.high.shift(2) - data.low.shift(2)) + (data.high.shift(3) - data.low.shift(3))) / 6 for j in range(1, RVIper + 3): #calculate RVI value with period maNEM = 0 maDEM = 0 for i in range(j, RVIper + j): maNEM = maNEM + data.iloc[-i].Nem maDEM = maDEM + data.iloc[-i].Dem data.at[30 - j, 'RVI'] = (maNEM / RVIper) / (maDEM / RVIper) data.at[29, 'RVIR'] = (data.iloc[-1].RVI + 2 * data.iloc[-2].RVI + 2 * data.iloc[-3].RVI + data.iloc[-4].RVI) / 6 print(data.iloc[-3:]) #get the newest stock price ret, stock = quote_ctx.get_cur_kline('HK.' + str(code), 3, SubType.K_3M, AuType.QFQ) print(stock.iloc[-3:]) #when to in if NumPos == 0: if (data.iloc[-1].RSI <= RSILo) | (data.iloc[-2].RSI <= RSILo) | ( data.iloc[-3].RSI <= RSILo): print('RSI match') if (data.iloc[-1].RVI_Ori > data.iloc[-1].RVIR_Ori) & ( data.iloc[-2].RVI_Ori < data.iloc[-2].RVIR_Ori): print('RVI match') print('-----buy signal-----') print(size) notify("AutoTrade.py", "!!!!!!!Buy Signal!!!!!!!" + str(code)) print('\007') print('\007') print('\007') now = datetime.now() print(now) print(data.iloc[-4].time_key) time_object = datetime.strptime(data.iloc[-4].time_key, '%Y-%m-%d %H:%M:%S') print(time_object) if (time_object >= today930): if (now > today940 and now < today11) or (now > today13 and now < today15): ret_code, info_data = trd_ctx.accinfo_query( trd_env=TrdEnv.REAL) #get ac info if ret_code == RET_OK: print('info data ok') else: while ret_code != RET_OK: ret_code, info_data = trd_ctx.accinfo_query( trd_env=TrdEnv.REAL) ''' ret, stock = quote_ctx.get_cur_kline('HK.' + str(code), 3, SubType.K_3M, AuType.QFQ) if ret == RET_OK: print('stock price get') else: while ret != RET_OK: print('stock price again loop') ret, stock = quote_ctx.get_cur_kline('HK.' + str(code), 3, SubType.K_3M, AuType.QFQ) ''' if info_data.iloc[-1].cash > ((stock.iloc[-1].close) * (size)): print('place order') notify("AutoTrade.py", "Buy Signal" + str(code)) buy(data.iloc[-1].close, False) #buy stock if NumPos > 0: #second in ''' ret, stock = quote_ctx.get_cur_kline('HK.' + str(code), 3, SubType.K_3M, AuType.QFQ) #refresh stock price if ret == RET_OK: print('stock price get') else: while ret != RET_OK: print('stock price again loop') ret, stock = quote_ctx.get_cur_kline('HK.' + str(code), 3, SubType.K_3M, AuType.QFQ) ''' if (stock.iloc[-1].close - openprice) > 0.003: buy(stock.iloc[-1].close, True) #sell print('RSI:') print(data.iloc[-1].RSI) print(data.iloc[-2].RSI) print(data.iloc[-3].RSI) print('RVI') print(data.iloc[-1].RVI - data.iloc[-1].RVIR) print('MA') print(data.iloc[-1].MA) print('close') print(stock.iloc[-1].close) print('openprice') print(openprice) if NumPos == size * hand: if (stock.iloc[-1].close - openprice) < -0.002: print(' ') print(stock.iloc[-1].close) print(openprice) print(' ') notify("AutoTrade.py", "!!!!!!!SELL SELL SELL!!!!!!! first hand") print('\007') print('\007') print('\007') print('~~~sell~~~') #sell stock sell(stock.iloc[-1].close) elif (stock.iloc[-1].close - openprice) < -0.001: print(' ') print(stock.iloc[-1].close) print(openprice) print(' ') notify("AutoTrade.py", "!!!!!!!SELL SELL SELL!!!!!!! multi hand" + str(code)) print('~~~sell~~~') #sell stock print('\007') print('\007') print('\007') sell(stock.iloc[-1].close) ''' if (data.iloc[-1].RSI >=RSIHi) | (data.iloc[-2].RSI >=RSIHi) | (data.iloc[-3].RSI >=RSIHi): if (data.iloc[-1].RVI <= data.iloc[-1].RVIR): if data.iloc[-1].close <= data.iloc[-1].MA: notify("AutoTrade.py", "!!!!!!!SELL SELL SELL!!!!!!!") print('~~~sell~~~') #sell stock sell(data.iloc[-1].close) if data.iloc[-1].close >= openprice*1.1: #sell if profit >10% sell(data.iloc[-1].close) ''' trd_ctx.close()
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Load the pre-built regressor dataframe['historical_mean'] = ta.MA(dataframe, timeperiod=33) return dataframe
print('one_dif ', c) print('two_dif ', c) # # 3. pandas数据处理试题 # 3.1 如何查看列名、怎么对数据转置 # 3.2 读取data里的600029这只股票的DataFrame,将其收盘价转换成用Numpy的Array格式,并用talib计算10日EMA值,返回ndarray的最后五个值 # In[4]: import talib.abstract as ta df_ma = pd.DataFrame({name: ta.MA(value, 10) for name, value in PN.iteritems()}) print(df_ma.tail()) # In[5]: # 3.3 读取sz50.xlsx的['600029.XSHG','600050.XSHG','601318.XSHG']的全数据做成Panel # In[6]: from datetime import datetime