MAPatternStrategy_v002.py 62 KB

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