瀏覽代碼

添加多均线穿越突破策略及相关文档,更新.gitignore以排除日志文件

betterMax 4 月之前
父節點
當前提交
f531ef20eb

+ 6 - 0
.cursor/rules/rule.mdc

@@ -0,0 +1,6 @@
+---
+description: 
+globs: 
+alwaysApply: false
+---
+# 核心准则:该项目仓库是一个探讨策略的仓库。实际运行环境并不在本地,所以不会有虚拟环境,也不需要安装包。所以忽略相关问题及报错。专注于代码逻辑的实现

+ 1 - 0
.cursorignore

@@ -0,0 +1 @@
+log/

+ 1222 - 0
Lib/future/MultiMABreakoutStrategy_v001.py

@@ -0,0 +1,1222 @@
+# 导入函数库
+from jqdata import *
+from jqdata import finance
+import pandas as pd
+import numpy as np
+from datetime import date, datetime, timedelta
+import re
+
+# 多均线穿越突破策略 v001
+# 基于K线实体穿越多条均线的交易策略
+
+# 设置以便完整打印 DataFrame
+pd.set_option('display.max_rows', None)
+pd.set_option('display.max_columns', None)
+pd.set_option('display.width', None)
+pd.set_option('display.max_colwidth', 20)
+
+## 初始化函数,设定基准等等
+def initialize(context):
+    # 设定沪深300作为基准
+    set_benchmark('000300.XSHG')
+    # 开启动态复权模式(真实价格)
+    set_option('use_real_price', True)
+    # 输出内容到日志
+    log.info('多均线穿越突破策略初始化开始')
+
+    ### 期货相关设定 ###
+    # 设定账户为金融账户
+    set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
+    # 期货类每笔交易时的手续费是: 买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
+    set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
+    
+    # 设置期货交易的滑点
+    set_slippage(StepRelatedSlippage(2))
+    
+    # 初始化全局变量
+    g.usage_percentage = 0.8  # 最大资金使用比例
+    g.min_cross_mas = 3  # 最少穿越均线数量
+    g.max_margin_per_position = 20000  # 单个标的最大持仓保证金(元)
+    g.price_deviation_min = 0.005  # 价格偏离临界线最小比例(0.5%)
+    g.price_deviation_max = 0.01   # 价格偏离临界线最大比例(1%)
+    
+    # 均线交叉数量检查相关参数
+    g.max_ma_crosses = 4  # 最大允许的均线交叉数量
+    g.ma_cross_check_days = 10  # 检查均线交叉的天数
+    
+    # 定义默认的保证金比例
+    g.margin_rates = {
+        'long': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
+        'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
+        'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
+        'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22, 
+        'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
+        'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
+        'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
+        'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
+        'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
+        'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05}, 
+        'short': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
+        'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
+        'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
+        'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22, 
+        'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
+        'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
+        'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
+        'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
+        'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
+        'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05}
+    }
+    
+    g.multiplier = {
+        'A': 10, 'AG': 15, 'AL': 5, 'AO': 20, 'AP': 10, 'AU': 1000, 'B': 10,
+        'BC': 5, 'BR': 5, 'BU': 10, 'C': 10, 'CF': 5, 'CJ': 5, 'CS': 10,
+        'CU': 5, 'CY': 5, 'EB': 5, 'EC': 50, 'EG': 10, 'FG': 20, 'FU': 10,
+        'HC': 10, 'I': 100, 'J': 60, 'JD': 5, 'JM': 100, 
+        'L': 5, 'LC': 1, 'LH': 16, 'LR': 0.05, 'LU': 10, 'M': 10, 'MA': 10, 'NI': 1, 'NR': 10, 'OI': 10,
+        'P': 10, 'PB': 5, 'PF': 5, 'PG': 20, 'PK': 5,
+        'PP': 5, 'RB': 10, 'RI': 0.05, 'RM': 10, 'RU': 10,
+        'SA': 20, 'SC': 1000, 'SF': 5, 'SH': 30, 'SI': 5, 'SM': 5, 'SN': 1, 'SP': 10, 'SR': 10,
+        'SS': 5, 'TA': 5, 'UR': 20, 'V': 5,
+        'Y': 10, 'ZC': 0.05, 'ZN': 5
+    }
+    
+    # 交易记录和数据存储
+    g.trade_history = {}
+    g.ma_cross_signals = {}  # 存储多均线穿越信号
+    g.daily_data_cache = {}  # 存储历史日线数据缓存
+    g.minute_data_cache = {}  # 存储今日分钟数据缓存
+    g.ma_data_cache = {}  # 存储均线数据缓存
+    g.ma_cross_filtered_futures = {}  # 存储通过均线交叉检查的品种(每日缓存)
+    
+    # 保证金比例管理(g.margin_rates会根据实际交易校准)
+    g.margin_rate_history = {}  # 保证金比例变化历史记录
+    g.today_trades = []  # 当日交易记录
+    
+    # 定时任务设置 - 根据新的时间安排
+    # 夜盘开始
+    run_daily(main_trading_21_05, time='21:05:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='21:35:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='22:05:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='22:35:00', reference_security='IF1808.CCFX')
+    
+    # 日盘开始
+    run_daily(main_trading_09_05, time='09:05:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='09:35:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='10:05:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='10:35:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='11:05:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='11:25:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='13:35:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_regular, time='14:05:00', reference_security='IF1808.CCFX')
+    
+    # 收盘前
+    run_daily(main_trading_before_close, time='14:35:00', reference_security='IF1808.CCFX')
+    run_daily(main_trading_before_close, time='14:55:00', reference_security='IF1808.CCFX')
+    
+    # 收盘后
+    run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
+
+############################ 主程序执行函数 ###################################
+
+def main_trading_21_05(context):
+    """21:05 执行任务1, 2, 3, 4, 5, 6, 9"""
+    log.info("-" * 50)
+    log.info("21:05 多均线穿越突破策略 - 夜盘开始")
+    log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
+    log.info("-" * 50)
+    
+    # 任务1: 获取所有可交易品种
+    task_1_get_tradable_futures(context)
+    
+    # 任务2: 获取历史数据并保存到内存
+    task_2_load_historical_data(context)
+    
+    # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
+    task_3_check_ma_crosses(context)
+    
+    # 任务4: 获取今日分钟数据并合并均线数据
+    task_4_update_realtime_data(context)
+    
+    # 任务5: 判断上穿下穿情况
+    task_5_analyze_ma_crosses(context)
+    
+    # 任务6: 检查开仓条件
+    filtered_signals = task_6_check_opening_conditions(context)
+
+    # 如果任务6有满足条件的,执行任务7开仓
+    if filtered_signals:
+        task_7_execute_trades(context, filtered_signals)
+    
+    # 任务9: 检查止损止盈
+    task_9_check_stop_loss_profit(context)
+
+def main_trading_09_05(context):
+    """09:05 执行任务1, 2, 3, 4, 5, 6, 9"""
+    log.info("-" * 50)
+    log.info("09:05 多均线穿越突破策略 - 日盘开始")
+    log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
+    log.info("-" * 50)
+    
+    # 任务1: 获取所有可交易品种
+    task_1_get_tradable_futures(context)
+    
+    # 任务2: 获取历史数据并保存到内存
+    task_2_load_historical_data(context)
+    
+    # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
+    task_3_check_ma_crosses(context)
+    
+    # 任务4: 获取今日分钟数据并合并均线数据
+    task_4_update_realtime_data(context)
+    
+    # 任务5: 判断上穿下穿情况
+    task_5_analyze_ma_crosses(context)
+    
+    # 任务6: 检查开仓条件
+    filtered_signals = task_6_check_opening_conditions(context)
+
+    # 如果任务6有满足条件的,执行任务7开仓
+    if filtered_signals:
+        task_7_execute_trades(context, filtered_signals)
+    
+    # 任务9: 检查止损止盈
+    task_9_check_stop_loss_profit(context)
+
+def main_trading_regular(context):
+    """常规时间执行任务4, 5, 6, 9"""
+    current_time = context.current_dt.strftime('%H:%M')
+    # log.info(f"----- {current_time} 常规检查 -----")
+    # log.info("执行任务: 4, 5, 6, 9")
+    
+    # 任务4: 获取今日分钟数据并合并均线数据
+    task_4_update_realtime_data(context)
+    
+    # 任务5: 判断上穿下穿情况
+    task_5_analyze_ma_crosses(context)
+    
+    # 任务6: 检查开仓条件
+    filtered_signals = task_6_check_opening_conditions(context)
+
+    # 如果任务6有满足条件的,执行任务7开仓
+    if filtered_signals:
+        task_7_execute_trades(context, filtered_signals)
+    
+    # 任务9: 检查止损止盈
+    task_9_check_stop_loss_profit(context)
+
+def main_trading_before_close(context):
+    """收盘前执行任务4, 5, 6, 8, 9"""
+    current_time = context.current_dt.strftime('%H:%M')
+    # log.info(f"----- {current_time} 收盘前检查 -----")
+    # log.info("执行任务: 4, 5, 6, 8, 9")
+    
+    # 任务4: 获取今日分钟数据并合并均线数据
+    task_4_update_realtime_data(context)
+    
+    # 任务5: 判断上穿下穿情况
+    task_5_analyze_ma_crosses(context)
+    
+    # 任务6: 检查开仓条件
+    filtered_signals = task_6_check_opening_conditions(context)
+
+    # 如果任务6有满足条件的,执行任务7开仓
+    if filtered_signals:
+        task_7_execute_trades(context, filtered_signals)
+    
+    # 任务8: 检查换月移仓
+    task_8_check_position_switch(context)
+    
+    # 任务9: 检查止损止盈
+    task_9_check_stop_loss_profit(context)
+
+############################ 核心任务函数 ###################################
+
+def task_1_get_tradable_futures(context):
+    """任务1: 获取所有可交易品种(分白天和晚上)"""
+    # log.info("执行任务1: 获取可交易品种")
+    
+    # 夜盘品种
+    # potential_night_list = ['NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM', 'RB', 'HC', 'I', 'J', 'JM']
+    potential_night_list = ['PF', 'Y', 'SN']
+    # 日盘品种  
+    potential_day_list = ['PK']
+    # potential_day_list = ['JD', 'UR', 'AP', 'CJ', 'PK']
+    
+    current_time = str(context.current_dt.time())[:2]
+    if current_time in ('21', '22'):
+        potential_icon_list = potential_night_list
+        log.info(f"夜盘时间,可交易品种: {potential_night_list}")
+    else:
+        potential_icon_list = potential_day_list + potential_night_list
+        log.info(f"日盘时间,可交易品种: {potential_icon_list}")
+    
+    potential_future_list = []
+    for symbol in potential_icon_list:
+        dominant_future = get_dominant_future(symbol)
+        if dominant_future:
+            potential_future_list.append(dominant_future)
+    
+    # 过滤掉已有持仓的品种
+    existing_positions = set(g.trade_history.keys())
+    potential_future_list = [f for f in potential_future_list if not check_symbol_prefix_match(f, existing_positions)]
+    
+    # 存储到全局变量
+    g.tradable_futures = potential_future_list
+    log.info(f"最终可交易期货品种数量: {len(potential_future_list)}")
+    
+    return potential_future_list
+
+def task_2_load_historical_data(context):
+    """任务2: 获取所有可交易品种今天之前所需的数据,并保存到内存中"""
+    # log.info("执行任务2: 加载历史数据到内存")
+    
+    if not hasattr(g, 'tradable_futures'):
+        return
+    
+    for future_code in g.tradable_futures:
+        try:
+            # 获取50天历史数据(用于计算均线)
+            data = attribute_history(future_code, 50, '1d', 
+                                   ['open', 'close', 'high', 'low', 'volume'], 
+                                   df=True)
+            
+            if data is not None and len(data) > 0:
+                # 排除今天的数据
+                today = context.current_dt.date()
+                data = data[data.index.date < today]
+                
+                g.daily_data_cache[future_code] = data
+                # log.info(f"已缓存 {future_code} 历史数据 {len(data)} 条")
+            
+        except Exception as e:
+            log.warning(f"加载{future_code}历史数据时出错: {str(e)}")
+            continue
+    
+    log.info(f"历史数据缓存完成,共缓存 {len(g.daily_data_cache)} 个品种")
+
+def task_3_check_ma_crosses(context):
+    """任务3: 检查均线交叉数量,过滤掉交叉过多的品种"""
+    # log.info("执行任务3: 检查均线交叉数量")
+    
+    if not hasattr(g, 'tradable_futures'):
+        return
+    
+    # 存储通过均线交叉检查的品种
+    today_date = context.current_dt.date()
+    if today_date not in g.ma_cross_filtered_futures:
+        g.ma_cross_filtered_futures[today_date] = []
+    
+    filtered_futures = []
+    
+    for future_code in g.tradable_futures:
+        try:
+            # 获取历史数据
+            historical_data = g.daily_data_cache.get(future_code)
+            if historical_data is None or len(historical_data) < 30:
+                log.warning(f"{future_code} 历史数据不足,跳过")
+                continue
+            
+            # 计算移动平均线
+            data_with_ma = historical_data.copy()
+            data_with_ma['MA5'] = data_with_ma['close'].rolling(window=5).mean()
+            data_with_ma['MA10'] = data_with_ma['close'].rolling(window=10).mean()
+            data_with_ma['MA20'] = data_with_ma['close'].rolling(window=20).mean()
+            data_with_ma['MA30'] = data_with_ma['close'].rolling(window=30).mean()
+            
+            # 检查均线交叉数量
+            ma_crosses = count_ma_crosses(data_with_ma, g.ma_cross_check_days)
+            
+            # 如果交叉数量在允许范围内,保留该品种
+            if ma_crosses <= g.max_ma_crosses:
+                filtered_futures.append(future_code)
+                log.info(f"{future_code} 通过均线交叉检查,交叉数量: {ma_crosses}")
+            else:
+                log.info(f"{future_code} 均线交叉过多,被过滤,交叉数量: {ma_crosses} > {g.max_ma_crosses}")
+            
+        except Exception as e:
+            log.warning(f"检查{future_code}均线交叉时出错: {str(e)}")
+            continue
+    
+    # 更新可交易品种列表
+    g.tradable_futures = filtered_futures
+    g.ma_cross_filtered_futures[today_date] = filtered_futures
+    
+    log.info(f"均线交叉检查完成,剩余可交易品种数量: {len(g.tradable_futures)}")
+    if len(g.tradable_futures) > 0:
+        log.info(f"通过检查的品种: {g.tradable_futures}")
+    
+    return filtered_futures
+
+def task_4_update_realtime_data(context):
+    """任务4: 获取所有可交易品种今天所需的分钟数据作为今天数据,和2中的数据合并出最新的均线数据,并保存到内存中"""
+    # log.info("执行任务4: 更新实时数据和均线")
+    
+    if not hasattr(g, 'tradable_futures'):
+        return
+    
+    for future_code in g.tradable_futures:
+        log.info(f"任务4 future_code: {future_code}")
+        try:
+            # 获取今日分钟数据
+            minute_data = get_today_minute_data(context, future_code)
+            # log.info(f"minute_data: {minute_data}")
+            if minute_data is None:
+                continue
+            
+            # 获取历史数据
+            historical_data = g.daily_data_cache.get(future_code)
+            if historical_data is None:
+                continue
+            
+            # 合并数据并计算均线
+            combined_data = combine_and_calculate_ma(historical_data, minute_data)
+            if combined_data is not None:
+                g.ma_data_cache[future_code] = combined_data
+                # log.info(f"已更新 {future_code} 均线数据")
+            
+        except Exception as e:
+            log.warning(f"更新{future_code}实时数据时出错: {str(e)}")
+            continue
+    
+    # log.info(f"实时数据更新完成,共更新 {len(g.ma_data_cache)} 个品种")
+
+def task_5_analyze_ma_crosses(context):
+    """任务5: 根据交易品种的今天数据和均线数据,判断是否出现了上穿或者下穿的情况"""
+    # log.info("执行任务5: 分析均线穿越")
+    
+    ma_cross_signals = []
+    
+    # 获取已持仓的品种列表
+    existing_positions = set(g.trade_history.keys())
+    
+    for future_code, data in g.ma_data_cache.items():
+        log.info(f"future_code: {future_code}")
+        try:
+            # 检查是否已有相似持仓,如果有则跳过分析
+            if check_symbol_prefix_match(future_code, existing_positions):
+                # log.(f"{future_code} 已有相似持仓,跳过均线穿越分析")
+                continue
+            
+            # 检查最新的多均线穿越
+            latest_cross = check_latest_multi_ma_cross(data, future_code)
+            if latest_cross:
+                ma_cross_signals.append(latest_cross)
+                log.info(f"{future_code} 发现多均线穿越: {latest_cross['direction']}")
+                log.info(f"开盘价格: {latest_cross['open']}, 当前价格: {latest_cross['close']}, 临界线: {latest_cross['critical_ma_name']}({latest_cross['critical_ma_value']:.2f}), 穿越数量: {latest_cross['crossed_count']}")
+                log.info(f"MA5: {latest_cross['ma5']}, MA10: {latest_cross['ma10']}, MA20: {latest_cross['ma20']}, MA30: {latest_cross['ma30']}")
+                
+        except Exception as e:
+            log.warning(f"分析{future_code}均线穿越时出错: {str(e)}")
+            continue
+    
+    # 存储到全局变量
+    g.ma_cross_signals = ma_cross_signals
+    if len(ma_cross_signals) > 0:
+        log.info(f"均线穿越分析完成,发现信号 {len(ma_cross_signals)} 个")
+        log.debug(f"ma_cross_signals: {ma_cross_signals}")
+    
+    return ma_cross_signals
+
+def task_6_check_opening_conditions(context):
+    """任务6: 针对那些有上穿和下穿的情况检查是否满足开仓条件"""
+    # log.info("执行任务6: 检查开仓条件")
+    
+    if not hasattr(g, 'ma_cross_signals'):
+        return []
+    
+    filtered_signals = []
+    
+    for signal in g.ma_cross_signals:
+        # 检查是否已有相似持仓
+        if check_symbol_prefix_match(signal['symbol'], set(g.trade_history.keys())):
+            log.warning(f"{signal['symbol']} 已有相似持仓,跳过")
+            continue
+        
+        # 检查价格位置合理性
+        if not check_price_position(signal):
+            log.warning(f"{signal['symbol']} 价格位置不合理,跳过")
+            continue
+        
+        filtered_signals.append(signal)
+        log.info(f"{signal['symbol']} 满足开仓条件")
+    
+    if len(filtered_signals) > 0:
+        log.info(f"开仓条件检查完成,满足条件 {len(filtered_signals)} 个")
+    return filtered_signals
+
+def task_7_execute_trades(context, filtered_signals):
+    """任务7: 针对满足开仓条件的标的,计算购买的金额,并发起交易请求"""
+    # log.info("执行任务7: 执行交易")
+    
+    for signal in filtered_signals:
+        symbol = signal['symbol']
+        direction = 'long' if signal['direction'] == 'up' else 'short'
+        
+        # 检查资金充足性
+        if not check_sufficient_capital(context, symbol):
+            log.warning(f"{symbol} 资金不足,跳过开仓")
+            continue
+        
+        # 计算开仓金额
+        order_value = calculate_order_value(context, symbol, direction)
+        log.info(f"计算开仓金额: {symbol} {direction} 金额: {order_value}")
+        
+        # 如果计算出的金额为0,说明资金不足,跳过开仓
+        if order_value <= 0:
+            log.warning(f"资金不足,跳过开仓 {symbol} {direction}")
+            continue
+        
+        # 执行开仓
+        success = open_position(context, symbol, order_value, direction, signal)
+        
+        if success:
+            # 获取实际保证金(只有在开仓成功时才能获取)
+            actual_margin = g.trade_history[symbol]['actual_margin']
+            log.info(f"成功开仓 {symbol} {direction} 金额: {order_value}, 实际保证金: {actual_margin:.0f}")
+        else:
+            log.warning(f"开仓失败 {symbol} {direction}")
+
+def task_8_check_position_switch(context):
+    """任务8: 针对已经持仓的标的,检查是否换月移仓"""
+    # log.info("执行任务8: 检查换月移仓")
+    
+    switch_result = position_auto_switch(context)
+    if switch_result:
+        log.info(f"执行了 {len(switch_result)} 次移仓换月")
+        for result in switch_result:
+            log.info(f"移仓: {result['before']} -> {result['after']}")
+    # else:
+    #     log.info("无需移仓换月")
+
+def task_9_check_stop_loss_profit(context):
+    """任务9: 针对已经持仓的标的,检查是否止损或止盈"""
+    # log.info("执行任务9: 检查止损止盈")
+    
+    # 遍历所有持仓进行止损止盈检查
+    subportfolio = context.subportfolios[0]
+    long_positions = list(subportfolio.long_positions.values())
+    short_positions = list(subportfolio.short_positions.values())
+    
+    closed_count = 0
+    for position in long_positions + short_positions:
+        if check_stop_loss_profit(context, position):
+            closed_count += 1
+    
+    if closed_count > 0:
+        log.info(f"执行了 {closed_count} 次止损止盈")
+    # else:
+    #     log.info("无需止损止盈")
+
+############################ 数据处理辅助函数 ###################################
+
+def check_has_night_session(underlying_symbol):
+    """检查品种是否有夜盘"""
+    # 有夜盘的品种列表
+    night_session_symbols = {
+        'NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM', 'RB', 'HC', 'I', 'J', 'JM',
+        'A', 'AG', 'AL', 'AU', 'BU', 'C', 'CU', 'FU', 'L', 'P', 'PB', 'RU', 
+        'SC', 'SP', 'SS', 'TA', 'V', 'ZC', 'ZN', 'MA', 'SR', 'OI', 'CF', 'RM',
+        'FG', 'SA', 'UR', 'NR', 'LU', 'BC', 'EC', 'PP', 'EB', 'EG', 'PG'
+    }
+    return underlying_symbol in night_session_symbols
+
+def get_today_minute_data(context, future_code):
+    """获取今日分钟数据"""
+    try:
+        # 判断该品种是否有夜盘
+        underlying_symbol = future_code.split('.')[0][:-4]
+        has_night_session = check_has_night_session(underlying_symbol)
+        
+        end_time = context.current_dt
+        
+        # 获取足够的历史分钟数据
+        minute_data = attribute_history(future_code, 
+                                      count=800,  # 获取足够多的数据
+                                      unit='1m',
+                                      fields=['open', 'close', 'high', 'low', 'volume'],
+                                      df=True)
+        
+        if minute_data is None or len(minute_data) == 0:
+            return None
+        
+        # log.debug(f"原始分钟数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
+        
+        # 提取所有日期(年月日维度)
+        minute_data['date'] = minute_data.index.date
+        unique_dates = sorted(minute_data['date'].unique())
+        # log.debug(f"数据包含的日期: {unique_dates}")
+        
+        if has_night_session:
+            # 有夜盘的品种:需要找到前一交易日的21:00作为今日开盘起点
+            today_date = end_time.date()
+            
+            # 找到今天之前的最后一个交易日
+            previous_trading_dates = [d for d in unique_dates if d < today_date]
+            # log.debug(f"夜盘标的 today_date: {today_date}, previous_trading_dates: {previous_trading_dates}")
+            if not previous_trading_dates:
+                # log.warning(f"找不到{future_code}的前一交易日数据")
+                return minute_data
+            
+            previous_trading_date = max(previous_trading_dates)
+            # log.debug(f"前一交易日: {previous_trading_date}")
+            
+            # 找到前一交易日21:00:00的数据作为开盘起点
+            previous_day_data = minute_data[minute_data['date'] == previous_trading_date]
+            night_21_data = previous_day_data[previous_day_data.index.hour == 21]
+            
+            if len(night_21_data) > 0:
+                # 从前一交易日21:00开始的所有数据
+                start_time = night_21_data.index[0]  # 21:00:00的时间点
+                filtered_data = minute_data[minute_data.index >= start_time]
+                # log.debug(f"夜盘品种,从{start_time}开始,数据量: {len(filtered_data)}")
+                return filtered_data.drop(columns=['date'])
+            else:
+                # log.warning(f"找不到{future_code}前一交易日21:00的数据")
+                # 备选方案:使用今天9:00开始的数据
+                today_data = minute_data[minute_data['date'] == today_date]
+                day_9_data = today_data[today_data.index.hour >= 9]
+                if len(day_9_data) > 0:
+                    return day_9_data.drop(columns=['date'])
+                else:
+                    return minute_data.drop(columns=['date'])
+        else:
+            # 没有夜盘的品种:从今天9:00:00开始
+            today_date = end_time.date()
+            today_data = minute_data[minute_data['date'] == today_date]
+            
+            # 找到今天9:00:00开始的数据
+            day_9_data = today_data[today_data.index.hour >= 9]
+            
+            if len(day_9_data) > 0:
+                # log.debug(f"日盘品种,从今天9:00开始,数据量: {len(day_9_data)}")
+                return day_9_data.drop(columns=['date'])
+            else:
+                # log.warning(f"找不到{future_code}今天9:00的数据")
+                return today_data.drop(columns=['date']) if len(today_data) > 0 else minute_data.drop(columns=['date'])
+        
+    except Exception as e:
+        log.warning(f"获取{future_code}今日分钟数据时出错: {str(e)}")
+    
+    return None
+
+def combine_and_calculate_ma(historical_data, minute_data):
+    """合并历史数据和分钟数据,计算均线"""
+    try:
+        # 将分钟数据聚合为日数据
+        today_data = aggregate_minute_to_daily(minute_data)
+        if today_data is None:
+            return None
+        
+        # 合并历史数据和今日数据
+        combined_data = pd.concat([historical_data, today_data])
+        
+        # 计算移动平均线
+        combined_data['MA5'] = combined_data['close'].rolling(window=5).mean()
+        combined_data['MA10'] = combined_data['close'].rolling(window=10).mean()
+        combined_data['MA20'] = combined_data['close'].rolling(window=20).mean()
+        combined_data['MA30'] = combined_data['close'].rolling(window=30).mean()
+        
+        return combined_data
+        
+    except Exception as e:
+        log.warning(f"合并数据和计算均线时出错: {str(e)}")
+        return None
+
+def aggregate_minute_to_daily(minute_data):
+    """将分钟数据聚合为日数据
+    注意:传入的minute_data已经是经过过滤的今日交易数据
+    - 对于有夜盘的品种:数据从前一交易日21:00开始
+    - 对于无夜盘的品种:数据从当日9:00开始
+    开盘价(open)是第一个分钟K线的开盘价(今日交易开盘价)
+    收盘价(close)是当前最新的分钟K线收盘价,会随时间更新
+    """
+    try:
+        if minute_data is None or len(minute_data) == 0:
+            return None
+        
+        # 获取今日日期(使用最后一条数据的日期作为今日日期)
+        today_date = minute_data.index[-1].date()
+        # log.debug(f"聚合数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
+        # log.debug(f"开盘价数据: {minute_data['open'].iloc[0]:.2f}")
+        
+        # 聚合为日数据
+        # 开盘价:今日交易开始时的第一个分钟K线的开盘价(固定不变)
+        # 收盘价:当前最新分钟K线的收盘价(实时更新)
+        # 最高价:所有分钟K线中的最高价
+        # 最低价:所有分钟K线中的最低价
+        # 成交量:所有分钟K线成交量的总和
+        daily_data = pd.DataFrame({
+            'open': [minute_data['open'].iloc[0]],  # 今日交易开始时的开盘价
+            'close': [minute_data['close'].iloc[-1]],  # 当前收盘价,实时更新
+            'high': [minute_data['high'].max()],
+            'low': [minute_data['low'].min()],
+            'volume': [minute_data['volume'].sum()]
+        }, index=[pd.Timestamp(today_date)])
+        
+        # log.debug(f"聚合后的日数据: 开盘价={daily_data['open'].iloc[0]:.2f}, 收盘价={daily_data['close'].iloc[0]:.2f}")
+        
+        return daily_data
+        
+    except Exception as e:
+        log.warning(f"聚合分钟数据时出错: {str(e)}")
+        return None
+
+############################ 原有函数保持不变 ###################################
+
+def check_latest_multi_ma_cross(data, future_code):
+    """检查最新的多均线穿越情况"""
+    if len(data) < 2:
+        return None
+        
+    # 获取最新两天的数据
+    today = data.iloc[-1]
+    yesterday = data.iloc[-2]
+    # log.info(f"today: {today}")
+    # log.info(f"yesterday: {yesterday}")
+    
+    # 检查多均线穿越
+    cross_result = check_multi_ma_cross_single_day(today)
+    if not cross_result:
+        return None
+    
+    # TODO:验证穿越的有效性,暂时感觉没用先注释了
+    # 验证穿越的有效性
+    # if not validate_ma_cross(today, yesterday):
+    #     return None
+    
+    return {
+        'symbol': future_code,
+        'date': today.name,
+        'direction': cross_result['direction'],
+        'open': today['open'],
+        'close': today['close'],
+        'high': today['high'],
+        'low': today['low'],
+        'ma5': today['MA5'],
+        'ma10': today['MA10'],
+        'ma20': today['MA20'],
+        'ma30': today['MA30'],
+        'critical_ma_name': cross_result['critical_ma_name'],
+        'critical_ma_value': cross_result['critical_ma_value'],
+        'crossed_count': cross_result['crossed_count']
+    }
+
+def check_multi_ma_cross_single_day(row):
+    """检查单日K线是否穿越了至少3条均线,并返回临界线信息"""
+    open_price = row['open']
+    close_price = row['close']
+    ma_values = [('MA5', row['MA5']), ('MA10', row['MA10']), ('MA20', row['MA20']), ('MA30', row['MA30'])]
+    log.debug(f"open_price: {open_price}, close_price: {close_price}, ma_values: {ma_values}")
+
+    # 检查是否有NaN值
+    if pd.isna(row['MA5']) or pd.isna(row['MA10']) or pd.isna(row['MA20']) or pd.isna(row['MA30']):
+        return None
+    
+    # 如果开盘价和收盘价相等,不可能有穿越
+    if open_price == close_price:
+        return None
+    
+    crossed_mas = []
+    
+    # 上涨(阳线),检查上穿
+    if close_price > open_price:
+        for ma_name, ma_value in ma_values:
+            if open_price < ma_value and close_price > ma_value:
+                crossed_mas.append((ma_name, ma_value))
+        
+        if len(crossed_mas) >= g.min_cross_mas:
+            # 找到最大的穿越线作为临界线
+            critical_ma = max(crossed_mas, key=lambda x: x[1])
+            return {
+                'direction': 'up',
+                'critical_ma_name': critical_ma[0],
+                'critical_ma_value': critical_ma[1],
+                'crossed_count': len(crossed_mas)
+            }
+    
+    # 下跌(阴线),检查下穿        
+    elif open_price > close_price:
+        for ma_name, ma_value in ma_values:
+            if open_price > ma_value and close_price < ma_value:
+                crossed_mas.append((ma_name, ma_value))
+        
+        if len(crossed_mas) >= g.min_cross_mas:
+            # 找到最小的穿越线作为临界线
+            critical_ma = min(crossed_mas, key=lambda x: x[1])
+            return {
+                'direction': 'down',
+                'critical_ma_name': critical_ma[0],
+                'critical_ma_value': critical_ma[1],
+                'crossed_count': len(crossed_mas)
+            }
+    
+    return None
+
+def validate_ma_cross(today, yesterday):
+    """验证均线穿越的有效性"""
+    # 检查均线排列是否合理
+    ma_today = [today['MA5'], today['MA10'], today['MA20'], today['MA30']]
+    ma_yesterday = [yesterday['MA5'], yesterday['MA10'], yesterday['MA20'], yesterday['MA30']]
+    
+    # 简单的均线排列检查
+    # 可以根据需要添加更复杂的验证逻辑
+    return True
+
+def check_sufficient_capital(context, symbol):
+    """检查资金是否充足"""
+    try:
+        # 计算单手保证金
+        single_hand_margin = calculate_required_margin(context, symbol)
+        # 使用实际可用资金(考虑资金使用比例)
+        available_cash = context.portfolio.available_cash * g.usage_percentage
+        
+        # 检查是否有足够资金开仓至少1手
+        return available_cash >= single_hand_margin
+    except:
+        return False
+
+def check_price_position(signal):
+    """检查价格位置的合理性"""
+    close = signal['close']
+    critical_ma_value = signal['critical_ma_value']
+    
+    # 检查收盘价与临界线的偏离度
+    deviation = abs(close - critical_ma_value) / critical_ma_value
+    
+    # 偏离度需要在合理范围内:大于最小偏离度且小于最大偏离度
+    if deviation < g.price_deviation_min:
+        log.warning(f"价格偏离度过小: {deviation:.3%} < {g.price_deviation_min:.1%}")
+        return False
+    elif deviation > g.price_deviation_max:
+        log.warning(f"价格偏离度过大: {deviation:.3%} > {g.price_deviation_max:.1%}")
+        return False
+    else:
+        log.info(f"价格偏离度合理: {g.price_deviation_min:.1%} <= {deviation:.3%} <= {g.price_deviation_max:.1%}")
+        return True
+
+############################ 交易执行函数 ###################################
+
+def open_position(context, security, value, direction, signal):
+    """开仓"""
+    try:
+        # 记录交易前的可用资金
+        cash_before = context.portfolio.available_cash
+        
+        order = order_target_value(security, value, side=direction)
+        log.info(f"order: {order}")
+        
+        if order is not None and order.filled > 0:
+            # 记录交易后的可用资金
+            cash_after = context.portfolio.available_cash
+            
+            # 计算实际资金变化
+            cash_change = cash_before - cash_after
+            
+            # 获取订单价格和数量
+            order_price = order.avg_cost if order.avg_cost else order.price
+            order_amount = order.filled
+            
+            # 计算实际保证金比例
+            underlying_symbol = security.split('.')[0][:-4]
+            multiplier = g.multiplier.get(underlying_symbol, 10)
+            
+            # 单笔保证金 = 资金变化 / 数量
+            single_margin = cash_change / order_amount if order_amount > 0 else 0
+            
+            # 实际保证金比例 = 单笔保证金 / (订单价格 * 合约乘数)
+            contract_value = order_price * multiplier
+            actual_margin_rate = single_margin / contract_value if contract_value > 0 else 0
+            
+            # 校准保证金比例(只有变化大于1%时才更新)
+            current_rate = g.margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
+            rate_change = abs(actual_margin_rate - current_rate) / current_rate if current_rate > 0 else 0
+            
+            if rate_change > 0.01:  # 变化大于1%
+                # 记录保证金比例变化历史
+                history_key = f"{underlying_symbol}_{direction}"
+                if history_key not in g.margin_rate_history:
+                    g.margin_rate_history[history_key] = []
+                
+                g.margin_rate_history[history_key].append({
+                    'date': context.current_dt.date(),
+                    'time': context.current_dt.time(),
+                    'old_rate': current_rate,
+                    'new_rate': actual_margin_rate,
+                    'change_pct': rate_change * 100,
+                    'security': security
+                })
+                
+                # 直接更新默认保证金比例
+                g.margin_rates[direction][underlying_symbol] = actual_margin_rate
+                
+                log.info(f"保证金比例校准: {underlying_symbol}_{direction} {current_rate:.4f} -> {actual_margin_rate:.4f} (变化{rate_change*100:.1f}%)")
+            
+            # 记录当日交易
+            g.today_trades.append({
+                'security': security,
+                'underlying_symbol': underlying_symbol,
+                'direction': direction,
+                'order_amount': order_amount,
+                'order_price': order_price,
+                'cash_change': cash_change,
+                'actual_margin_rate': actual_margin_rate,
+                'time': context.current_dt
+            })
+            
+            # 记录交易信息
+            g.trade_history[security] = {
+                'entry_price': order_price,
+                'position_value': value,
+                'actual_margin': cash_change,
+                'direction': direction, 
+                'entry_time': context.current_dt,
+                'signal_info': signal
+            }
+            
+            log.info(f"开仓成功 - 品种: {underlying_symbol}, 手数: {order_amount}, 订单价格: {order_price:.2f}")
+            log.info(f"资金变化: {cash_change:.0f}, 实际保证金比例: {actual_margin_rate:.4f}")
+            return True
+            
+    except Exception as e:
+        log.warning(f"开仓失败 {security}: {str(e)}")
+    
+    return False
+
+def close_position(context, security, direction):
+    """平仓"""
+    try:
+        order = order_target_value(security, 0, side=direction)
+        
+        if order is not None and order.filled > 0:
+            underlying_symbol = security.split('.')[0][:-4]
+            
+            # 记录当日交易(平仓)
+            g.today_trades.append({
+                'security': security,
+                'underlying_symbol': underlying_symbol,
+                'direction': direction,
+                'order_amount': -order.filled,  # 负数表示平仓
+                'order_price': order.avg_cost if order.avg_cost else order.price,
+                'cash_change': 0,  # 平仓不计算保证金变化
+                'actual_margin_rate': 0,
+                'time': context.current_dt
+            })
+            
+            log.info(f"平仓成功 - 品种: {underlying_symbol}, 手数: {order.filled}")
+            
+            # 从交易历史中移除
+            if security in g.trade_history:
+                del g.trade_history[security]
+            return True
+            
+    except Exception as e:
+        log.warning(f"平仓失败 {security}: {str(e)}")
+    
+    return False
+
+def check_stop_loss_profit(context, position):
+    """检查止损止盈"""
+    security = position.security
+    
+    if security not in g.trade_history:
+        return False
+    
+    trade_info = g.trade_history[security]
+    entry_price = trade_info['entry_price']
+    current_price = position.price
+    direction = trade_info['direction']
+    
+    # 计算盈亏
+    if direction == 'long':
+        pnl_ratio = (current_price - entry_price) / entry_price
+    else:
+        pnl_ratio = (entry_price - current_price) / entry_price
+    
+    # 止损条件
+    stop_loss_ratio = -0.03  # 3%止损
+    # 止盈条件
+    take_profit_ratio = 0.05  # 5%止盈
+    
+    if pnl_ratio <= stop_loss_ratio:
+        log.info(f"触发止损 {security} 盈亏比例: {pnl_ratio:.2%}")
+        close_position(context, security, direction)
+        return True
+    elif pnl_ratio >= take_profit_ratio:
+        log.info(f"触发止盈 {security} 盈亏比例: {pnl_ratio:.2%}")
+        close_position(context, security, direction) 
+        return True
+    
+    return False
+
+############################ 辅助函数 ###################################
+
+def calculate_order_value(context, security, direction):
+    """计算开仓金额"""
+    current_price = get_current_data()[security].last_price
+    underlying_symbol = security.split('.')[0][:-4]
+    
+    # 使用保证金比例(已经过校准)
+    margin_rate = g.margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
+    
+    multiplier = g.multiplier.get(underlying_symbol, 10)
+    
+    # 计算单手保证金
+    single_hand_margin = current_price * multiplier * margin_rate
+    
+    # 还要考虑可用资金限制
+    available_cash = context.portfolio.available_cash * g.usage_percentage
+    log.info(f"可用资金: {available_cash:.0f}")
+    
+    # 根据单个标的最大持仓保证金限制计算开仓数量
+    max_margin = g.max_margin_per_position
+    
+    if single_hand_margin <= max_margin:
+        # 如果单手保证金不超过最大限制,计算最大可开仓手数
+        max_hands = int(max_margin / single_hand_margin)
+        
+        max_hands_by_cash = int(available_cash / single_hand_margin)
+        
+        # 取两者较小值
+        actual_hands = min(max_hands, max_hands_by_cash)
+
+        # 实际保证金金额
+        actual_margin = current_price * multiplier * margin_rate * actual_hands
+
+        # 计算订单金额
+        order_value = actual_margin
+        
+        log.info(f"单手保证金: {single_hand_margin:.0f}, 最大手数(保证金限制): {max_hands}, 最大手数(资金限制): {max_hands_by_cash}, 实际开仓手数: {actual_hands}, 实际保证金: {actual_margin:.0f}")
+    else:
+        # 如果单手保证金超过最大限制,默认开仓1手
+        actual_hands = 1
+        actual_margin = current_price * multiplier * margin_rate * actual_hands
+
+        # 计算订单金额
+        order_value = actual_margin
+        
+        log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手, 实际保证金: {actual_margin:.0f}")
+    
+    log.info(f"计算结果 - 品种: {underlying_symbol}, 开仓手数: {actual_hands}, 订单金额: {order_value:.0f}, 实际保证金: {actual_margin:.0f}")
+    
+    return order_value
+
+def calculate_required_margin(context, symbol):
+    """计算所需保证金"""
+    current_price = get_current_data()[symbol].last_price
+    underlying_symbol = symbol.split('.')[0][:-4]
+    
+    margin_rate = g.margin_rates.get('long', {}).get(underlying_symbol, 0.10)
+    multiplier = g.multiplier.get(underlying_symbol, 10)
+    
+    return current_price * multiplier * margin_rate
+
+def check_symbol_prefix_match(symbol, hold_symbols):
+    """检查是否有相似的持仓品种"""
+    symbol_prefix = symbol[:-9]
+    
+    for hold_symbol in hold_symbols:
+        hold_symbol_prefix = hold_symbol[:-9]
+        if symbol_prefix == hold_symbol_prefix:
+            return True
+    return False
+
+def after_market_close(context):
+    """收盘后运行函数"""
+    log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
+    
+    # 只有当天有交易时才打印统计信息
+    if g.today_trades:
+        print_daily_trading_summary(context)
+        print_margin_rate_changes(context)
+        
+        # 清空当日交易记录
+        g.today_trades = []
+    
+    log.info('A day ends')
+    log.info('##############################################################')
+
+def print_daily_trading_summary(context):
+    """打印当日交易汇总"""
+    if not g.today_trades:
+        return
+    
+    log.info("\n=== 当日交易汇总 ===")
+    total_margin = 0
+    
+    for trade in g.today_trades:
+        if trade['order_amount'] > 0:  # 开仓
+            log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
+                  f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f} "
+                  f"比例:{trade['actual_margin_rate']:.4f}")
+            total_margin += trade['cash_change']
+        else:  # 平仓
+            log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
+                  f"价格:{trade['order_price']:.2f}")
+    
+    log.info(f"当日保证金占用: {total_margin:.0f}")
+    log.info("==================\n")
+
+def print_margin_rate_changes(context):
+    """打印保证金比例变化记录"""
+    if not g.margin_rate_history:
+        return
+    
+    log.info("\n=== 保证金比例变化记录 ===")
+    for key, history in g.margin_rate_history.items():
+        log.info(f"{key}:")
+        for record in history:
+            log.info(f"  {record['date']} {record['time']}: {record['old_rate']:.4f} -> {record['new_rate']:.4f} "
+                  f"(变化{record['change_pct']:.1f}%)")
+    log.info("========================\n")
+
+########################## 自动移仓换月函数 #################################
+def position_auto_switch(context,pindex=0,switch_func=None, callback=None):
+    """
+    期货自动移仓换月。默认使用市价单进行开平仓。
+    :param context: 上下文对象
+    :param pindex: 子仓对象
+    :param switch_func: 用户自定义的移仓换月函数.
+        函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
+    :param callback: 移仓换月完成后的回调函数。
+        函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
+    :return: 发生移仓换月的标的。类型为列表。
+    """
+    import re
+    subportfolio = context.subportfolios[pindex]
+    symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
+    switch_result = []
+    for symbol in symbols:
+        match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
+        if not match:
+            # raise ValueError("未知期货标的: {}".format(symbol))
+            raise ValueError("Unknow target: {}".format(symbol))
+        else:
+            dominant = get_dominant_future(match.groupdict()["underlying_symbol"])
+            cur = get_current_data()
+            symbol_last_price = cur[symbol].last_price
+            dominant_last_price = cur[dominant].last_price
+            log.info(f'current_hold_symbol: {symbol}, current_main_symbol: {dominant}')
+            
+            if dominant > symbol:
+                for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
+                    if symbol not in positions_.keys():
+                        continue
+                    else :
+                        p = positions_[symbol]
+
+                    if switch_func is not None:
+                        switch_func(context, pindex, p, dominant)
+                    else:
+                        amount = p.total_amount
+                        # 跌停不能开空和平多,涨停不能开多和平空。
+                        if p.side == "long":
+                            symbol_low_limit = cur[symbol].low_limit
+                            dominant_high_limit = cur[dominant].high_limit
+                            if symbol_last_price <= symbol_low_limit:
+                                # log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
+                                log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
+                                continue
+                            elif dominant_last_price >= dominant_high_limit:
+                                # log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(symbol))
+                                log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
+                                continue
+                            else:
+                                # log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
+                                log.info("Start the exchange: ({0},long) -> ({1},long)".format(symbol, dominant))
+                                order_old = order_target(symbol,0,side='long')
+                                if order_old != None and order_old.filled > 0:
+                                    order_new = order_target(dominant,amount,side='long')
+                                    if order_new != None and order_new.filled >0:
+                                        switch_result.append({"before": symbol, "after":dominant, "side": "long"})
+                                        # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
+                                        g.trade_history[dominant] = g.trade_history[symbol]
+                                        del g.trade_history[symbol]
+                                    else:
+                                        # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(domaint))
+                                        log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
+                                        # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
+                                        log.warning(f'换月多头失败{dominant}, {g.trade_history[symbol]}')
+                                        g.change_fail_history[domaint] = g.trade_history[symbol]
+                                        del g.trade_history[symbol]
+                            if callback:
+                                callback(context, pindex, p, dominant)
+                        if p.side == "short":
+                            symbol_high_limit = cur[symbol].high_limit
+                            dominant_low_limit = cur[dominant].low_limit
+                            if symbol_last_price >= symbol_high_limit:
+                                # log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
+                                log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
+                                continue
+                            elif dominant_last_price <= dominant_low_limit:
+                                # log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(symbol))
+                                log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
+                                continue
+                            else:
+                                # log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
+                                log.info("Start the exchange: ({0},short) -> ({1},short)".format(symbol, dominant))
+                                order_old = order_target(symbol,0,side='short')
+                                if order_old != None and order_old.filled > 0:
+                                    log.info(f'换月做空{dominant},数量位{amount}')
+                                    order_new = order_target(dominant,amount,side='short')
+                                    if order_new != None and order_new.filled >0:
+                                        switch_result.append({"before": symbol, "after":dominant, "side": "short"})
+                                        # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
+                                        g.trade_history[dominant] = g.trade_history[symbol]
+                                        del g.trade_history[symbol]
+                                    else:
+                                        # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(dominant))
+                                        log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
+                                        # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
+                                        log.warning(f'换月空头失败{dominant}, {g.trade_history[symbol]}')
+                                        g.change_fail_history[dominant] = g.trade_history[symbol]
+                                        log.warning(f'失败记录{g.change_fail_history}')
+                                        del g.trade_history[symbol]
+                                # order_target(symbol,0,side='short')
+                                # order_target(dominant,amount,side='short')
+                                # switch_result.append({"before": symbol, "after": dominant, "side": "short"})
+                                if callback:
+                                    callback(context, pindex, p, dominant)
+    return switch_result
+
+def count_ma_crosses(data, days):
+    """
+    判断过去指定天数内4条MA均线的交叉次数
+    :param data: 包含MA5, MA10, MA20, MA30的DataFrame
+    :param days: 检查的天数
+    :return: 总交叉次数
+    """
+    if len(data) < days + 1:
+        return 0
+    
+    # 获取最近days天的数据
+    recent_data = data.iloc[-days-1:]
+    
+    ma5 = recent_data['MA5'].values
+    ma10 = recent_data['MA10'].values
+    ma20 = recent_data['MA20'].values
+    ma30 = recent_data['MA30'].values
+    
+    # 检查是否有NaN值
+    if np.any(np.isnan([ma5, ma10, ma20, ma30])):
+        return 0
+    
+    # 计算各均线间的交叉次数
+    cross_5_10 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma10[i] and ma5[i-1] < ma10[i-1]) or 
+                                                      (ma5[i] < ma10[i] and ma5[i-1] > ma10[i-1]))])
+    cross_5_20 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma20[i] and ma5[i-1] < ma20[i-1]) or 
+                                                      (ma5[i] < ma20[i] and ma5[i-1] > ma20[i-1]))])
+    cross_5_30 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma30[i] and ma5[i-1] < ma30[i-1]) or 
+                                                      (ma5[i] < ma30[i] and ma5[i-1] > ma30[i-1]))])
+    cross_10_20 = sum([1 for i in range(1, len(ma10)) if ((ma10[i] > ma20[i] and ma10[i-1] < ma20[i-1]) or 
+                                                      (ma10[i] < ma20[i] and ma10[i-1] > ma20[i-1]))])
+    cross_10_30 = sum([1 for i in range(1, len(ma10)) if ((ma10[i] > ma30[i] and ma10[i-1] < ma30[i-1]) or 
+                                                      (ma10[i] < ma30[i] and ma10[i-1] > ma30[i-1]))])
+    cross_20_30 = sum([1 for i in range(1, len(ma20)) if ((ma20[i] > ma30[i] and ma20[i-1] < ma30[i-1]) or 
+                                                      (ma20[i] < ma30[i] and ma20[i-1] > ma30[i-1]))])
+    
+    total_crosses = cross_5_10 + cross_5_20 + cross_5_30 + cross_10_20 + cross_10_30 + cross_20_30
+    
+    log.debug(f'总交叉数: {total_crosses}, MA5-MA10: {cross_5_10}, MA5-MA20: {cross_5_20}, MA5-MA30: {cross_5_30}, MA10-MA20: {cross_10_20}, MA10-MA30: {cross_10_30}, MA20-MA30: {cross_20_30}')
+    
+    return total_crosses

