MAPatternStrategy_v002.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  1. # 导入函数库
  2. from jqdata import *
  3. from jqdata import finance
  4. import pandas as pd
  5. import numpy as np
  6. import math
  7. from datetime import date, datetime, timedelta, time
  8. import re
  9. # 顺势交易策略 v001
  10. # 基于均线走势(前提条件)+ K线形态(开盘价差、当天价差)的期货交易策略
  11. #
  12. # 核心逻辑:
  13. # 1. 开盘时检查均线走势(MA30<=MA20<=MA10<=MA5为多头,反之为空头)
  14. # 2. 检查开盘价差是否符合方向要求(多头>=0.5%,空头<=-0.5%)
  15. # 3. 14:35和14:55检查当天价差(多头>0,空头<0),满足条件则开仓
  16. # 4. 应用固定止损和动态追踪止盈
  17. # 5. 自动换月移仓
  18. # 设置以便完整打印 DataFrame
  19. pd.set_option('display.max_rows', None)
  20. pd.set_option('display.max_columns', None)
  21. pd.set_option('display.width', None)
  22. pd.set_option('display.max_colwidth', 20)
  23. ## 初始化函数,设定基准等等
  24. def initialize(context):
  25. # 设定沪深300作为基准
  26. set_benchmark('000300.XSHG')
  27. # 开启动态复权模式(真实价格)
  28. set_option('use_real_price', True)
  29. # 输出内容到日志
  30. log.info('=' * 60)
  31. log.info('均线形态交易策略 v001 初始化开始')
  32. log.info('策略类型: 均线走势 + K线形态')
  33. log.info('=' * 60)
  34. ### 期货相关设定 ###
  35. # 设定账户为金融账户
  36. set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
  37. # 期货类每笔交易时的手续费是: 买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
  38. set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
  39. # 设置期货交易的滑点
  40. set_slippage(StepRelatedSlippage(2))
  41. # 初始化全局变量
  42. g.usage_percentage = 0.8 # 最大资金使用比例
  43. g.max_margin_per_position = 20000 # 单个标的最大持仓保证金(元)
  44. # 均线策略参数
  45. g.ma_periods = [5, 10, 20, 30] # 均线周期
  46. g.ma_historical_days = 60 # 获取历史数据天数(确保足够计算MA30)
  47. g.ma_open_gap_threshold = 0.001 # 方案1开盘价差阈值(0.2%)
  48. g.ma_pattern_lookback_days = 10 # 历史均线模式一致性检查的天数
  49. g.ma_pattern_consistency_threshold = 0.8 # 历史均线模式一致性阈值(80%)
  50. g.check_intraday_spread = False # 是否检查日内价差(True: 检查, False: 跳过)
  51. g.ma_proximity_min_threshold = 8 # MA5与MA10贴近计数和的最低阈值
  52. g.ma_pattern_extreme_days_threshold = 4 # 极端趋势天数阈值
  53. g.ma_distribution_lookback_days = 5 # MA5分布过滤回溯天数
  54. g.ma_distribution_min_ratio = 0.4 # MA5分布满足比例阈值
  55. g.enable_ma_distribution_filter = True # 是否启用MA5分布过滤
  56. g.ma_cross_threshold = 1 # 均线穿越数量阈值
  57. # 均线价差策略方案选择
  58. g.ma_gap_strategy_mode = 3 # 策略模式选择(1: 原方案, 2: 新方案, 3: 方案3)
  59. g.ma_open_gap_threshold2 = 0.001 # 方案2开盘价差阈值(0.2%)
  60. g.ma_intraday_threshold_scheme2 = 0.005 # 方案2日内变化阈值(0.5%)
  61. # 止损止盈策略参数
  62. g.fixed_stop_loss_rate = 0.01 # 固定止损比率(1%)
  63. g.ma_offset_ratio_normal = 0.003 # 均线跟踪止盈常规偏移量(0.3%)
  64. g.ma_offset_ratio_close = 0.01 # 均线跟踪止盈收盘前偏移量(1%)
  65. g.days_for_adjustment = 4 # 持仓天数调整阈值
  66. # 输出策略参数
  67. log.info("均线形态策略参数:")
  68. log.info(f" 均线周期: {g.ma_periods}")
  69. log.info(f" 策略模式: 方案{g.ma_gap_strategy_mode}")
  70. log.info(f" 方案1开盘价差阈值: {g.ma_open_gap_threshold:.1%}")
  71. log.info(f" 方案2开盘价差阈值: {g.ma_open_gap_threshold2:.1%}")
  72. log.info(f" 方案2日内变化阈值: {g.ma_intraday_threshold_scheme2:.1%}")
  73. log.info(f" 历史均线模式检查天数: {g.ma_pattern_lookback_days}天")
  74. log.info(f" 历史均线模式一致性阈值: {g.ma_pattern_consistency_threshold:.1%}")
  75. log.info(f" 极端趋势天数阈值: {g.ma_pattern_extreme_days_threshold}")
  76. log.info(f" 均线贴近计数阈值: {g.ma_proximity_min_threshold}")
  77. log.info(f" MA5分布过滤天数: {g.ma_distribution_lookback_days}")
  78. log.info(f" MA5分布最低比例: {g.ma_distribution_min_ratio:.0%}")
  79. log.info(f" 启用MA5分布过滤: {g.enable_ma_distribution_filter}")
  80. log.info(f" 是否检查日内价差: {g.check_intraday_spread}")
  81. log.info(f" 均线穿越阈值: {g.ma_cross_threshold}")
  82. log.info(f" 固定止损: {g.fixed_stop_loss_rate:.1%}")
  83. log.info(f" 均线跟踪止盈常规偏移: {g.ma_offset_ratio_normal:.1%}")
  84. log.info(f" 均线跟踪止盈收盘前偏移: {g.ma_offset_ratio_close:.1%}")
  85. log.info(f" 持仓天数调整阈值: {g.days_for_adjustment}天")
  86. # 期货品种完整配置字典
  87. g.futures_config = {
  88. # 贵金属
  89. 'AU': {'has_night_session': True, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 1000, 'trading_start_time': '21:00'},
  90. 'AG': {'has_night_session': True, 'margin_rate': {'long': 0.22, 'short': 0.22}, 'multiplier': 15, 'trading_start_time': '21:00'},
  91. # 有色金属
  92. 'CU': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  93. 'AL': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  94. 'ZN': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '21:00'},
  95. 'PB': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '21:00'},
  96. 'NI': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 1, 'trading_start_time': '21:00'},
  97. 'SN': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 1, 'trading_start_time': '21:00'},
  98. 'SS': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  99. # 黑色系
  100. 'RB': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  101. 'HC': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  102. 'I': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 100, 'trading_start_time': '21:00'},
  103. 'JM': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 100, 'trading_start_time': '21:00'},
  104. 'J': {'has_night_session': True, 'margin_rate': {'long': 0.25, 'short': 0.25}, 'multiplier': 60, 'trading_start_time': '21:00'},
  105. # 能源化工
  106. 'SP': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  107. 'FU': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 10, 'trading_start_time': '21:00'},
  108. 'BU': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 10, 'trading_start_time': '21:00'},
  109. 'RU': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10, 'trading_start_time': '21:00'},
  110. 'BR': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  111. 'SC': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 1000, 'trading_start_time': '21:00'},
  112. 'NR': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10, 'trading_start_time': '21:00'},
  113. 'LU': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 10, 'trading_start_time': '21:00'},
  114. 'LC': {'has_night_session': False, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 1, 'trading_start_time': '09:00'},
  115. # 化工
  116. 'FG': {'has_night_session': True, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 20, 'trading_start_time': '21:00'},
  117. 'TA': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  118. 'MA': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  119. 'SA': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 20, 'trading_start_time': '21:00'},
  120. 'L': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  121. 'V': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  122. 'EG': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  123. 'PP': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  124. 'EB': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5, 'trading_start_time': '21:00'},
  125. 'PG': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 20, 'trading_start_time': '21:00'},
  126. 'PX': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 5, 'trading_start_time': '21:00'},
  127. # 农产品
  128. 'RM': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  129. 'OI': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  130. 'CF': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  131. 'SR': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  132. 'PF': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '21:00'},
  133. 'C': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  134. 'CS': {'has_night_session': True, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 10, 'trading_start_time': '21:00'},
  135. 'CY': {'has_night_session': True, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 5, 'trading_start_time': '21:00'},
  136. 'A': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  137. 'B': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  138. 'M': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  139. 'Y': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 10, 'trading_start_time': '21:00'},
  140. 'P': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '21:00'},
  141. # 无夜盘品种
  142. 'IF': {'has_night_session': False, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 300, 'trading_start_time': '09:30'},
  143. 'IH': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 300, 'trading_start_time': '09:30'},
  144. 'IC': {'has_night_session': False, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 200, 'trading_start_time': '09:30'},
  145. 'IM': {'has_night_session': False, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 200, 'trading_start_time': '09:30'},
  146. 'AP': {'has_night_session': False, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 10, 'trading_start_time': '09:00'},
  147. 'CJ': {'has_night_session': False, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '09:00'},
  148. 'PK': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5, 'trading_start_time': '09:00'},
  149. 'JD': {'has_night_session': False, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 10, 'trading_start_time': '09:00'},
  150. 'LH': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 16, 'trading_start_time': '09:00'},
  151. 'T': {'has_night_session': False, 'margin_rate': {'long': 0.03, 'short': 0.03}, 'multiplier': 1000000, 'trading_start_time': '09:30'},
  152. 'PS': {'has_night_session': False, 'margin_rate': {'long': 0.16, 'short': 0.16}, 'multiplier': 3, 'trading_start_time': '09:00'},
  153. 'UR': {'has_night_session': False, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 20, 'trading_start_time': '09:00'},
  154. 'MO': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 100, 'trading_start_time': '21:00'},
  155. 'LF': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1, 'trading_start_time': '09:30'},
  156. 'HO': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 100, 'trading_start_time': '09:30'},
  157. 'LR': {'has_night_session': True, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 1, 'trading_start_time': '21:00'},
  158. 'LG': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 1, 'trading_start_time': '21:00'},
  159. 'FB': {'has_night_session': True, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 1, 'trading_start_time': '21:00'},
  160. 'PM': {'has_night_session': True, 'margin_rate': {'long': 0.2, 'short': 0.2}, 'multiplier': 1, 'trading_start_time': '21:00'},
  161. 'EC': {'has_night_session': False, 'margin_rate': {'long': 0.23, 'short': 0.23}, 'multiplier': 50, 'trading_start_time': '09:00'},
  162. 'RR': {'has_night_session': True, 'margin_rate': {'long': 0.11, 'short': 0.11}, 'multiplier': 10, 'trading_start_time': '21:00'},
  163. 'OP': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 40, 'trading_start_time': '09:00'},
  164. 'IO': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 1, 'trading_start_time': '21:00'},
  165. 'BC': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '21:00'},
  166. 'WH': {'has_night_session': False, 'margin_rate': {'long': 0.2, 'short': 0.2}, 'multiplier': 20, 'trading_start_time': '09:00'},
  167. 'SH': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 30, 'trading_start_time': '21:00'},
  168. 'RI': {'has_night_session': False, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 20, 'trading_start_time': '09:00'},
  169. 'TS': {'has_night_session': False, 'margin_rate': {'long': 0.015, 'short': 0.015}, 'multiplier': 2000000, 'trading_start_time': '09:30'},
  170. 'JR': {'has_night_session': False, 'margin_rate': {'long': 0.21, 'short': 0.21}, 'multiplier': 20, 'trading_start_time': '09:00'},
  171. 'AD': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10, 'trading_start_time': '09:00'},
  172. 'BB': {'has_night_session': False, 'margin_rate': {'long': 0.19, 'short': 0.19}, 'multiplier': 500, 'trading_start_time': '09:00'},
  173. 'PL': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 20, 'trading_start_time': '09:00'},
  174. 'RS': {'has_night_session': False, 'margin_rate': {'long': 0.26, 'short': 0.26}, 'multiplier': 10, 'trading_start_time': '09:00'},
  175. 'SI': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '09:00'},
  176. 'ZC': {'has_night_session': True, 'margin_rate': {'long': 0.56, 'short': 0.56}, 'multiplier': 100, 'trading_start_time': '21:00'},
  177. 'SM': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 5, 'trading_start_time': '09:00'},
  178. 'AO': {'has_night_session': True, 'margin_rate': {'long': 0.17, 'short': 0.17}, 'multiplier': 20, 'trading_start_time': '21:00'},
  179. 'TL': {'has_night_session': False, 'margin_rate': {'long': 0.045, 'short': 0.045}, 'multiplier': 1000000, 'trading_start_time': '09:00'},
  180. 'SF': {'has_night_session': False, 'margin_rate': {'long': 0.14, 'short': 0.14}, 'multiplier': 5, 'trading_start_time': '09:00'},
  181. 'WR': {'has_night_session': False, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10, 'trading_start_time': '09:00'},
  182. 'PR': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 15, 'trading_start_time': '21:00'},
  183. 'TF': {'has_night_session': False, 'margin_rate': {'long': 0.022, 'short': 0.022}, 'multiplier': 1000000, 'trading_start_time': '09:00'},
  184. 'VF': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1, 'trading_start_time': '09:00'},
  185. 'BZ': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 30, 'trading_start_time': '09:00'},
  186. }
  187. # 策略品种选择策略配置
  188. # 方案1:全品种策略 - 考虑所有配置的期货品种
  189. g.strategy_focus_symbols = ['J'] # 空列表表示考虑所有品种
  190. # 方案2:精选品种策略 - 只交易流动性较好的特定品种(如需使用请取消下行注释)
  191. # g.strategy_focus_symbols = ['RM', 'CJ', 'CY', 'JD', 'L', 'LC', 'SF', 'SI']
  192. log.info(f"品种选择策略: {'全品种策略(覆盖所有配置品种)' if not g.strategy_focus_symbols else '精选品种策略(' + str(len(g.strategy_focus_symbols)) + '个品种)'}")
  193. # 交易记录和数据存储
  194. g.trade_history = {} # 持仓记录 {symbol: {'entry_price': xxx, 'direction': xxx, ...}}
  195. g.daily_ma_candidates = {} # 通过均线和开盘价差检查的候选品种 {symbol: {'direction': 'long'/'short', 'open_price': xxx, ...}}
  196. g.today_trades = [] # 当日交易记录
  197. g.excluded_contracts = {} # 每日排除的合约缓存 {dominant_future: {'reason': 'ma_trend'/'open_gap', 'trading_day': xxx}}
  198. g.ma_checked_underlyings = {} # 记录各品种在交易日的均线检查状态 {symbol: trading_day}
  199. g.last_ma_trading_day = None # 最近一次均线检查所属交易日
  200. # 定时任务设置
  201. # 夜盘开始(21:05) - 均线和开盘价差检查
  202. run_daily(check_ma_trend_and_open_gap, time='21:05:00', reference_security='IF1808.CCFX')
  203. # 日盘开始 - 均线和开盘价差检查
  204. run_daily(check_ma_trend_and_open_gap, time='09:05:00', reference_security='IF1808.CCFX')
  205. run_daily(check_ma_trend_and_open_gap, time='09:35:00', reference_security='IF1808.CCFX')
  206. # 夜盘开仓和止损止盈检查
  207. run_daily(check_open_and_stop, time='21:05:00', reference_security='IF1808.CCFX')
  208. run_daily(check_open_and_stop, time='21:35:00', reference_security='IF1808.CCFX')
  209. run_daily(check_open_and_stop, time='22:05:00', reference_security='IF1808.CCFX')
  210. run_daily(check_open_and_stop, time='22:35:00', reference_security='IF1808.CCFX')
  211. # 日盘开仓和止损止盈检查
  212. run_daily(check_open_and_stop, time='09:05:00', reference_security='IF1808.CCFX')
  213. run_daily(check_open_and_stop, time='09:35:00', reference_security='IF1808.CCFX')
  214. run_daily(check_open_and_stop, time='10:05:00', reference_security='IF1808.CCFX')
  215. run_daily(check_open_and_stop, time='10:35:00', reference_security='IF1808.CCFX')
  216. run_daily(check_open_and_stop, time='11:05:00', reference_security='IF1808.CCFX')
  217. run_daily(check_open_and_stop, time='11:25:00', reference_security='IF1808.CCFX')
  218. run_daily(check_open_and_stop, time='13:35:00', reference_security='IF1808.CCFX')
  219. run_daily(check_open_and_stop, time='14:05:00', reference_security='IF1808.CCFX')
  220. run_daily(check_open_and_stop, time='14:35:00', reference_security='IF1808.CCFX')
  221. run_daily(check_open_and_stop, time='14:55:00', reference_security='IF1808.CCFX')
  222. run_daily(check_ma_trailing_reactivation, time='14:55:00', reference_security='IF1808.CCFX')
  223. # 收盘后
  224. run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
  225. log.info('=' * 60)
  226. ############################ 主程序执行函数 ###################################
  227. def get_current_trading_day(current_dt):
  228. """根据当前时间推断对应的期货交易日"""
  229. current_date = current_dt.date()
  230. current_time = current_dt.time()
  231. trade_days = get_trade_days(end_date=current_date, count=1)
  232. if trade_days and trade_days[0] == current_date:
  233. trading_day = current_date
  234. else:
  235. next_days = get_trade_days(start_date=current_date, count=1)
  236. trading_day = next_days[0] if next_days else current_date
  237. if current_time >= time(20, 59):
  238. next_trade_days = get_trade_days(start_date=trading_day, count=2)
  239. if len(next_trade_days) >= 2:
  240. return next_trade_days[1]
  241. if len(next_trade_days) == 1:
  242. return next_trade_days[0]
  243. return trading_day
  244. def normalize_trade_day_value(value):
  245. """将交易日对象统一转换为 datetime.date"""
  246. if isinstance(value, date) and not isinstance(value, datetime):
  247. return value
  248. if isinstance(value, datetime):
  249. return value.date()
  250. if hasattr(value, 'to_pydatetime'):
  251. return value.to_pydatetime().date()
  252. try:
  253. return pd.Timestamp(value).date()
  254. except Exception:
  255. return value
  256. def check_ma_trend_and_open_gap(context):
  257. """阶段一:开盘时均线走势和开盘价差检查(一天一次)"""
  258. log.info("=" * 60)
  259. current_trading_day = get_current_trading_day(context.current_dt)
  260. log.info(f"执行均线走势和开盘价差检查 - 时间: {context.current_dt}, 交易日: {current_trading_day}")
  261. log.info("=" * 60)
  262. # 换月移仓检查(在所有部分之前)
  263. position_auto_switch(context)
  264. # ==================== 第一部分:基础数据获取 ====================
  265. # 步骤1:交易日检查和缓存清理
  266. if g.last_ma_trading_day != current_trading_day:
  267. if g.excluded_contracts:
  268. log.info(f"交易日切换至 {current_trading_day},清空上一交易日的排除缓存")
  269. g.excluded_contracts = {}
  270. g.ma_checked_underlyings = {}
  271. g.last_ma_trading_day = current_trading_day
  272. # 步骤2:获取当前时间和筛选可交易品种
  273. current_time = str(context.current_dt.time())[:5] # HH:MM格式
  274. focus_symbols = g.strategy_focus_symbols if g.strategy_focus_symbols else list(g.futures_config.keys())
  275. tradable_symbols = []
  276. # 根据当前时间确定可交易的时段
  277. # 21:05 -> 仅接受21:00开盘的合约
  278. # 09:05 -> 接受09:00或21:00开盘的合约
  279. # 09:35 -> 接受所有时段(21:00, 09:00, 09:30)的合约
  280. for symbol in focus_symbols:
  281. trading_start_time = get_futures_config(symbol, 'trading_start_time', '09:05')
  282. should_trade = False
  283. if current_time == '21:05':
  284. should_trade = trading_start_time.startswith('21:00')
  285. elif current_time == '09:05':
  286. should_trade = trading_start_time.startswith('21:00') or trading_start_time.startswith('09:00')
  287. elif current_time == '09:35':
  288. should_trade = True
  289. if should_trade:
  290. tradable_symbols.append(symbol)
  291. if not tradable_symbols:
  292. log.info(f"当前时间 {current_time} 无品种开盘,跳过检查")
  293. return
  294. log.info(f"当前时间 {current_time} 开盘品种: {tradable_symbols}")
  295. # 步骤3:对每个品种循环处理
  296. for symbol in tradable_symbols:
  297. # 步骤3.1:检查是否已处理过
  298. if g.ma_checked_underlyings.get(symbol) == current_trading_day:
  299. log.info(f"{symbol} 已在交易日 {current_trading_day} 完成均线检查,跳过本次执行")
  300. continue
  301. try:
  302. g.ma_checked_underlyings[symbol] = current_trading_day
  303. # 步骤3.2:获取主力合约
  304. dominant_future = get_dominant_future(symbol)
  305. if not dominant_future:
  306. log.info(f"{symbol} 未找到主力合约,跳过")
  307. continue
  308. # 步骤3.3:检查排除缓存
  309. if dominant_future in g.excluded_contracts:
  310. excluded_info = g.excluded_contracts[dominant_future]
  311. if excluded_info['trading_day'] == current_trading_day:
  312. continue
  313. else:
  314. # 新的一天,从缓存中移除(会在after_market_close统一清理,这里也做兜底)
  315. del g.excluded_contracts[dominant_future]
  316. # 步骤3.4:检查是否已有持仓
  317. if check_symbol_prefix_match(dominant_future, set(g.trade_history.keys())):
  318. log.info(f"{symbol} 已有持仓,跳过")
  319. continue
  320. # 步骤3.5:获取历史数据和前一交易日数据(合并优化)
  321. # 获取历史数据(需要足够计算MA30)
  322. historical_data = get_price(dominant_future, end_date=context.current_dt,
  323. frequency='1d', fields=['open', 'close', 'high', 'low'],
  324. count=g.ma_historical_days)
  325. if historical_data is None or len(historical_data) < max(g.ma_periods):
  326. log.info(f"{symbol} 历史数据不足,跳过")
  327. continue
  328. # 获取前一交易日并在历史数据中匹配
  329. previous_trade_days = get_trade_days(end_date=current_trading_day, count=2)
  330. previous_trade_days = [normalize_trade_day_value(d) for d in previous_trade_days]
  331. previous_trading_day = None
  332. if len(previous_trade_days) >= 2:
  333. previous_trading_day = previous_trade_days[-2]
  334. elif len(previous_trade_days) == 1 and previous_trade_days[0] < current_trading_day:
  335. previous_trading_day = previous_trade_days[0]
  336. if previous_trading_day is None:
  337. log.info(f"{symbol} 无法确定前一交易日,跳过")
  338. continue
  339. # 在历史数据中匹配前一交易日
  340. historical_dates = historical_data.index.date
  341. match_indices = np.where(historical_dates == previous_trading_day)[0]
  342. if len(match_indices) == 0:
  343. earlier_indices = np.where(historical_dates < previous_trading_day)[0]
  344. if len(earlier_indices) == 0:
  345. log.info(f"{symbol} 历史数据缺少 {previous_trading_day} 之前的记录,跳过")
  346. continue
  347. match_indices = [earlier_indices[-1]]
  348. # 提取截至前一交易日的数据,并一次性提取所有需要的字段
  349. data_upto_yesterday = historical_data.iloc[:match_indices[-1] + 1]
  350. yesterday_data = data_upto_yesterday.iloc[-1]
  351. yesterday_close = yesterday_data['close']
  352. yesterday_open = yesterday_data['open']
  353. # 步骤3.6:获取当前价格数据
  354. current_data = get_current_data()[dominant_future]
  355. today_open = current_data.day_open
  356. # ==================== 第二部分:核心指标计算 ====================
  357. # 步骤4:计算均线相关指标(合并优化)
  358. ma_values = calculate_ma_values(data_upto_yesterday, g.ma_periods)
  359. ma_proximity_counts = calculate_ma_proximity_counts(data_upto_yesterday, g.ma_periods, g.ma_pattern_lookback_days)
  360. log.info(f"{symbol}({dominant_future}) 均线检查:")
  361. log.info(f" 均线贴近统计: {ma_proximity_counts}")
  362. # 检查均线贴近计数
  363. proximity_sum = ma_proximity_counts.get('MA5', 0) + ma_proximity_counts.get('MA10', 0)
  364. if proximity_sum < g.ma_proximity_min_threshold:
  365. log.info(f" {symbol}({dominant_future}) ✗ 均线贴近计数不足,MA5+MA10={proximity_sum} < {g.ma_proximity_min_threshold},跳过")
  366. add_to_excluded_contracts(dominant_future, 'ma_proximity', current_trading_day)
  367. continue
  368. # 步骤5:计算极端趋势天数
  369. extreme_above_count, extreme_below_count = calculate_extreme_trend_days(
  370. data_upto_yesterday,
  371. g.ma_periods,
  372. g.ma_pattern_lookback_days
  373. )
  374. extreme_total = extreme_above_count + extreme_below_count
  375. min_extreme = min(extreme_above_count, extreme_below_count)
  376. filter_threshold = max(2, g.ma_pattern_extreme_days_threshold)
  377. log.info(
  378. f" 极端趋势天数统计: 收盘在所有均线上方 {extreme_above_count} 天, 收盘在所有均线下方 {extreme_below_count} 天, "
  379. f"合计 {extreme_total} 天, min(A,B)={min_extreme} (过滤阈值: {filter_threshold})"
  380. )
  381. if extreme_above_count > 0 and extreme_below_count > 0 and min_extreme >= filter_threshold:
  382. log.info(
  383. f" {symbol}({dominant_future}) ✗ 极端趋势多空同时出现且 min(A,B)={min_extreme} ≥ {filter_threshold},跳过"
  384. )
  385. add_to_excluded_contracts(dominant_future, 'ma_extreme_trend', current_trading_day)
  386. continue
  387. # 步骤6:判断均线走势
  388. direction = None
  389. if check_ma_pattern(ma_values, 'long'):
  390. direction = 'long'
  391. elif check_ma_pattern(ma_values, 'short'):
  392. direction = 'short'
  393. else:
  394. add_to_excluded_contracts(dominant_future, 'ma_trend', current_trading_day)
  395. continue
  396. # 步骤7:检查MA5分布过滤
  397. if g.enable_ma_distribution_filter:
  398. distribution_passed, distribution_stats = check_ma5_distribution_filter(
  399. data_upto_yesterday,
  400. g.ma_distribution_lookback_days,
  401. direction,
  402. g.ma_distribution_min_ratio
  403. )
  404. log.info(
  405. f" MA5分布过滤: 方向 {direction}, 有效天数 "
  406. f"{distribution_stats['valid_days']}/{distribution_stats['lookback_days']},"
  407. f"满足天数 {distribution_stats['qualified_days']}/{distribution_stats['required_days']}"
  408. )
  409. if not distribution_passed:
  410. insufficiency = distribution_stats['valid_days'] < distribution_stats['lookback_days']
  411. reason = "有效数据不足" if insufficiency else "满足天数不足"
  412. log.info(
  413. f" {symbol}({dominant_future}) ✗ MA5分布过滤未通过({reason})"
  414. )
  415. add_to_excluded_contracts(dominant_future, 'ma5_distribution', current_trading_day)
  416. continue
  417. # 步骤8:检查历史均线模式一致性
  418. consistency_passed, consistency_ratio = check_historical_ma_pattern_consistency(
  419. historical_data, direction, g.ma_pattern_lookback_days, g.ma_pattern_consistency_threshold
  420. )
  421. if not consistency_passed:
  422. log.info(f" {symbol}({dominant_future}) ✗ 历史均线模式一致性不足 "
  423. f"({consistency_ratio:.1%} < {g.ma_pattern_consistency_threshold:.1%}),跳过")
  424. add_to_excluded_contracts(dominant_future, 'ma_consistency', current_trading_day)
  425. continue
  426. else:
  427. log.info(f" {symbol}({dominant_future}) ✓ 历史均线模式一致性检查通过 "
  428. f"({consistency_ratio:.1%} >= {g.ma_pattern_consistency_threshold:.1%})")
  429. # 步骤9:计算开盘价差并检查(合并优化)
  430. open_gap_ratio = (today_open - yesterday_close) / yesterday_close
  431. log.info(f" 开盘价差检查: 昨收 {yesterday_close:.2f}, 今开 {today_open:.2f}, "
  432. f"价差比例 {open_gap_ratio:.2%}")
  433. # 检查开盘价差是否符合方向要求
  434. gap_check_passed = False
  435. if g.ma_gap_strategy_mode == 1:
  436. # 方案1:多头检查上跳,空头检查下跳
  437. if direction == 'long' and open_gap_ratio >= g.ma_open_gap_threshold:
  438. log.info(f" {symbol}({dominant_future}) ✓ 方案1多头开盘价差检查通过 ({open_gap_ratio:.2%} >= {g.ma_open_gap_threshold:.2%})")
  439. gap_check_passed = True
  440. elif direction == 'short' and open_gap_ratio <= -g.ma_open_gap_threshold:
  441. log.info(f" {symbol}({dominant_future}) ✓ 方案1空头开盘价差检查通过 ({open_gap_ratio:.2%} <= {-g.ma_open_gap_threshold:.2%})")
  442. gap_check_passed = True
  443. elif g.ma_gap_strategy_mode == 2 or g.ma_gap_strategy_mode == 3:
  444. # 方案2和方案3:多头检查下跳,空头检查上跳
  445. if direction == 'long' and open_gap_ratio <= -g.ma_open_gap_threshold2:
  446. log.info(f" {symbol}({dominant_future}) ✓ 方案{g.ma_gap_strategy_mode}多头开盘价差检查通过 ({open_gap_ratio:.2%} <= {-g.ma_open_gap_threshold2:.2%})")
  447. gap_check_passed = True
  448. elif direction == 'short' and open_gap_ratio >= g.ma_open_gap_threshold2:
  449. log.info(f" {symbol}({dominant_future}) ✓ 方案{g.ma_gap_strategy_mode}空头开盘价差检查通过 ({open_gap_ratio:.2%} >= {g.ma_open_gap_threshold2:.2%})")
  450. gap_check_passed = True
  451. if not gap_check_passed:
  452. add_to_excluded_contracts(dominant_future, 'open_gap', current_trading_day)
  453. continue
  454. # 步骤10:将通过检查的品种加入候选列表
  455. g.daily_ma_candidates[dominant_future] = {
  456. 'symbol': symbol,
  457. 'direction': direction,
  458. 'open_price': today_open,
  459. 'yesterday_close': yesterday_close,
  460. 'yesterday_open': yesterday_open,
  461. 'ma_values': ma_values
  462. }
  463. log.info(f" ✓✓ {symbol} 通过均线和开盘价差检查,加入候选列表")
  464. except Exception as e:
  465. g.ma_checked_underlyings.pop(symbol, None)
  466. log.warning(f"{symbol} 检查时出错: {str(e)}")
  467. continue
  468. log.info(f"候选列表更新完成,当前候选品种: {list(g.daily_ma_candidates.keys())}")
  469. log.info("=" * 60)
  470. def check_open_and_stop(context):
  471. """统一的开仓和止损止盈检查函数"""
  472. # 先检查换月移仓
  473. log.info("=" * 60)
  474. current_trading_day = get_current_trading_day(context.current_dt)
  475. log.info(f"执行开仓和止损止盈检查 - 时间: {context.current_dt}, 交易日: {current_trading_day}")
  476. log.info("=" * 60)
  477. log.info(f"先检查换月:")
  478. position_auto_switch(context)
  479. # 获取当前时间
  480. current_time = str(context.current_dt.time())[:2]
  481. # 判断是否为夜盘时间
  482. is_night_session = (current_time in ['21', '22', '23', '00', '01', '02'])
  483. # 第一步:检查开仓条件
  484. log.info(f"检查开仓条件:")
  485. if g.daily_ma_candidates:
  486. log.info("=" * 60)
  487. log.info(f"执行开仓检查 - 时间: {context.current_dt}, 候选品种数量: {len(g.daily_ma_candidates)}")
  488. # 遍历候选品种
  489. candidates_to_remove = []
  490. for dominant_future, candidate_info in g.daily_ma_candidates.items():
  491. try:
  492. symbol = candidate_info['symbol']
  493. direction = candidate_info['direction']
  494. open_price = candidate_info['open_price']
  495. yesterday_close = candidate_info.get('yesterday_close')
  496. yesterday_open = candidate_info.get('yesterday_open')
  497. # 检查是否已有持仓
  498. if check_symbol_prefix_match(dominant_future, set(g.trade_history.keys())):
  499. log.info(f"{symbol} 已有持仓,从候选列表移除")
  500. candidates_to_remove.append(dominant_future)
  501. continue
  502. # 获取当前价格
  503. current_data = get_current_data()[dominant_future]
  504. current_price = current_data.last_price
  505. # 计算当天价差
  506. intraday_diff = current_price - open_price
  507. intraday_diff_ratio = intraday_diff / open_price
  508. log.info(f"{symbol}({dominant_future}) 开仓条件检查:")
  509. log.info(f" 方向: {direction}, 开盘价: {open_price:.2f}, 当前价: {current_price:.2f}, "
  510. f"当天价差: {intraday_diff:.2f}, 变化比例: {intraday_diff_ratio:.2%}")
  511. # 判断是否满足开仓条件
  512. should_open = False
  513. if g.ma_gap_strategy_mode == 1:
  514. # 方案1:根据参数决定是否检查日内价差
  515. if not g.check_intraday_spread:
  516. log.info(f" 方案1跳过日内价差检查(check_intraday_spread=False)")
  517. should_open = True
  518. elif direction == 'long' and intraday_diff > 0:
  519. log.info(f" ✓ 方案1多头当天价差检查通过 ({intraday_diff:.2f} > 0)")
  520. should_open = True
  521. elif direction == 'short' and intraday_diff < 0:
  522. log.info(f" ✓ 方案1空头当天价差检查通过 ({intraday_diff:.2f} < 0)")
  523. should_open = True
  524. else:
  525. log.info(f" ✗ 方案1当天价差不符合{direction}方向要求")
  526. elif g.ma_gap_strategy_mode == 2:
  527. # 方案2:强制检查日内变化,使用专用阈值
  528. if direction == 'long' and intraday_diff_ratio >= g.ma_intraday_threshold_scheme2:
  529. log.info(f" ✓ 方案2多头日内变化检查通过 ({intraday_diff_ratio:.2%} >= {g.ma_intraday_threshold_scheme2:.2%})")
  530. should_open = True
  531. elif direction == 'short' and intraday_diff_ratio <= -g.ma_intraday_threshold_scheme2:
  532. log.info(f" ✓ 方案2空头日内变化检查通过 ({intraday_diff_ratio:.2%} <= {-g.ma_intraday_threshold_scheme2:.2%})")
  533. should_open = True
  534. else:
  535. log.info(f" ✗ 方案2日内变化不符合{direction}方向要求(阈值: ±{g.ma_intraday_threshold_scheme2:.2%})")
  536. elif g.ma_gap_strategy_mode == 3:
  537. # 方案3:下跳后上涨(多头)或上跳后下跌(空头),并检查当前价格与前一日开盘收盘均值的关系
  538. if yesterday_open is not None and yesterday_close is not None:
  539. prev_day_avg = (yesterday_open + yesterday_close) / 2
  540. log.debug(f" 前一日开盘价: {yesterday_open:.2f}, 前一日收盘价: {yesterday_close:.2f}, 前一日开盘收盘均值: {prev_day_avg:.2f}")
  541. if direction == 'long':
  542. # 多头:当前价格 >= 前一日开盘收盘均值
  543. if current_price >= prev_day_avg:
  544. log.info(f" ✓ 方案3多头入场条件通过: 当前价 {current_price:.2f} >= 前日均值 {prev_day_avg:.2f}")
  545. should_open = True
  546. else:
  547. log.info(f" ✗ 方案3多头入场条件未通过: 当前价 {current_price:.2f} < 前日均值 {prev_day_avg:.2f}")
  548. elif direction == 'short':
  549. # 空头:当前价格 <= 前一日开盘收盘均值
  550. if current_price <= prev_day_avg:
  551. log.info(f" ✓ 方案3空头入场条件通过: 当前价 {current_price:.2f} <= 前日均值 {prev_day_avg:.2f}")
  552. should_open = True
  553. else:
  554. log.info(f" ✗ 方案3空头入场条件未通过: 当前价 {current_price:.2f} > 前日均值 {prev_day_avg:.2f}")
  555. else:
  556. log.info(f" ✗ 方案3缺少前一日开盘或收盘价数据")
  557. if should_open:
  558. ma_values = candidate_info.get('ma_values') or {}
  559. cross_score = calculate_ma_cross_score(open_price, current_price, ma_values, direction)
  560. log.info(f" 均线穿越得分: {cross_score}, 阈值: {g.ma_cross_threshold}")
  561. if cross_score < g.ma_cross_threshold:
  562. log.info(f" ✗ 均线穿越得分不足,跳过开仓")
  563. continue
  564. # 执行开仓
  565. log.info(f" 准备开仓: {symbol} {direction}")
  566. target_hands = calculate_target_hands(context, dominant_future, direction)
  567. if target_hands > 0:
  568. success = open_position(context, dominant_future, target_hands, direction,
  569. f'均线形态开仓')
  570. if success:
  571. log.info(f" ✓✓ {symbol} 开仓成功,从候选列表移除")
  572. candidates_to_remove.append(dominant_future)
  573. else:
  574. log.warning(f" ✗ {symbol} 开仓失败")
  575. else:
  576. log.warning(f" ✗ {symbol} 计算目标手数为0,跳过开仓")
  577. except Exception as e:
  578. log.warning(f"{dominant_future} 处理时出错: {str(e)}")
  579. continue
  580. # 从候选列表中移除已开仓的品种
  581. for future in candidates_to_remove:
  582. if future in g.daily_ma_candidates:
  583. del g.daily_ma_candidates[future]
  584. log.info(f"剩余候选品种: {list(g.daily_ma_candidates.keys())}")
  585. log.info("=" * 60)
  586. # 第二步:检查止损止盈
  587. log.info(f"检查止损止盈条件:")
  588. subportfolio = context.subportfolios[0]
  589. long_positions = list(subportfolio.long_positions.values())
  590. short_positions = list(subportfolio.short_positions.values())
  591. closed_count = 0
  592. skipped_count = 0
  593. for position in long_positions + short_positions:
  594. security = position.security
  595. underlying_symbol = security.split('.')[0][:-4]
  596. # 检查交易时间适配性
  597. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  598. # 如果是夜盘时间,但品种不支持夜盘交易,则跳过
  599. if is_night_session and not has_night_session:
  600. skipped_count += 1
  601. continue
  602. # 执行止损止盈检查
  603. if check_position_stop_loss_profit(context, position):
  604. closed_count += 1
  605. if closed_count > 0:
  606. log.info(f"执行了 {closed_count} 次止损止盈")
  607. if skipped_count > 0:
  608. log.info(f"夜盘时间跳过 {skipped_count} 个日间品种的止损止盈检查")
  609. def check_ma_trailing_reactivation(context):
  610. """检查是否需要恢复均线跟踪止盈"""
  611. subportfolio = context.subportfolios[0]
  612. positions = list(subportfolio.long_positions.values()) + list(subportfolio.short_positions.values())
  613. if not positions:
  614. return
  615. reenabled_count = 0
  616. current_data = get_current_data()
  617. for position in positions:
  618. security = position.security
  619. trade_info = g.trade_history.get(security)
  620. if not trade_info or trade_info.get('ma_trailing_enabled', True):
  621. continue
  622. direction = trade_info['direction']
  623. ma_values = calculate_realtime_ma_values(security, [5])
  624. ma5_value = ma_values.get('ma5')
  625. if ma5_value is None or security not in current_data:
  626. continue
  627. today_price = current_data[security].last_price
  628. if direction == 'long' and today_price > ma5_value:
  629. trade_info['ma_trailing_enabled'] = True
  630. reenabled_count += 1
  631. log.info(f"恢复均线跟踪止盈: {security} {direction}, 当前价 {today_price:.2f} > MA5 {ma5_value:.2f}")
  632. elif direction == 'short' and today_price < ma5_value:
  633. trade_info['ma_trailing_enabled'] = True
  634. reenabled_count += 1
  635. log.info(f"恢复均线跟踪止盈: {security} {direction}, 当前价 {today_price:.2f} < MA5 {ma5_value:.2f}")
  636. if reenabled_count > 0:
  637. log.info(f"恢复均线跟踪止盈持仓数量: {reenabled_count}")
  638. def check_position_stop_loss_profit(context, position):
  639. """检查单个持仓的止损止盈"""
  640. log.info(f"检查持仓: {position.security}")
  641. security = position.security
  642. if security not in g.trade_history:
  643. return False
  644. trade_info = g.trade_history[security]
  645. direction = trade_info['direction']
  646. entry_price = trade_info['entry_price']
  647. entry_time = trade_info['entry_time']
  648. entry_trading_day = trade_info.get('entry_trading_day')
  649. if entry_trading_day is None:
  650. entry_trading_day = get_current_trading_day(entry_time)
  651. trade_info['entry_trading_day'] = entry_trading_day
  652. if entry_trading_day is not None:
  653. entry_trading_day = normalize_trade_day_value(entry_trading_day)
  654. current_trading_day = normalize_trade_day_value(get_current_trading_day(context.current_dt))
  655. current_price = position.price
  656. # 计算当前盈亏比率
  657. if direction == 'long':
  658. profit_rate = (current_price - entry_price) / entry_price
  659. else:
  660. profit_rate = (entry_price - current_price) / entry_price
  661. # 检查固定止损
  662. log.info("=" * 60)
  663. log.info(f"检查固定止损:")
  664. log.info("=" * 60)
  665. if profit_rate <= -g.fixed_stop_loss_rate:
  666. log.info(f"触发固定止损 {security} {direction}, 当前亏损率: {profit_rate:.3%}, "
  667. f"成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  668. close_position(context, security, direction)
  669. return True
  670. else:
  671. log.debug(f"未触发固定止损 {security} {direction}, 当前亏损率: {profit_rate:.3%}, "
  672. f"成本价: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  673. if entry_trading_day is not None and entry_trading_day == current_trading_day:
  674. log.info(f"{security} 建仓交易日内跳过动态止盈检查")
  675. return False
  676. # 检查是否启用均线跟踪止盈
  677. log.info("=" * 60)
  678. log.info(f"检查是否启用均线跟踪止盈:")
  679. log.info("=" * 60)
  680. if not trade_info.get('ma_trailing_enabled', True):
  681. return False
  682. # 检查均线跟踪止盈
  683. # 获取持仓天数
  684. entry_date = entry_time.date()
  685. current_date = context.current_dt.date()
  686. all_trade_days = get_all_trade_days()
  687. holding_days = sum((entry_date <= d <= current_date) for d in all_trade_days)
  688. # 计算变化率
  689. today_price = get_current_data()[security].last_price
  690. avg_daily_change_rate = calculate_average_daily_change_rate(security)
  691. historical_data = attribute_history(security, 1, '1d', ['close'])
  692. yesterday_close = historical_data['close'].iloc[-1]
  693. today_change_rate = abs((today_price - yesterday_close) / yesterday_close)
  694. # 根据时间判断使用的偏移量
  695. current_time = context.current_dt.time()
  696. target_time = datetime.strptime('14:55:00', '%H:%M:%S').time()
  697. if current_time > target_time:
  698. offset_ratio = g.ma_offset_ratio_close
  699. log.debug(f"当前时间是:{current_time},使用偏移量: {offset_ratio:.3%}")
  700. else:
  701. offset_ratio = g.ma_offset_ratio_normal
  702. log.debug(f"当前时间是:{current_time},使用偏移量: {offset_ratio:.3%}")
  703. # 选择止损均线
  704. close_line = None
  705. if today_change_rate >= 1.5 * avg_daily_change_rate:
  706. close_line = 'ma5' # 波动剧烈时用短周期
  707. elif holding_days <= g.days_for_adjustment:
  708. close_line = 'ma5' # 持仓初期用短周期
  709. else:
  710. close_line = 'ma5' if today_change_rate >= 1.2 * avg_daily_change_rate else 'ma10'
  711. # 计算实时均线值
  712. ma_values = calculate_realtime_ma_values(security, [5, 10])
  713. ma_value = ma_values[close_line]
  714. # 应用偏移量
  715. if direction == 'long':
  716. adjusted_ma_value = ma_value * (1 - offset_ratio)
  717. else:
  718. adjusted_ma_value = ma_value * (1 + offset_ratio)
  719. # 判断是否触发均线止损
  720. if (direction == 'long' and today_price < adjusted_ma_value) or \
  721. (direction == 'short' and today_price > adjusted_ma_value):
  722. log.info(f"触发均线跟踪止盈 {security} {direction}, 止损均线: {close_line}, "
  723. f"均线值: {ma_value:.2f}, 调整后: {adjusted_ma_value:.2f}, "
  724. f"当前价: {today_price:.2f}, 持仓天数: {holding_days}")
  725. close_position(context, security, direction)
  726. return True
  727. else:
  728. log.debug(f"未触发均线跟踪止盈 {security} {direction}, 止损均线: {close_line}, "
  729. f"均线值: {ma_value:.2f}, 调整后: {adjusted_ma_value:.2f}, "
  730. f"当前价: {today_price:.2f}, 持仓天数: {holding_days}")
  731. return False
  732. ############################ 核心辅助函数 ###################################
  733. def calculate_ma_values(data, periods):
  734. """计算均线值
  735. Args:
  736. data: DataFrame,包含'close'列的历史数据(最后一行是最新的数据)
  737. periods: list,均线周期列表,如[5, 10, 20, 30]
  738. Returns:
  739. dict: {'MA5': value, 'MA10': value, 'MA20': value, 'MA30': value}
  740. 返回最后一行(最新日期)的各周期均线值
  741. """
  742. ma_values = {}
  743. for period in periods:
  744. if len(data) >= period:
  745. # 计算最后period天的均线值
  746. ma_values[f'MA{period}'] = data['close'].iloc[-period:].mean()
  747. else:
  748. ma_values[f'MA{period}'] = None
  749. return ma_values
  750. def calculate_ma_cross_score(open_price, current_price, ma_values, direction):
  751. """根据开盘价与当前价统计多周期均线穿越得分"""
  752. if not ma_values:
  753. return 0
  754. assert direction in ('long', 'short')
  755. score = 0
  756. for period in g.ma_periods:
  757. key = f'MA{period}'
  758. ma_value = ma_values.get(key)
  759. if ma_value is None:
  760. continue
  761. cross_up = open_price < ma_value and current_price > ma_value
  762. cross_down = open_price > ma_value and current_price < ma_value
  763. if not (cross_up or cross_down):
  764. continue
  765. if direction == 'long':
  766. delta = 1 if cross_up else -1
  767. else:
  768. delta = -1 if cross_up else 1
  769. score += delta
  770. log.debug(
  771. f" 均线穿越[{key}] - 开盘 {open_price:.2f}, 当前 {current_price:.2f}, "
  772. f"均线 {ma_value:.2f}, 方向 {direction}, 增量 {delta}, 当前得分 {score}"
  773. )
  774. return score
  775. def calculate_ma_proximity_counts(data, periods, lookback_days):
  776. """统计近 lookback_days 天收盘价贴近各均线的次数"""
  777. proximity_counts = {f'MA{period}': 0 for period in periods}
  778. if len(data) < lookback_days:
  779. return proximity_counts
  780. closes = data['close'].iloc[-lookback_days:]
  781. ma_series = {
  782. period: data['close'].rolling(window=period).mean().iloc[-lookback_days:]
  783. for period in periods
  784. }
  785. for idx, close_price in enumerate(closes):
  786. min_diff = None
  787. closest_period = None
  788. for period in periods:
  789. ma_value = ma_series[period].iloc[idx]
  790. if pd.isna(ma_value):
  791. continue
  792. diff = abs(close_price - ma_value)
  793. if min_diff is None or diff < min_diff:
  794. min_diff = diff
  795. closest_period = period
  796. if closest_period is not None:
  797. proximity_counts[f'MA{closest_period}'] += 1
  798. return proximity_counts
  799. def calculate_extreme_trend_days(data, periods, lookback_days):
  800. """统计过去 lookback_days 天收盘价相对所有均线的极端趋势天数"""
  801. if len(data) < lookback_days:
  802. return 0, 0
  803. recent_closes = data['close'].iloc[-lookback_days:]
  804. ma_series = {
  805. period: data['close'].rolling(window=period).mean().iloc[-lookback_days:]
  806. for period in periods
  807. }
  808. above_count = 0
  809. below_count = 0
  810. for idx, close_price in enumerate(recent_closes):
  811. ma_values = []
  812. valid = True
  813. for period in periods:
  814. ma_value = ma_series[period].iloc[idx]
  815. if pd.isna(ma_value):
  816. valid = False
  817. break
  818. ma_values.append(ma_value)
  819. if not valid or not ma_values:
  820. continue
  821. if all(close_price > ma_value for ma_value in ma_values):
  822. above_count += 1
  823. elif all(close_price < ma_value for ma_value in ma_values):
  824. below_count += 1
  825. return above_count, below_count
  826. def check_ma5_distribution_filter(data, lookback_days, direction, min_ratio):
  827. """检查近 lookback_days 天收盘价相对于MA5的分布情况"""
  828. stats = {
  829. 'lookback_days': lookback_days,
  830. 'valid_days': 0,
  831. 'qualified_days': 0,
  832. 'required_days': max(0, math.ceil(lookback_days * min_ratio))
  833. }
  834. if lookback_days <= 0:
  835. return True, stats
  836. if len(data) < max(lookback_days, 5):
  837. return False, stats
  838. recent_closes = data['close'].iloc[-lookback_days:]
  839. ma5_series = data['close'].rolling(window=5).mean().iloc[-lookback_days:]
  840. for close_price, ma5_value in zip(recent_closes, ma5_series):
  841. if pd.isna(ma5_value):
  842. continue
  843. stats['valid_days'] += 1
  844. if direction == 'long' and close_price < ma5_value:
  845. stats['qualified_days'] += 1
  846. elif direction == 'short' and close_price > ma5_value:
  847. stats['qualified_days'] += 1
  848. if stats['valid_days'] < lookback_days:
  849. return False, stats
  850. return stats['qualified_days'] >= stats['required_days'], stats
  851. def check_ma_pattern(ma_values, direction):
  852. """检查均线排列模式是否符合方向要求
  853. Args:
  854. ma_values: dict,包含MA5, MA10, MA20, MA30的均线值
  855. direction: str,'long'或'short'
  856. Returns:
  857. bool: 是否符合均线排列要求
  858. """
  859. ma5 = ma_values['MA5']
  860. ma10 = ma_values['MA10']
  861. ma20 = ma_values['MA20']
  862. ma30 = ma_values['MA30']
  863. if direction == 'long':
  864. # 多头模式:MA30 <= MA20 <= MA10 <= MA5 或 MA30 <= MA20 <= MA5 <= MA10
  865. # 或者:MA20 <= MA30 <= MA10 <= MA5 或 MA20 <= MA30 <= MA5 <= MA10
  866. pattern1 = (ma30 <= ma20 <= ma10 <= ma5)
  867. pattern2 = (ma30 <= ma20 <= ma5 <= ma10)
  868. pattern3 = (ma20 <= ma30 <= ma10 <= ma5)
  869. pattern4 = (ma20 <= ma30 <= ma5 <= ma10)
  870. return pattern1 or pattern2 or pattern3 or pattern4
  871. elif direction == 'short':
  872. # 空头模式:MA10 <= MA5 <= MA20 <= MA30 或 MA5 <= MA10 <= MA20 <= MA30
  873. # 或者:MA10 <= MA5 <= MA30 <= MA20 或 MA5 <= MA10 <= MA30 <= MA20
  874. pattern1 = (ma10 <= ma5 <= ma20 <= ma30)
  875. pattern2 = (ma5 <= ma10 <= ma20 <= ma30)
  876. pattern3 = (ma10 <= ma5 <= ma30 <= ma20)
  877. pattern4 = (ma5 <= ma10 <= ma30 <= ma20)
  878. return pattern1 or pattern2 or pattern3 or pattern4
  879. else:
  880. return False
  881. def check_historical_ma_pattern_consistency(historical_data, direction, lookback_days, consistency_threshold):
  882. """检查历史均线模式的一致性
  883. Args:
  884. historical_data: DataFrame,包含足够天数的历史数据
  885. direction: str,'long'或'short'
  886. lookback_days: int,检查过去多少天
  887. consistency_threshold: float,一致性阈值(0-1之间)
  888. Returns:
  889. tuple: (bool, float) - (是否通过一致性检查, 实际一致性比例)
  890. """
  891. if len(historical_data) < max(g.ma_periods) + lookback_days:
  892. # 历史数据不足
  893. return False, 0.0
  894. match_count = 0
  895. total_count = lookback_days
  896. # log.debug(f"历史均线模式一致性检查: {direction}, 检查过去{lookback_days}天的数据")
  897. # log.debug(f"历史数据: {historical_data}")
  898. # 检查过去lookback_days天的均线模式
  899. for i in range(lookback_days):
  900. # 获取倒数第(i+1)天的数据(i=0时是昨天,i=1时是前天,依此类推)
  901. end_idx = -(i + 1)
  902. # 获取这一天的具体日期
  903. date = historical_data.index[end_idx].date()
  904. # 获取到该天(包括该天)为止的所有数据
  905. if i == 0:
  906. data_slice = historical_data
  907. else:
  908. data_slice = historical_data.iloc[:-i]
  909. # 计算该天的均线值
  910. # log.debug(f"对于倒数第{i+1}天,end_idx: {end_idx},日期: {date},计算均线值: {data_slice}")
  911. ma_values = calculate_ma_values(data_slice, g.ma_periods)
  912. # log.debug(f"end_idx: {end_idx},日期: {date},倒数第{i+1}天的均线值: {ma_values}")
  913. # 检查是否符合模式
  914. if check_ma_pattern(ma_values, direction):
  915. match_count += 1
  916. # log.debug(f"日期: {date},对于倒数第{i+1}天,历史均线模式一致性检查: {direction} 符合模式")
  917. # else:
  918. # log.debug(f"日期: {date},对于倒数第{i+1}天,历史均线模式一致性检查: {direction} 不符合模式")
  919. consistency_ratio = match_count / total_count
  920. passed = consistency_ratio >= consistency_threshold
  921. return passed, consistency_ratio
  922. ############################ 交易执行函数 ###################################
  923. def open_position(context, security, target_hands, direction, reason=''):
  924. """开仓"""
  925. try:
  926. # 记录交易前的可用资金
  927. cash_before = context.portfolio.available_cash
  928. # 使用order_target按手数开仓
  929. order = order_target(security, target_hands, side=direction)
  930. if order is not None and order.filled > 0:
  931. # 记录交易后的可用资金
  932. cash_after = context.portfolio.available_cash
  933. # 计算实际资金变化
  934. cash_change = cash_before - cash_after
  935. # 获取订单价格和数量
  936. order_price = order.avg_cost if order.avg_cost else order.price
  937. order_amount = order.filled
  938. # 记录当日交易
  939. underlying_symbol = security.split('.')[0][:-4]
  940. g.today_trades.append({
  941. 'security': security,
  942. 'underlying_symbol': underlying_symbol,
  943. 'direction': direction,
  944. 'order_amount': order_amount,
  945. 'order_price': order_price,
  946. 'cash_change': cash_change,
  947. 'time': context.current_dt
  948. })
  949. # 记录交易信息
  950. entry_trading_day = get_current_trading_day(context.current_dt)
  951. g.trade_history[security] = {
  952. 'entry_price': order_price,
  953. 'target_hands': target_hands,
  954. 'actual_hands': order_amount,
  955. 'actual_margin': cash_change,
  956. 'direction': direction,
  957. 'entry_time': context.current_dt,
  958. 'entry_trading_day': entry_trading_day
  959. }
  960. ma_trailing_enabled = True
  961. ma_values_at_entry = calculate_realtime_ma_values(security, [5])
  962. ma5_value = ma_values_at_entry.get('ma5')
  963. if ma5_value is not None:
  964. if direction == 'long' and order_price < ma5_value:
  965. ma_trailing_enabled = False
  966. log.info(f"禁用均线跟踪止盈: {security} {direction}, 开仓价 {order_price:.2f} < MA5 {ma5_value:.2f}")
  967. elif direction == 'short' and order_price > ma5_value:
  968. ma_trailing_enabled = False
  969. log.info(f"禁用均线跟踪止盈: {security} {direction}, 开仓价 {order_price:.2f} > MA5 {ma5_value:.2f}")
  970. g.trade_history[security]['ma_trailing_enabled'] = ma_trailing_enabled
  971. log.info(f"开仓成功: {security} {direction} {order_amount}手 @{order_price:.2f}, "
  972. f"保证金: {cash_change:.0f}, 原因: {reason}")
  973. return True
  974. except Exception as e:
  975. log.warning(f"开仓失败 {security}: {str(e)}")
  976. return False
  977. def close_position(context, security, direction):
  978. """平仓"""
  979. try:
  980. # 使用order_target平仓到0手
  981. order = order_target(security, 0, side=direction)
  982. if order is not None and order.filled > 0:
  983. underlying_symbol = security.split('.')[0][:-4]
  984. # 记录当日交易(平仓)
  985. g.today_trades.append({
  986. 'security': security,
  987. 'underlying_symbol': underlying_symbol,
  988. 'direction': direction,
  989. 'order_amount': -order.filled,
  990. 'order_price': order.avg_cost if order.avg_cost else order.price,
  991. 'cash_change': 0,
  992. 'time': context.current_dt
  993. })
  994. log.info(f"平仓成功: {underlying_symbol} {direction} {order.filled}手")
  995. # 从交易历史中移除
  996. if security in g.trade_history:
  997. del g.trade_history[security]
  998. return True
  999. except Exception as e:
  1000. log.warning(f"平仓失败 {security}: {str(e)}")
  1001. return False
  1002. ############################ 辅助函数 ###################################
  1003. def get_futures_config(underlying_symbol, config_key=None, default_value=None):
  1004. """获取期货品种配置信息的辅助函数"""
  1005. if underlying_symbol not in g.futures_config:
  1006. if config_key and default_value is not None:
  1007. return default_value
  1008. return {}
  1009. if config_key is None:
  1010. return g.futures_config[underlying_symbol]
  1011. return g.futures_config[underlying_symbol].get(config_key, default_value)
  1012. def get_margin_rate(underlying_symbol, direction, default_rate=0.10):
  1013. """获取保证金比例的辅助函数"""
  1014. return g.futures_config.get(underlying_symbol, {}).get('margin_rate', {}).get(direction, default_rate)
  1015. def get_multiplier(underlying_symbol, default_multiplier=10):
  1016. """获取合约乘数的辅助函数"""
  1017. return g.futures_config.get(underlying_symbol, {}).get('multiplier', default_multiplier)
  1018. def add_to_excluded_contracts(dominant_future, reason, current_trading_day):
  1019. """将合约添加到排除缓存"""
  1020. g.excluded_contracts[dominant_future] = {
  1021. 'reason': reason,
  1022. 'trading_day': current_trading_day
  1023. }
  1024. def has_reached_trading_start(current_dt, trading_start_time_str, has_night_session=False):
  1025. """判断当前是否已到达合约允许交易的起始时间"""
  1026. if not trading_start_time_str:
  1027. return True
  1028. try:
  1029. hour, minute = [int(part) for part in trading_start_time_str.split(':')[:2]]
  1030. except Exception:
  1031. return True
  1032. start_time = time(hour, minute)
  1033. current_time = current_dt.time()
  1034. if has_night_session:
  1035. if current_time >= start_time:
  1036. return True
  1037. if current_time < time(12, 0):
  1038. return True
  1039. if time(8, 30) <= current_time <= time(15, 30):
  1040. return True
  1041. return False
  1042. if current_time < start_time:
  1043. return False
  1044. if current_time >= time(20, 0):
  1045. return False
  1046. return True
  1047. def calculate_target_hands(context, security, direction):
  1048. """计算目标开仓手数"""
  1049. current_price = get_current_data()[security].last_price
  1050. underlying_symbol = security.split('.')[0][:-4]
  1051. # 使用保证金比例
  1052. margin_rate = get_margin_rate(underlying_symbol, direction)
  1053. multiplier = get_multiplier(underlying_symbol)
  1054. # 计算单手保证金
  1055. log.debug(f"计算单手保证金: {current_price:.2f} * {multiplier:.2f} * {margin_rate:.2f} = {current_price * multiplier * margin_rate:.2f}")
  1056. single_hand_margin = current_price * multiplier * margin_rate
  1057. # 还要考虑可用资金限制
  1058. available_cash = context.portfolio.available_cash * g.usage_percentage
  1059. # 根据单个标的最大持仓保证金限制计算开仓数量
  1060. max_margin = g.max_margin_per_position
  1061. if single_hand_margin <= max_margin:
  1062. # 如果单手保证金不超过最大限制,计算最大可开仓手数
  1063. max_hands = int(max_margin / single_hand_margin)
  1064. max_hands_by_cash = int(available_cash / single_hand_margin)
  1065. # 取两者较小值
  1066. actual_hands = min(max_hands, max_hands_by_cash)
  1067. # 确保至少开1手
  1068. actual_hands = max(1, actual_hands)
  1069. log.info(f"单手保证金: {single_hand_margin:.0f}, 目标开仓手数: {actual_hands}")
  1070. return actual_hands
  1071. else:
  1072. # 如果单手保证金超过最大限制,默认开仓1手
  1073. actual_hands = 1
  1074. log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手")
  1075. return actual_hands
  1076. def check_symbol_prefix_match(symbol, hold_symbols):
  1077. """检查是否有相似的持仓品种"""
  1078. symbol_prefix = symbol[:-9]
  1079. for hold_symbol in hold_symbols:
  1080. hold_symbol_prefix = hold_symbol[:-9] if len(hold_symbol) > 9 else hold_symbol
  1081. if symbol_prefix == hold_symbol_prefix:
  1082. return True
  1083. return False
  1084. def calculate_average_daily_change_rate(security, days=30):
  1085. """计算日均变化率"""
  1086. historical_data = attribute_history(security, days + 1, '1d', ['close'])
  1087. daily_change_rates = abs(historical_data['close'].pct_change()).iloc[1:]
  1088. return daily_change_rates.mean()
  1089. def calculate_realtime_ma_values(security, ma_periods):
  1090. """计算包含当前价格的实时均线值"""
  1091. historical_data = attribute_history(security, max(ma_periods), '1d', ['close'])
  1092. today_price = get_current_data()[security].last_price
  1093. close_prices = historical_data['close'].tolist() + [today_price]
  1094. ma_values = {f'ma{period}': sum(close_prices[-period:]) / period for period in ma_periods}
  1095. return ma_values
  1096. def after_market_close(context):
  1097. """收盘后运行函数"""
  1098. log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
  1099. # 清空候选列表(每天重新检查)
  1100. g.daily_ma_candidates = {}
  1101. # 清空排除缓存(每天重新检查)
  1102. excluded_count = len(g.excluded_contracts)
  1103. if excluded_count > 0:
  1104. log.info(f"清空排除缓存,共 {excluded_count} 个合约")
  1105. g.excluded_contracts = {}
  1106. # 只有当天有交易时才打印统计信息
  1107. if g.today_trades:
  1108. print_daily_trading_summary(context)
  1109. # 清空当日交易记录
  1110. g.today_trades = []
  1111. log.info('##############################################################')
  1112. def print_daily_trading_summary(context):
  1113. """打印当日交易汇总"""
  1114. if not g.today_trades:
  1115. return
  1116. log.info("\n=== 当日交易汇总 ===")
  1117. total_margin = 0
  1118. for trade in g.today_trades:
  1119. if trade['order_amount'] > 0: # 开仓
  1120. log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
  1121. f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f}")
  1122. total_margin += trade['cash_change']
  1123. else: # 平仓
  1124. log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
  1125. f"价格:{trade['order_price']:.2f}")
  1126. log.info(f"当日保证金占用: {total_margin:.0f}")
  1127. log.info("==================\n")
  1128. ########################## 自动移仓换月函数 #################################
  1129. def position_auto_switch(context, pindex=0, switch_func=None, callback=None):
  1130. """期货自动移仓换月"""
  1131. import re
  1132. subportfolio = context.subportfolios[pindex]
  1133. symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  1134. switch_result = []
  1135. for symbol in symbols:
  1136. match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
  1137. if not match:
  1138. raise ValueError("未知期货标的: {}".format(symbol))
  1139. else:
  1140. underlying_symbol = match.groupdict()["underlying_symbol"]
  1141. trading_start = get_futures_config(underlying_symbol, 'trading_start_time', None)
  1142. has_night_session = get_futures_config(underlying_symbol, 'has_night_session', False)
  1143. # log.debug(f"移仓换月: {symbol}, 交易开始时间: {trading_start}, 夜盘: {has_night_session}")
  1144. if trading_start and not has_reached_trading_start(context.current_dt, trading_start, has_night_session):
  1145. # log.info("{} 当前时间 {} 未到达交易开始时间 {} (夜盘:{} ),跳过移仓".format(
  1146. # symbol,
  1147. # context.current_dt.strftime('%H:%M:%S'),
  1148. # trading_start,
  1149. # has_night_session
  1150. # ))
  1151. continue
  1152. dominant = get_dominant_future(underlying_symbol)
  1153. cur = get_current_data()
  1154. symbol_last_price = cur[symbol].last_price
  1155. dominant_last_price = cur[dominant].last_price
  1156. if dominant > symbol:
  1157. for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
  1158. if symbol not in positions_.keys():
  1159. continue
  1160. else :
  1161. p = positions_[symbol]
  1162. if switch_func is not None:
  1163. switch_func(context, pindex, p, dominant)
  1164. else:
  1165. amount = p.total_amount
  1166. # 跌停不能开空和平多,涨停不能开多和平空
  1167. if p.side == "long":
  1168. symbol_low_limit = cur[symbol].low_limit
  1169. dominant_high_limit = cur[dominant].high_limit
  1170. if symbol_last_price <= symbol_low_limit:
  1171. log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
  1172. continue
  1173. elif dominant_last_price >= dominant_high_limit:
  1174. log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(dominant))
  1175. continue
  1176. else:
  1177. log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
  1178. order_old = order_target(symbol, 0, side='long')
  1179. if order_old != None and order_old.filled > 0:
  1180. order_new = order_target(dominant, amount, side='long')
  1181. if order_new != None and order_new.filled > 0:
  1182. switch_result.append({"before": symbol, "after": dominant, "side": "long"})
  1183. # 换月成功,更新交易记录
  1184. if symbol in g.trade_history:
  1185. g.trade_history[dominant] = g.trade_history[symbol]
  1186. del g.trade_history[symbol]
  1187. else:
  1188. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1189. if p.side == "short":
  1190. symbol_high_limit = cur[symbol].high_limit
  1191. dominant_low_limit = cur[dominant].low_limit
  1192. if symbol_last_price >= symbol_high_limit:
  1193. log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
  1194. continue
  1195. elif dominant_last_price <= dominant_low_limit:
  1196. log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(dominant))
  1197. continue
  1198. else:
  1199. log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
  1200. order_old = order_target(symbol, 0, side='short')
  1201. if order_old != None and order_old.filled > 0:
  1202. order_new = order_target(dominant, amount, side='short')
  1203. if order_new != None and order_new.filled > 0:
  1204. switch_result.append({"before": symbol, "after": dominant, "side": "short"})
  1205. # 换月成功,更新交易记录
  1206. if symbol in g.trade_history:
  1207. g.trade_history[dominant] = g.trade_history[symbol]
  1208. del g.trade_history[symbol]
  1209. else:
  1210. log.warning("标的{}交易失败,无法开仓。移仓换月失败。".format(dominant))
  1211. if callback:
  1212. callback(context, pindex, p, dominant)
  1213. return switch_result