版本 v1.0
### 多头排列回踩均线选股策略的交易规则
### 策略构建步骤
### 策略的实现
可视化策略实现如下:
# 本代码由可视化策略环境自动生成 2023年1月11日 18:41
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
# 回测引擎:初始化函数,只执行一次
def m3_initialize_bigquant_run(context):
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
context.stock_max_num = 20 # 最多同时持有20只股票
# 回测引擎:每日数据处理函数,每天执行一次
def m3_handle_data_bigquant_run(context, data):
# 回测引擎:每日数据处理函数,每天执行一次
today = data.current_dt.strftime('%Y-%m-%d') # 日期
# 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值
stock_hold_now = {e.symbol: p.amount * p.last_sale_price
for e, p in context.perf_tracker.position_tracker.positions.items()}
hold_num=len(stock_hold_now)
# 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;
# 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
cash_for_buy = context.portfolio.cash
# 获取当日符合买入/卖出条件的股票列表
try:
buy_stock = context.daily_stock_buy[today] # 当日符合买入条件的股票
except:
buy_stock=[]
try:
sell_stock = context.daily_stock_sell[today] # 当日符合卖出条件的股票
except:
sell_stock = []
# 需要卖出的股票:已有持仓中符合卖出条件的股票
stock_to_sell = [i for i in stock_hold_now if i in sell_stock]
# 需要买入的股票:没有持仓且符合买入条件的股票
stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]
# 卖出
for instrument in stock_to_sell:
# 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
# 如果返回真值,则可以正常下单,否则会出错
# 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
if data.can_trade(context.symbol(instrument)):
# order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档
context.order_target_percent(context.symbol(instrument), 0)
# 因为设置的是早盘卖出早盘买入,需要根据卖出的股票更新可用现金;如果设置尾盘卖出早盘买入,则不需更新可用现金(可以删除下面的语句)
cash_for_buy += stock_hold_now[instrument]
hold_num-=1
# 当日还允许买入建仓的股票数目
stock_can_buy_num = context.stock_max_num - hold_num
stock_to_buy_num = min(stock_can_buy_num,len(stock_to_buy))
# 如果当天没有买入的股票,就返回
if stock_to_buy_num == 0:
return
# 记录已经买入的股票数量
buy_num = 0
for instrument in stock_to_buy:
# 使用当日可用现金等资金比例下单买入
cash = cash_for_buy / stock_to_buy_num
if data.can_trade(context.symbol(instrument)) and buy_num<stock_to_buy_num:
# 整百下单
current_price = data.current(context.symbol(instrument), 'price')
amount = math.floor(cash / current_price / 100) * 100
context.order(context.symbol(instrument), amount)
buy_num += 1
# 回测引擎:准备数据,只执行一次
def m3_prepare_bigquant_run(context):
# 加载预测数据
df = context.options['data'].read_df()
# 函数:求满足开仓条件的股票列表
def open_pos_con(df):
return list(df[df['buy_condition']>0].instrument)
# 函数:求满足平仓条件的股票列表
def close_pos_con(df):
return list(df[df['sell_condition']>0].instrument)
# 每日买入股票的数据框
context.daily_stock_buy= df.groupby('date').apply(open_pos_con)
# 每日卖出股票的数据框
context.daily_stock_sell= df.groupby('date').apply(close_pos_con)
m1 = M.input_features.v1(
features="""# #号开始的表示注释
# 多个特征,每行一个,可以包含基础特征和衍生特征
buy_condition=where((mean(close_0,5)>mean(close_0,10))&(mean(close_0,10)>mean(close_0,20))&(mean(close_0,20)>mean(close_0,40))&(mean(close_0,40)>mean(close_0,120))&(low_0<mean(close_0,10)),1,0)
sell_condition=where(mean(close_0,5)<mean(close_0,40),1,0)"""
)
m2 = M.instruments.v2(
start_date=T.live_run_param('trading_date', '2020-12-01'),
end_date=T.live_run_param('trading_date', '2022-2-01'),
market='CN_STOCK_A',
instrument_list='',
max_count=0
)
m7 = M.general_feature_extractor.v7(
instruments=m2.data,
features=m1.data,
start_date='',
end_date='',
before_start_days=300
)
m8 = M.derived_feature_extractor.v3(
input_data=m7.data,
features=m1.data,
date_col='date',
instrument_col='instrument',
drop_na=False,
remove_extra_columns=False
)
m4 = M.dropnan.v2(
input_data=m8.data
)
m3 = M.trade.v4(
instruments=m2.data,
options_data=m4.data,
start_date='',
end_date='',
initialize=m3_initialize_bigquant_run,
handle_data=m3_handle_data_bigquant_run,
prepare=m3_prepare_bigquant_run,
volume_limit=0.025,
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'
)
[2023-01-11 18:38:25.594681] INFO: moduleinvoker: input_features.v1 开始运行..
[2023-01-11 18:38:25.612247] INFO: moduleinvoker: 命中缓存
[2023-01-11 18:38:25.615431] INFO: moduleinvoker: input_features.v1 运行完成[0.020824s].
[2023-01-11 18:38:27.980419] INFO: moduleinvoker: instruments.v2 开始运行..
[2023-01-11 18:38:28.100852] INFO: moduleinvoker: instruments.v2 运行完成[0.120424s].
[2023-01-11 18:38:28.138347] INFO: moduleinvoker: general_feature_extractor.v7 开始运行..
[2023-01-11 18:38:32.413100] INFO: 基础特征抽取: 年份 2020, 特征行数=877512
[2023-01-11 18:38:36.083936] INFO: 基础特征抽取: 年份 2021, 特征行数=1061527
[2023-01-11 18:38:37.212498] INFO: 基础特征抽取: 年份 2022, 特征行数=89016
[2023-01-11 18:38:37.512639] INFO: 基础特征抽取: 总行数: 2028055
[2023-01-11 18:38:37.532992] INFO: moduleinvoker: general_feature_extractor.v7 运行完成[9.394678s].
[2023-01-11 18:38:37.584916] INFO: moduleinvoker: derived_feature_extractor.v3 开始运行..
[2023-01-11 18:39:01.854736] INFO: derived_feature_extractor: 提取完成 buy_condition=where((mean(close_0,5)>mean(close_0,10))&(mean(close_0,10)>mean(close_0,20))&(mean(close_0,20)>mean(close_0,40))&(mean(close_0,40)>mean(close_0,120))&(low_0[2023-01-11 18:39:05.374380] INFO: derived_feature_extractor: 提取完成 sell_condition=where(mean(close_0,5)[2023-01-11 18:39:07.168743] INFO: derived_feature_extractor: /y_2020, 877512[2023-01-11 18:39:09.539603] INFO: derived_feature_extractor: /y_2021, 1061527[2023-01-11 18:39:09.977722] INFO: derived_feature_extractor: /y_2022, 89016[2023-01-11 18:39:10.177651] INFO: moduleinvoker: derived_feature_extractor.v3 运行完成[32.592713s].[2023-01-11 18:39:10.199820] INFO: moduleinvoker: dropnan.v2 开始运行..[2023-01-11 18:39:12.184752] INFO: dropnan: /y_2020, 877512/877512[2023-01-11 18:39:14.387282] INFO: dropnan: /y_2021, 1061527/1061527[2023-01-11 18:39:14.613241] INFO: dropnan: /y_2022, 89016/89016[2023-01-11 18:39:14.725136] INFO: dropnan: 行数: 2028055/2028055[2023-01-11 18:39:14.733109] INFO: moduleinvoker: dropnan.v2 运行完成[4.533286s].[2023-01-11 18:39:20.013195] INFO: moduleinvoker: backtest.v8 开始运行..[2023-01-11 18:39:20.026560] INFO: backtest: biglearning backtest:V8.6.3[2023-01-11 18:39:26.501268] INFO: backtest: product_type:stock by specified[2023-01-11 18:39:26.678152] INFO: moduleinvoker: cached.v2 开始运行..[2023-01-11 18:39:38.635508] INFO: backtest: 读取股票行情完成:2444925[2023-01-11 18:39:42.206580] INFO: moduleinvoker: cached.v2 运行完成[15.528405s].[2023-01-11 18:39:56.381403] INFO: backtest: algo history_data=DataSource(2b0b5437718f4b78956f52b582801ec8T)[2023-01-11 18:39:56.383369] INFO: algo: TradingAlgorithm V1.8.9[2023-01-11 18:39:57.110237] INFO: algo: trading transform...[2023-01-11 18:40:10.418936] INFO: Performance: Simulated 285 trading days out of 285.[2023-01-11 18:40:10.421182] INFO: Performance: first open: 2020-12-01 09:30:00+00:00[2023-01-11 18:40:10.424560] INFO: Performance: last close: 2022-01-28 15:00:00+00:00[2023-01-11 18:40:14.266917] INFO: moduleinvoker: backtest.v8 运行完成[54.253684s].[2023-01-11 18:40:14.269210] INFO: moduleinvoker: trade.v4 运行完成[59.517227s].
m3.read_raw_perf().to_csv("多头排列回踩.csv")