This commit is contained in:
Your Name 2025-07-04 14:35:51 +08:00
parent 51ca0877d9
commit c4ad8b9398
5 changed files with 51 additions and 23 deletions

View File

@ -135,4 +135,7 @@ class state:
获取昨日涨停股票列表
:return: 昨日涨停股票列表
"""
return self.data["high_stock_list"]
return self.data["high_stock_list"]
def get_hold_list(self):
return self.data["position_list"]

View File

@ -20,6 +20,8 @@ def initialize(context: Any) -> None:
# # 初始化策略参数
strategy.init_strategy() # 策略初始化函数
# # 注册调度任务
# run_daily(check_positions_before_market_open_func, time='9:01') # 开盘前先检查持仓状态
# run_daily(check_holdings_yesterday_func, time='9:00')
@ -37,8 +39,8 @@ def initialize(context: Any) -> None:
# run_daily(process_pending_buys_func, time='14:45') # 收盘前再处理一次买入
# run_daily(close_account_func, time='14:50')
# run_weekly(print_position_info_func, 5, time='15:10') # 周五收盘后打印持仓信息
task = check_state_before_task(strategy)
task.process(context)
# task = check_state_before_task(strategy)
# task.process(context)

View File

@ -22,14 +22,15 @@ class buy_stocks_func_task(base_task):
# 每次调仓的目标股票数量
self.stock_num = self.get_config('stock_num')
# 获取当前持仓列表
self.hold_list = [position.security for position in list(context.portfolio.positions.values())]
self.hold_list = self.strategy.state.get_hold_list()
self.index_stocks = self.get_config('index_stocks')
self.target_list = DataHelper.get_stock_list(context, self.index_stocks, self.stock_num)
self.temp_target_list = self.target_list[:self.stock_num]
# 昨日涨停股票列表
self.yesterday_HL_list: List[str] = self.strategy.state.get_yesterday_high_list()
self.today_trade_switch = self.get_config('today_trade_switch')
self.temp_sells_list = {}
self.temp_buys_list = {}
def run(self, context: Any):
if not self.today_trade_switch:
@ -41,13 +42,15 @@ class buy_stocks_func_task(base_task):
# 取目标持仓数以内的股票作为调仓目标
self.log.info(f"每周调仓目标股票: {self.temp_target_list}")
# 遍历当前持仓,若股票不在目标列表且非昨日涨停,则执行卖出操作
# 遍历当前持仓,若股票不在目标列表,则执行卖出操作
for stock in self.hold_list:
if stock not in self.temp_target_list and stock not in self.yesterday_HL_list:
if stock not in self.temp_target_list:
pos = context.portfolio.positions.get(stock)
self.log.info(f"调仓决策:卖出股票 {stock}")
# 通过持仓监控器注册卖出请求,而不是直接卖出
self.strategy.state.set_sell_request(stock, pos, 'rebalance')
self
#self.strategy.state.set_sell_request(stock, pos, 'rebalance')
self.sell_request(stock, pos, 'rebalance')
else:
self.log.info(f"调仓决策:继续持有股票 {stock}")
@ -56,14 +59,10 @@ class buy_stocks_func_task(base_task):
if buy_targets:
for stock in buy_targets:
pos = context.portfolio.positions.get(stock)
self.strategy.state.set_buy_request(stock, pos, 'buy')
#self.strategy.state.set_buy_request(stock, pos, 'buy')
self.buys_request(stock,pos,'buy')
self.log.info(f"调仓决策:将 {len(buy_targets)} 只股票加入待买入队列: {buy_targets}")
# 更新当天已买入记录,防止重复买入
# for position in list(context.portfolio.positions.values()):
# if position.security not in self.position_manager.get_not_buy_again():
# self.position_manager.get_not_buy_again().append(position.security)
def handle(self, context: Any):
self.strategy.set_target_list(self.temp_target_list)
pass
@ -71,3 +70,9 @@ class buy_stocks_func_task(base_task):
def end(self, context: Any):
pass
# 这里可以添加任何必要的清理或总结操作
def sell_request(self,stock,data,reason):
self.temp_sells_list[f"{stock}_{reason}"] = data
def buys_request(self,stock,data,reason):
self.temp_buys_list[f"{stock}_{reason}"] = data

View File

@ -10,9 +10,6 @@ class check_positions_stop_loss_task(base_task):
def __init__(self, strategy: trade_strategy):
super().__init__(strategy)
def init(self, context: Any):
pass
def config(self, context: Any):
@ -22,8 +19,10 @@ class check_positions_stop_loss_task(base_task):
self.stoploss_strategy = self.get_config('stoploss_strategy') # 止损策略
self.stoploss_stock_rate_data = self.get_config('stoploss_stock_rate_data') # 个股止损阀值
self.stoploss_market_rate_data = self.get_config('stoploss_market_rate_data') # 市场止损阀值
self.reason_to_sell = self.strategy.state.get_sell_reason() # 卖出原因
# self.reason_to_sell = self.strategy.state.get_sell_reason() # 卖出原因
self.index_stocks = self.get_config('index_stocks') # 指数代码
self.temp_sells_list = {}
def run(self, context: Any):
if len(self.hold_list) == 0:
@ -37,13 +36,15 @@ class check_positions_stop_loss_task(base_task):
pos = context.portfolio.positions[stock]
if pos.price >= pos.avg_cost * 2:
# 通过持仓监控器注册卖出请求,而不是直接卖出
self.strategy.state.set_sell_request(stock, pos, 'take_profit')
# self.strategy.state.set_sell_request(stock, pos, 'take_profit')
self.sell_request(stock,pos,'take_profit')
self.log.debug(f"股票 {stock} 实现100%盈利,执行止盈卖出。")
elif pos.price < pos.avg_cost * self.stoploss_stock_rate_data:
# 通过持仓监控器注册卖出请求,而不是直接卖出
self.strategy.state.set_sell_request(stock, pos, 'stop_loss')
self.sell_request(stock,pos,'take_profit')
self.log.debug(f"股票 {stock} 触及止损阈值,执行卖出。")
self.strategy.state.set_sell_reason("stoploss")
#self.strategy.state.set_sell_reason("stoploss")
if self.stoploss_strategy == 2 or self.stoploss_strategy == 3:
# 大盘止损判断,若整体市场跌幅过大则平仓所有股票
@ -59,9 +60,27 @@ class check_positions_stop_loss_task(base_task):
if df is not None and not df.empty:
down_ratio = (df['close'] / df['open']).mean()
if down_ratio <= self.stoploss_market_rate_data:
self.strategy.state.set_sell_reason("stoploss")
#self.strategy.state.set_sell_reason("stoploss")
self.log.debug(f"市场检测到跌幅(平均跌幅 {down_ratio:.2%}),卖出所有持仓。")
for stock in list(context.portfolio.positions.keys()):
pos = context.portfolio.positions[stock]
# 通过持仓监控器注册卖出请求,而不是直接卖出
self.position_monitor.register_sell_request(stock, pos, 'market_stop_loss')
self.sell_request(stock, pos, 'market_stop_loss')
def handle(self, context: Any):
# 将出售的数据传递给state
pass
def end(self, context: Any):
self.log.info("-----------------")
self.log.info("止损策略开关:{}".format("启用" if self.stoploss_switch else "不启用"))
self.log.info("今日交易开关:{}")
self.log.info("止损策略方式:{}")
self.log.info("当前卖出请求")
pass
def sell_request(self,stock,data,reason):
self.temp_sells_list[f"{stock}_{reason}"] = data

View File

@ -19,7 +19,6 @@ class process_pending_buy_task(base_task):
self.buy_requests_list = self.strategy.state.get_buy_requests()
def run(self, context: Any):
# 如果在特殊月份1月/4月或没有待买入股票直接返回
if self.today_trade_switch or not self.buy_requests_list:
return