easyquant/task/check_market_env_task.py
2025-07-03 23:39:31 +08:00

73 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Any
from strategy import trade_strategy
from task.base_task import base_task
class check_market_env_task(base_task):
"""
交易环境确认
1、判断是否为特殊月份1月/4月
2、如果是特殊月份且通过了清仓检查则清仓所有持仓
3、如果不是特殊月份且没有交易信号则重置交易信号
"""
def __init__(self, strategy: trade_strategy):
super().__init__(strategy)
def config(self, context: Any):
self.current_date = context.current_dt.date()
self.current_month = self.current_date.month
self.current_day = self.current_date.day
# 判断是否执行空仓策略
self.filter_month_clear_switch = self.get_config('filter_month_clear_switch')
self.filer_month_data = self.get_config('filter_month_data')
# 判断是否为特殊月 = True时 等于 执行1月/4月 全部清仓
self.in_special_month = str(self.current_month) in self.filer_month_data
self.today_trade_switch = self.get_config('today_trade_switch') # 是否为不交易信号
def run(self, context: Any):
#
if self.filter_month_clear_switch and self.in_special_month:
# 进入特殊月份,应清仓
for stock in self.strategy.state.data['position_list'].keys():
self.strategy.state.set_sell_request(stock, self.strategy.state.data['position_list'][stock], f"enter_{self.current_month}_month")
# 清仓后就不交易
self.today_trade_switch = False
elif not self.filter_month_clear_switch:
# 不在特殊月 或 不执行空仓策略 可以交易
self.today_trade_switch = True
else:
# 如果是特殊月份但没有清仓条件,则继续交易
self.today_trade_switch = True
def handle(self, context: Any):
# 保存状态
old_today_trade_switch = self.strategy_config.get_config("today_trade_switch")
if old_today_trade_switch != self.today_trade_switch:
self.strategy_config.set_config("today_trade_switch", self.today_trade_switch) # 临时变量
self.log.info(f"交易环境更新: today_trade_switch 状态更新为 {self.today_trade_switch}")
def end(self, context: Any):
self.log.info("-----------------")
self.log.info("一.今日环境确认:")
self.log.info(" 当前日期: {}".format(self.current_date))
self.log.info(" 空仓策略: {}".format("开启" if self.filter_month_clear_switch else "关闭"))
self.log.info(" 今日交易: {}".format("交易" if self.today_trade_switch else "清仓"))
self.log.info(" 特殊月份: {}".format(",".join(str(item) for item in self.filer_month_data)))
self.log.info(" 当前月份: {}".format(self.current_month))
# 今日清仓