以下是利用easytrader库,可在python环境中实现该交易策略示例的实操源码:
import easytraderimport talibimport numpy as np# 初始化easytraderuser = easytrader.use('ht')user.prepare('ht.json') # 根据自己的情况填写自己的信息# 获取历史数据hist_data = user.get_history_data('sh000001', 365)# 计算MACDema12 = talib.EMA(hist_data['close'].values, timeperiod=12)ema26 = talib.EMA(hist_data['close'].values, timeperiod=26)macd, signal, hist = talib.MACD(hist_data['close'].values, fastperiod=12, slowperiod=26, signalperiod=9)# 定义交易函数def trade(hist_data, ema12, ema26, macd, signal, position): current_close = hist_data['close'][-1] current_macd = macd[-1] current_signal = signal[-1] # 判断是否可以开仓或平仓 if (ema12[-1] > ema26[-1]) and (ema12[-2] <= ema26[-2]): # 突破EMA上穿 if position == 'short': # 如果是做空,则买入平仓 user.buy('sh000001', current_close, 100) # 假设买100股 position = 'none' elif position == 'none': # 如果未持仓,则买入开仓 user.buy('sh000001', current_close, 100) # 假设买100股 position = 'long' elif (ema12[-1] < ema26[-1]) and (ema12[-2] >= ema26[-2]): # 突破EMA下穿 if position == 'long': # 如果是做多,则卖出平仓 user.sell('sh000001', current_close, 100) # 假设卖100股 position = 'none' elif position == 'none': # 如果未持仓,则卖出开仓 user.sell('sh000001', current_close, 100) position = 'short' # 判断是否保持持仓 elif current_macd > current_signal and position == 'long': # MACD高于信号线保持多仓 pass elif current_macd < current_signal and position == 'short': # MACD低于信号线保持空仓 pass else: # 其他情况则平仓 if position == 'long': user.sell('sh000001', current_close, 100) position = 'none' elif position == 'short': user.buy('sh000001', current_close, 100) position = 'none' return position# 开始交易position = 'none' # 初始化持仓for i in range(len(hist_data)): position = trade(hist_data[:i+1], ema12[:i+1], ema26[:i+1], macd[:i+1], signal[:i+1], position)
该代码使用了easytrader库中的buy和sell函数进行交易,get_history_data函数获取了过去一年的历史数据,MACD指标使用了talib库进行计算。在交易函数中,判断了突破EMA上穿和下穿的情况,并使用了current_macd和current_signal判断是否保持持仓。最后在交易循环中调用了该交易函数。
联系客服