期货双均线
由bqppsd5s创建,最终由bqppsd5s 被浏览 7 用户
from bigmodule import M
# <aistudiograph>
# @module(comment="1. 输入特征:计算双均线及120日趋势过滤信号")
m1 = M.input_features_dai.v30(
mode="表达式",
expr="""
m_avg(close,10) as short_ma,
m_avg(close,30) as long_ma,
m_avg(close,120) as trend_ma,
close > m_avg(close,120) as is_uptrend,
m_lag(short_ma, 1) <= m_lag(long_ma, 1) and short_ma > long_ma as golden_cross,
m_lag(short_ma, 1) >= m_lag(long_ma, 1) and short_ma < long_ma as death_cross
""",
# 将参数定义直接放在模块内部
expr_filters="instrument in ({{instruments}})",
instruments={'name': '合约代码', 'default': 'RB888', 'type': '字符串', 'description': '期货合约代码,多个用英文逗号分隔,如:RB888, AG888'},
expr_tables="cn_futures_prefactors",
extra_fields="date,instrument",
order_by="date, instrument",
expr_drop_na=True,
extract_data=False,
m_name="m1"
)
# @module(comment="2. 抽取回测区间数据")
m4 = M.extract_data_dai.v20(
sql=m1.data,
# 将参数定义直接放在模块内部
start_date={'name': '开始日期', 'default': '2023-01-01', 'type': '字符串'},
end_date={'name': '结束日期', 'default': '2023-12-31', 'type': '字符串'},
start_date_bound_to_trading_date=True,
end_date_bound_to_trading_date=True,
before_start_days=200,
m_name="m4"
)
# @module(comment="3. 初始化:设置期货手续费")
def m3_initialize_bigquant_run(context):
from bigtrader.finance.commission import PerOrder
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# @module(comment="4. 每日处理:执行交易信号")
def m3_handle_data_bigquant_run(context, data):
if not context.rebalance_period.is_signal_date(data.current_dt.date()):
return
today_df = context.data[context.data["date"] == data.current_dt.strftime("%Y-%m-%d")]
if len(today_df) == 0:
return
positions = context.get_account_positions()
for stock in context.instruments:
hold_num = positions\[stock\].current_qty if stock in positions else 0
try:
golden_cross = bool(today_df\[today_df\["instrument"\] == stock\].golden_cross.values\[0\])
death_cross = bool(today_df\[today_df\["instrument"\] == stock\].death_cross.values\[0\])
is_uptrend = bool(today_df\[today_df\["instrument"\] == stock\].is_uptrend.values\[0\])
except:
continue
weight = 1.0 / len(context.instruments)
if golden_cross and is_uptrend and hold_num == 0:
context.order_target_percent(stock, weight)
print(f"{data.current_dt.date()} 开多 {stock}")
if death_cross and hold_num > 0:
context.order_target_percent(stock, 0)
print(f"{data.current_dt.date()} 平多 {stock}")
# @module(comment="5. 回测引擎:期货模式")
m3 = M.bigtrader.v43(
data=m4.data,
start_date="",
end_date="",
initialize=m3_initialize_bigquant_run,
handle_data=m3_handle_data_bigquant_run,
capital_base=1000000,
frequency="daily",
product_type="期货",
rebalance_period_type="交易日",
rebalance_period_days="1",
order_price_field_buy="open",
order_price_field_sell="open",
benchmark="",
plot_charts=True,
debug=False,
m_name="m3"
)
# </aistudiograph>