策略核心:
1.增加止损逻辑
2.每个周期进行一次交易
def initialize(context):
run_daily(period,time="every_bar")
# 设定好要交易的股票数量
g.stacknum = 7
# 设定好交易周期
g.period = 13
# 记录策略进行天数
g.days = 0
def period(context):
# 1.止损逻辑:检查持仓股票的盈亏比例
for stock in context.portfolio.positions:
# 获取持仓信息
position = context.portfolio.positions[stock]
cost_price = position.avg_cost # 持仓成本价
current_price = position.price # 当前价格
# 计算盈亏比例
profit_ratio = (current_price - cost_price) / cost_price * 100
# 如果亏损大于5%,则卖出股票
if profit_ratio < -5:
order_target(stack,0)
log.info(f"股票 {stock} 亏损超过5%,已卖出")
# 2.每周期进行交易
# 判断是否达到交易周期
if g.days % g.period == 0:
# 找出市值排名最小的前stacknums只股票作为要买入的股票
# 获取当天股票列表
Total_list = get_all_securities(date = context.current_dt).index.tolist()
# 获取当前单位时间(当天/当前分钟)的涨跌停价, 是否停牌,当天的开盘价等
current_data = get_current_data()
# 剔除st/停牌/退市/涨跌停 得到scu
scu = [stock for stock in Total_list if not (
current_data[stock].paused or current_data[stock].is_st or current_data[stock].last_price ==
current_data[stock].high_limit or current_data[stock].last_price == current_data[stock].low_limit)]
# 选出在scu内的市值排名最小的前stocknum只股票
q = query(valuation.code
).filter(
valuation.code.in_(scu)
).order_by(
valuation.market_cap.asc()
).limit(g.stacknum)
df = get_fundamentals(q)
# 选取股票代码并转让为list
buylist = list(df['code'])
# 已经持有的股票已经不在足够小,不能在要买入的股票中,则卖出这些股票
# 对每个当下持有的股票进行判断:现在是否已经不在buylist里,如果是则卖出
for stock in context.portfolio.positions:
if stock not in buylist:
order_target(stock,0) #调整stock的持仓为0,即卖出
# 买入要买入的股票,买入金额作为当前可用资金的stocksum分之一
# 将资金分成g.stocknum份
position_per_stk = context.portfolio.cash/g.stacknum
# 购买股票
for stock in buylist:
order_value(stock,position_per_stk)
g.days += 1
2025-06-24