def initialize(context):
# 设置标的(新增创业板股票需确认权限)
g.stocks = ['002043.XSHE', '002582.XSHE']
# 设置参数
g.ma_window = 20 # 均线周期
g.position_ratio = 0.5 # 单票仓位比例(分散风险)
# 设置手续费和滑点
set_order_cost(
OrderCost(
open_tax=0,
close_tax=0.001, # 印花税(仅卖出)
open_commission=0.0003,
close_commission=0.0003,
min_commission=5
),
type='stock'
)
set_slippage(FixedSlippage(0.01)) # 滑点1分钱
def handle_data(context, data):
# 获取当前时间
current_date = context.current_dt.date()
# 避免非交易日操作(如回测时)
if current_date.weekday() >= 5:
return
# 计算每个标的的均线
ma_dict = {}
for stock in g.stocks:
# 获取20日收盘价历史数据
hist = data.history(
stock,
'close',
bar_count=g.ma_window+1, # 多取1日用于计算前20日均线
frequency='1d'
)
# 计算20日均线(排除当日)
ma_dict[stock] = hist[:-1].mean()
# 分配可用资金
available_cash = context.portfolio.available_cash
cash_per_stock = available_cash * g.position_ratio
for stock in g.stocks:
current_price = data[stock].close
ma_price = ma_dict[stock]
position = context.portfolio.positions[stock].amount
# 买入条件:价格上穿均线且当前无持仓
if current_price > ma_price and position == 0:
# 计算可买数量(按现金比例)
shares = int(cash_per_stock // current_price)
if shares > 0:
order(stock, shares)
log.info(f"{current_date} 买入 {stock} {shares}股,价格{current_price:.2f}")
# 卖出条件:价格下穿均线且有持仓
elif current_price < ma_price and position > 0:
order_target(stock, 0)
log.info(f"{current_date} 卖出 {stock},价格{current_price:.2f}")
2025-02-15