换代码:缩减到60行左右,卖出条件加上了一个涨停不卖。
```Python
from jqdata import *
def initialize(context):
set_benchmark('000300.XSHG')
set_option('use_real_price', True)
log.set_level('order', 'error')
g.security_universe_index = "399101.XSHE" # 中小板
g.buy_stock_count = 5
run_daily(my_trade, time='14:40', reference_security='000300.XSHG')
def my_trade(context):
# type: (Context) -> None
# 中小板成分股
check_out_lists = get_index_stocks(g.security_universe_index)
# 成分股中最小市值N只
q = query(
valuation.code
).filter(
valuation.code.in_(check_out_lists)
).order_by(
valuation.circulating_market_cap.asc()
).limit(
g.buy_stock_count * 3
)
check_out_lists = list(get_fundamentals(q).code)
# 常规过滤
curr_data = get_current_data()
check_out_lists = [
stock for stock in check_out_lists if not (
curr_data[stock].paused or
curr_data[stock].is_st or
('ST' in curr_data[stock].name) or
('*' in curr_data[stock].name) or
('退' in curr_data[stock].name) or
(curr_data[stock].last_price == curr_data[stock].high_limit) or
(curr_data[stock].last_price == curr_data[stock].low_limit)
)]
# 截取想要的g.buy_stock_count只
targets = check_out_lists[:g.buy_stock_count]
# 卖出: 不在目标池中,且未涨停,就卖出
for stock in context.portfolio.positions:
if stock in targets or curr_data[stock].last_price == curr_data[stock].high_limit:
continue
#
order_target(stock, 0)
# 买入
position_count = len(context.portfolio.positions)
if g.buy_stock_count > position_count:
value = context.portfolio.available_cash / (g.buy_stock_count - position_count)
for stock in targets:
if stock not in context.portfolio.positions:
order_target_value(stock, value)
if len(context.portfolio.positions) >= g.buy_stock_count:
break
```
回测时间不变,`收益从11年1700倍提升到了2539倍`。

2023-12-20