
等级: 新手上路
- 注册:
- 2025-7-8
- 曾用名:
|

楼主 |
发表于 2025-7-9 09:31
|
显示全部楼层
import datetime
import pandas as pd
def init(context):
context.strategy_capital = 100_000
context.positions = {}
context.pending_sell_orders = {}
context.already_bought = False
context.trading_day_count = 0
context.MAX_ATTEMPTS = 5
context.TARGET_BUY_COUNT = 5
context.rate=1.05
df = pd.read_csv("D:/tushare/analyse_data/result/final_top20_combined_score_2025-06-27.csv", dtype=str)
df['code'] = df['code'].astype(str).str.strip().str.upper()
context.target_stocks = df['code'].tolist()
def handle_bar(context):
if context.trading_day_count > 3:
return # 限制最多运行3个交易日
# Step 0: 处理未完成追单
for stock in list(context.pending_sell_orders.keys()):
price = get_price(stock)
volume = context.pending_sell_orders[stock]['volume']
attempts = context.pending_sell_orders[stock]['attempts']
if price is None or price <= 0:
context.pending_sell_orders[stock]['attempts'] += 1
if attempts + 1 >= context.MAX_ATTEMPTS:
print(f"{stock} 清仓失败超过最大次数,放弃追单")
del context.pending_sell_orders[stock]
continue
# 卖出时使用开盘价
sell_price = get_price(stock) # 获取开盘价
sell_close(stock, 'Limit', sell_price, volume,serial_id = 1)
print(f"{stock} 第 {attempts + 1} 次追单挂出")
del context.pending_sell_orders[stock]
# Step 1: 第1个交易日建仓(支持涨停候补)
if context.trading_day_count == 1 and not context.already_bought:
cash_per_stock = context.strategy_capital / context.TARGET_BUY_COUNT
built_count = 0
candidate_stocks = []
for stock in context.target_stocks:
if built_count >= context.TARGET_BUY_COUNT:
break
price = get_price(stock)
if price is None or price <= 0:
print(f"{stock} 无法获取价格,加入候补池")
candidate_stocks.append(stock)
continue
volume = int(cash_per_stock / price // 100) * 100
if volume < 100:
print(f"{stock} 成交量不足 100 股,加入候补池")
candidate_stocks.append(stock)
continue
turnover_rate = get_turnover_rate(stock, 1, 5)
#print(turnover_rate[-1].values)
if turnover_rate[-1].values is None or turnover_rate[-1].values < 0.01:
print(f"{stock} 换手率过低,跳过")
continue
buy_price = get_price(stock) # 获取开盘价
print(buy_price)
buy_open(stock, 'Market', buy_price, volume,serial_id = 2)
context.positions[stock] = {'buy_price': price, 'volume': volume}
built_count += 1
print(f"成功建仓 {stock},价格 {price:.2f},数量 {volume}")
# 候补建仓
for stock in candidate_stocks:
if built_count >= context.TARGET_BUY_COUNT:
break
price = get_price(stock)
if price is None or price <= 0:
continue
volume = int(cash_per_stock / price // 100) * 100
if volume < 100:
continue
buy_price = get_price(stock) # 获取开盘
buy_open(stock, 'Market', buy_price, volume,serial_id = 3)
context.positions[stock] = {'buy_price': price, 'volume': volume}
built_count += 1
print(f"候补建仓成功:{stock},价格 {price:.2f},数量 {volume}")
context.already_bought = True
print(f"第1个交易日建仓完成,共建仓 {built_count} 只股票")
# Step 2: 第2个交易日止盈止损
elif context.trading_day_count == 2:
for stock in list(context.positions.keys()):
price = get_price(stock)
if price is None or price <= 0:
context.pending_sell_orders[stock] = {
'volume': context.positions[stock]['volume'],
'attempts': 1
}
print(f"{stock} 无法获取价格,加入追单池")
continue
buy_price = context.positions[stock]['buy_price']
volume = context.positions[stock]['volume']
if price >= buy_price * context.rate or price <= buy_price * 0.95:
# 卖出时使用开盘价
sell_price = get_price(stock) # 获取开盘价
print(sell_price)
sell_close(stock, 'Market', sell_price, volume,serial_id = 4)
print(f"{stock} 触发止盈/止损,卖出")
del context.positions[stock]
# Step 3: 第3个交易日强制清仓
elif context.trading_day_count == 3:
for stock in list(context.positions.keys()):
price = get_price(stock)
volume = context.positions[stock]['volume']
if price is None or price <= 0:
context.pending_sell_orders[stock] = {'volume': volume, 'attempts': 1}
print(f"{stock} 第3日仍无法获取价格,加入追单池")
continue
# 卖出时使用开盘价
sell_price = get_price(stock) # 获取开盘价
print(sell_price)
sell_close(stock, 'Market', sell_price, volume,serial_id = 5)
print(f"{stock} 第3日强制清仓完成")
del context.positions[stock]
context.trading_day_count += 1
def get_price(stock):
bars = history_bars(stock, 1, '1d', ['OPEN'], skip_suspended=True, include_now=False)
if not bars or len(bars) == 0:
return None
#print(bars[-1])
return bars[-1] # 确保获取的是当天的开盘价 |
|