```
# 导入函数库
from jqdata import *
# 初始化函数,设定基准等等
def initialize(context):
run_daily(period, "every_bar")
g.stocks_count = 30
g.period = 15
g.accu_days = 0
def period(context):
if g.accu_days % g.period == 0:
all_stocks = get_all_securities(types=["stock"], date=context.current_dt).index.tolist()
q = query(
valuation.code, valuation.market_cap
).filter(
valuation.code.in_(all_stocks)
).order_by(
valuation.market_cap.asc()
).limit(g.stocks_count*20)
df = get_fundamentals(q)
candidate_stocks = list(df["code"])
buylist = []
for stock_code in candidate_stocks:
current_data = get_current_data()
current_data = current_data[stock_code]
if current_data.paused == False and \
current_data.is_st == False and \
current_data.high_limit != \
get_price(stock_code, end_date=context.current_dt, fields=["high"], count=1)["high"].tolist()[0] and \
current_data.low_limit != \
get_price(stock_code, end_date=context.current_dt, fields=["low"], count=1)["low"].tolist()[0]:
buylist.append(stock_code)
if len(buylist) >= g.stocks_count:
break
inhand_stocks = list(context.portfolio.positions.keys())
stocks_out = set(inhand_stocks) - set(buylist)
for stock_id in stocks_out:
order_target(stock_id, 0)
position_per_stk = context.portfolio.available_cash / g.stocks_count
for candidate in buylist:
order_value(candidate, position_per_stk)
else:
for stock in context.portfolio.positions:
cost = context.portfolio.positions[stock].avg_cost
price = context.portfolio.positions[stock].price
ratio = price / cost - 1
if ratio > 0.15 or ratio < -0.2:
order_target(stock, 0)
g.accu_days += 1
```
2023-05-03