def macd_side(close): macd, signal, hist = talib.MACD(close.values) hist = pd.Series(hist).fillna(1).values return pd.Series(2 * ((hist > 0).astype(float) - 0.5), index=close.index[-len(hist):])
def MACD(self,se,fast=6,slow=12,signal=9): macd, signal, hist = talib.MACD(np.array(se),fastperiod=fast, slowperiod=slow, signalperiod=signal) return macd,signal,hist
def CalculateIndicators(self): #Get all available stocks stocks =[x['BBGTicker'] for x in list(self.db.Stocks.find({}))] #For each stocks get price and volume and calculate analytics for s in stocks: print(s) #Get adjusted close price if available else close price c = self.db.Prices.find_one({'BBGTicker' : s},{'Adj Close' : 1}) if 'Adj Close' not in list(c.keys()): c = self.db.Prices.find_one({'BBGTicker' : s},{'Close' : 1}) close=c['Close'] else: close=c['Adj Close'] #Get adjusted low price if available else low price l = self.db.Prices.find_one({'BBGTicker' : s},{'Adj Low' : 1}) if 'Adj Low' not in list(l.keys()): l = self.db.Prices.find_one({'BBGTicker' : s},{'Low' : 1}) low=l['Low'] else: low=l['Adj Low'] #Get adjusted high price if available else high price h = self.db.Prices.find_one({'BBGTicker' : s},{'Adj High' : 1}) if 'Adj High' not in list(h.keys()): h = self.db.Prices.find_one({'BBGTicker' : s},{'High' : 1}) high=h['High'] else: high=h['Adj High'] #Get adjusted volume if available else volume v = self.db.Prices.find_one({'BBGTicker' : s},{'Adj Volume' : 1}) if 'Adj Volume' not in list(v.keys()): v = self.db.Prices.find_one({'BBGTicker' : s},{'Volume' : 1}) vol=v['Volume'] else: vol=v['Adj Volume'] dates = sorted(close.keys()) #Transform dictionary into numpy array closeP = numpy.zeros(shape=(len(dates),)) highP = numpy.zeros(shape=(len(dates),)) lowP = numpy.zeros(shape=(len(dates),)) volume = numpy.zeros(shape=(len(dates),)) i=0 for dt in dates: closeP[i] = close[dt] highP[i] = high[dt] lowP[i] = low[dt] volume[i] = vol[dt] i=i+1 #Calculate different moving average rawsma = talib.SMA(closeP,timeperiod=14) rawema = talib.EMA(closeP,timeperiod=30) rawkama = talib.KAMA(closeP,timeperiod=30) sma=numpy.copy(rawsma) ema=numpy.copy(rawema) kama=numpy.copy(rawkama) #Transform moving average into signal (MA - close price) for k in range(len(closeP)): sma[k] = rawsma[k]-closeP[k] ema[k] = rawema[k]-closeP[k] kama[k] = rawkama[k]-closeP[k] #Calculate different analytics (RSI, ADX, MFI, CCI OBV etc) adx = talib.ADX(highP,lowP,closeP,timeperiod=14) rsi = talib.RSI(closeP,timeperiod=14) cci = talib.CCI(highP,lowP,closeP,timeperiod=14) macd, signal, hist = talib.MACD(closeP,fastperiod=12,slowperiod=26,signalperiod=9) mfi = talib.MFI(highP,lowP,closeP,volume,timeperiod=14) ad = talib.AD(highP,lowP,closeP,volume) adosc = talib.ADOSC(highP,lowP,closeP,volume,fastperiod=3, slowperiod=10) atr = talib.ATR(highP,lowP,closeP,timeperiod=14) obv = talib.OBV(closeP,volume) slowk, slowd = talib.STOCH(highP,lowP,closeP,fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) mom = talib.MOM(closeP,timeperiod=10) roc = talib.ROC(closeP,timeperiod=10) upperBB, middleBB, lowerBB = talib.BBANDS(closeP, matype=MA_Type.T3) ht = talib.HT_TRENDLINE(closeP) willR = talib.WILLR(highP,lowP,closeP,timeperiod=14) #Define dictionary keys analytics = {'BBGTicker' : s} analytics['RAWSMA']={} analytics['RAWEMA']={} analytics['RAWKAMA']={} analytics['SMA']={} analytics['EMA']={} analytics['KAMA']={} analytics['ADX']={} analytics['RSI']={} analytics['CCI']={} analytics['MACD']={} analytics['MACDSIGNAL']={} analytics['MACDHIST']={} analytics['MFI']={} analytics['AD']={} analytics['ADOSCILLATOR']={} analytics['ATR']={} analytics['OBV']={} analytics['STOCHSLOWD']={} analytics['STOCHSLOWK']={} analytics['MOM']={} analytics['ROC']={} analytics['LOWERBB']={} analytics['MIDDLEBB']={} analytics['UPPERBB']={} analytics['HILBERT']={} analytics['WILLIAMR']={} #For each date dt insert into corresponding dictionary i=0 for dt in dates: analytics['RAWSMA'][dt]=rawsma[i] analytics['RAWEMA'][dt]=rawema[i] analytics['RAWKAMA'][dt]=rawkama[i] analytics['SMA'][dt]=sma[i] analytics['EMA'][dt]=ema[i] analytics['KAMA'][dt]=kama[i] analytics['ADX'][dt]=adx[i] analytics['RSI'][dt]=rsi[i] analytics['CCI'][dt]=cci[i] analytics['MACD'][dt]=macd[i] analytics['MACDSIGNAL'][dt]=signal[i] analytics['MACDHIST'][dt]=hist[i] analytics['MFI'][dt]=mfi[i] analytics['AD'][dt]=ad[i] analytics['ADOSCILLATOR'][dt]=adosc[i] analytics['ATR'][dt]=atr[i] analytics['OBV'][dt]=obv[i] analytics['STOCHSLOWD'][dt]=slowd[i] analytics['STOCHSLOWK'][dt]=slowk[i] analytics['MOM'][dt]=mom[i] analytics['ROC'][dt]=roc[i] analytics['LOWERBB'][dt]=lowerBB[i] analytics['MIDDLEBB'][dt]=middleBB[i] analytics['UPPERBB'][dt]=upperBB[i] analytics['HILBERT'][dt]=ht[i] analytics['WILLIAMR'][dt]=willR[i] i=i+1 #Insert data into mongo DB record = [analytics] self.db.Analytics.delete_many({'BBGTicker' : s}) self.db.Analytics.insert_many(record) #Calculate future returns for horizon between 1 and 30 days futureReturn = {'BBGTicker' : s} for k in range(60): k=k+1 futureReturn['FUTURERETURN'+str(k)+'DAYS'] = {} for dt in dates: p1 = close[dt] dateIndex = dates.index(dt) if dateIndex + k < len(dates): d2 = dates[dateIndex + k] #Lookup corresponding future date for horizon k p2 = close[d2] futureReturn['FUTURERETURN'+str(k)+'DAYS'][dt] = p2/p1-1 #Calculate future return #Insert future returns into Mongo DB record = [futureReturn] self.db.Returns.delete_many({'BBGTicker' : s}) self.db.Returns.insert_many(record)
def tickerti (tickertxt): ticker = tickertxt today = date.today ().strftime ("%Y-%m-%d") # print(today) # print(ticker) stock_data = yf.download(ticker, start="2020-04-01", end=today) st.table(stock_data.tail()) plt.plot(stock_data['Close'], color='blue') plt.title("Daily Close Price (ticker)") st.pyplot (plt , use_container_width=True) # plt.show() stock_data['SMA_20'] = talib.SMA(stock_data['Close'], timeperiod=20) st.table (stock_data['SMA_20'].tail()) stock_data['SMA_50'] = talib.SMA(stock_data['Close'], timeperiod=50) st.table (stock_data['SMA_50'].tail()) plt.plot(stock_data['Close'], color='blue', label='Daily Close Price') plt.plot(stock_data['SMA_20'], color='green', label='SMA 20') plt.plot(stock_data['SMA_50'], color='red', label='SMA 50') plt.legend() plt.title('Simple Moving Averages') st.pyplot (plt , use_container_width=True) # plt.show() stock_data['EMA_20'] = talib.EMA(stock_data['Close'], timeperiod=20) st.table(stock_data['SMA_20'].tail()) stock_data['EMA_50'] = talib.EMA(stock_data['Close'], timeperiod=50) st.table(stock_data['SMA_50'].tail()) plt.plot(stock_data['Close'], color='blue', label='Daily Close Price') plt.plot(stock_data['EMA_20'], color='green', label='EMA 20') plt.plot(stock_data['EMA_50'], color='red', label='EMA 50') plt.legend() plt.title('Exponential Moving Averages') st.pyplot (plt , use_container_width=True) # plt.show() plt.plot(stock_data['Close'], color='blue', label='Daily Close Price') plt.plot(stock_data['SMA_50'], color='green', label='SMA 50') plt.plot(stock_data['EMA_50'], color='red', label='EMA 50') plt.legend() plt.title('SMA 50 vs EMA 50') st.pyplot (plt , use_container_width=True) # plt.show() stock_data['ADX'] = talib.ADX(stock_data['High'], stock_data['Low'], stock_data['Close'], timeperiod=14) st.table(stock_data['ADX'].tail()) fig, (ax1, ax2) = plt.subplots(2, sharex=True) ax1.set_ylabel('Price') ax1.plot(stock_data['Close']) ax2.set_ylabel('ADX') ax2.plot(stock_data['ADX'], color='green') ax1.set_title('Daily Close Price and ADX') ax2.axhline(y = 50, color = 'r', linestyle = '-') ax2.axhline(y = 25, color = 'r', linestyle = '-') st.pyplot (plt , use_container_width=True) # plt.show() macd, macdsignal, macdhist = talib.MACD(stock_data['Close'], fastperiod=12, slowperiod=26, signalperiod=9) fig, (ax1, ax2) = plt.subplots(2, sharex=True) ax1.set_ylabel('Price') ax1.plot(stock_data['Close']) ax2.set_ylabel('MACD') ax2.plot(macdsignal, color='green', label='Signal Line') ax2.plot(macd, color='red', label='MACD') ax2.bar(macdhist.index, macdhist, color='purple') ax1.set_title('Daily Close Price and MACD') plt.legend() st.pyplot (plt , use_container_width=True) # plt.show() stock_data['RSI'] = talib.RSI(stock_data['Close'], timeperiod=14) st.table(stock_data['RSI'].tail()) fig, (ax1, ax2) = plt.subplots(2, sharex=True) ax1.set_ylabel('Price') ax1.plot(stock_data['Close']) ax2.set_ylabel('RSI') ax2.plot(stock_data['RSI'], color='green') ax2.axhline(y = 70, color = 'r', linestyle = '-') ax2.axhline(y = 30, color = 'r', linestyle = '-') ax1.set_title('Daily Close Price and RSI') st.pyplot (plt , use_container_width=True) # plt.show() upper, mid, lower = talib.BBANDS(stock_data['Close'], nbdevup=2, nbdevdn=2, timeperiod=20) plt.plot(upper, label="Upper band") plt.plot(mid, label='Middle band') plt.plot(lower, label='Lower band') plt.title('Bollinger Bands') plt.legend() st.pyplot (plt , use_container_width=True)
def generate_tech_data(p1_df,p2_df): sample = pd.DataFrame({'p1': p1_df.values.ravel(), 'p2': p2_df.values.ravel()}, index=p1_df.index) p1=p1_df.values.ravel() p2=p2_df.values.ravel() sample['p1'+'_mom'] = talib.MOM(p1) sample['p1' + '_macd'], sample['p1' + '_macd_sig'], sample['p1' + '_macd_hist'] = talib.MACD(p1) sample['p1' + '_rsi'] = talib.RSI(p1, timeperiod=10) sample['p1' + '_cmo'] = talib.CMO(p1) sample['p2' + '_mom'] = talib.MOM(p2) sample['p2' + '_macd'], sample['p2' + '_macd_sig'], sample['p2' + '_macd_hist'] = talib.MACD(p2) sample['p2' + '_rsi'] = talib.RSI(p2, timeperiod=10) sample['p2' + '_cmo'] = talib.CMO(p2) spread = p1 / p2 sample['spread'] = spread sample['diff'] = sample['spread'] / sample['spread'].shift(1) sample = sample.dropna() return sample
def handle_bar(context, bar_dict): end_date = bar_dict[context.s1].datetime.strftime('%Y-%m-%d') start_date = (datetime.strptime(end_date, '%Y-%m-%d') - timedelta( days=400)).strftime('%Y-%m-%d') print("start_date: %s " % start_date) print("end_date: %s " % end_date) stock_history = context.stock_price # # check suspend # if stock_history.loc[(stock_history['date'] == end_date)].empty: # print("suspend happens on %s " % end_date) # return # stock_history = pd.read_csv('/Users/keli/Documents/Quant/Stock_data/price_pre', sep='|') prices = stock_history.loc[(stock_history['date'] >= start_date) & (stock_history['date'] <= end_date) & ( stock_history['stock_code'] == context.s1)]['close'].values prices = np.array(prices)[len(prices) - 200:] macd, signal, hist = talib.MACD(prices, 12, 26, 9) # print ("history hist: ",2 * hist[-1]) if context.first_time: context.last = hist[-1] context.first_time = False else: if hist[-1] < 0 and context.last > 0: print ("@@@@@@@@@@ sell signal - hist is moving up->down across the axis @@@@@@@@@@") # print ("current hist: %s " % (str(2 * hist[-1]))) # print ("previous hist: %s " % (str(2 * context.last))) print(end_date) order_percent(context.s1, -1) elif hist[-1] > 0 and context.last < 0: print ("@@@@@@@@@@ buy signal - hist is moving down->up across the axis @@@@@@@@@@") # print ("current hist: %s " % (str(2 * hist[-1]))) # print ("previous hist: %s " % (str(2 * context.last))) # print(end_date) # order_percent(context.s1, 1) macd_60m(context, bar_dict) if hist[-1] > 0 and context.last > 0 and abs(hist[-1]) < abs(context.last): print ( "@@@@@@@@@@ sell signal - hist is above the axis and current hist is less than previous hist @@@@@@@@@@") # print ("current hist: %s " % (str(2 * hist[-1]))) # print ("previous hist: %s " % (str(2 * context.last))) # print("prices: ",prices) print (end_date) # macd_60m(context,bar_dict) order_percent(context.s1, -1) elif hist[-1] < 0 and context.last < 0 and abs(hist[-1]) < abs(context.last): print ( "@@@@@@@@@@ buy signal - hist is below the axis and current hist is larger than previous hist @@@@@@@@@@") # print ("current hist: %s " % (str(2 * hist[-1]))) # print ("previous hist: %s " % (str(2 * context.last))) print(end_date) macd_60m(context, bar_dict) # if context.portfolio.cash > prices[-1] * 100: # print(context.portfolio) # print("place order") # order_value(context.s1, context.portfolio.cash) # else: # print("skip order, no money") context.last = hist[-1]
def add_macd_indicators(self, df): ''' minimum data size: 11198 ''' # factor_9t = self.daily_count * 25 factor_8t = self.daily_count * 20 factor_7t = self.daily_count * 15 factor_6t = self.daily_count * 10 factor_5t = self.daily_count * 5 factor_4t = self.daily_count * 4 factor_3t = self.daily_count * 3 factor_2t = self.daily_count * 2 factor_1t = self.daily_count * 1 factor_1h = 4 # df['macd_9t'], df['macdsignal_9t'], df['machhist_9t'] = talib.MACD(df.close, fastperiod=12*factor_9t, slowperiod=26*factor_9t, signalperiod=9*factor_9t) df['macd_8t'], df['macdsignal_8t'], df['machhist_8t'] = talib.MACD( df.close, fastperiod=12 * factor_8t, slowperiod=26 * factor_8t, signalperiod=9 * factor_8t) df['macd_7t'], df['macdsignal_7t'], df['machhist_7t'] = talib.MACD( df.close, fastperiod=12 * factor_7t, slowperiod=26 * factor_7t, signalperiod=9 * factor_7t) df['macd_6t'], df['macdsignal_6t'], df['machhist_6t'] = talib.MACD( df.close, fastperiod=12 * factor_6t, slowperiod=26 * factor_6t, signalperiod=9 * factor_6t) df['macd_5t'], df['macdsignal_5t'], df['machhist_5t'] = talib.MACD( df.close, fastperiod=12 * factor_5t, slowperiod=26 * factor_5t, signalperiod=9 * factor_5t) df['macd_4t'], df['macdsignal_4t'], df['machhist_4t'] = talib.MACD( df.close, fastperiod=12 * factor_4t, slowperiod=26 * factor_4t, signalperiod=9 * factor_4t) df['macd_3t'], df['macdsignal_3t'], df['machhist_3t'] = talib.MACD( df.close, fastperiod=12 * factor_3t, slowperiod=26 * factor_3t, signalperiod=9 * factor_3t) df['macd_2t'], df['macdsignal_2t'], df['machhist_2t'] = talib.MACD( df.close, fastperiod=12 * factor_2t, slowperiod=26 * factor_2t, signalperiod=9 * factor_2t) df['macd_1t'], df['macdsignal_1t'], df['machhist_1t'] = talib.MACD( df.close, fastperiod=12 * factor_1t, slowperiod=26 * factor_1t, signalperiod=9 * factor_1t) df['macd_1h'], df['macdsignal_1h'], df['machhist_1h'] = talib.MACD( df.close, fastperiod=12 * factor_1h, slowperiod=26 * factor_1h, signalperiod=9 * factor_1h) return df
def _update_ta(self): """更新辅助技术指标""" if not self.ma: ma_temp = dict() close_ = np.array([x["close"] for x in self.kline_raw], dtype=np.double) for p in self.ma_params: ma_temp['ma%i' % p] = ta.SMA(close_, p) for i in range(len(self.kline_raw)): ma_ = { 'ma%i' % p: ma_temp['ma%i' % p][i] for p in self.ma_params } ma_.update({"dt": self.kline_raw[i]['dt']}) self.ma.append(ma_) else: ma_ = { 'ma%i' % p: sum([x['close'] for x in self.kline_raw[-p:]]) / p for p in self.ma_params } ma_.update({"dt": self.kline_raw[-1]['dt']}) if self.verbose: print("ma new: %s" % str(ma_)) if self.kline_raw[-2]['dt'] == self.ma[-1]['dt']: self.ma.append(ma_) else: self.ma[-1] = ma_ assert self.ma[-2]['dt'] == self.kline_raw[-2]['dt'] if not self.macd: close_ = np.array([x["close"] for x in self.kline_raw], dtype=np.double) # m1 is diff; m2 is dea; m3 is macd m1, m2, m3 = ta.MACD(close_, fastperiod=12, slowperiod=26, signalperiod=9) for i in range(len(self.kline_raw)): self.macd.append({ "dt": self.kline_raw[i]['dt'], "diff": m1[i], "dea": m2[i], "macd": m3[i] }) else: close_ = np.array([x["close"] for x in self.kline_raw[-200:]], dtype=np.double) # m1 is diff; m2 is dea; m3 is macd m1, m2, m3 = ta.MACD(close_, fastperiod=12, slowperiod=26, signalperiod=9) macd_ = { "dt": self.kline_raw[-1]['dt'], "diff": m1[-1], "dea": m2[-1], "macd": m3[-1] } if self.verbose: print("macd new: %s" % str(macd_)) if self.kline_raw[-2]['dt'] == self.macd[-1]['dt']: self.macd.append(macd_) else: self.macd[-1] = macd_ assert self.macd[-2]['dt'] == self.kline_raw[-2]['dt']
def to_df(self, ma_params=(5, 20), use_macd=False, max_count=1000, mode="raw"): """整理成 df 输出 :param ma_params: tuple of int 均线系统参数 :param use_macd: bool :param max_count: int :param mode: str 使用K线类型, raw = 原始K线,new = 去除包含关系的K线 :return: pd.DataFrame """ if mode == "raw": bars = self.kline_raw[-max_count:] elif mode == "new": bars = self.kline_raw[-max_count:] else: raise ValueError fx_list = { x["dt"]: { "fx_mark": x["fx_mark"], "fx": x['fx'] } for x in self.fx_list[-(max_count // 2):] } bi_list = { x["dt"]: { "fx_mark": x["fx_mark"], "bi": x['bi'] } for x in self.bi_list[-(max_count // 4):] } xd_list = { x["dt"]: { "fx_mark": x["fx_mark"], "xd": x['xd'] } for x in self.xd_list[-(max_count // 8):] } results = [] for k in bars: k['fx_mark'], k['fx'], k['bi'], k['xd'] = "o", None, None, None fx_ = fx_list.get(k['dt'], None) bi_ = bi_list.get(k['dt'], None) xd_ = xd_list.get(k['dt'], None) if fx_: k['fx_mark'] = fx_["fx_mark"] k['fx'] = fx_["fx"] if bi_: k['bi'] = bi_["bi"] if xd_: k['xd'] = xd_["xd"] results.append(k) df = pd.DataFrame(results) for p in ma_params: df.loc[:, "ma{}".format(p)] = ta.SMA(df.close.values, p) if use_macd: diff, dea, macd = ta.MACD(df.close.values) df.loc[:, "diff"] = diff df.loc[:, "dea"] = diff df.loc[:, "macd"] = diff return df
path2 = os.path.join(parent_folder, 'simulator') sys.path.append(path2) from basic_ploter import BasicPloter from basic_simulator import BasicSimulator # ------------------------------------------------------------- # ------------------------------------------------------------- # data # ------------------------------------------------------------- instrument = 'GBP_USD' data_file = '{}.csv'.format(instrument) data_folder = os.path.join(parent_folder, 'data') date_file_path = os.path.join(data_folder, data_file) # ------------------------------------------------------------- df = pd.read_csv(date_file_path) closeMidData = df['closeMid'].values dateData = df['date'].values macd, macdsignal, macdhist = talib.MACD(closeMidData, fastperiod=12, slowperiod=26, signalperiod=9) forex_ploter = BasicPloter() forex_ploter.plot_basic_trend(dateData, closeMidData, title=instrument) forex_ploter.plot_MACD(dateData, closeMidData, macd, macdsignal, macdhist, title=instrument)
def plot(self, symbolId): start = datetime.datetime(2020, 1, 1) end = datetime.datetime.today() for stock in symbolId: stock = str(stock) df = web.DataReader([stock + '.TW'], 'yahoo', start, end) ma5 = talib.SMA(df['Close'][stock + '.TW'], timeperiod=5) ma20 = talib.SMA(df['Close'][stock + '.TW'], timeperiod=20) ma10 = talib.SMA(df['Close'][stock + '.TW'], timeperiod=10) dif, dem, hist = talib.MACD(df['Close'][stock + '.TW']) ema12 = talib.EMA(df['Close'][stock + '.TW'], 12) ema26 = talib.EMA(df['Close'][stock + '.TW'], 26) rsi5 = talib.RSI(df['Close'][stock + '.TW'].values, 5) rsi10 = talib.RSI(df['Close'][stock + '.TW'].values, 10) k, d, j = self.kd(df, stock) df.index = df.index.to_series().apply( lambda x: x.strftime('%Y-%m-%d')) #畫圖 fig = plt.figure(figsize=(24, 16)) ax1 = fig.add_axes([0.05, 0.55, 0.9, 0.4]) plt.title(stock, fontsize=25, fontweight='bold') ax2 = fig.add_axes([0.05, 0.4, 0.9, 0.15]) ax3 = fig.add_axes([0.05, 0.25, 0.9, 0.15]) ax4 = fig.add_axes([0.05, 0.1, 0.9, 0.15]) mpf.candlestick2_ochl(ax1, df['Open'][stock + '.TW'], df['Close'][stock + '.TW'], df['High'][stock + '.TW'], df['Low'][stock + '.TW'], width=0.6, colorup='r', colordown='g', alpha=0.75) ax1.plot(ma5.values, label='MA5') ax1.plot(ma10.values, label='MA10') ax1.plot(ma20.values, label='MA20') ax1.legend() ax2.plot(dif, label='DIF') ax2.plot(dem, label='DEM') ax2.fill_between(hist.index, 0, hist, label='HIST') ax2.legend() ax3.plot(k.values, label='K') ax3.plot(d.values, label='D') ax3.plot(j.values, '--', label='J') ax3.legend() ax4.plot(rsi5, label='RSI5') ax4.plot(rsi10, label='RSI10') ax4.legend() ax4.set_xticks(range(0, len(df.index), 10)) ax4.set_xticklabels(df.index[::10]) plt.savefig('技術分析圖' + stock + '.png') plt.show()
rsi_entry_length = 405 rsi_exit_length = 362 rsi_entry_filter = 50 rsi_exit_filter = 52 fastLength = 30 slowLength = 57 signalLength = 4 exit_fastLength = 30 exit_slowLength = 34 exit_signalLength = 4 Macd, Macdsignal, Macdhist = ta.MACD(close, fastperiod=fastLength, slowperiod=slowLength, signalperiod=signalLength) exit_Macd, exit_Macdsignal, exit_Macdhist = ta.MACD( close, fastperiod=exit_fastLength, slowperiod=exit_slowLength, signalperiod=exit_signalLength) Week_Macd, Week_Macdsignal, Week_Macdhist = ta.MACD( weekclose, fastperiod=Week_fastLength, slowperiod=Week_slowLength, signalperiod=Week_signalLength) entry_Rsi = ta.RSI(close, rsi_entry_length) exit_Rsi = ta.RSI(close, rsi_exit_length)
t_high = np.transpose(x[:,[1]]) t_low = np.transpose(x[:,[2]]) t_vol = np.transpose(x[:,[3]]) t_y = np.transpose(x[:,[4]]) #array로 변환 open = np.array(t_open[0],dtype='float') high = np.array(t_high[0],dtype='float') low = np.array(t_low[0],dtype='float') volume = np.array(t_vol[0],dtype='float') close = np.array(t_y[0],dtype='float') #------------------------------------------------------------------------------ #주가데이터를 지표데이터로 변환(TA-Lib 이용) ma = ta.MA(close,timeperiod=5) #moving average dmi = ta.DX(high,low,close,timeperiod=5)#direct movement index macd, macdsignal, macdhist = ta.MACD(close,fastperiod=6, slowperiod=12,signalperiod=4) #moving average convergence/divergence #------------------------------------------------------------------------------ #x를 지표데이터 15개 묶음으로 변경 x = np.c_[ma,dmi,macd, macdsignal, macdhist] #***************************************************************************************************#여기서부터 사용하는 변수 다름 # train Parameters R_seq_length = 10 #10일 데이치를 넣어 R_after = 9 #그로부터 10일뒤 종가 예측 R_data_dim = 5 #지표로 변환하여 데이터 5개가 들어감 R_hidden_dim = 10 #lstm에서 output은 10개가 나옴 R_output_dim = 1 #FC를 통해 10개에서 1개로 R_learning_rate = 0.01 #학습률 R_iterations = 1000 #반복 횟수 #X,Y
df_amd_bb_upper, df_amd_bb_middle, df_amd_bb_lower = ta.BBANDS(df_amd['Close'], timeperiod=timeperiod) # Directionalmovementindex df_amd_dx = ta.DX(df_amd['Close'],df_amd['Open'],df_amd['High'], timeperiod=timeperiod) # Exponentialmovingaverages df_amd_ema = ta.EMA(df_amd['Close'], timeperiod=timeperiod) # Stochasticindex df_amd_slowk, df_amd_slowd = ta.STOCH(df_amd['High'], df_amd['Low'], df_amd['Close'], fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) # Movingaverages df_amd_ma5 = ta.MA(df_amd['Close'], timeperiod=timeperiod) # MACD df_amd_macd, df_amd_macdsignal, df_amd_macdhist = ta.MACD(df_amd['Close'], fastperiod=12, slowperiod=26, signalperiod=9) # Relativestrengthindex df_amd_rsi = ta.RSI(df_amd['Close'], timeperiod=timeperiod) df_amd_total = df_amd.copy() df_amd_total = pd.concat([df_amd_total, df_amd_bb_upper, df_amd_bb_middle, df_amd_bb_lower, # Bollingerbands df_amd_dx, # Directionalmovementindex df_amd_ema, # Exponentialmovingaverages df_amd_slowk, df_amd_slowd, # Stochasticindex df_amd_ma5, # Movingaverages df_amd_macd, df_amd_macdsignal, df_amd_macdhist, # MACD df_amd_rsi], axis = 1) # Relativestrengthindex
def Get_MACD(df, dtype='d', days=ct.Power_Ma_Days, lastday=ct.Power_last_da): # 参数12,26,9 df = df.sort_index(ascending=True) if len(df) > 1 + lastday: if lastday != 0: df = df[:-lastday] if len(df) < limitCount: return (df, 1) # df=df.fillna(0) macd, macdsignal, macdhist = ta.MACD(np.array(df['close']), fastperiod=5, slowperiod=34, signalperiod=5) 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['diff%s' % dtype] = pd.Series(macd, index=df.index) # DIFF 13 df['dea%s' % dtype] = pd.Series(macdsignal, index=df.index) # DEA 14 df['ddea%s' % dtype] = pd.Series(macdhist, index=df.index) # DIFF-DEA 15 dflen = df.shape[0] MAlen = len(SignalMA5) operate = 0 dd = df.dropna() print dd[['diffd', 'dead', 'ddead']], dd.ddead.argmin() import ipdb ipdb.set_trace() # 2个数组 1.DIFF、DEA均为正,DIFF向上突破DEA,买入信号。 2.DIFF、DEA均为负,DIFF向下跌破DEA,卖出信号。 # 待修改 diff = df.loc[df.index[-1], 'diff%s' % dtype] diff2 = df.loc[df.index[-2], 'diff%s' % dtype] dea = df.loc[df.index[-1], 'dea%s' % dtype] dea2 = df.loc[df.index[-2], 'dea%s' % dtype] if diff > 0: if dea > 0: if diff > dea and diff2 <= dea2: operate = operate + 10 # 买入 else: if dea < 0: if diff == dea2: operate = operate - 10 # 卖出 # 3.DEA线与K线发生背离,行情反转信号。 ma5 = df.loc[df.index[-1], 'ma5%s' % dtype] # 7 ma10 = df.loc[df.index[-1], 'ma10%s' % dtype] # 8 ma20 = df.loc[df.index[-1], 'ma20%s' % dtype] # 9 if ma5 >= ma10 and ma10 >= ma20: # K线上涨 if SignalMA5[MAlen - 1] <= SignalMA10[MAlen - 1] and SignalMA10[ MAlen - 1] <= SignalMA20[MAlen - 1]: # DEA下降 operate = operate - 1 elif ma5 <= ma10 and ma10 <= ma20: # K线下降 if SignalMA5[MAlen - 1] >= SignalMA10[MAlen - 1] and SignalMA10[ MAlen - 1] >= SignalMA20[MAlen - 1]: # DEA上涨 operate = operate + 1 # 4.分析MACD柱状线,由负变正,买入信号。 diffdea = df.loc[df.index[-1], 'ddea%s' % dtype] # diffdea2 = df.loc[df.index[-2],'macdhist%s'%dtype] if diffdea > 0 and dflen > 30: for i in range(1, 26): if df.loc[df.index[-1 - i], 'ddea%s' % dtype] <= 0: operate = operate + 5 break # 由正变负,卖出信号 if diffdea < 0 and dflen > 30: dayl = 26 if len(df) > 26 else len(df) for i in range(1, ): if df.loc[df.index[-1 - i], 'ddea%s' % dtype] >= 0: operate = operate - 5 break for cl in ['diff%s' % dtype, 'dea%s' % dtype]: operate = algoMultiTech(df, column=cl, days=days, op=operate) df = df.sort_index(ascending=False) return (df, operate)
data_stats = pd.DataFrame(index=stock_tickers, columns=header) meanAcc = [0, 0, 0, 0] meanAccStd = [0, 0, 0, 0] meanFscore = [0, 0, 0, 0] meanFscoreStd = [0, 0, 0, 0] latex_confusion_matrices = '' for ticker in stock_tickers: hist = data[ticker].dropna() rsi = pd.DataFrame(talib.RSI(hist['Close'])).fillna(0) stoch = pd.DataFrame( talib.STOCH(hist['High'], hist['Low'], hist['Close'])[0]).fillna(0) macd = pd.DataFrame(talib.MACD(hist['Close'])[0]).fillna(0) sma = pd.DataFrame(talib.SMA(hist['Close'], 10)).fillna(0) will = pd.DataFrame(talib.WILLR(hist['High'], hist['Low'], hist['Close'])).fillna(0) mom = pd.DataFrame(talib.MOM(hist['Close'])).fillna(0) # Number of days used for calculating indicators init_days = 50 X = np.zeros((hist.shape[0], 6)) X[:, 0] = np.where(rsi > 70, -1, np.where(rsi < 30, 1, np.where(rsi > rsi.shift(1), 1, -1))).squeeze() X[:, 1] = np.where(stoch > stoch.shift(1), 1, -1).squeeze() X[:, 2] = np.where(macd > macd.shift(1), 1, -1).squeeze()
def macd_60m(context,bar_dict): price_60 = pd.read_csv('/Users/keli/Documents/Quant/Stock_data/price_pre_600888_60m2', sep='|') cur_date = (bar_dict[context.s1].datetime.strftime('%Y-%m-%d')) previous_date = calTime(cur_date,-1) last_date = calTime(cur_date,+1) first_date = calTime(previous_date,-100) previous_price_history = price_60.loc[ (price_60['date'] >= first_date) & (price_60['date'] < cur_date) & ( price_60['stock_code'] == context.s1)]['close'].values # dataframe previous_price_history = np.array(previous_price_history)[len(previous_price_history) - 200:] hist_60 = talib.MACD(previous_price_history, 12, 26, 9)[2] last_hist = hist_60[-1] rops = price_60.loc[ (price_60['date'] >= cur_date) & (price_60['date'] < last_date) & ( price_60['stock_code'] == context.s1)]['date'].values # print ("rops: ", rops) for i in range(len(rops)): print ("current rop: ", rops[i]) previous_price_history = price_60.loc[ (price_60['date'] >= first_date) & (price_60['date'] <= rops[i]) & ( price_60['stock_code'] == context.s1)]['close'].values previous_price_history = np.array(previous_price_history)[len(previous_price_history) - 200:] hist_60 = talib.MACD(previous_price_history, 12, 26, 9)[2] if hist_60[-1] < 0 and last_hist > 0: print("@@@@@@@@@@ 60m sell signal - hist is moving up->down across the axis @@@@@@@@@@") # print ("current hist: %s " % (str(2 * hist[-1]))) # print ("previous hist: %s " % (str(2 * context.last))) order_percent(context.s1, -1) # last_hist = hist_60[-1] elif hist_60[-1] > 0 and last_hist < 0: print("@@@@@@@@@@ 60m buy signal - hist is moving down->up across the axis @@@@@@@@@@") # print ("current hist: %s " % (str(2 * hist[-1]))) # print ("previous hist: %s " % (str(2 * context.last))) # print(end_date) if context.portfolio.cash > previous_price_history[-1] * 100: print("place order") # order_value(context.s1, context.portfolio.cash) order_percent(context.s1, 1) print(context.portfolio) else: print("skip order, no money") # last_hist = hist_60[-1] elif hist_60[-1] > 0 and last_hist > 0 and abs(hist_60[-1]) < abs(last_hist): print( "@@@@@@@@@@ 60m sell signal - hist is above the axis and current hist is less than previous hist @@@@@@@@@@") # print("current hist: %s " % (str(2 * hist_60[-1]))) # print("previous hist: %s " % (str(2 * last_hist))) # print("prices: ", previous_price_history) print("sell") order_percent(context.s1, -1) # last_hist = hist_60[-1] elif hist_60[-1] < 0 and last_hist < 0 and abs(hist_60[-1]) < abs(last_hist): print( "@@@@@@@@@@ 60m buy signal - hist is below the axis and current hist is larger than previous hist @@@@@@@@@@") # print("current hist: %s " % (str(2 * hist_60[-1]))) # print("previous hist: %s " % (str(2 * last_hist))) if context.portfolio.cash > previous_price_history[-1] * 100: print("place order") # order_value(context.s1, context.portfolio.cash) order_percent(context.s1, 1) print(context.portfolio) else: print("skip order, no money") last_hist = hist_60[-1]
def before_close(self): if (self.pos_amount - len(self.positions)) > 0: history = bao_stock.get_last_data(days_ago=40, fuquan=2) history['code'] = history['code'].apply(lambda x: x.replace('.', '')) codes = list(set(history['code'].tolist())) dd = [] for i in range(0, len(codes), 500): # 新浪获取实时数据不能一次获取全部,这里每次获取500只股票的数据 dd = dd + get_sina_live_data(codes[i:i+500]) current = pd.DataFrame(dd) # 选出有用的列 current = current[['date', 'code', 'open', 'high', 'low', 'current', 'volume', 'amount', 'preclose']] current.rename(columns={'current': 'close'}, inplace=True) print(type(current.at[0, 'open'])) # 添加到历史数据中 history = history.append(current, ignore_index=True, sort=False) history.sort_values(by=['code', 'date'], inplace=True) # history['turn'] = history['turn'].apply(lambda x : x if x is np.nan else history['turn'].shift(1) * (history['volume'] / history['volume'].shift(1))) # history['turn'] = history['turn'] if history['turn'] is np.nan else history['turn'].shift(1) * (history['volume'] / history['volume'].shift(1)) history['turn'].fillna(value=history['turn'].shift(1) * history['volume'] / history['volume'].shift(1), inplace=True) history['pctChg'].fillna(value=(history['close'] - history['preclose']) / history['preclose'], inplace=True) history.to_csv(config.OUTPUT_PATH + '/8888.csv', encoding='utf-8-sig', index=None) print(history) df = history # 将时间字符串转换成datetime格式 df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # 计算kdj kdj(df) # 计算rsi rsi(df) # 动量 df['mom'] = talib.MOM(df['close'], timeperiod=20) # 波动率 df['atr'] = talib.ATR(df.high, df.low, df.close, timeperiod=20) # macd df['dif'], df['dea'], df['macd'] = talib.MACD(df['close'].values, fastperiod=12, slowperiod=26, signalperiod=9) # SAR抛物线 df['sar'] = talib.SAR(df['high'], df['low'], acceleration=0.02, maximum=0.2) # ADX df['adx'] = talib.ADX(df.high, df.low, df.close, timeperiod=20) # 多均线 df['ma_5'] = df['close'].rolling(5, min_periods=1).mean() df['ma_10'] = df['close'].rolling(10, min_periods=1).mean() df['ma_15'] = df['close'].rolling(15, min_periods=1).mean() df['ma_50'] = df['close'].rolling(50, min_periods=1).mean() df['ma_100'] = df['close'].rolling(100, min_periods=1).mean() # macd买入信号 condition1 = (df['dif'] > df['dea']) condition2 = (df['dif'].shift(1) < df['dea'].shift(1)) df.loc[condition1 & condition2, 'macd_b'] = 1 # macd卖出信号 condition3 = (df['dif'] < df['dea']) condition4 = (df['dif'].shift(1) > df['dea'].shift(1)) df.loc[condition3 & condition4, 'macd_s'] = 1 # kdj买入信号 condition5 = (df['k'] > df['d']) condition6 = (df['k'].shift(1) < df['d'].shift(1)) df.loc[condition5 & condition6, 'kdj_b'] = 1 # kdj卖出信号 condition7 = (df['k'] < df['d']) condition8 = (df['k'].shift(1) > df['d'].shift(1)) df.loc[condition7 & condition8, 'kdj_s'] = 1 # rsi买入信号 condition5 = (df['rsi_6'] > df['rsi_24']) condition6 = (df['rsi_6'].shift(1) < df['rsi_24'].shift(1)) df.loc[condition5 & condition6, 'rsi_b'] = 1 # rsi卖出信号 condition7 = (df['rsi_6'] < df['rsi_24']) condition8 = (df['rsi_6'].shift(1) > df['rsi_24'].shift(1)) df.loc[condition7 & condition8, 'rsi_s'] = 1 # sar买入信号 condition9 = (df['close'] > df['sar']) condition10 = (df['close'].shift(1) < df['sar'].shift(1)) df.loc[condition9 & condition10, 'sar_b'] = 1 # sar卖出信号 condition11 = (df['close'] < df['sar']) condition12 = (df['close'].shift(1) > df['sar'].shift(1)) df.loc[condition11 & condition12, 'sar_s'] = 1 # 金叉多均线 condition13 = (df['close'] > df['ma_5']) condition14 = (df['close'] > df['ma_10']) condition15 = (df['close'] > df['ma_15']) condition16 = (df['close'].shift(1) < df['ma_5'].shift(1)) condition17 = (df['close'].shift(1) < df['ma_10'].shift(1)) condition18 = (df['close'].shift(1) < df['ma_15'].shift(1)) df.loc[condition13 & condition14 & condition15 & condition16 & condition17 & condition18, 'ma3_b'] = 1 """ 开始筛选 """ today_df = df[df['date'] == self.today] # 今天的 today_df = today_df[today_df['kdj_b'] == 1] # 有信号的 today_df = today_df[today_df['close'] < 20] # 价格小于20 的 today_df = today_df[today_df['pctChg'] < 9] # 涨幅不超过9 today_df.sort_values(by=['turn'], ascending=False, inplace=True) # 按换手率排序 # 可用仓位 empty_pos = self.pos_amount - len(self.positions) # 获取余额 accounts = self.sub_accounts.iloc[0]['可用金额'] # 获取可能需要的手续费 commission = accounts * self.commission # 每个仓位的钱 one_money = (accounts - commission) / empty_pos print(self.sub_accounts) print(self.sub_accounts) today_df = today_df[:empty_pos] for c in today_df.iterrows(): now_df = get_sina_live_data([c['code'].replace('.', '')]) if now_df is None: continue now_df = now_df[0] buy_money = round(now_df['current'] * (1 + self.slippage), 2) buy_num = one_money / buy_money buy_num = int(buy_num / 100) * 100 self.buy(code=c['code'].split('.')[1], price=buy_money, amount=buy_num) self.get_positions()
def macd(self, fastPeriod, slowPeriod, signalPeriod, array=True): macd, signal, hist = talib.MACD(self.close, fastPeriod, slowPeriod, signalPeriod) if array: return macd, signal, hist return macd[-1], signal[-1], hist[-1]
def onBar(self, bar): if self.barHour != int(bar.datetime.hour): self.barHour = int(bar.datetime.hour) self.bar = VtBarData() self.bar.open = bar.open self.bar.high = bar.high self.bar.low = bar.low self.bar.close = bar.close self.bar.datetime = bar.datetime else: self.bar.high = max(bar.high, self.bar.high) self.bar.low = min(bar.low, self.bar.low) self.bar.close = bar.close return if bar.close == self.closeArray[-1]: self.no_data += 1 else: self.no_data = 0 if self.no_data > 10: # 无数的周期过多时进行过滤 return # print("initCapital {0}".format(self.initCapital)) # for orderID in self.orderList: # self.cancelOrder(orderID) # self.orderList = [] # 保存K线数据 self.closeArray[0:self.bufferSize - 1] = self.closeArray[1:self.bufferSize] self.closeArray[-1] = bar.close self.bufferCount += 1 if not self.init_data_loaded or self.bufferCount < self.slowMaLength: return # slow_arr = talib.MA(self.closeArray, self.slowMaLength) # fast_arr = talib.MA(self.closeArray, self.fastMaLength) macd, macdsignal, macdhist = talib.MACD(self.closeArray, self.fast_period, self.slow_period, self.signal_period) # slow_arr = talib.WMA(self.closeArray, self.slowMaLength) # fast_arr = talib.WMA(self.closeArray, self.fastMaLength) # slow_1 = slow_arr[-1] # slow_2 = slow_arr[-2] # fast_1 = fast_arr[-1] # fast_2 = fast_arr[-2] # 判断买卖 # crossOver = fast_1 > slow_1 and fast_2 <= slow_2 #and macd[-1] > macdsignal[-1] # 上穿 # crossBelow = fast_1 < slow_1 and fast_2 >= slow_2 #and macd[-1] < macdsignal[-1] # 下穿 crossOver = macd[-1] > macdsignal[-1] and macd[-2] <= macdsignal[ -2] # 上穿 crossBelow = macd[-1] < macdsignal[-1] and macd[-2] >= macdsignal[ -2] # 下穿 increasing = 0 # fast_1 > slow_1 # 快线在上 decreasing = 0 # fast_1 < slow_1 # 快线在下 volume = 0 self.cancelAll() if self.ctaEngine.engineType == ENGINETYPE_TRADING: # 加载没有完成成交的订单 incomplete_orders = self.ctaEngine.load_incomplete_orders(self) for order in incomplete_orders: if increasing and order['order_type'] == 3: # 平空 self.short(bar.close, order['order_amount'] - order['deal_amount']) elif decreasing and order['order_type'] == 4: # 平多 self.sell(bar.close, order['order_amount'] - order['deal_amount']) # account_right = self.ctaEngine.query_account().balance # btc 账户权益 account_right = self.ctaEngine.query_account().info[ self.vtSymbol[:3].lower()]['account_rights'] strategy_margin = self.margin_percent * account_right * bar.close # 用些策略的金额 else: strategy_margin = self.initCapital if self.pos == 0: volume = strategy_margin / self.contract_size if crossOver: if self.stop == 0: self.buy(bar.close, int(volume * 0.5)) else: self.stop -= 1 elif crossBelow: if self.stop == 0: self.short(bar.close, int(volume * 2)) else: self.stop -= 1 # 持有多头仓位 elif self.pos > 0: sell_order = short_order = False if self.last_entry_price > 0 and ( bar.close - self.last_entry_price ) / self.last_entry_price > self.stop_profit: self.stop = 4 sell_order = True # print("*"*20) elif crossBelow: sell_order = short_order = True if sell_order: self.sell(bar.close, abs(self.pos)) if self.ctaEngine.engineType != ENGINETYPE_TRADING: self.initCapital = self.trade_result(bar) strategy_margin = self.initCapital volume = strategy_margin / self.contract_size if short_order: self.short(bar.close, int(volume * 2)) # 持有空头仓位 elif self.pos < 0: cover_order = long_order = False if self.last_entry_price > 0 and ( self.last_entry_price - bar.close) / self.last_entry_price > self.stop_profit: self.stop = 4 cover_order = True # print("*" * 20) elif crossOver: cover_order = long_order = True if cover_order: self.cover(bar.close, abs(self.pos)) if self.ctaEngine.engineType != ENGINETYPE_TRADING: self.initCapital = self.trade_result(bar) strategy_margin = self.initCapital volume = strategy_margin / self.contract_size if long_order: self.buy(bar.close, int(volume * 0.5)) # 发出状态更新事件 self.putEvent()
def getMACD(closePrices): macd, macdsignal, macdhist = talib.MACD(closePrices, fastperiod=12, slowperiod=26, signalperiod=9) return macd, macdsignal, macdhist
def mytest(): data = getStockallDataByCODE_mysql_step1(20150101, 20190921) sector = data['3645'] sector = sector.set_index('DATE') sector.index = pd.to_datetime(sector.index) sector = sector.astype(float) # sector = getDF(data['3645'],'close_price') sector = sector.dropna() # sector = data.get_group('3645') # sector = sector.set_index('DATE') # sector = sector.astype(float) # close = sector.close_price # sector= sector.dropna() # sector.head() # test.initData(sector.close_price.values) # test.start() dif, dea, macd = ta.MACD(sector.close_price.values, fastperiod=12, slowperiod=26, signalperiod=9) sector['dif'] = dif sector['dea'] = dea sector['macd'] = macd sector.tail() sector['close_price'].plot(figsize=(12, 4)) sector[['dif', 'dea']].plot(figsize=(12, 4)) sector[['macd']].plot(figsize=(12, 4), kind='bar', xticks=[], color='b') plt.show() sector.close_price.plot(figsize=(10, 5)) plt.ylabel("Gold ETF Prices") # plt.show() sector['S_3'] = sector['close_price'].shift(1).rolling(window=3).mean() sector['S_9'] = sector['close_price'].shift(1).rolling(window=9).mean() sector = sector.dropna() X = sector[['S_3', 'S_9']] X.head() y = sector['close_price'] y.head() t = .8 t = int(t * len(sector)) # Train dataset X_train = X[:t] y_train = y[:t] # Test dataset X_test = X[t:] y_test = y[t:] # y_test2 = ['20190904'] linear = LinearRegression().fit(X_train, y_train) print("Gold ETF Price =", round(linear.coef_[0], 2), "* 3 Days Moving Average", round(linear.coef_[1], 2), "* 9 Days Moving Average +", round(linear.intercept_, 2)) predicted_price = linear.predict(X_test) predicted_price = pd.DataFrame(predicted_price, index=y_test.index, columns=['close_price']) predicted_price.plot(figsize=(10, 5)) y_test.plot() plt.legend(['predicted_price', 'actual_price']) plt.ylabel("Gold ETF Price") plt.show() r2_score = linear.score(X[t:], y[t:]) * 100 r_squared = float("{0:.2f}".format(r2_score)) print(r_squared)
def add_macd(df): close = np.array([float(x) for x in df['close']]) diff, dea, macd = talib.MACD(close, fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod) df['DIFF'] = diff df['MACD'] = macd
t_low = np.transpose(x[:, [2]]) t_vol = np.transpose(x[:, [3]]) t_y = np.transpose(y) high = np.array(t_high[0], dtype='float') low = np.array(t_low[0], dtype='float') volume = np.array(t_vol[0], dtype='float') close = np.array(t_y[0], dtype='float') #----------------------------------------- #-------------TA-Lib function 이용----------------- b_upper, b_middle, b_lower = ta.BBANDS(close) #bollinger ban ma = ta.MA(close, timeperiod=predict_len) #moving average dmi = ta.DX(high, low, close, timeperiod=predict_len) #direct movement index macd, macdsignal, macdhist = ta.MACD( close, fastperiod=predict_len, slowperiod=predict_len * 2, signalperiod=4) #moving average convergence/divergence slowk, slowd = ta.STOCH(high, low, close, fastk_period=predict_len, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) #Stochastic mom = ta.MOM(close, timeperiod=predict_len) rsi = ta.RSI(close, timeperiod=predict_len * 2) #Relative Strength Index cci = ta.CCI(high, low, close, timeperiod=predict_len * 2) sma = ta.SMA(close, timeperiod=predict_len) #Simple Moving average wma = ta.WMA(close, timeperiod=predict_len) #Weigth Moving average
def handle_data(context): # 获取历史数据, 取后longest_history根bar hist = context.data.get_price(context.security, count=context.user_data.longest_history, frequency="1d") if len(hist.index) < context.user_data.longest_history: context.log.warn("bar的数量不足, 等待下一根bar...") return # 历史收盘价 prices = np.array(hist["close"]) # 初始化买入卖出信号 long_signal_triggered = False short_signal_triggered = False try: # talib计算MACD,返回三个数组,分别为DIF, DEA和MACD的值 macd_tmp = talib.MACD(prices, fastperiod=context.user_data.short_window, slowperiod=context.user_data.long_window, signalperiod=context.user_data.macd_window) # 获取MACD值 macd_hist = macd_tmp[2] # 获取最新一个MACD的值 macd = macd_hist[-1] context.log.info("当前MACD为: %s" % macd) except: context.log.error("计算MACD出错...") return # macd大于0时,产生买入信号 if macd > 0: long_signal_triggered = True # macd小于0时,产生卖出信号 elif macd < 0: short_signal_triggered = True # 有卖出信号,且持有仓位,则市价单全仓卖出 if short_signal_triggered: context.log.info("MACD小于0,产生卖出信号") if context.account.huobi_cny_btc >= HUOBI_CNY_BTC_MIN_ORDER_QUANTITY: # 卖出信号,且不是空仓,则市价单全仓清空 context.log.info("正在卖出 %s" % context.security) context.log.info("卖出数量为 %s" % context.account.huobi_cny_btc) context.order.sell_limit(context.security, quantity=str( context.account.huobi_cny_btc), price=str(prices[-1] * 0.98)) else: context.log.info("仓位不足,无法卖出") # 有买入信号,且持有现金,则市价单全仓买入 elif long_signal_triggered: context.log.info("MACD大于0,产生买入信号") if context.account.huobi_cny_cash >= HUOBI_CNY_BTC_MIN_ORDER_CASH_AMOUNT: # 买入信号,且持有现金,则市价单全仓买入 context.log.info("正在买入 %s" % context.security) context.log.info("下单金额为 %s 元" % context.account.huobi_cny_cash) context.order.buy_limit( context.security, quantity=str(context.account.huobi_cny_cash / prices[-1] * 0.98), price=str(prices[-1] * 1.02)) else: context.log.info("现金不足,无法下单") else: context.log.info("无交易信号,进入下一根bar")
MACD_SIGNAL = 9 STOCH_K = 14 STOCH_D = 3 SIGNAL_TOL = 3 Y_AXIS_SIZE = 12 analysis = pd.DataFrame(index=sec_id['timestamp_datetime']) analysis['sma_f'] = pd.rolling_mean(sec_id['close'], SMA_FAST) analysis['sma_s'] = pd.rolling_mean(sec_id['close'], SMA_SLOW) analysis['rsi'] = ta.RSI(sec_id['close'].as_matrix(), RSI_PERIOD) analysis['sma_r'] = pd.rolling_mean(analysis.rsi, RSI_AVG_PERIOD) # check shift analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = ta.MACD( sec_id['close'].as_matrix(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL) analysis['stoch_k'], analysis['stoch_d'] = ta.STOCH( sec_id['high'].as_matrix(), sec_id['low'].as_matrix(), sec_id['close'].as_matrix(), slowk_period=STOCH_K, slowd_period=STOCH_D) analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0) analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1, 0) analysis['stoch_k_test'] = np.where( (analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0) analysis['rsi_test'] = np.where(
stk_df = get_total_table_data(conn_k, 'ksh').loc[0:600, :] # 计算均值 stk_df['close_5'] = stk_df['close'].rolling(window=5).mean() stk_df['close_20'] = stk_df['close'].rolling(window=10).mean() # 求20日均线导数 stk_df["M20_Diff"] = stk_df['close_20'] - stk_df['close_20'].shift(1) stk_df["M20_Diff2"] = stk_df['M20_Diff'] - stk_df['M20_Diff'].shift(1) stk_df['close_90'] = stk_df['close'].rolling(window=90).mean() stk_df['C20-C90'] = stk_df['close_20'] - stk_df['close_90'] stk_df['20-90Diff'] = stk_df['C20-C90'] - stk_df['C20-C90'].shift(1) stk_df['MACD'], stk_df['MACDsignal'], stk_df['MACDhist'] = talib.MACD( stk_df.close, fastperiod=12, slowperiod=26, signalperiod=9) stk_df['MACD_M5'], stk_df['MACDsignal_M20'], stk_df[ 'MACDhist_M20'] = talib.MACD(stk_df.close_5, fastperiod=12, slowperiod=26, signalperiod=9) stk_df['RSI12'] = talib.RSI(stk_df.close, timeperiod=12) # 将控制填0方便对其 stk_df = stk_df.fillna(0) fig, ax = subplots(ncols=1, nrows=2) ax[0].plot(stk_df['close'], 'g*--', label='close', linewidth=0.5, markersize=1)
def CalculateIndicators(startDate='', endDate=''): client = MongoClient() db = client.Project stocks = [x['BBGTicker'] for x in list(db.Stocks.find({}))] if startDate == '' and endDate == '': db.HistSignals.delete_many({}) else: d1 = datetime.strptime(startDate, '%Y-%m-%d') d2 = datetime.strptime(endDate, '%Y-%m-%d') delta = (d2 - d1).days + 1 for i in range(delta): db.HistSignals.delete_many( {'Date': (d1 + td(days=i)).strftime('%Y-%m-%d')}) for s in stocks: print(s) if startDate == '' and endDate == '': data = GetDataSerieFromMongo(s) else: start = (datetime.strptime(startDate, '%Y-%m-%d') - td(days=90)).strftime('%Y-%m-%d') data = GetDataSerieFromMongo(s, start, endDate) header = data[0].tolist() header.append('SMA') header.append('EMA') header.append('KAMA') header.append('ADX') header.append('RSI') header.append('CCI') header.append('MACD') header.append('MACDSIGNAL') header.append('MACDHIST') header.append('MFI') header.append('AD') header.append('ADOSCILLATOR') header.append('ATR') header.append('OBV') header.append('STOCH') header.append('MOM') header.append('ROC') header.append('BOLLINGERUPPER') header.append('BOLLINGERMIDDLE') header.append('BOLLINGERLOWER') header.append('HILBERTTRENDLINE') header.append('WILLIAMR') if len(data) > 1: closeP = numpy.array(data[1:, 1], dtype='f8') #openP = numpy.array(data[1:,6], dtype='f8') highP = numpy.array(data[1:, 3], dtype='f8') lowP = numpy.array(data[1:, 4], dtype='f8') volume = numpy.array(data[1:, 7], dtype='f8') sma = talib.SMA(closeP, timeperiod=14) ema = talib.EMA(closeP, timeperiod=30) kama = talib.KAMA(closeP, timeperiod=30) adx = talib.ADX(highP, lowP, closeP, timeperiod=14) rsi = talib.RSI(closeP, timeperiod=14) cci = talib.CCI(highP, lowP, closeP, timeperiod=14) macd, signal, hist = talib.MACD(closeP, fastperiod=12, slowperiod=26, signalperiod=9) mfi = talib.MFI(highP, lowP, closeP, volume, timeperiod=14) ad = talib.AD(highP, lowP, closeP, volume) adOscillator = talib.ADOSC(highP, lowP, closeP, volume, fastperiod=3, slowperiod=10) atr = talib.ATR(highP, lowP, closeP, timeperiod=14) obv = talib.OBV(closeP, volume) slowk, slowd = talib.STOCH(highP, lowP, closeP, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) mom = talib.MOM(closeP, timeperiod=10) roc = talib.ROC(closeP, timeperiod=10) upperBB, middleBB, lowerBB = talib.BBANDS(closeP, matype=MA_Type.T3) hilbertTL = talib.HT_TRENDLINE(closeP) williamR = talib.WILLR(highP, lowP, closeP, timeperiod=14) res = numpy.c_[data[1:, :], sma, ema, kama, adx, rsi, cci, macd, signal, hist, mfi, ad, adOscillator, atr, obv, slowk, slowd, mom, roc, upperBB, middleBB, lowerBB, hilbertTL, williamR] records = res.tolist() jsonDict = [] for item in records: jsonDict.append(dict(zip(header, item))) if startDate == '' and endDate == '': db.HistSignals.insert_many(jsonDict) else: jsonDictFilter = [ a for a in jsonDict if datetime.strptime(startDate, '%Y-%m-%d') <= datetime.strptime(a['Date'], '%Y-%m-%d') <= datetime.strptime(endDate, '%Y-%m-%d') ] db.HistSignals.insert_many(jsonDictFilter)
print u"开始判断是否有突破" a = [] #数组暂存收盘价用来接下来MACD生成 for i in range(1, 25): a.append(n['data'][i] ['close']) #return float, this is close value,消去刚出现的价格 Open, Close, High, Low = n['data'][1]['open'], n['data'][1][ 'close'], n['data'][1]['high'], n['data'][1]['low'] a.reverse() #此处翻转是为了下面的MACD生成 a = np.array(a) real = talib.SMA(a, timeperiod=10) #EMA线 dif, dea, bar = talib.MACD(a, fastperiod=6, slowperiod=13, signalperiod=6) #MACD 参数 6,13,6 if (bar[-2] < 0 and bar[-1] > 0) and (dif[-1] < 0 and dea[-1] < 0): f = open('status.txt', 'r+') status = float(f.readline()) #读取持仓状态,是否有其他币种的持仓 f.close() if status == 0: f = open('money.txt', 'r+') zijin = float(f.readline()) #读取文本中设置的初始资金,模拟盘专用 f.close() print "向上突破" f = open('status.txt', 'w+') f.write('1') #锁仓 f.close() pp = tupo_1(float(real[-1]), Open, Close, High, Low,
# In[91]: x.shape # In[76]: events['side'].values # In[37]: help(talib.MACD) # In[42]: macd, signal, hist = talib.MACD(close.values) # In[45]: np.max(macd[100:] - signal[100:] - hist[100:]) # In[49]: macd[np.isfinite(macd)].shape # In[51]: signal = signal[np.isfinite(signal)] # In[55]: