start_date = '2016-01-01'
end_date = '2017-09-14'
instrument = D.instruments(start_date=start_date, end_date=end_date)
df =D.history_data(instrument, start_date, end_date, ['high', 'low','price_limit_status' ,'amount'])
raw_df = df[(df['price_limit_status']==3)&(df['high']==df['low'])&(df['amount']>=10000)] # 选出一字涨停的股票
result = raw_df.groupby('date').apply(lambda df: list(df['instrument'])) # 整理出每日一字涨停的股票列表
def initialize(context):
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) # 设置手续费
context.hold_days = dict()
context.max_hold = 25 # 一共持有25个股票
def handle_data(context, data):
dt = data.current_dt.strftime('%Y-%m-%d')
stock_hold_now = [equity.symbol for equity in context.portfolio.positions] # 目前持有的股票
# 当日买入股票列表
try:
buy = result.ix[dt]
except KeyError as e:
buy = []
weight = 1 / context.max_hold # 先采取固定比例
for st in buy: # 达到买入条件就买入
sid = context.symbol(st)
cur_position = context.portfolio.positions[sid].amount
if cur_position == 0 and data.can_trade(sid):
order_target_percent(sid, weight)
context.hold_days[st] = context.trading_day_index # 记录买入时间
for st in stock_hold_now: # 持仓大于1天就卖出
sid = context.symbol(st)
cur_position = context.portfolio.positions[sid].amount
if cur_position > 0 and data.can_trade(sid) and context.trading_day_index - context.hold_days[st] > 1:
order_target_percent(sid, 0)
m = M.trade.v2( # 执行回测
instruments=instrument,
start_date=start_date,
end_date=end_date,
initialize=initialize,
handle_data=handle_data,
order_price_field_buy='open',
order_price_field_sell='open',
capital_base=20000000,
benchmark='000300.INDX',
)