Python talib.MACD Examples
The following are 30
code examples of talib.MACD().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
talib
, or try the search function
.
Example #1
Source File: data_preprocessing.py From StarTrader with MIT License | 22 votes |
def technical_indicators_df(self, daily_data): """ Assemble a dataframe of technical indicator series for a single stock """ o = daily_data['Open'].values c = daily_data['Close'].values h = daily_data['High'].values l = daily_data['Low'].values v = daily_data['Volume'].astype(float).values # define the technical analysis matrix # Most data series are normalized by their series' mean ta = pd.DataFrame() ta['MA5'] = tb.MA(c, timeperiod=5) / tb.MA(c, timeperiod=5).mean() ta['MA10'] = tb.MA(c, timeperiod=10) / tb.MA(c, timeperiod=10).mean() ta['MA20'] = tb.MA(c, timeperiod=20) / tb.MA(c, timeperiod=20).mean() ta['MA60'] = tb.MA(c, timeperiod=60) / tb.MA(c, timeperiod=60).mean() ta['MA120'] = tb.MA(c, timeperiod=120) / tb.MA(c, timeperiod=120).mean() ta['MA5'] = tb.MA(v, timeperiod=5) / tb.MA(v, timeperiod=5).mean() ta['MA10'] = tb.MA(v, timeperiod=10) / tb.MA(v, timeperiod=10).mean() ta['MA20'] = tb.MA(v, timeperiod=20) / tb.MA(v, timeperiod=20).mean() ta['ADX'] = tb.ADX(h, l, c, timeperiod=14) / tb.ADX(h, l, c, timeperiod=14).mean() ta['ADXR'] = tb.ADXR(h, l, c, timeperiod=14) / tb.ADXR(h, l, c, timeperiod=14).mean() ta['MACD'] = tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0] / \ tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0].mean() ta['RSI'] = tb.RSI(c, timeperiod=14) / tb.RSI(c, timeperiod=14).mean() ta['BBANDS_U'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0] / \ tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0].mean() ta['BBANDS_M'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1] / \ tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1].mean() ta['BBANDS_L'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2] / \ tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2].mean() ta['AD'] = tb.AD(h, l, c, v) / tb.AD(h, l, c, v).mean() ta['ATR'] = tb.ATR(h, l, c, timeperiod=14) / tb.ATR(h, l, c, timeperiod=14).mean() ta['HT_DC'] = tb.HT_DCPERIOD(c) / tb.HT_DCPERIOD(c).mean() ta["High/Open"] = h / o ta["Low/Open"] = l / o ta["Close/Open"] = c / o self.ta = ta
Example #2
Source File: features.py From trading-server with GNU General Public License v3.0 | 10 votes |
def MACD(self, name, bars: list): """ Return MACD for given time series. Bars list must be 26 bars in length (last 26 bars for period). MACD = EMA(12) - EMA(26) Note we only use the MACD, not signal or histogram. """ self.check_bars_type(bars) macd, signal, hist = ta.MACD( bars['close'], fastperiod=12, slowperiod=26, signalperiod=9) return macd
Example #3
Source File: macd.py From jesse with MIT License | 7 votes |
def macd(candles: np.ndarray, fastperiod=12, slowperiod=26, signalperiod=9, source_type="close", sequential=False) -> MACD: """ MACD - Moving Average Convergence/Divergence :param candles: np.ndarray :param fastperiod: int - default: 12 :param slow_period: int - default: 26 :param signal_period: int - default: 9 :param source_type: str - default: "close" :param sequential: bool - default: False :return: MACD(macd, signal, hist) """ if not sequential and len(candles) > 240: candles = candles[-240:] source = get_candle_source(candles, source_type=source_type) macd, macdsignal, macdhist = talib.MACD(source, fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod) if sequential: return MACD(macd, macdsignal, macdhist) else: return MACD(macd[-1], macdsignal[-1], macdhist[-1])
Example #4
Source File: IF_macd.py From Rqalpha-myquant-learning with Apache License 2.0 | 6 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # 获取历史收盘价序列,history_bars函数直接返回ndarray,方便之后的有关指标计算 prices = history_bars(context.s1, context.OBSERVATION, '1d', 'close') # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd,signal 和 hist macd, signal, hist = talib.MACD(prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD) # macd 是长短均线的差值,signal是macd的均线,如果短均线从下往上突破长均线,为入场信号,进行买入开仓操作 if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0: sell_qty = context.portfolio.positions[context.s1].sell_quantity # 先判断当前卖方仓位,如果有,则进行平仓操作 if sell_qty > 0: buy_close(context.s1, 1) # 买入开仓 buy_open(context.s1, 1) if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0: buy_qty = context.portfolio.positions[context.s1].buy_quantity # 先判断当前买方仓位,如果有,则进行平仓操作 if buy_qty > 0: sell_close(context.s1, 1) # 卖出开仓 sell_open(context.s1, 1)
Example #5
Source File: IF_macd.py From InplusTrader_Linux with MIT License | 6 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # 获取历史收盘价序列,history_bars函数直接返回ndarray,方便之后的有关指标计算 prices = history_bars(context.s1, context.OBSERVATION, '1d', 'close') # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd,signal 和 hist macd, signal, hist = talib.MACD(prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD) # macd 是长短均线的差值,signal是macd的均线,如果短均线从下往上突破长均线,为入场信号,进行买入开仓操作 if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0: sell_qty = context.portfolio.positions[context.s1].sell_quantity # 先判断当前卖方仓位,如果有,则进行平仓操作 if sell_qty > 0: buy_close(context.s1, 1) # 买入开仓 buy_open(context.s1, 1) if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0: buy_qty = context.portfolio.positions[context.s1].buy_quantity # 先判断当前买方仓位,如果有,则进行平仓操作 if buy_qty > 0: sell_close(context.s1, 1) # 卖出开仓 sell_open(context.s1, 1)
Example #6
Source File: test_f_macd.py From InplusTrader_Linux with MIT License | 6 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # 获取历史收盘价序列,history_bars函数直接返回ndarray,方便之后的有关指标计算 prices = history_bars(context.s1, context.OBSERVATION, '1d', 'close') # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd,signal 和 hist macd, signal, hist = talib.MACD(prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD) # macd 是长短均线的差值,signal是macd的均线,如果短均线从下往上突破长均线,为入场信号,进行买入开仓操作 if (macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0): sell_qty = context.portfolio.positions[context.s1].sell_quantity # 先判断当前卖方仓位,如果有,则进行平仓操作 if (sell_qty > 0): buy_close(context.s1, 1) # 买入开仓 buy_open(context.s1, 1) if (macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0): buy_qty = context.portfolio.positions[context.s1].buy_quantity # 先判断当前买方仓位,如果有,则进行平仓操作 if (buy_qty > 0): sell_close(context.s1, 1) # 卖出开仓 sell_open(context.s1, 1)
Example #7
Source File: talib_simple.py From catalyst with Apache License 2.0 | 6 votes |
def isSell(context, analysis): # Bearish SMA Crossover if (getLast(analysis, 'sma_test') == 0): # Bearish MACD if (getLast(analysis, 'macd_test') == 0): return True # # Bearish Stochastics # if(getLast(analysis, 'stoch_over_bought') == 0): # return True # # Bearish RSI # if(getLast(analysis, 'rsi_over_bought') == 0): # return True return False
Example #8
Source File: kline_data.py From klineyes with MIT License | 6 votes |
def get_indicator(df, indicator): ret_df = df if 'MACD' in indicator: macd, macdsignal, macdhist = ta.MACD(df.close.values, fastperiod=12, slowperiod=26, signalperiod=9) ret_df = KlineData._merge_dataframe(pd.DataFrame([macd, macdsignal, macdhist]).T.rename(columns={0: "macddif", 1: "macddem", 2: "macdhist"}), ret_df) ret_df = KlineData._merge_dataframe(line_intersections(ret_df, columns=['macddif', 'macddem']), ret_df) if 'MFI' in indicator: real = ta.MFI(df.high.values, df.low.values, df.close.values, df.volume.values, timeperiod=14) ret_df = KlineData._merge_dataframe(pd.DataFrame([real]).T.rename(columns={0: "mfi"}), ret_df) if 'ATR' in indicator: real = ta.NATR(df.high.values, df.low.values, df.close.values, timeperiod=14) ret_df = KlineData._merge_dataframe(pd.DataFrame([real]).T.rename(columns={0: "atr"}), ret_df) if 'ROCR' in indicator: real = ta.ROCR(df.close.values, timeperiod=10) ret_df = KlineData._merge_dataframe(pd.DataFrame([real]).T.rename(columns={0: "rocr"}), ret_df) ret_df['date'] = pd.to_datetime(ret_df['date'], format='%Y-%m-%d') return ret_df
Example #9
Source File: Filter_Stock_CHN_1.py From StockRecommendSystem with MIT License | 6 votes |
def macd_rule_1(df): try: df = MACD(df) except: return False input_1 = 0 input_2 = -0.8 input_3 = 0.05 dif_len = len(df['macd_dif']) if dif_len < 2: return False if abs(df['macd_dif'][-1]) > input_3: return False for idx in range(dif_len-1, 1, -1): if ((df['macd_dif'][idx] - df['macd_dif'][idx-1]) > input_1): continue if df['macd_dif'][idx] <= input_2: return True else: return False
Example #10
Source File: Filter_Stock_CHN_1.py From StockRecommendSystem with MIT License | 6 votes |
def macd_rule(df): try: df = MACD(df) except: return False input_1 = 0.2 input_2 = -0.8 input_3 = 22 * 3 index = -1 df['macd_dif_1'] = df['macd_dif'].shift(1) df['macd_dea_1'] = df['macd_dea'].shift(1) return (abs(df['macd_dea'][index]) < input_1) & \ (abs(df['macd_dif'][index]) < input_1) & \ (df['macd_dif'][-input_3:].min() < input_2) & \ (df['macd_dif'][index] > df['macd_dea'][index]) & \ ((df['macd_dea_1'][index] > df['macd_dif_1'][index]) | (abs(df['macd_dea_1'][index] - df['macd_dif_1'][index]) < 0.007))
Example #11
Source File: ABuNDMacd.py From abu with GNU General Public License v3.0 | 6 votes |
def _calc_macd_from_ta(price, fast_period=12, slow_period=26, signal_period=9): """ 使用talib计算macd, 即透传talib.MACD计算结果 :param price: 收盘价格序列,pd.Series或者np.array :param fast_period: 快的加权移动均线线, 默认12,即EMA12 :param slow_period: 慢的加权移动均线, 默认26,即EMA26 :param signal_period: dif的指数移动平均线,默认9 """ import talib if isinstance(price, pd.Series): price = price.values dif, dea, bar = talib.MACD(price, fastperiod=fast_period, slowperiod=slow_period, signalperiod=signal_period) return dif, dea, bar
Example #12
Source File: new_strategy.py From pyfx with MIT License | 6 votes |
def annotate_data(self, feed, timeframe): # Get SMAs for k, v in six.iteritems(self.sma_intervals): feed[k] = talib.SMA(feed['closeMid'].values, v) # Get MACD # NOTE: talib.MACD() returns (macd, signal, hist) feed['macd'], _, feed['macd_hist'] = talib.MACD( feed['closeMid'].values, fastperiod=12, slowperiod=26, signalperiod=9 ) # Get RSI feed['rsi'] = talib.RSI(feed['closeMid'].values) return feed
Example #13
Source File: Filter_Stock_CHN.py From StockRecommendSystem with MIT License | 6 votes |
def macd_rule(df, index = -1): try: if not {'macd_dif', 'macd_dea', 'macd'}.issubset(df.columns): df = MACD(df) except Exception as e: print(e) return False input_1 = -3 input_2 = 0.05 # df['macd_dif_1'] = df['macd_dif'].shift(1) # df['macd_dea_1'] = df['macd_dea'].shift(1) #(df['macd_dif'][-input_3:].min() < input_2) & \ return (df['macd_dif'][index] > input_1) & \ (df['macd_dif'][index] < input_2) & \ (df['macd_dif'][index] > df['macd_dea'][index]) & \ ((df['macd_dea'][index-1] > df['macd_dif'][index-1]) | (abs(df['macd_dea'][index-1] - df['macd_dif'][index-1]) < 0.007))
Example #14
Source File: macd.py From equant with GNU General Public License v2.0 | 6 votes |
def handle_data(context): # 等待数据就绪,否则计算果结为异常值 if len(Close()) < slow + back - 1: return # 计算MACD diff, dea, macd = talib.MACD(Close(), fast, slow, back) # 突破下单 if MarketPosition() != 1 and macd[-1] > macd_dx: Buy(qty, Open()[-1]) elif MarketPosition() != -1 and macd[-1] < -macd_dx: SellShort(qty, Open()[-1]) # 绘制MACD曲线 PlotStickLine('macd', 0, macd[-1], RGB_Red() if macd[-1] > 0 else RGB_Blue(), False, False) PlotNumeric('diff', diff[-1], RGB_Red(), False, False) PlotNumeric('dea', dea[-1], RGB_Blue(), False, False) # 绘制盈亏曲线 PlotNumeric("profit", NetProfit() + FloatProfit() - TradeCost(), 0xcccccc, False, True)
Example #15
Source File: test_reg.py From finta with GNU Lesser General Public License v3.0 | 5 votes |
def test_macd(): """test MACD""" macd = TA.MACD(ohlc) talib_macd = talib.MACD(ohlc['close']) assert round(talib_macd[0][-1], 3) == round(macd["MACD"].values[-1], 3) assert round(talib_macd[1][-1], 3) == round(macd["SIGNAL"].values[-1], 3)
Example #16
Source File: macd.py From InplusTrader_Linux with MIT License | 5 votes |
def init(context): context.s1 = "000001.XSHE" # 使用MACD需要设置长短均线和macd平均线的参数 context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 100 # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
Example #17
Source File: macd.py From InplusTrader_Linux with MIT License | 5 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! # 读取历史数据,使用sma方式计算均线准确度和数据长度无关,但是在使用ema方式计算均线时建议将历史数据窗口适当放大,结果会更加准确 prices = history_bars(context.s1, context.OBSERVATION,'1d','close') # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd, signal 和 hist macd, signal, hist = talib.MACD(prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD) plot("macd", macd[-1]) plot("macd signal", signal[-1]) # macd 是长短均线的差值,signal是macd的均线,使用macd策略有几种不同的方法,我们这里采用macd线突破signal线的判断方法 # 如果macd从上往下跌破macd_signal if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0: # 计算现在portfolio中股票的仓位 curPosition = context.portfolio.positions[context.s1].quantity #进行清仓 if curPosition > 0: order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0: # 满仓入股 order_target_percent(context.s1, 1)
Example #18
Source File: test_f_macd.py From InplusTrader_Linux with MIT License | 5 votes |
def init(context): # context内引入全局变量s1,存储目标合约信息 context.s1 = "IF88" # 使用MACD需要设置长短均线和macd平均线的参数 context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 50 # 初始化时订阅合约行情。订阅之后的合约行情会在handle_bar中进行更新 subscribe(context.s1) # 你选择的期货数据更新将会触发此段逻辑,例如日线或分钟线更新
Example #19
Source File: DySS_MacdBottomDeviation.py From DevilYuan with MIT License | 5 votes |
def _macd(self, df, indicator='close'): values = df[indicator] try: diff, dea, bar = talib.MACD(values.values, fastperiod=12, slowperiod=26, signalperiod=9) bar *= 2 except Exception as ex: return None, None, None return diff, dea, bar
Example #20
Source File: IF_macd.py From InplusTrader_Linux with MIT License | 5 votes |
def init(context): # context内引入全局变量s1,存储目标合约信息 context.s1 = 'IF1606' # 使用MACD需要设置长短均线和macd平均线的参数 context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 50 # 初始化时订阅合约行情。订阅之后的合约行情会在handle_bar中进行更新 subscribe(context.s1) # 你选择的期货数据更新将会触发此段逻辑,例如日线或分钟线更新
Example #21
Source File: macd.py From InplusTrader_Linux with MIT License | 5 votes |
def init(context): context.s1 = "000001.XSHE" # 使用MACD需要设置长短均线和macd平均线的参数 context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 100 # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
Example #22
Source File: DySS_MacdBottomDeviation.py From DevilYuan with MIT License | 5 votes |
def __init__(self, param, info): super().__init__(param, info) # unpack parameters self._baseDate = param['基准日期'] self._macdIndicator = param['MACD指标'] self._extremaWindow = param['极值窗口'] self._bottomDeviationNbr = param['底背离次数'] self._crossOver = True if param['金叉'] else False
Example #23
Source File: macd.py From InplusTrader_Linux with MIT License | 5 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! # 读取历史数据,使用sma方式计算均线准确度和数据长度无关,但是在使用ema方式计算均线时建议将历史数据窗口适当放大,结果会更加准确 prices = history_bars(context.s1, context.OBSERVATION, '1m', 'close') # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd, signal 和 hist macd, signal, hist = talib.MACD(prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD) plot("macd", macd[-1]) plot("macd signal", signal[-1]) # macd 是长短均线的差值,signal是macd的均线,使用macd策略有几种不同的方法,我们这里采用macd线突破signal线的判断方法 # 如果macd从上往下跌破macd_signal if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0: # 计算现在portfolio中股票的仓位 curPosition = context.portfolio.positions[context.s1].quantity # 进行清仓 if curPosition > 0: order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0: # 满仓入股 order_target_percent(context.s1, 1)
Example #24
Source File: Strategy_fun.py From BakTst_Org with Apache License 2.0 | 5 votes |
def macd(data,index): close_arry = tranform_arry(data['close']) macd, macdsignal, macdhist = talib.MACD(close_arry, fastperiod=12, slowperiod=26, signalperiod=9) index['macd'] = {'macd':macd,'macdsignal':macdsignal,'macdhist':macdhist}
Example #25
Source File: talib_wrapper.py From tia with BSD 3-Clause "New" or "Revised" License | 5 votes |
def MACD(series, fast=12, slow=26, signal=9): return _series_to_frame(series, ['MACD', 'MACD_SIGNAL', 'MACD_HIST'], talib.MACD, fast, slow, signal)
Example #26
Source File: TinyStrateMACD.py From futuquant with Apache License 2.0 | 5 votes |
def on_bar_min1(self, tiny_bar): """每一分钟触发一次回调""" symbol = self.symbol_pools[0] now = datetime.datetime.now() work_time = now.replace(hour=15, minute=55, second=0) if now == work_time: quote_ctx = OpenQuoteContext(host='172.24.31.139', port=11111) data = tiny_bar price = data.open start_day = (now - datetime.timedelta(days=100)).strftime('%Y-%m-%d') end_day = now.strftime('%Y-%m-%d') history_result, history_kline_result = quote_ctx.get_history_kline(symbol, start=start_day, end=end_day) result, kline_result = quote_ctx.get_history_kline(symbol, start=start_day, end=end_day, ktype='K_5M') if history_result == 0 and result == 0 and history_kline_result.shape[0] >= 25 and kline_result.shape[0] > 0 : close_price = kline_result[-1:] close_price_array = history_kline_result['close'] close_price_array.append(close_price) df = pd.DataFrame() df['EMA12'] = talib.EMA(np.array(close_price_array), timeperiod=6) df['EMA26'] = talib.EMA(np.array(close_price_array), timeperiod=12) df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(np.array(close_price_array), fastperiod=6, slowperiod=12, signalperiod=9) signal = df['MACDsignal'][-1:].values[0] if signal > 0: self.do_trade(symbol, price, "buy") elif signal <0: self.do_trade(symbol, price, "sell") quote_ctx = OpenQuoteContext(host='172.24.31.139', port=11111)
Example #27
Source File: TinyQuantBase.py From futuquant with Apache License 2.0 | 5 votes |
def macd(self, fastPeriod, slowPeriod, signalPeriod, array=False): """MACD指标""" macd, signal, hist = talib.MACD(self.close, fastPeriod, slowPeriod, signalPeriod) if array: return macd, signal, hist return macd[-1], signal[-1], hist[-1] # ----------------------------------------------------------------------
Example #28
Source File: IF_macd.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def init(context): # context内引入全局变量s1,存储目标合约信息 context.s1 = 'IF1606' # 使用MACD需要设置长短均线和macd平均线的参数 context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 50 # 初始化时订阅合约行情。订阅之后的合约行情会在handle_bar中进行更新 subscribe(context.s1) # 你选择的期货数据更新将会触发此段逻辑,例如日线或分钟线更新
Example #29
Source File: macd.py From InplusTrader_Linux with MIT License | 5 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! # 读取历史数据,使用sma方式计算均线准确度和数据长度无关,但是在使用ema方式计算均线时建议将历史数据窗口适当放大,结果会更加准确 prices = history_bars(context.s1, context.OBSERVATION,'1d','close') # 用Talib计算MACD取值,得到三个时间序列数组,分别为macd, signal 和 hist macd, signal, hist = talib.MACD(prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD) plot("macd", macd[-1]) plot("macd signal", signal[-1]) # macd 是长短均线的差值,signal是macd的均线,使用macd策略有几种不同的方法,我们这里采用macd线突破signal线的判断方法 # 如果macd从上往下跌破macd_signal if macd[-1] - signal[-1] < 0 and macd[-2] - signal[-2] > 0: # 计算现在portfolio中股票的仓位 curPosition = context.portfolio.positions[context.s1].quantity #进行清仓 if curPosition > 0: order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if macd[-1] - signal[-1] > 0 and macd[-2] - signal[-2] < 0: # 满仓入股 order_target_percent(context.s1, 1)
Example #30
Source File: macd.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def init(context): context.s1 = "000001.XSHE" # 使用MACD需要设置长短均线和macd平均线的参数 context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 100 # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新