版本 v1.0
### MACD策略的交易规则
### 策略构建步骤
### 策略的实现
相关指标定义如下:
DIF=EMA(close,12)−EMA(close,26)
DEM=EMA(DIF,9)
DIF从下而上穿过DEA,买入开仓;
可视化策略实现如下:
# 本代码由可视化策略环境自动生成 2021年12月6日 22:50
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m4_run_bigquant_run(input_1, input_2, input_3,before_days):
# 示例代码如下。在这里编写您的代码
start_date=(pd.to_datetime(input_1.read_pickle()['start_date']) - datetime.timedelta(days=before_days)).strftime('%Y-%m-%d')
end_date=input_1.read_pickle()['end_date']
instruments=input_1.read_pickle()['instruments']
fields=['open','high','low','close']
df = DataSource('bar1d_CN_FUTURE').read(instruments,start_date,end_date,fields)
df['adjust_factor']=1.0
data_1 = DataSource.write_df(df)
return Outputs(data_1=data_1, data_2=None, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m4_post_run_bigquant_run(outputs):
return outputs
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m1_run_bigquant_run(input_1, input_2, input_3):
# 示例代码如下。在这里编写您的代码
df = input_1.read_df()
close = [float(x) for x in df['close']]
import talib
# 调用talib计算6日指数移动平均线的值
df['EMA12'] = talib.EMA(np.array(close), timeperiod=6)
df['EMA26'] = talib.EMA(np.array(close), timeperiod=12)
# 调用talib计算MACD指标
df['DIF'],df['DEA'],df['MACD'] = talib.MACD(np.array(close),
fastperiod=6, slowperiod=12, signalperiod=9)
data_1 = DataSource.write_df(df)
return Outputs(data_1=data_1, data_2=None, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m1_post_run_bigquant_run(outputs):
return outputs
# 回测引擎:初始化函数,只执行一次
def m3_initialize_bigquant_run(context):
# 设置是否是结算模式
context.set_need_settle(False)
# 设置最大杠杆
context.set_max_leverage(1, 'fill_amap')
# 回测引擎:每日数据处理函数,每天执行一次
def m3_handle_data_bigquant_run(context, data):
# 获取当日多头/空头信号数据
today = data.current_dt.strftime('%Y-%m-%d') # 当前交易日期
try:
buy_condition = context.buy_condition[today]
except:
buy_condition = 0
try:
sell_condition = context.sell_condition[today]
except:
sell_condition = 0
instrument = context.future_symbol(context.instruments[0]) # 交易标的
curr_po=context.portfolio.positions[instrument] # 组合持仓
curr_position = curr_po.amount # 持仓数量
# 交易逻辑
if sell_condition>0: # 卖出开仓
if curr_position >= 0 and data.can_trade(instrument):
order_target(instrument, -20)
print(today,'今日DIF下穿DEA,平多,卖空开仓')
elif buy_condition>0:# 买入开仓
if curr_position <= 0 and data.can_trade(instrument):
order_target(instrument, 20)
print(today,'今日DIF上穿DEA,平空,买多开仓')
# 回测引擎:准备数据,只执行一次
def m3_prepare_bigquant_run(context):
df = context.options['data'].read_df()
df['date']=df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
df.set_index('date',inplace=True)
context.buy_condition=df['buy_condition']
context.sell_condition=df['sell_condition']
# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
def m3_before_trading_start_bigquant_run(context, data):
pass
m2 = M.instruments.v2(
start_date='2017-11-01',
end_date='2018-05-01',
market='CN_FUTURE',
instrument_list='RU1809.SHF',
max_count=0
)
m4 = M.cached.v3(
input_1=m2.data,
run=m4_run_bigquant_run,
post_run=m4_post_run_bigquant_run,
input_ports='',
params='{\'before_days\':60}',
output_ports=''
)
m1 = M.cached.v3(
input_1=m4.data_1,
run=m1_run_bigquant_run,
post_run=m1_post_run_bigquant_run,
input_ports='',
params='{}',
output_ports=''
)
m6 = M.input_features.v1(
features="""
# #号开始的表示注释
# 多个特征,每行一个,可以包含基础特征和衍生特征
buy_condition=where((shift(DIF,1)>shift(DEA,1))&(shift(DIF,2)<shift(DEA,2)),1,0)
sell_condition=where((shift(DIF,1)<shift(DEA,1))&(shift(DIF,2)>shift(DEA,2)),1,0)"""
)
m5 = M.derived_feature_extractor.v3(
input_data=m1.data_1,
features=m6.data,
date_col='date',
instrument_col='instrument',
drop_na=False,
remove_extra_columns=False,
user_functions={}
)
m7 = M.dropnan.v1(
input_data=m5.data
)
m3 = M.trade.v4(
instruments=m2.data,
options_data=m7.data,
start_date='',
end_date='',
initialize=m3_initialize_bigquant_run,
handle_data=m3_handle_data_bigquant_run,
prepare=m3_prepare_bigquant_run,
before_trading_start=m3_before_trading_start_bigquant_run,
volume_limit=0,
order_price_field_buy='open',
order_price_field_sell='open',
capital_base=1000000,
auto_cancel_non_tradable_orders=True,
data_frequency='daily',
price_type='后复权',
product_type='期货',
plot_charts=True,
backtest_only=False,
benchmark='000300.HIX'
)