def initialize(context):
run_daily(period, time='every_bar')
g.stock_num = 7
g.days = 0
g.period= 13
def period(context):
# ========== 1. 止盈检查(每天执行) ==========
current_data = get_current_data() # 获取当前行情数据
for stock in list(context.portfolio.positions.keys()):
position = context.portfolio.positions[stock]
if position.total_amount > 0:
current_price = current_data[stock].last_price
cost = position.avg_cost
if current_price/cost -1 >=0.05:
order_target(stock,0)
log.info("止盈卖出:%s,收益率:%.2f%%"%(stock,(current_price/cost -1)*100))
# ========== 2. 定期轮动(仅在调仓日执行) ==========
if g.days % g.period == 0:
# 1. 基础股票池:所有A股
a = get_all_securities(date= context.current_dt).index.tolist()
# 2. 过滤ST、停牌、涨停
scu = []
for stock in a:
if stock not in current_data:
continue
if current_data[stock].is_st:
continue
if current_data[stock].paused:
continue
last = current_data[stock].last_price
high_limit = current_data[stock].high_limit
if last >= high_limit-0.001:
continue
scu.append(stock)
q =query(valuation.code).filter(valuation.code.in_(a)).order_by(
valuation.market_cap.asc()).limit(g.stock_num)
df = get_fundamentals(q)
buylist = list(df['code'])
for stock in context.portfolio.positions:
if stock not in buylist:
order_target(stock,0)
positions_per_sto=context.portfolio.cash/g.stock_num
for stock in buylist:
order_value(stock,positions_per_sto)
g.days = g.days+1
18天前