# 本代码由可视化策略环境自动生成 2023年6月24日 18:48
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m5_run_bigquant_run(input_1, input_2, input_3):
df = input_1.read()
data_1 = DataSource.write_df(df)
return Outputs(data_1=data_1, data_2=None, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m5_post_run_bigquant_run(outputs):
return outputs
# 回测引擎:初始化函数,只执行一次
def m7_initialize_bigquant_run(context):
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
# 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
stock_count = 10
# 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
context.stock_weights = 0.1
# 设置每只股票占用的最大资金比例
context.max_cash_per_instrument = 0.1
context.options['hold_days'] = 10
# 回测引擎:每日数据处理函数,每天执行一次
def m7_handle_data_bigquant_run(context, data):
# 按日期过滤得到今日的预测数据
df = context.options['data'].read_df()
print("------------------")
cur_date = data.current_dt.strftime('%Y-%m-%d')
df = df[df['date'] == cur_date]
instruments = np.array(df['instrument']).tolist()
print(instruments)
# 读取数据 默认会返回全部证券代码数据, 通过指定参数 instruments 可以读取到指定的证券代码数据
df = DataSource("market_value_CN_STOCK_A").read(instruments=instruments,start_date=cur_date, end_date=cur_date)
#按最后1列的值从小到大排序
df.sort_values(by='market_cap',ascending=True,inplace=True)
print("==============df2==================")
print(df.instrument[:20])
# 1. 资金分配
# 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
# 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
cash_avg = context.portfolio.portfolio_value / context.options['hold_days']
cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
positions = {e.symbol: p.amount * p.last_sale_price
for e, p in context.portfolio.positions.items()}
# 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
if not is_staging and cash_for_sell > 0:
equities = {e.symbol: e for e, p in context.portfolio.positions.items()}
instruments = list(reversed(list(df.instrument[df.instrument.apply(
lambda x: x in equities)])))
for instrument in instruments:
context.order_target(context.symbol(instrument), 0)
cash_for_sell -= positions[instrument]
if cash_for_sell <= 0:
break
# 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
buy_cash_weights = context.stock_weights
buy_instruments = list(df.instrument[:20])
portfolio_value = context.portfolio.portfolio_value
max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
for i, instrument in enumerate(buy_instruments):
cash = portfolio_value - context.portfolio.positions_value # 可用资金 账户总价值 - 持仓市值
if( cash > portfolio_value * buy_cash_weights ):
#sid = context.symbol(instrument) # 将标的转化为equity格式
if data.can_trade(context.symbol(instrument)):
context.order_target_percent(context.symbol(instrument), buy_cash_weights) # 买入
#------------------------------------------止赢模块START--------------------------------------------
positions = {e.symbol: p.cost_basis for e, p in context.portfolio.positions.items()}
# 新建当日止赢股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
current_stopwin_stock = []
if len(positions) > 0:
for i in positions.keys():
stock_cost = positions[i]
stock_market_price = data.current(context.symbol(i), 'price')
# 赚10%就止赢
if (stock_market_price - stock_cost ) / stock_cost>= 0.3:
context.order_target_percent(context.symbol(i),0)
current_stopwin_stock.append(i)
print('日期:',cur_date,'股票:',i,'出现止盈状况')
#-------------------------------------------止赢模块END---------------------------------------------
#------------------------------------------止损模块START--------------------------------------------
positions = {e.symbol: p.cost_basis for e, p in context.portfolio.positions.items()}
# 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
current_stoploss_stock = []
if len(positions) > 0:
for i in positions.keys():
stock_cost = positions[i]
stock_market_price = data.current(context.symbol(i), 'price')
# 亏5%就止损
if (stock_market_price - stock_cost) / stock_cost <= -0.03:
context.order_target_percent(context.symbol(i),0)
current_stoploss_stock.append(i)
print('日期:',cur_date,'股票:',i,'出现止损状况')
#-------------------------------------------止损模块END---------------------------------------------
#------------------------------------------止损模块START--------------------------------------------
equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
# 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
current_stoploss_stock = []
if len(equities) > 0:
for i in equities.keys():
stock_market_price = data.current(context.symbol(i), 'price') # 最新市场价格
last_sale_date = equities[i].last_sale_date # 上次交易日期
delta_days = data.current_dt - last_sale_date
hold_days = delta_days.days # 持仓天数
# 建仓以来的最高价
highest_price_since_buy = data.history(context.symbol(i), 'high', hold_days, '1d').max()
# 确定止损位置
stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.05
record('止损位置', stoploss_line)
# 如果价格下穿止损位置
if stock_market_price < stoploss_line:
context.order_target_percent(context.symbol(i), 0)
current_stoploss_stock.append(i)
print('日期:', cur_date , '股票:', i, '出现止损状况')
#-------------------------------------------止损模块END--------------------------------------------------
# 回测引擎:准备数据,只执行一次
def m7_prepare_bigquant_run(context):
pass
m6 = M.datahub_load_datasource.v1(
table='bar1d_CN_STOCK_A',
start_date='2022-06-01',
end_date='2023-06-15',
instruments="""# #号开始的表示注释,注释需单独一行
# 每行一条
""",
fields="""# #号开始的表示注释,注释需单独一行
# 每行一条
"""
)
m3 = M.chinaa_stock_filter.v1(
input_data=m6.data,
index_constituent_cond=['中证500'],
board_cond=['全部', '上证主板', '深证主板', '创业板', '科创板'],
industry_cond=['全部'],
st_cond=['正常'],
delist_cond=['非退市'],
output_left_data=False
)
m5 = M.cached.v3(
input_1=m3.data,
run=m5_run_bigquant_run,
post_run=m5_post_run_bigquant_run,
input_ports='',
params='{}',
output_ports=''
)
m2 = M.instruments.v2(
start_date='2022-06-01',
end_date='2023-06-15',
market='CN_STOCK_A',
instrument_list="""000009.SZA
000012.SZA
000021.SZA
000027.SZA
000031.SZA
000039.SZA
000050.SZA
000060.SZA
000066.SZA
000089.SZA
000155.SZA
000156.SZA
000400.SZA
000401.SZA
000402.SZA
000415.SZA
000423.SZA
000513.SZA
000519.SZA
000537.SZA
000547.SZA
000553.SZA
000559.SZA
000563.SZA
000581.SZA
000591.SZA
000598.SZA
000623.SZA
000629.SZA
000630.SZA
000636.SZA
000683.SZA
000703.SZA
000709.SZA
000728.SZA
000729.SZA
000738.SZA
000739.SZA
000750.SZA
000778.SZA
000783.SZA
000785.SZA
000807.SZA
000825.SZA
000830.SZA
000831.SZA
000869.SZA
000878.SZA
000883.SZA
000887.SZA
000893.SZA
000898.SZA
000930.SZA
000932.SZA
000933.SZA
000937.SZA
000958.SZA
000959.SZA
000960.SZA
000967.SZA
000970.SZA
000975.SZA
000987.SZA
000988.SZA
000997.SZA
000998.SZA
001203.SZA
001227.SZA
001872.SZA
001914.SZA
002008.SZA
002010.SZA
002019.SZA
002025.SZA
002028.SZA
002030.SZA
002032.SZA
002056.SZA
002065.SZA
002078.SZA
002080.SZA
002081.SZA
002092.SZA
002110.SZA
002128.SZA
002131.SZA
002138.SZA
002152.SZA
002153.SZA
002155.SZA
002156.SZA
002183.SZA
002185.SZA
002192.SZA
002195.SZA
002203.SZA
002221.SZA
002223.SZA
002240.SZA
002244.SZA
002249.SZA
002250.SZA
002266.SZA
002268.SZA
002273.SZA
002281.SZA
002294.SZA
002299.SZA
002326.SZA
002340.SZA
002353.SZA
002368.SZA
002372.SZA
002373.SZA
002384.SZA
002385.SZA
002399.SZA
002407.SZA
002408.SZA
002409.SZA
002422.SZA
002423.SZA
002429.SZA
002430.SZA
002432.SZA
002439.SZA
002444.SZA
002463.SZA
002465.SZA
002468.SZA
002487.SZA
002497.SZA
002500.SZA
002505.SZA
002506.SZA
002507.SZA
002508.SZA
002511.SZA
002518.SZA
002531.SZA
002532.SZA
002557.SZA
002563.SZA
002568.SZA
002572.SZA
002595.SZA
002600.SZA
002608.SZA
002624.SZA
002625.SZA
002653.SZA
002670.SZA
002673.SZA
002683.SZA
002690.SZA
002705.SZA
002738.SZA
002739.SZA
002745.SZA
002761.SZA
002791.SZA
002797.SZA
002831.SZA
002850.SZA
002867.SZA
002901.SZA
002925.SZA
002926.SZA
002936.SZA
002939.SZA
002945.SZA
002958.SZA
002966.SZA
002985.SZA
003035.SZA
300001.SZA
300003.SZA
300009.SZA
300012.SZA
300017.SZA
300024.SZA
300026.SZA
300037.SZA
300058.SZA
300070.SZA
300073.SZA
300088.SZA
300115.SZA
300118.SZA
300136.SZA
300144.SZA
300146.SZA
300182.SZA
300212.SZA
300244.SZA
300251.SZA
300253.SZA
300257.SZA
300285.SZA
300296.SZA
300308.SZA
300357.SZA
300363.SZA
300373.SZA
300383.SZA
300390.SZA
300395.SZA
300418.SZA
300438.SZA
300442.SZA
300474.SZA
300482.SZA
300487.SZA
300529.SZA
300558.SZA
300568.SZA
300595.SZA
300604.SZA
300618.SZA
300676.SZA
300677.SZA
300682.SZA
300699.SZA
300724.SZA
300741.SZA
300748.SZA
300776.SZA
300832.SZA
300850.SZA
300861.SZA
300866.SZA
300888.SZA
301029.SZA
600008.SHA
600021.SHA
600022.SHA
600027.SHA
600032.SHA
600038.SHA
600056.SHA
600060.SHA
600062.SHA
600066.SHA
600079.SHA
600095.SHA
600096.SHA
600109.SHA
600118.SHA
600126.SHA
600131.SHA
600141.SHA
600143.SHA
600153.SHA
600155.SHA
600157.SHA
600160.SHA
600161.SHA
600166.SHA
600167.SHA
600170.SHA
600171.SHA
600177.SHA
600195.SHA
600208.SHA
600258.SHA
600259.SHA
600271.SHA
600282.SHA
600297.SHA
600298.SHA
600299.SHA
600315.SHA
600316.SHA
600325.SHA
600329.SHA
600339.SHA
600348.SHA
600350.SHA
600352.SHA
600369.SHA
600372.SHA
600373.SHA
600377.SHA
600378.SHA
600380.SHA
600390.SHA
600392.SHA
600398.SHA
600399.SHA
600409.SHA
600415.SHA
600416.SHA
600418.SHA
600435.SHA
600481.SHA
600482.SHA
600486.SHA
600487.SHA
600489.SHA
600497.SHA
600498.SHA
600499.SHA
600500.SHA
600507.SHA
600511.SHA
600516.SHA
600517.SHA
600521.SHA
600528.SHA
600529.SHA
600535.SHA
600536.SHA
600546.SHA
600549.SHA
600556.SHA
600563.SHA
600566.SHA
600580.SHA
600582.SHA
600597.SHA
600598.SHA
600623.SHA
600637.SHA
600642.SHA
600655.SHA
600663.SHA
600667.SHA
600673.SHA
600699.SHA
600704.SHA
600705.SHA
600707.SHA
600718.SHA
600737.SHA
600739.SHA
600755.SHA
600764.SHA
600765.SHA
600782.SHA
600801.SHA
600808.SHA
600820.SHA
600827.SHA
600839.SHA
600848.SHA
600859.SHA
600862.SHA
600863.SHA
600867.SHA
600871.SHA
600873.SHA
600879.SHA
600885.SHA
600895.SHA
600901.SHA
600906.SHA
600909.SHA
600927.SHA
600928.SHA
600956.SHA
600959.SHA
600967.SHA
600968.SHA
600970.SHA
600985.SHA
600988.SHA
600995.SHA
600998.SHA
601000.SHA
601005.SHA
601016.SHA
601058.SHA
601077.SHA
601098.SHA
601106.SHA
601108.SHA
601118.SHA
601128.SHA
601136.SHA
601139.SHA
601156.SHA
601158.SHA
601162.SHA
601168.SHA
601179.SHA
601187.SHA
601198.SHA
601228.SHA
601231.SHA
601233.SHA
601298.SHA
601456.SHA
601555.SHA
601568.SHA
601577.SHA
601598.SHA
601608.SHA
601611.SHA
601636.SHA
601665.SHA
601666.SHA
601696.SHA
601717.SHA
601718.SHA
601778.SHA
601828.SHA
601866.SHA
601869.SHA
601880.SHA
601928.SHA
601958.SHA
601966.SHA
601969.SHA
601990.SHA
601991.SHA
601992.SHA
601997.SHA
603000.SHA
603026.SHA
603056.SHA
603077.SHA
603127.SHA
603156.SHA
603160.SHA
603218.SHA
603225.SHA
603228.SHA
603233.SHA
603267.SHA
603317.SHA
603338.SHA
603355.SHA
603379.SHA
603444.SHA
603456.SHA
603517.SHA
603529.SHA
603568.SHA
603589.SHA
603596.SHA
603638.SHA
603650.SHA
603658.SHA
603688.SHA
603707.SHA
603712.SHA
603737.SHA
603786.SHA
603816.SHA
603826.SHA
603858.SHA
603866.SHA
603868.SHA
603882.SHA
603883.SHA
603885.SHA
603893.SHA
603927.SHA
603939.SHA
605358.SHA
688002.SHA
688006.SHA
688009.SHA
688029.SHA
688052.SHA
688072.SHA
688082.SHA
688099.SHA
688105.SHA
688107.SHA
688116.SHA
688169.SHA
688185.SHA
688188.SHA
688200.SHA
688208.SHA
688220.SHA
688234.SHA
688248.SHA
688256.SHA
688276.SHA
688281.SHA
688289.SHA
688295.SHA
688301.SHA
688385.SHA
688390.SHA
688516.SHA
688520.SHA
688521.SHA
688536.SHA
688538.SHA
688567.SHA
688690.SHA
688772.SHA
688777.SHA
688778.SHA
688779.SHA
688819.SHA
689009.SHA
""",
max_count=0
)
m7 = M.trade.v4(
instruments=m2.data,
options_data=m5.data_1,
start_date='2022-06-01',
end_date='2023-06-21',
initialize=m7_initialize_bigquant_run,
handle_data=m7_handle_data_bigquant_run,
prepare=m7_prepare_bigquant_run,
volume_limit=0.025,
order_price_field_buy='open',
order_price_field_sell='close',
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-06-24 18:47:24.309640] INFO: 读取数据(DataSource): 读取数据 bar1d_CN_STOCK_A, count: 1277214
[2023-06-24 18:47:24.938205] INFO: 读取数据(DataSource): ds: DataSource(03354bf785e84aad847a3542f1d39a2dT)
[2023-06-24 18:47:24.946768] INFO: moduleinvoker: datahub_load_datasource.v1 运行完成[1.575736s].
[2023-06-24 18:47:24.952361] INFO: moduleinvoker: chinaa_stock_filter.v1 开始运行..
[2023-06-24 18:47:31.425645] INFO: A股股票过滤: 过滤 /data, 127474/0/1277214
[2023-06-24 18:47:31.429239] INFO: A股股票过滤: 过滤完成, 127474 + 0
[2023-06-24 18:47:31.452534] INFO: moduleinvoker: chinaa_stock_filter.v1 运行完成[6.500157s].
[2023-06-24 18:47:31.459954] INFO: moduleinvoker: cached.v3 开始运行..
[2023-06-24 18:47:31.828167] INFO: moduleinvoker: cached.v3 运行完成[0.368222s].
[2023-06-24 18:47:31.833022] INFO: moduleinvoker: instruments.v2 开始运行..
[2023-06-24 18:47:31.838449] INFO: moduleinvoker: 命中缓存
[2023-06-24 18:47:31.840013] INFO: moduleinvoker: instruments.v2 运行完成[0.006995s].
[2023-06-24 18:47:31.883122] INFO: moduleinvoker: backtest.v8 开始运行..
[2023-06-24 18:47:31.889126] INFO: backtest: biglearning backtest:V8.6.3
[2023-06-24 18:47:31.890908] INFO: backtest: product_type:stock by specified
[2023-06-24 18:47:31.961569] INFO: moduleinvoker: cached.v2 开始运行..
[2023-06-24 18:47:31.968184] INFO: moduleinvoker: 命中缓存
[2023-06-24 18:47:31.970503] INFO: moduleinvoker: cached.v2 运行完成[0.008955s].
[2023-06-24 18:47:34.451632] INFO: backtest: algo history_data=DataSource(af1d4446030d483399e6ff3b13463330T)
[2023-06-24 18:47:34.453392] INFO: algo: TradingAlgorithm V1.8.9
[2023-06-24 18:47:34.743593] INFO: algo: trading transform...
[2023-06-24 18:47:35.256934] ERROR: moduleinvoker: module name: backtest, module version: v8, trackeback: zipline.errors.SymbolNotFound: Symbol '600466.SHA' was not found.
[2023-06-24 18:47:35.260146] ERROR: moduleinvoker: module name: trade, module version: v4, trackeback: zipline.errors.SymbolNotFound: Symbol '600466.SHA' was not found.