+ 157 - 1
Lib/future/README.md

@@ -1,5 +1,11 @@
 # 期货投资策略说明
 
+## 通用信息
+
+### API相关
+1. 期货交易里的`order_target_value`里的`value`建议用保证金的金额,而不是实际价格
+2. 期货交易里的`order_target_value`里的`side`建议用`long`或`short`,而不能为空
+
 ## 沪深300期货蜘蛛网策略
 
 ### 核心思路
@@ -87,7 +93,7 @@
 ### 核心思路
 该策略基于K线实体与多条均线的关系进行交易,通过监控K线实体与均线的交叉、穿越情况以及均线之间的排列形态来判断趋势方向。策略同时结合止损和移仓换月机制来控制风险。
 
-1. [策略来源](https://www.joinquant.com)
+1. [策略来源](https://www.joinquant.com)/ [本地](Lib\future\TrendFalseChange_v002.py)
 2. 策略名称:K线趋势交易策略
 
 ### 主要特点
@@ -187,3 +193,153 @@
   - 手续费:按照不同品种设置
   - 滑点:按照品种特性设置
   - 保证金:按照交易所要求设置
+
+## 穿越均线趋势交易策略
+
+### 核心思路
+该策略基于K线实体在同一天内穿越多条均线来识别建仓时机。策略同时结合止损和移仓换月机制来控制风险。
+
+1. [策略来源](https://www.joinquant.com)
+2. 策略名称:穿越均线趋势交易策略
+
+### 主要特点
+1. 多均线系统(5、10、20、30日均线)
+2. K线形态分析
+3. 完整的止损机制
+4. 自动移仓换月
+5. 支持日内和夜盘交易
+
+### 具体策略逻辑
+
+#### 1. 交易品种
+- 交易品种:商品期货和金融期货
+- 夜盘品种:金属、能源、农产品等
+- 日盘品种:其他商品、股指期货等
+- 交易合约:主力合约
+
+#### 2. 信号生成
+
+##### 2.1 开仓条件
+- 均线系统:
+  - MA5(5日均线)
+  - MA10(10日均线)
+  - MA20(20日均线)
+  - MA30(30日均线)
+- 均线数据更新:
+  - 均线非当天数据更新:这部分数据是在开盘的时候就可以获得日线级别的数据,然后保存在内存中一天的任何时候都可以使用。一天执行一次
+  - 均线当天数据更新:这部分数据是在当天交易过程中获得的分钟级别的数据,然后将最终数据暂时定义为当天收盘价拼接到内存中。每30分钟执行一次。
+- K线形态要求:
+  - 上穿:
+    - 开盘价小于等于5日均线,收盘价大于20日或30日均线
+    - 最低价小于5日均线,收盘价大于30日均线
+    - 开盘价小于等于10日均线,收盘价大于30日均线
+  - 下穿:
+    - 开盘价大于等于5日均线,收盘价小于20日或30日均线
+    - 最高价大于5日均线,收盘价小于30日均线
+    - 开盘价大于等于10日均线,收盘价小于30日均线
+  - 最后开仓点:
+    - 多仓:
+      - 满足上穿条件
+      - 针对最后一根要穿越的均线,盘中(14:30之前),最新价格高于均线价格0.5%,则开仓
+      - 14:30之后,针对最后一根要穿越的均线,最新价格高于均线0.2%,则开仓
+    - 空仓:
+      - 满足下穿条件
+      - 针对最后一根要穿越的均线,盘中(14:30之前),最新价格低于均线价格0.5%,则开仓
+      - 14:30之后,针对最后一根要穿越的均线,最新价格低于均线0.2%,则开仓
+
+#### 3. 仓位管理
+
+##### 3.1 开仓规则
+- 计算开仓数量:
+  ```python
+  订单金额 = 总资产 × 单次开仓比例
+  开仓手数 = 订单金额 / (合约价格 × 合约乘数)
+  ```
+- 开仓限制:
+  1. 检查涨跌停限制
+  2. 考虑保证金要求
+  3. 检查流动性条件
+
+##### 3.2 持仓调整
+- 移仓换月条件:
+  1. 主力合约更换时自动执行
+  2. 确保新旧合约可交易
+  3. 保持原有持仓方向
+- 移仓流程:
+  1. 平掉旧合约
+  2. 开仓新合约
+  3. 更新交易记录
+
+#### 4. 风险控制
+
+##### 4.1 止损机制
+- 固定止损:
+  - 初始止损额度:**initial_loss_limit**(默认-4000)
+  - 每日调整:**loss_increment_per_day**(默认200)
+- 均线止损:
+  - 监控均线偏离度
+  - 突破重要均线立即止损
+
+##### 4.2 特殊情况处理
+- 涨跌停板:
+  - 无法开仓时取消交易
+  - 无法平仓时持续尝试
+- 移仓失败:
+  - 记录失败历史(**g.change_fail_history**)
+  - 保留原有持仓信息
+
+#### 5. 交易执行
+
+##### 5.1 交易时间
+- 日盘:09:00开始交易
+- 夜盘:21:00开始交易
+- 14:55最后一次检查是否开新仓
+
+##### 5.2 核心交易步骤
+1. 获取所有可交易品种(分白天和晚上)
+2. 获取所有可交易品种今天之前所需的数据,并保存到内存中
+3. 检查均线交叉数量,过滤掉交叉过多的品种(一天执行一次)
+4. 获取所有可交易品种今天所需的分钟数据作为今天数据,和2中的数据合并出最新的均线数据,并保存到内存中
+5. 根据交易品种的今天数据和均线数据,判断是否出现了上穿或者下穿的情况
+6. 针对那些有上穿和下穿的情况检查是否满足开仓条件
+7. 针对满足开仓条件的标的,计算购买的金额,并发起交易请求
+8. 针对已经持仓的标的,检查是否换月移仓
+9. 针对已经持仓的标的,检查是否止损或止盈
+
+##### 5.3 均线交叉过滤机制
+- **目的**:过滤掉均线频繁交叉的品种,避免在震荡行情中开仓
+- **检查参数**:
+  - `g.max_ma_crosses`:最大允许的均线交叉数量(默认3次)
+  - `g.ma_cross_check_days`:检查均线交叉的天数(默认5天)
+- **检查逻辑**:
+  - 计算过去5天内MA5、MA10、MA20、MA30之间的交叉次数
+  - 统计所有均线对(MA5-MA10、MA5-MA20、MA5-MA30、MA10-MA20、MA10-MA30、MA20-MA30)的交叉
+  - 如果总交叉数超过最大允许值,该品种当天不参与交易
+- **执行时机**:每天21:05和09:05各执行一次
+
+##### 5.4 不同时间点任务分配
+- 由具体时间触发的
+  - 21:05:任务1, 2, 3, 4, 5, 6, 9
+  - 21:35:任务4, 5, 6, 9
+  - 22:05:任务4, 5, 6, 9
+  - 22:35:任务4, 5, 6, 9
+  - 09:05:任务1, 2, 3, 4, 5, 6, 9
+  - 09:35:任务4, 5, 6, 9
+  - 10:05:任务4, 5, 6, 9
+  - 10:35:任务4, 5, 6, 9
+  - 11:05:任务4, 5, 6, 9
+  - 11:25:任务4, 5, 6, 9
+  - 13:35:任务4, 5, 6, 9
+  - 14:05:任务4, 5, 6, 9
+  - 14:35:任务4, 5, 6, 8, 9
+  - 14:55:任务4, 5, 6, 8, 9
+- 由具体时间触发的
+  - 任务7:任务6满足条件要开仓的时候才会执行任务7
+
+### 交易规则
+- 采用异步报单模式
+- 使用真实价格
+- 考虑交易成本:
+  - 手续费:按照不同品种设置
+  - 滑点:按照品种特性设置
+  - 保证金:按照交易所要求设置

+ 715 - 0
Lib/future/TrendBreakoutStrategy_v003.py

@@ -0,0 +1,715 @@
+# 导入函数库
+from jqdata import *
+from jqdata import finance
+import pandas as pd
+from datetime import date, datetime, timedelta
+import re
+
+# 趋势突破交易策略 v003
+# 基于均线趋势突破的期货交易策略 - 修复版本
+
+# 设置以便完整打印 DataFrame
+pd.set_option('display.max_rows', None)
+pd.set_option('display.max_columns', None)
+pd.set_option('display.width', None)
+pd.set_option('display.max_colwidth', 20)
+
+## 初始化函数
+def initialize(context):
+    # 设定沪深300作为基准
+    set_benchmark('000300.XSHG')
+    # 开启动态复权模式(真实价格)
+    set_option('use_real_price', True)
+    log.info('趋势突破交易策略初始化开始')
+
+    ### 期货相关设定 ###
+    # 设定账户为金融账户
+    set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
+    # 期货类每笔交易时的手续费
+    set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
+    # 设置期货交易的滑点
+    set_slippage(StepRelatedSlippage(2))
+    
+    # 初始化全局变量
+    g.usage_percentage = 0.8  # 最大持股数量
+    g.default_days = 10  # 判断趋势线的最小天数
+    g.continuous_days_length = 5  # 破趋势后的观察天数
+    g.change_direction_days = 5  # 检查均线穿过的天数范围
+    g.crossed_symbols_history = {}  # 用于存储过去几天的穿越信息
+    g.trade_history = {}  # 初始化交易记录
+    g.change_fail_history = {}  # 初始化换月建仓失败的记录
+    g.high_low_ma_relations = {}
+    
+    # 定义默认的保证金比例
+    g.default_margin_rates = {
+        'long': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
+        'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
+        'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
+        'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22, 
+        'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
+        'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
+        'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
+        'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
+        'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
+        'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05}, 
+        'short': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
+        'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
+        'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
+        'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22, 
+        'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
+        'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
+        'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
+        'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
+        'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
+        'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05}
+    }
+    
+    g.multiplier = {
+        'A': 10, 'AG': 15, 'AL': 5, 'AO': 20, 'AP': 10, 'AU': 1000, 'B': 10,
+        'BC': 5, 'BR': 5, 'BU': 10, 'C': 10, 'CF': 5, 'CJ': 5, 'CS': 10,
+        'CU': 5, 'CY': 5, 'EB': 5, 'EC': 50, 'EG': 10, 'FG': 20, 'FU': 10,
+        'HC': 10, 'I': 100, 'J': 60, 'JD': 5, 'JM': 100, 
+        'L': 5, 'LC': 1, 'LH': 16, 'LR': 0.05, 'LU': 10, 'M': 10, 'MA': 10, 'NI': 1, 'NR': 10, 'OI': 10,
+        'P': 10, 'PB': 5, 'PF': 5, 'PG': 20, 'PK': 5,
+        'PP': 5, 'RB': 10, 'RI': 0.05, 'RM': 10, 'RU': 10,
+        'SA': 20, 'SC': 1000, 'SF': 5, 'SH': 30, 'SI': 5, 'SM': 5, 'SN': 1, 'SP': 10, 'SR': 10,
+        'SS': 5, 'TA': 5, 'UR': 20, 'V': 5,
+        'Y': 10, 'ZC': 0.05, 'ZN': 5
+    }
+    
+    # 临时止损检查
+    run_daily(loss_control, time='21:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='21:45:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='22:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='22:45:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='09:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='09:45:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='10:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='10:45:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='11:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='13:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='13:45:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='14:15:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='14:56:00', reference_security='IF1808.CCFX')
+
+    # 收盘前运行
+    run_daily(before_market_close, time='14:55', reference_security='IF8888.CCFX')
+
+############################ 主程序中执行函数 ###################################
+
+def before_market_close(context):
+    """收盘前主策略执行"""
+    print("-" * 20 + "New day ending!" + "-" * 20)
+    if len(g.trade_history) > 0:
+        print(f'当前交易记录: {g.trade_history}, 换月失败记录: {g.change_fail_history}')
+    
+    # 1. 检查趋势
+    trend_symbols, daily_data_info = check_trend(context)
+    print_list_elements("趋势标的", trend_symbols)
+    
+    # 2. 检查影线穿越
+    crossed_symbols = check_shadow_cross(context, trend_symbols, daily_data_info)
+    print_list_elements("穿越标的", crossed_symbols)
+    
+    # 3. 检查买入条件
+    buy_symbols = check_buy_condition(context, crossed_symbols)
+    print_list_elements("买入标的", buy_symbols)
+    
+    # 4. 执行交易
+    subportfolio = context.subportfolios[0]
+    hold_symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
+    
+    for symbol, line_label, line_type, direction in buy_symbols:
+        if check_symbol_prefix_match(symbol, hold_symbols):
+            print(f'已有相似持仓 {symbol},跳过交易')
+        else: 
+            print(f'无相似持仓 {symbol},执行交易')
+            value_to_invest = calculate_order_value(context, symbol, direction)
+            open_position(symbol, value_to_invest, direction, line_label)
+
+def loss_control(context):
+    """止损控制"""
+    print("-" * 20 + "止损控制" + "-" * 20)
+    
+    # 检查是否有正常的夜盘
+    now = context.current_dt.time()
+    now_hour = now.hour
+    if now_hour >= 21:
+        test_future = get_dominant_future("A")
+        if test_future:
+            test_data = attribute_history(test_future, 1, '1m', 'close')
+            test_hour = test_data.index[0].hour
+            if test_hour <= 15:
+                print(f'最近的数据小时为: {test_hour},该夜盘不存在,直接停止')
+                return
+    
+    # 先把换月买入失败的重新买入
+    if len(g.change_fail_history) > 0:
+        print(f'检查换月失败的{g.change_fail_history}')
+        for symbol in list(g.change_fail_history.keys()):
+            direction = g.change_fail_history[symbol]['direction']
+            value_to_invest = calculate_order_value(context, symbol, direction)
+            success = open_position(symbol, value_to_invest, direction, g.change_fail_history[symbol].get("line_label", "unknown"))
+            if success:
+                del g.change_fail_history[symbol]
+    
+    # 检查损失
+    target_time = datetime.strptime('14:55:00', '%H:%M:%S').time()
+    potential_future_list = get_potential_future_list(context)
+    
+    # 遍历所有持仓
+    subportfolio = context.subportfolios[0]
+    all_positions = list(subportfolio.long_positions.values()) + list(subportfolio.short_positions.values())
+    
+    for position in all_positions:
+        if position.security in potential_future_list:
+            # 检查固定止损
+            if check_loss_for_close(context, position, position.side):
+                continue
+            
+            # 检查基于动态跟踪线的平仓条件
+            if now > target_time:
+                check_ma_for_close(context, position, 0.01, 4)
+            else:
+                check_ma_for_close(context, position, 0.003, 4)
+
+############################ 交易模块 ###################################
+
+def order_target_value_(security, value, direction):
+    """自定义下单"""
+    if value == 0:
+        log.debug("平仓 %s" % (security))
+    else:
+        log.debug("下单 %s 金额 %f" % (security, value))
+    return order_target_value(security, value, side=direction)
+
+def open_position(security, value, direction, line_label):
+    """开仓"""
+    order = order_target_value_(security, value, direction)
+    if order is not None and order.filled > 0:
+        print(f'成功开仓 {security} 方向 {direction} 线标 {line_label}')
+        g.trade_history[security] = {
+            'entry_price': get_current_data()[security].last_price,
+            'position_value': value,
+            'direction': direction,
+            'line_label': line_label,
+            'finish_time': order.finish_time
+        }
+        return True
+    return False
+
+def close_position(position, direction):
+    """平仓"""
+    security = position.security
+    order = order_target_value_(security, 0, direction)
+    if order is not None:
+        if order.status == OrderStatus.held and order.filled == order.amount:
+            # 如果成功平仓,从交易历史中移除该标的
+            if security in g.trade_history:
+                del g.trade_history[security]
+            return True
+    return False
+
+############################ 策略核心函数 ###################################
+
+def get_potential_future_list(context):
+    """获取可交易的期货品种列表"""
+    potential_night_list = ['NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM']
+    potential_day_list = ['JD', 'UR']
+    
+    if str(context.current_dt.time())[:2] in ('21', '22'):
+        potential_icon_list = potential_night_list
+    else:
+        potential_icon_list = potential_day_list + potential_night_list
+    
+    potential_future_list = []
+    for i in potential_icon_list:
+        dominant_future = get_dominant_future(i)
+        if dominant_future:
+            potential_future_list.append(dominant_future)
+    
+    return potential_future_list
+
+def check_trend(context):
+    """检查品类的主连是否满足形成趋势的条件"""
+    print("-" * 20 + "检查趋势" + "-" * 20)
+    trend_symbols = []
+    daily_data_info = {}
+    
+    # 获取可以交易的所有标的主连
+    potential_future_list = get_potential_future_list(context)
+    potential_future_list = [item for item in potential_future_list if item not in g.trade_history.keys()]
+    
+    # 针对所有标的需要的基础数据
+    ma_crosses_dict = {}
+    for symbol in potential_future_list:
+        # 获取50天的收盘价数据
+        close_data = attribute_history(symbol, 50, '1d', ['close', 'high', 'low', 'open'], df=True)
+        close_series = close_data['close']
+
+        # 计算移动平均线
+        ma5 = close_series.rolling(window=5).mean()
+        ma10 = close_series.rolling(window=10).mean()
+        ma20 = close_series.rolling(window=20).mean()
+        ma30 = close_series.rolling(window=30).mean()
+
+        trend_info = {'symbol': symbol, 'trend_lines': []}
+        daily_data = []
+
+        # 初始化连续天数计数器
+        continuous_days = {
+            'above_ma5': [0] * g.continuous_days_length,
+            'below_ma5': [0] * g.continuous_days_length,
+            'above_ma10': [0] * g.continuous_days_length,
+            'below_ma10': [0] * g.continuous_days_length,
+            'above_ma20': [0] * g.continuous_days_length,
+            'below_ma20': [0] * g.continuous_days_length,
+            'above_ma30': [0] * g.continuous_days_length,
+            'below_ma30': [0] * g.continuous_days_length
+        }
+        
+        # 获取连续在某一个均线上或者下的天数
+        for i in range(len(close_series)):
+            update_continuous_days(continuous_days, close_series[i], ma5[i], ma10[i], ma20[i], ma30[i], g.continuous_days_length)
+
+            # 收集每日数据
+            day_data = {
+                'date': close_data.index[i].date(),
+                'close': close_series[i],
+                'high': close_data['high'][i],
+                'low': close_data['low'][i],
+                'open': close_data['open'][i],
+                'ma5': ma5[i],
+                'ma10': ma10[i],
+                'ma20': ma20[i],
+                'ma30': ma30[i],
+                'continuous_above_ma5': continuous_days['above_ma5'].copy(),
+                'continuous_below_ma5': continuous_days['below_ma5'].copy(),
+                'continuous_above_ma10': continuous_days['above_ma10'].copy(),
+                'continuous_below_ma10': continuous_days['below_ma10'].copy(),
+                'continuous_above_ma20': continuous_days['above_ma20'].copy(),
+                'continuous_below_ma20': continuous_days['below_ma20'].copy(),
+                'continuous_above_ma30': continuous_days['above_ma30'].copy(),
+                'continuous_below_ma30': continuous_days['below_ma30'].copy()
+            }
+            daily_data.append(day_data)
+        
+        daily_data_info[symbol] = daily_data
+        
+        # 检查过去一定天数内均线的相交次数
+        ma_crosses_dict[symbol] = count_ma_crosses(daily_data_info[symbol], g.change_direction_days)
+                
+        # 检查哪些均线会形成什么类型的趋势
+        for ma_type in ['ma5', 'ma10', 'ma20', 'ma30']:
+            above_days = continuous_days[f'above_{ma_type}']
+            below_days = continuous_days[f'below_{ma_type}']
+        
+            above_condition = any(day >= g.default_days for day in above_days)
+            below_condition = any(day >= g.default_days for day in below_days)
+        
+            if above_condition:
+                trend_info['trend_lines'].append((ma_type, 'support'))
+        
+            if below_condition:
+                trend_info['trend_lines'].append((ma_type, 'resistance'))
+
+        if trend_info['trend_lines']:
+            trend_symbols.append(trend_info)
+    
+    # 去除掉在一段时间内均线过于频繁交叉的对象
+    valid_trend_symbols = []
+    
+    for trend_info in trend_symbols:
+        symbol = trend_info["symbol"]
+        ma_crosses = ma_crosses_dict[symbol]
+        
+        if ma_crosses <= 3:
+            valid_trend_symbols.append(trend_info)
+                
+    return valid_trend_symbols, daily_data_info
+
+def check_shadow_cross(context, trend_symbols, daily_data_info):
+    """检查影线穿越"""
+    print("-" * 20 + "检查影线穿越" + "-" * 20)
+    
+    # 检查并进行换月
+    switch_result = position_auto_switch(context)
+    if switch_result:
+        print(f'换月结果: {switch_result}')
+    
+    today_crossed_symbols = {}
+    
+    for trend_info in trend_symbols:
+        symbol = trend_info['symbol']
+        
+        # 获取昨天的数据
+        yesterday_data = daily_data_info[symbol][-1]
+        
+        # 临时存储当前标的的穿越信息
+        symbol_crosses = []
+
+        for line_label, line_type in trend_info['trend_lines']:
+            yesterday_day = yesterday_data['date']
+            close = yesterday_data['close']
+            high = yesterday_data['high']
+            low = yesterday_data['low']
+            ma_value = yesterday_data[line_label]
+            close_ma_difference = (close - ma_value) / ma_value
+            
+            # 删除指定的键
+            yesterday_data_copy = yesterday_data.copy()
+            keys_to_remove = ['continuous_above_ma5', 'continuous_below_ma5', 'continuous_above_ma10', 'continuous_below_ma10', 'continuous_above_ma20', 'continuous_below_ma20', 'continuous_above_ma30', 'continuous_below_ma30']
+            for key in keys_to_remove:
+                yesterday_data_copy.pop(key, None)
+
+            # 判断上一个交易日完整的数据中是否穿越
+            if (line_type == 'support' and low < ma_value and close_ma_difference <= 0.0005) or (line_type == 'resistance' and high > ma_value and close_ma_difference >= -0.0005):
+                symbol_crosses.append({
+                    'date': yesterday_day,
+                    'symbol': symbol,
+                    'line_label': line_label,
+                    'line_type': line_type,
+                    'direction': 'long' if line_type == 'support' else 'short',
+                    'latest_data': yesterday_data_copy
+                })
+                print(f"{symbol} 穿越 {line_label} ({line_type})")
+
+        # 从符合条件的趋势线中选择数字较大的
+        if symbol_crosses:
+            best_cross = max(symbol_crosses, key=lambda x: int(''.join(filter(str.isdigit, x['line_label']))))
+            update_crossed_symbols_history(context, best_cross)
+            
+    # 针对出现趋势变化的检查均线顺序、破趋势天数、收盘价和均线的最高点关系
+    for symbol, records in g.crossed_symbols_history.items():
+        latest_record = max(records, key=lambda x: x['date'])
+        
+        # 检查各种条件
+        relation_check = check_ma_relations(context, symbol)
+        duration_check, ma_close = check_cross_details(context, symbol)
+        
+        if relation_check and duration_check and ma_close:
+            print(f'{symbol}满足所有条件,加入购买清单')
+            today_crossed_symbols[symbol] = [latest_record]
+            
+    return [item for sublist in today_crossed_symbols.values() for item in sublist]
+
+def check_buy_condition(context, crossed_symbols):
+    """检查买入条件"""
+    print("-" * 20 + "检查买入条件" + "-" * 20)
+    buy_symbols = []
+
+    for crossed_symbol in crossed_symbols:
+        symbol = crossed_symbol['symbol']
+        line_label = crossed_symbol['line_label']
+        line_type = crossed_symbol['line_type']
+        
+        # 获取最新数据
+        latest_data = crossed_symbol['latest_data']
+        ma_value = latest_data[line_label]
+        close_price = latest_data['close']
+        today_change = (latest_data['close'] - latest_data['open']) / latest_data['open']
+
+        if line_label != "ma5":
+            if line_type == 'support' and 1.005 * ma_value <= close_price <= 1.02 * ma_value and today_change >= -0.002:
+                buy_symbols.append((symbol, line_label, 'support', 'long'))
+            elif line_type == 'resistance' and 0.98 * ma_value <= close_price <= 0.995 * ma_value and today_change <= 0.002:
+                buy_symbols.append((symbol, line_label, 'resistance', 'short'))
+
+    return buy_symbols
+
+############################ 辅助函数 ###################################
+
+def calculate_order_value(context, security, direction):
+    """计算可以用于交易的金额"""
+    current_price = get_current_data()[security].last_price
+    underlying_symbol = security.split('.')[0][:-4]
+
+    # 获取保证金比例
+    margin_rate = g.default_margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
+    # 获取合约乘数
+    multiplier = g.multiplier.get(underlying_symbol, 10)
+    # 计算单手保证金
+    single_hand_margin = current_price * multiplier * margin_rate
+
+    # 根据单手保证金决定购买手数
+    if single_hand_margin <= 20000:
+        total_margin = 20000
+    else:
+        total_margin = single_hand_margin
+
+    return total_margin
+
+def update_continuous_days(continuous_days, close, ma5, ma10, ma20, ma30, length):
+    """更新连续天数"""
+    for key in ['above_ma5', 'below_ma5', 'above_ma10', 'below_ma10', 'above_ma20', 'below_ma20', 'above_ma30', 'below_ma30']:
+        condition_met = False
+        if ((key == 'above_ma5' and close > ma5) or
+            (key == 'below_ma5' and close < ma5) or
+            (key == 'above_ma10' and close > ma10) or
+            (key == 'below_ma10' and close < ma10) or
+            (key == 'above_ma20' and close > ma20) or
+            (key == 'below_ma20' and close < ma20) or
+            (key == 'above_ma30' and close > ma30) or
+            (key == 'below_ma30' and close < ma30)):
+            condition_met = True
+        
+        if condition_met:
+            continuous_days[key].insert(0, continuous_days[key][0] + 1)
+        else:
+            continuous_days[key].insert(0, 0)
+        continuous_days[key] = continuous_days[key][:length]
+
+def count_ma_crosses(future_data, days):
+    """计算均线交叉次数"""
+    recent_data = future_data[-days:]
+    ma5 = [day['ma5'] for day in recent_data]
+    ma10 = [day['ma10'] for day in recent_data]
+    ma20 = [day['ma20'] for day in recent_data]
+    ma30 = [day['ma30'] for day in recent_data]
+    
+    cross_5_10 = sum([1 for i in range(1, len(ma5)) if ((ma5[-i] > ma10[-i] and ma5[-i-1] < ma10[-i-1]) or 
+                                                      (ma5[-i] < ma10[-i] and ma5[-i-1] > ma10[-i-1]))])
+    cross_5_20 = sum([1 for i in range(1, len(ma5)) if ((ma5[-i] > ma20[-i] and ma5[-i-1] < ma20[-i-1]) or 
+                                                      (ma5[-i] < ma20[-i] and ma5[-i-1] > ma20[-i-1]))])
+    cross_5_30 = sum([1 for i in range(1, len(ma5)) if ((ma5[-i] > ma30[-i] and ma5[-i-1] < ma30[-i-1]) or 
+                                                      (ma5[-i] < ma30[-i] and ma5[-i-1] > ma30[-i-1]))])
+    cross_10_20 = sum([1 for i in range(1, len(ma10)) if ((ma10[-i] > ma20[-i] and ma10[-i-1] < ma20[-i-1]) or 
+                                                      (ma10[-i] < ma20[-i] and ma10[-i-1] > ma20[-i-1]))])
+    cross_10_30 = sum([1 for i in range(1, len(ma10)) if ((ma10[-i] > ma30[-i] and ma10[-i-1] < ma30[-i-1]) or 
+                                                      (ma10[-i] < ma30[-i] and ma10[-i-1] > ma30[-i-1]))])
+    cross_20_30 = sum([1 for i in range(1, len(ma20)) if ((ma20[-i] > ma30[-i] and ma20[-i-1] < ma30[-i-1]) or 
+                                                      (ma20[-i] < ma30[-i] and ma20[-i-1] > ma30[-i-1]))])
+    
+    return cross_5_10 + cross_5_20 + cross_5_30 + cross_10_20 + cross_10_30 + cross_20_30
+
+def update_crossed_symbols_history(context, new_record):
+    """更新穿越历史记录"""
+    symbol = new_record['symbol']
+    
+    if symbol not in g.crossed_symbols_history:
+        g.crossed_symbols_history[symbol] = []
+    
+    g.crossed_symbols_history[symbol].append(new_record)
+
+def check_ma_relations(context, symbol):
+    """检查MA均线之间的关系"""
+    if symbol not in g.crossed_symbols_history:
+        return False
+        
+    latest_record = g.crossed_symbols_history[symbol][-1]
+    line_label = latest_record['line_label'].lower()
+    line_type = latest_record['line_type']
+    MA_values = latest_record['latest_data']
+    
+    MA5 = MA_values['ma5']
+    MA10 = MA_values['ma10']
+    MA20 = MA_values['ma20']
+    MA30 = MA_values['ma30']
+    
+    conditions = {
+        ('ma10', 'resistance'): MA5 > MA10 > MA20 > MA30,
+        ('ma10', 'support'): MA30 > MA20 > MA10 > MA5,
+        ('ma20', 'resistance'): (MA30 >= MA20 * 0.999 and MA5 >= MA10 * 0.999) or (MA30 > MA20 > MA10 > MA5),
+        ('ma20', 'support'): (MA20 >= MA30 * 0.999 and MA10 >= MA5 * 0.999) or (MA5 > MA10 > MA20 > MA30),
+        ('ma30', 'resistance'): (MA30 >= MA20 * 0.999 and MA5 >= MA10 * 0.999) or (MA30 > MA20 > MA10 > MA5),
+        ('ma30', 'support'): (MA20 >= MA30 * 0.999 and MA10 >= MA5 * 0.999) or (MA5 > MA10 > MA20 > MA30),
+    }
+    
+    return conditions.get((line_label, line_type), False)
+
+def check_cross_details(context, symbol):
+    """检查穿越详情"""
+    if symbol not in g.crossed_symbols_history:
+        return False, False
+        
+    all_records = g.crossed_symbols_history[symbol]
+    if not all_records:
+        return False, False
+
+    # 检查穿越天数
+    first_day = all_records[0]['date']
+    today = context.current_dt.date()
+    all_days = get_trade_days(first_day, today)
+    duration_length = len(all_days)
+    cross_duration = duration_length <= 6
+
+    # 检查价格与均线的关系
+    ma_close = False
+    for record in all_records:
+        line_label = record['line_label']
+        ma_price = record['latest_data'][line_label]
+        close = record['latest_data']['close']
+        ma_close_rate = abs((close - ma_price) / ma_price)
+        if ma_close_rate <= 0.02:
+            ma_close = True
+
+    return cross_duration, ma_close
+
+def check_loss_for_close(context, position, direction, initial_loss_limit=-4000, loss_increment_per_day=200):
+    """检查固定止损"""
+    if position.security not in g.trade_history:
+        return False
+        
+    trade_info = g.trade_history.get(position.security, {})
+    finish_time = trade_info.get('finish_time')
+    
+    # 获取持仓天数
+    holding_days = 0
+    if finish_time:
+        finish_date = finish_time.date()
+        current_date = context.current_dt.date()
+        all_trade_days = get_all_trade_days()
+        holding_days = sum((finish_date <= d <= current_date) for d in all_trade_days)
+        
+    # 调整损失限制
+    adjusted_loss_limit = initial_loss_limit + holding_days * loss_increment_per_day
+    
+    # 计算盈亏
+    multiplier = position.value / (position.total_amount * position.price)
+    if direction == 'long':
+        revenue = multiplier * (position.price - position.acc_avg_cost) * position.total_amount
+    else:
+        revenue = multiplier * (position.acc_avg_cost - position.price) * position.total_amount
+
+    if revenue < adjusted_loss_limit:
+        close_position(position, g.trade_history[position.security]['direction'])
+        return True
+
+    return False
+
+def check_ma_for_close(context, position, offset_ratio, days_for_adjustment):
+    """根据均线止损"""
+    security = position.security
+    if security not in g.trade_history:
+        return False
+    
+    trade_info = g.trade_history.get(position.security, {})
+    finish_time = trade_info.get('finish_time')
+    line_label = trade_info.get('line_label')
+    
+    # 获取持仓天数
+    holding_days = 0
+    if finish_time:
+        finish_date = finish_time.date()
+        current_date = context.current_dt.date()
+        all_trade_days = get_all_trade_days()
+        holding_days = sum((finish_date <= d <= current_date) for d in all_trade_days)
+    
+    # 计算变化率
+    today_price = get_current_data()[position.security].last_price
+    avg_daily_change_rate = calculate_average_daily_change_rate(position.security)
+    historical_data = attribute_history(position.security, 1, '1d', ['close'])
+    yesterday_close = historical_data['close'].iloc[-1]
+    today_change_rate = abs((today_price - yesterday_close) / yesterday_close)
+
+    # 选择止损均线
+    close_line = None
+    if today_change_rate >= 1.5 * avg_daily_change_rate:
+        close_line = 'ma5'
+    elif holding_days <= days_for_adjustment:
+        close_line = line_label
+    else:
+        close_line = 'ma5' if today_change_rate >= 1.2 * avg_daily_change_rate else 'ma10'
+    
+    # 计算MA值并进行平仓判断
+    ma_values = calculate_ma_values(position.security, [5, 10, 20, 30])
+    adjusted_ma_value = ma_values[close_line] * (1 + offset_ratio if position.side == 'short' else 1 - offset_ratio)
+
+    if (position.side == 'long' and today_price < adjusted_ma_value) or \
+       (position.side == 'short' and today_price > adjusted_ma_value):
+        close_position(position, g.trade_history[position.security]['direction'])
+        return True
+
+    return False
+
+def calculate_average_daily_change_rate(security, days=30):
+    """计算日均变化率"""
+    historical_data = attribute_history(security, days + 1, '1d', ['close'])
+    daily_change_rates = abs(historical_data['close'].pct_change()).iloc[1:]
+    return daily_change_rates.mean()
+
+def calculate_ma_values(security, ma_periods):
+    """计算MA值"""
+    historical_data = attribute_history(security, max(ma_periods), '1d', ['close'])
+    today_price = get_current_data()[security].last_price
+    close_prices = historical_data['close'].tolist() + [today_price]
+    ma_values = {f'ma{period}': sum(close_prices[-period:]) / period for period in ma_periods}
+    return ma_values
+
+def check_symbol_prefix_match(symbol, hold_symbols):
+    """检查是否有相似持仓"""
+    symbol_prefix = symbol[:-9]
+    
+    for hold_symbol in hold_symbols:
+        hold_symbol_prefix = hold_symbol[:-9]
+        if symbol_prefix == hold_symbol_prefix:
+            return True
+    return False
+
+def print_list_elements(title, elements):
+    """打印列表元素"""
+    print(f"{title}:")
+    for item in elements:
+        print(item)
+
+############################ 移仓换月函数 ###################################
+
+def position_auto_switch(context, pindex=0):
+    """期货自动移仓换月"""
+    import re
+    subportfolio = context.subportfolios[pindex]
+    symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
+    switch_result = []
+    
+    for symbol in symbols:
+        match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
+        if not match:
+            continue
+            
+        dominant = get_dominant_future(match.groupdict()["underlying_symbol"])
+        if not dominant or dominant <= symbol:
+            continue
+            
+        cur = get_current_data()
+        symbol_last_price = cur[symbol].last_price
+        dominant_last_price = cur[dominant].last_price
+        
+        for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
+            if symbol not in positions_.keys():
+                continue
+                
+            position = positions_[symbol]
+            amount = position.total_amount
+            side = position.side
+            
+            # 检查涨跌停限制
+            if side == "long":
+                symbol_low_limit = cur[symbol].low_limit
+                dominant_high_limit = cur[dominant].high_limit
+                if symbol_last_price <= symbol_low_limit or dominant_last_price >= dominant_high_limit:
+                    continue
+            else:
+                symbol_high_limit = cur[symbol].high_limit
+                dominant_low_limit = cur[dominant].low_limit
+                if symbol_last_price >= symbol_high_limit or dominant_last_price <= dominant_low_limit:
+                    continue
+            
+            # 执行移仓换月
+            order_old = order_target(symbol, 0, side=side)
+            if order_old is not None and order_old.filled > 0:
+                order_new = order_target(dominant, amount, side=side)
+                if order_new is not None and order_new.filled > 0:
+                    # 换月成功,更新交易记录
+                    if symbol in g.trade_history:
+                        g.trade_history[dominant] = g.trade_history[symbol]
+                        del g.trade_history[symbol]
+                    switch_result.append({"before": symbol, "after": dominant, "side": side})
+                    print(f"移仓换月成功: {symbol} -> {dominant}")
+                else:
+                    # 换月失败,记录失败信息
+                    if symbol in g.trade_history:
+                        g.change_fail_history[dominant] = g.trade_history[symbol]
+                        del g.trade_history[symbol]
+                    print(f"移仓换月失败: {symbol} -> {dominant}")
+    
+    return switch_result 

+ 41 - 41
Lib/future/TrendFalseChange_v002.py

@@ -86,19 +86,19 @@ def initialize(context):
     g.high_low_ma_relations = {}
     
     # 临时止损检查
-    run_daily(loss_control, time='21:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='21:45:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='22:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='22:45:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='09:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='09:45:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='10:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='10:45:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='11:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='13:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='13:45:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='14:15:00', reference_security='IF1808.CCFX')
-    run_daily(loss_control, time='14:56:00', reference_security='IF1808.CCFX')
+    run_daily(loss_control, time='21:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='21:35:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='22:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='22:35:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='09:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='09:35:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='10:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='10:35:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='11:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='13:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='13:35:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='14:05:00', reference_security='IF8888.CCFX')
+    run_daily(loss_control, time='14:35:00', reference_security='IF8888.CCFX')
 
     # 收盘前运行
     run_daily(before_market_close, time='14:55', reference_security='IF8888.CCFX')
@@ -269,35 +269,35 @@ def order_target_value_(security, value, direction):
 #1-1 交易模块-开仓
 #买入指定价值的证券,报单成功并成交(包括全部成交或部分成交,此时成交量大于0)返回True,报单失败或者报单成功但被取消(此时成交量等于0),返回False
 def open_position(security, value, direction, line_label):
-	order = order_target_value_(security, value, direction)
+    order = order_target_value_(security, value, direction)
     # print(f'order: {order}') # 查看订单的信息
-	if order != None and order.filled > 0:
-	    print(f'Make an order of {security} with {line_label} and {direction}')
-	    g.trade_history[security] = {
-	        'entry_price': get_current_data()[security].last_price,
-	        'position_value': value,
-	        'direction': direction,
-	        'line_label': line_label,
-	        'finish_time': order.finish_time
-	    }
-	    return True
-	return False
+    if order != None and order.filled > 0:
+        print(f'Make an order of {security} with {line_label} and {direction}')
+        g.trade_history[security] = {
+            'entry_price': get_current_data()[security].last_price,
+            'position_value': value,
+            'direction': direction,
+            'line_label': line_label,
+            'finish_time': order.finish_time
+        }
+        return True
+    return False
 
 #1-2 交易模块-平仓
 #卖出指定持仓,报单成功并全部成交返回True,报单失败或者报单成功但被取消(此时成交量等于0),或者报单非全部成交,返回False
 def close_position(position, direction):
-	security = position.security
-	order = order_target_value_(security, 0, direction)  # 可能会因停牌失败
-	if order != None:
-		if order.status == OrderStatus.held and order.filled == order.amount:
-		    # g.sold_future[security] = 0 # 避免连续重复买入
-			# 如果成功平仓,从交易历史中移除该标的
-		    if security in g.trade_history:
-		        del g.trade_history[security]
-		      #  print(f'after deal, g.trade_history: {g.trade_history}')
-		    return True
-	
-	return False
+    security = position.security
+    order = order_target_value_(security, 0, direction)  # 可能会因停牌失败
+    if order != None:
+        if order.status == OrderStatus.held and order.filled == order.amount:
+            # g.sold_future[security] = 0 # 避免连续重复买入
+            # 如果成功平仓,从交易历史中移除该标的
+            if security in g.trade_history:
+                del g.trade_history[security]
+              #  print(f'after deal, g.trade_history: {g.trade_history}')
+            return True
+    
+    return False
 	
 #1-3 根据标的情况开仓
 def open_position_by_margin(context, security, direction):
@@ -1512,11 +1512,11 @@ def position_auto_switch(context,pindex=0,switch_func=None, callback=None):
                             dominant_high_limit = cur[dominant].high_limit
                             if symbol_last_price <= symbol_low_limit:
                                 # log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
-                                log.warning("Cant close {} position due to the limit up. Cancelling the exchange.".format(symbol))
+                                log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
                                 continue
                             elif dominant_last_price >= dominant_high_limit:
                                 # log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(symbol))
-                                log.warning("Cant close {} position due to the limit down. Cancelling the exchange.".format(symbol))
+                                log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
                                 continue
                             else:
                                 # log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
@@ -1543,11 +1543,11 @@ def position_auto_switch(context,pindex=0,switch_func=None, callback=None):
                             dominant_low_limit = cur[dominant].low_limit
                             if symbol_last_price >= symbol_high_limit:
                                 # log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
-                                log.warning("Cant close {} position due to the limit up. Cancelling the exchange.".format(symbol))
+                                log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
                                 continue
                             elif dominant_last_price <= dominant_low_limit:
                                 # log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(symbol))
-                                log.warning("Cant close {} position due to the limit down. Cancelling the exchange.".format(symbol))
+                                log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
                                 continue
                             else:
                                 # log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))

+ 251 - 131
Lib/research/future_ma_cross_analysis.py

@@ -5,171 +5,291 @@ import datetime
 import matplotlib.pyplot as plt
 
 def get_all_key_info(the_type='futures'):
-    """Get all futures main contracts information"""
+    """获取所有期货主力合约信息并进行日期过滤"""
     main = get_all_securities(types=[the_type]).reset_index()
-    the_main = main[main.display_name.str.endswith('主力合约')]
+    the_main = main[main.display_name.str.endswith('主力合约')].copy()  # 使用copy()避免警告
     the_main.rename(columns={'index': 'code'}, inplace=True)
-    all_future_list = the_main['code'].unique()
-    return the_main, all_future_list
+    
+    # 将start_date转换为datetime格式
+    the_main['start_date'] = pd.to_datetime(the_main['start_date'])
+    
+    return the_main
+
+def get_future_data_with_ma(future_code, start_date, end_date):
+    """获取单个期货合约的价格数据并计算多条移动平均线"""
+    try:
+#         if future_code != "A9999.XDCE":
+#             print(f"跳过: {future_code}的数据")
+#             return None
+#         else:
+        print(f"获取期货: {future_code}的数据")
+        data = get_price(future_code, 
+                        start_date=start_date, 
+                        end_date=end_date, 
+                        frequency='daily',
+                        fields=['open', 'close', 'high', 'low', 'volume'],
+                        skip_paused=False,
+                        panel=False)
 
-def get_period_range(start_year, end_year):
-    """Get trading period range between years"""
-    now = datetime.datetime.now()
-    start_date = datetime.datetime(start_year, 1, 1)
-    end_date = datetime.datetime(end_year, 12, 31)
+        if data is None or len(data) == 0:
+            return None
 
-    if end_year == now.year and now < end_date:
-        end_date = now
+        # 重置索引,使日期成为一列,避免复制警告
+        data = data.reset_index()
 
-    trade_days = get_trade_days(start_date=start_date, end_date=end_date)
-    actual_start_date = trade_days[0]
-    actual_end_date = trade_days[-1]
-    print(f'Analysis period: {actual_start_date} to {actual_end_date}')
-    return actual_start_date, actual_end_date
+        # 计算多条移动平均线
+        data['MA5'] = data['close'].rolling(window=5).mean()
+        data['MA10'] = data['close'].rolling(window=10).mean()
+        data['MA20'] = data['close'].rolling(window=20).mean()
+        data['MA30'] = data['close'].rolling(window=30).mean()
+        data.to_csv("A9999.csv", index=False, encoding='utf-8-sig')
 
-def get_future_data(future_code, start_date, end_date):
-    """Get price data for a single future contract"""
-    data = get_price(future_code, 
-                    start_date=start_date, 
-                    end_date=end_date, 
-                    frequency='daily',
-                    fields=['open', 'close', 'high', 'low', 'volume'],
-                    skip_paused=False,
-                    panel=False)
-    
-    if data is None or len(data) == 0:
+        return data
+    except Exception as e:
+        print(f"获取{future_code}数据时出错: {str(e)}")
         return None
+
+def check_multi_ma_cross(row):
+    """
+    检查单日K线是否向上或向下穿越了至少3条均线。
+    这个新版本精确计算被K线实体穿越的均线数量。
+    返回: 'up', 'down', 或 None
+    """
+    date = row['index']
+    open_price = row['open']
+    close_price = row['close']
+    ma_values = [row['MA5'], row['MA10'], row['MA20'], row['MA30']]
+#     print(f"date: {date}, open_price: {open_price}, close_price: {close_price}")
+#     print(f"ma_values: {ma_values}")
+    
+    # 如果任何均线为NaN则跳过,确保数据完整性
+    if pd.isna(row['MA5']) or pd.isna(row['MA10']) or pd.isna(row['MA20']) or pd.isna(row['MA30']):
+#         print(f"date: {date}, MA5: {row['MA5']}, MA10: {row['MA10']}, MA20: {row['MA20']}, MA30: {row['MA30']}")
+#         print("ma里有NaN跳过")
+        return None
+    
+    # 如果开盘价和收盘价相等,不可能有穿越发生
+    if open_price == close_price:
+#         print("开盘价和收盘价相等,跳过")
+        return None
+        
+    crossed_mas_count = 0
+#     print("开始检查穿越情况")
     
-    # Create a copy to avoid SettingWithCopyWarning
-    data = data.copy()
+    # 情况一:上涨(阳线),检查上穿
+    if close_price > open_price:
+#         print(f"收盘价大于开盘价: open_price: {open_price}, close_price: {close_price}")
+        for ma in ma_values:
+#             print(f"检查{ma}和收盘价和开盘价的关系")
+            # 精确判断:开盘价在均线下方,且收盘价在均线上方
+            if open_price < ma and close_price > ma:
+                crossed_mas_count += 1
         
-    # Calculate 5-day MA
-    data['MA5'] = data['close'].rolling(window=5).mean()
-    return data
+        if crossed_mas_count >= 3:
+            return 'up'
+            
+    # 情况二:下跌(阴线),检查下穿
+    elif open_price > close_price:
+        for ma in ma_values:
+            # 精确判断:开盘价在均线上方,且收盘价在均线下方
+            if open_price > ma and close_price < ma:
+                crossed_mas_count += 1
+                
+        if crossed_mas_count >= 3:
+            return 'down'
+            
+    # 如果以上条件都不满足(包括穿越数量不足),则返回None
+#     print("以上情况均不满足,跳过")
+    return None
 
-def analyze_ma_crosses(data):
-    """Analyze MA crosses and calculate statistics"""
-    if data is None or len(data) < 5:  # Need at least 5 days for MA5
+def analyze_multi_ma_crosses(data, future_code, future_name):
+    """分析多均线穿越并计算未来收益率"""
+    if data is None or len(data) < 30:  # 需要至少30天数据来计算30日均线
         return pd.DataFrame()
     
-    # Create a copy of the data to avoid warnings
-    data = data.copy()
+    results = []
+    
+    for i in range(len(data)):
+        row = data.iloc[i]
+        cross_type = check_multi_ma_cross(row)
         
-    # Initialize cross detection
-    data['cross_up'] = (data['open'] < data['MA5']) & (data['close'] > data['MA5'])
-    data['cross_down'] = (data['open'] > data['MA5']) & (data['close'] < data['MA5'])
+        if cross_type is not None:
+            # 使用包含日期的'index'列
+            cross_date = row['index']
+            open_price = row['open']
+            close_price = row['close']
+            
+            # 计算当日收益率(收盘价和开盘价的变化率)
+            intraday_return = (close_price - open_price) / open_price * 100
+            
+            # 计算未来收益率
+            future_5d_return = None
+            future_20d_return = None
+            future_30d_return = None
+            
+            # 后5日收益率
+            if i + 5 < len(data):
+                future_5d_price = data.iloc[i + 5]['close']
+                future_5d_return = (future_5d_price - close_price) / close_price * 100
+                
+            # 后10日收益率
+            if i + 10 < len(data):
+                future_10d_price = data.iloc[i + 10]['close']
+                future_10d_return = (future_5d_price - close_price) / close_price * 100
+            
+            # 后20日收益率
+            if i + 20 < len(data):
+                future_20d_price = data.iloc[i + 20]['close']
+                future_20d_return = (future_20d_price - close_price) / close_price * 100
+            
+            # 后30日收益率
+            if i + 30 < len(data):
+                future_30d_price = data.iloc[i + 30]['close']
+                future_30d_return = (future_30d_price - close_price) / close_price * 100
+            
+            # 【【【 这是关键的修复点 】】】
+            # 从 'row' 中获取当天的均线值,而不是从 'data' 中获取整个列
+            results.append({
+                '代码': future_code,
+                '名称': future_name,
+                '日期': cross_date,
+                '方向': '上穿' if cross_type == 'up' else '下穿',
+                '开盘价': round(open_price, 2),
+                '收盘价': round(close_price, 2),
+                'MA5': round(row['MA5'], 2),
+                'MA10': round(row['MA10'], 2),
+                'MA20': round(row['MA20'], 2),
+                'MA30': round(row['MA30'], 2),
+                '当日变化率': round(intraday_return, 2),
+                '后5日变化率': round(future_5d_return, 2) if future_5d_return is not None else None,
+                '后10日变化率': round(future_10d_return, 2) if future_10d_return is not None else None,
+                '后20日变化率': round(future_20d_return, 2) if future_20d_return is not None else None,
+                '后30日变化率': round(future_30d_return, 2) if future_30d_return is not None else None
+            })
     
-    # Get indices where crosses occur
-    cross_dates = data.index[data['cross_up'] | data['cross_down']].tolist()
+    # 将结果转换为DataFrame并确保列的顺序
+    result_df = pd.DataFrame(results, columns=[
+        '日期', '代码', '名称', '开盘价', '收盘价', '当日变化率', '方向',
+        'MA5', 'MA10', 'MA20', 'MA30', '后5日变化率', '后10日变化率',
+        '后20日变化率', '后30日变化率'
+    ])
     
-    results = []
-    for i in range(len(cross_dates) - 1):
-        current_date = cross_dates[i]
-        next_date = cross_dates[i + 1]
-        
-        # Get cross type
-        is_up_cross = data.loc[current_date, 'cross_up']
-        
-        # Calculate trading days between crosses
-        trading_days = len(data.loc[current_date:next_date].index) - 1
-        
-        # Calculate price change
-        start_price = data.loc[current_date, 'close']
-        end_price = data.loc[next_date, 'close']
-        price_change_pct = (end_price - start_price) / start_price * 100
-        
-        results.append({
-            'cross_date': current_date,
-            'next_cross_date': next_date,
-            'cross_type': 'Upward' if is_up_cross else 'Downward',
-            'trading_days': trading_days,
-            'price_change_pct': price_change_pct
-        })
-    
-    return pd.DataFrame(results)
+    return result_df
 
-def analyze_all_futures(start_year, end_year):
-    """Analyze MA crosses for all futures contracts"""
-    start_date, end_date = get_period_range(start_year, end_year)
-    all_future_df, all_future_list = get_all_key_info()
+def analyze_all_futures_multi_ma(start_date, end_date):
+    """分析所有期货合约的多均线穿越情况"""
+    all_future_df = get_all_key_info()
+    
+    # 过滤在分析结束日期之前有数据且在分析结束日期之前开始交易的期货
+    valid_futures = all_future_df[
+        (all_future_df['start_date'] <= pd.to_datetime(end_date))
+    ].copy()
+    
+    print(f"找到{len(valid_futures)}个期货合约需要分析")
+    
+    # 创建代码到名称的映射
+    code_to_name = dict(zip(valid_futures['code'], valid_futures['display_name']))
     
     all_results = []
+    total_futures = len(valid_futures)
     
-    for future in all_future_list:
-        print(f'Analyzing {future}...')
-        data = get_future_data(future, start_date, end_date)
-        if data is not None and len(data) >= 5:
-            results = analyze_ma_crosses(data)
-            if not results.empty:
-                results['future_code'] = future
-                all_results.append(results)
+    for idx, row in valid_futures.iterrows():
+        future = row['code']
+        future_start_date = row['start_date']
+        
+        # 调整开始日期为分析开始日期或期货开始日期中的较晚者
+        effective_start_date = max(pd.to_datetime(start_date), future_start_date)
+        
+        print(f'正在分析 {future} ({idx+1}/{total_futures}) 从 {effective_start_date.strftime("%Y-%m-%d")} 开始...')
+        
+        try:
+            data = get_future_data_with_ma(future, effective_start_date, end_date)
+            if data is not None and len(data) >= 30:
+                future_name = code_to_name.get(future, future)
+                results = analyze_multi_ma_crosses(data, future, future_name)
+                if not results.empty:
+                    all_results.append(results)
+                    print(f'  为{future}找到{len(results)}次多均线穿越')
+                else:
+                    print(f'  {future}未找到多均线穿越')
+            else:
+                print(f'  {future}数据不足 (获得{len(data) if data is not None else 0}天数据)')
+        except Exception as e:
+            print(f'  分析{future}时出错: {str(e)}')
+            continue
     
     if not all_results:
+        print("未找到多均线穿越结果")
         return pd.DataFrame()
         
     combined_results = pd.concat(all_results, ignore_index=True)
     return combined_results
 
-def generate_statistics(results):
-    """Generate summary statistics for the analysis"""
+def generate_summary_stats(results):
+    """生成多均线穿越分析的汇总统计"""
     if results.empty:
-        print("No results to analyze")
+        print("没有结果可供分析")
         return
-        
-    # Group by future code and cross type
-    stats = results.groupby(['future_code', 'cross_type']).agg({
-        'trading_days': ['count', 'mean', 'std', 'min', 'max'],
-        'price_change_pct': ['mean', 'std', 'min', 'max']
-    }).round(2)
     
-    return stats
-
-def plot_results(results):
-    """Plot distribution of trading days and price changes"""
-    if results.empty:
-        print("No results to plot")
-        return
-        
-    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
-    
-    # Plot trading days distribution
-    for cross_type in ['Upward', 'Downward']:
-        data = results[results['cross_type'] == cross_type]['trading_days']
-        ax1.hist(data, bins=30, alpha=0.5, label=cross_type)
-    ax1.set_title('Distribution of Trading Days Between Crosses')
-    ax1.set_xlabel('Trading Days')
-    ax1.set_ylabel('Frequency')
-    ax1.legend()
-    
-    # Plot price change distribution
-    for cross_type in ['Upward', 'Downward']:
-        data = results[results['cross_type'] == cross_type]['price_change_pct']
-        ax2.hist(data, bins=30, alpha=0.5, label=cross_type)
-    ax2.set_title('Distribution of Price Changes')
-    ax2.set_xlabel('Price Change (%)')
-    ax2.set_ylabel('Frequency')
-    ax2.legend()
-    
-    plt.tight_layout()
-    plt.show()
+    print(f"\n=== 多均线穿越分析结果汇总 ===")
+    print(f"总共发现 {len(results)} 次多均线穿越事件")
+    print(f"涉及 {results['代码'].nunique()} 个不同的期货品种")
+    
+    # 按穿越方向统计
+    cross_type_stats = results['方向'].value_counts()
+    print(f"\n穿越方向分布:")
+    for cross_type, count in cross_type_stats.items():
+        print(f"  {cross_type}: {count} 次")
+    
+    # 收益率统计
+    print(f"\n收益率统计:")
+    for col in ['当日变化率', '后5日变化率', 
+                '后20日变化率', '后30日变化率']:
+        valid_data = results[col].dropna()
+        if len(valid_data) > 0:
+            print(f"  {col}:")
+            print(f"    平均值: {valid_data.mean():.2f}%")
+            print(f"    中位数: {valid_data.median():.2f}%")
+            print(f"    标准差: {valid_data.std():.2f}%")
+            print(f"    最小值: {valid_data.min():.2f}%")
+            print(f"    最大值: {valid_data.max():.2f}%")
+    
+    # 按品种统计
+    print(f"\n各品种穿越次数统计:")
+    variety_stats = results.groupby('代码').size().sort_values(ascending=False)
+    for code, count in variety_stats.head(10).items():
+        name = results[results['代码'] == code]['名称'].iloc[0]
+        print(f"  {code} ({name}): {count} 次")
 
 def main():
-    # Set analysis period (e.g., last 2 years)
-    current_year = datetime.datetime.now().year
-    results = analyze_all_futures(current_year - 1, current_year)
+    """运行多均线穿越分析的主函数"""
+    # 设置分析期间
+    start_date = datetime.datetime(2024, 6, 1)
+    end_date = datetime.datetime(2025, 6, 1)
+    
+    print(f"开始分析期货多均线穿越情况...")
+    print(f"分析期间: {start_date.strftime('%Y-%m-%d')} 到 {end_date.strftime('%Y-%m-%d')}")
+    
+    # 分析所有期货
+    results = analyze_all_futures_multi_ma(start_date, end_date)
     
     if not results.empty:
-        # Generate and display statistics
-        stats = generate_statistics(results)
-        print("\nSummary Statistics:")
-        print(stats)
+        # 生成并显示统计信息
+        generate_summary_stats(results)
         
-        # Plot distributions
-        plot_results(results)
+        # 导出结果到CSV文件
+        output_filename = 'multi_ma_cross_analysis_results.csv'
+        results.to_csv(output_filename, index=False, encoding='utf-8-sig')
+        print(f"\n结果已保存到文件: {output_filename}")
         
-        # Export results to CSV
-        results.to_csv('ma_cross_analysis_results.csv', index=False)
-        stats.to_csv('ma_cross_analysis_stats.csv')
+        # 显示前几行结果
+        print(f"\n前10条结果预览:")
+        print(results.head(10).to_string(index=False))
+        
+        return results
+    else:
+        print("未找到符合条件的多均线穿越事件")
+        return pd.DataFrame()
 
 if __name__ == "__main__":
-    main() 
+    results = main()