涨幅监控策略(中证500版本)
当股票当日涨幅超过9%时买入,第二天开盘卖出
from xtquant import xtdata
from khQTTools import generate_signal
import logging
import os
配置日志系统
LOGS_DIR = os.path.join(os.path.dirname(os.path.dirname(file)), ‘logs’)
os.makedirs(LOGS_DIR, exist_ok=True)
logging.basicConfig(
filename=os.path.join(LOGS_DIR, ‘strategy.log’),
level=logging.INFO,
format=’%(asctime)s – %(levelname)s – %(message)s’,
filemode=’a’
)
全局变量
g_today_bought = set() # 今日买入的股票
g_yesterday_bought = set() # 昨日买入的股票,今日开盘卖出
g_is_first_bar = True # 是否是当天第一个bar
g_trigger_prices = {} # 存储触发价格的字典
g_max_positions = 5 # 最大持仓数量
def init(stock_list, context):
"""策略初始化函数,系统启动时会调用此函数"""
global g_today_bought, g_yesterday_bought, g_is_first_bar, g_trigger_prices, g_max_positions
# 记录日志
logging.info('策略开始运行,初始化函数全局只运行一次')
# 获取框架实例
framework = context.get("__framework__")
if framework and hasattr(framework, 'trader_callback') and hasattr(framework.trader_callback, 'gui'):
framework.trader_callback.gui.log_message(f'策略开始运行,初始化函数全局只运行一次', "INFO")
framework.trader_callback.gui.log_message(f'设置监控股票数量: {len(stock_list)} 只', "INFO")
# 初始化全局变量
g_today_bought = set()
g_yesterday_bought = set()
g_is_first_bar = True
g_trigger_prices = {}
# 预加载关键历史数据
try:
batch_size = 50# 每次处理50只股票
for i in range(0, len(stock_list), batch_size):
batch_stocks = stock_list[i:i+batch_size]
# 批量获取历史数据以提高效率
xtdata.get_market_data(
field_list=['open', 'close'],
stock_list=batch_stocks,
period='1d',
count=5
)
except Exception as e:
logging.error(f"预加载历史数据时出错: {str(e)}")
logging.info("初始化完成")
def khPreMarket(data):
"""盘前回调函数,计算当日触发价格"""
global g_today_bought, g_yesterday_bought, g_is_first_bar, g_trigger_prices
# 获取当前日期并转换为API所需格式
current_time = data["__current_time__"]
date = current_time["date"]
date_yyyymmdd = date.replace('-', '')
# 获取框架实例
framework = data.get("__framework__")
gui = None
if framework and hasattr(framework, 'trader_callback') and hasattr(framework.trader_callback, 'gui'):
gui = framework.trader_callback.gui
gui.log_message(f'=== 交易日 {date} 盘前运行 ===', "INFO")
# 重置每日状态
g_today_bought = set()
g_is_first_bar = True
g_trigger_prices = {}
# 获取股票列表
stock_list = []
try:
# 尝试从配置获取股票列表
if framework and hasattr(framework, 'config'):
stock_list_file = framework.config.config_dict.get("data", {}).get("stock_list_file", "")
if stock_list_file and os.path.exists(stock_list_file):
with open(stock_list_file, 'r', encoding='utf-8') as f:
stock_list = [line.strip() for line in f if line.strip()]
# 如果无法从配置获取,尝试从持仓中获取
ifnot stock_list:
positions = data.get("__positions__", {})
stock_list = list(positions.keys())
except Exception as e:
logging.error(f"获取股票列表失败: {str(e)}")
# 计算所有股票的触发价格
if stock_list:
try:
# 批量获取前一日收盘价并计算触发价
hist_data = xtdata.get_market_data_ex(
field_list=['close'],
stock_list=stock_list,
period='1d',
start_time=str(int(date_yyyymmdd) - 1),
end_time=str(int(date_yyyymmdd) - 1),
dividend_type='none'
)
# 处理每只股票的数据
for stock in stock_list:
if stock in hist_data and len(hist_data[stock]['close']) > 0:
prev_close = hist_data[stock]['close'].iloc[0]
if prev_close > 0:
g_trigger_prices[stock] = prev_close * 1.09
except Exception as e:
logging.error(f"批量计算触发价格时出错: {str(e)}")
# 确保昨日买入的股票在今日卖出
positions = data.get("__positions__", {})
g_yesterday_bought.update(positions.keys())
return []
def khHandlebar(data):
"""策略主函数,处理实时行情并生成交易信号"""
global g_today_bought, g_yesterday_bought, g_is_first_bar, g_trigger_prices, g_max_positions
signals = []
# 获取当前时间和股票代码列表
current_time = data["__current_time__"]
date = current_time["date"]
date_yyyymmdd = date.replace('-', '')
# 获取有效的股票代码列表(过滤掉特殊键)
stock_codes = [key for key in data.keys() ifnot key.startswith('__')]
# 获取账户和持仓信息
account = data.get("__account__", {})
positions = data.get("__positions__", {})
available_cash = account.get("cash", 0)
current_positions_count = len(positions)
# 如果是当天第一个bar,先处理卖出昨日买入的股票
if g_is_first_bar:
for stock in g_yesterday_bought:
if stock in positions:
# 获取当前价格
current_price = positions[stock].get("close", 0)
if current_price 0:
sell_signals = generate_signal(data, stock, current_price, 1.0, "sell", "涨停后第二天卖出")
signals.extend(sell_signals)
g_is_first_bar = False
# 如果有卖出信号,先返回执行
if signals:
return signals
# 如果持仓已达到最大限制,不执行买入操作
if current_positions_count >= g_max_positions:
return signals
# 计算单股可用资金(平均分配)
position_value = available_cash / g_max_positions if g_max_positions > 0else0
# 遍历所有股票检查是否满足买入条件
for stock_code in stock_codes:
# 跳过已买入或已持有的股票
if stock_code in g_today_bought or stock_code in positions:
continue
# 获取当前价格
current_price = data[stock_code].get("close", 0)
if current_price 0:
open_price = hist_data[stock_code]['open'].iloc[0]
if open_price > 0:
trigger_price = open_price * 1.09
g_trigger_prices[stock_code] = trigger_price
except Exception as e:
logging.error(f"补充计算 {stock_code} 触发价格时出错: {str(e)}")
# 如果当前价格达到或超过触发价,执行买入
if trigger_price and current_price >= trigger_price:
# 计算可买股数(整数手)
shares_to_buy = int(position_value / current_price / 100) * 100
# 确保至少买一手(100股)
if shares_to_buy >= 100:
# 生成买入信号
buy_signals = generate_signal(data, stock_code, current_price, shares_to_buy, "buy", "当日涨幅超过9%买入")
signals.extend(buy_signals)
# 添加到今日买入记录
g_today_bought.add(stock_code)
# 如果已达到最大持仓数,立即返回
if len(g_today_bought) + current_positions_count >= g_max_positions:
break
return signals
def khPostMarket(data):
"""盘后回调函数,记录今日买入的股票"""
global g_yesterday_bought, g_today_bought
# 获取当前时间
current_time = data["__current_time__"]
date_time = current_time["datetime"]
# 更新昨日买入记录,用于明天开盘卖出
g_yesterday_bought = g_today_bought.copy()
# 记录日志
if g_today_bought:
logging.info(f"今日买入股票: {list(g_today_bought)}")
logging.info(f"明日开盘将卖出股票: {list(g_yesterday_bought)}")
else:
logging.info(f"今日未买入股票")
# 获取账户信息
account = data.get("__account__", {})
available_cash = account.get("cash", 0)
total_asset = account.get("total_asset", 0)
logging.info(f"=== 交易日 {date_time} 盘后运行 ===")
logging.info(f"当前资金: {available_cash:.2f}, 总资产: {total_asset:.2f}")
logging.info(f"====================")
return []