MultiMABreakoutStrategy_v002.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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
  7. import re
  8. # 多均线穿越突破策略 v001
  9. # 基于K线实体穿越多条均线的交易策略
  10. # 设置以便完整打印 DataFrame
  11. pd.set_option('display.max_rows', None)
  12. pd.set_option('display.max_columns', None)
  13. pd.set_option('display.width', None)
  14. pd.set_option('display.max_colwidth', 20)
  15. ## 初始化函数,设定基准等等
  16. def initialize(context):
  17. # 设定沪深300作为基准
  18. set_benchmark('000300.XSHG')
  19. # 开启动态复权模式(真实价格)
  20. set_option('use_real_price', True)
  21. # 输出内容到日志
  22. log.info('多均线穿越突破策略初始化开始')
  23. ### 期货相关设定 ###
  24. # 设定账户为金融账户
  25. set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
  26. # 期货类每笔交易时的手续费是: 买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
  27. set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
  28. # 设置期货交易的滑点
  29. set_slippage(StepRelatedSlippage(2))
  30. # 初始化全局变量
  31. g.usage_percentage = 0.8 # 最大资金使用比例
  32. g.min_cross_mas = 3 # 最少穿越均线数量
  33. g.max_margin_per_position = 20000 # 单个标的最大持仓保证金(元)
  34. g.price_deviation_min = 0.005 # 价格偏离临界线最小比例(0.5%)
  35. g.price_deviation_max = 0.01 # 价格偏离临界线最大比例(1%)
  36. # 均线交叉数量检查相关参数
  37. g.max_ma_crosses = 4 # 最大允许的均线交叉数量
  38. g.ma_cross_check_days = 10 # 检查均线交叉的天数
  39. # 止损止盈策略参数
  40. g.gap_ratio_threshold = 0.002 # 跳空比例:0.2%
  41. g.market_close_times = ["14:55:00"] # 盘尾时间
  42. g.profit_thresholds = [5000, 15000] # 价格分区
  43. g.stop_ratios = [0.0025, 0.005, 0.01, 0.02] # 止盈止损比例:[0.25%, 0.5%, 1%, 2%]
  44. # 新增参数
  45. g.fixed_profit_threshold = 4000 # 固定金额止盈止损阈值(元)
  46. g.daily_change_threshold = 0.01 # 日内变化比例阈值:1%
  47. # 期货品种完整配置字典
  48. g.futures_config = {
  49. # 贵金属
  50. 'AU': {'has_night_session': True, 'margin_rate': {'long': 0.04, 'short': 0.04}, 'multiplier': 1000},
  51. 'AG': {'has_night_session': True, 'margin_rate': {'long': 0.04, 'short': 0.04}, 'multiplier': 15},
  52. # 有色金属
  53. 'CU': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  54. 'AL': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  55. 'ZN': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  56. 'PB': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  57. 'NI': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 1},
  58. 'SN': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 1},
  59. 'SS': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  60. # 黑色系
  61. 'RB': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  62. 'HC': {'has_night_session': True, 'margin_rate': {'long': 0.04, 'short': 0.04}, 'multiplier': 10},
  63. 'I': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 100},
  64. 'JM': {'has_night_session': True, 'margin_rate': {'long': 0.22, 'short': 0.22}, 'multiplier': 100},
  65. 'J': {'has_night_session': True, 'margin_rate': {'long': 0.22, 'short': 0.22}, 'multiplier': 60},
  66. # 能源化工
  67. 'SP': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 10},
  68. 'FU': {'has_night_session': True, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 10},
  69. 'BU': {'has_night_session': True, 'margin_rate': {'long': 0.04, 'short': 0.04}, 'multiplier': 10},
  70. 'RU': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  71. 'BR': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  72. 'AO': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  73. # 'SC': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 1000},
  74. 'NR': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 10},
  75. 'LU': {'has_night_session': True, 'margin_rate': {'long': 0.15, 'short': 0.15}, 'multiplier': 10},
  76. 'BC': {'has_night_session': True, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5},
  77. # 化工
  78. 'FG': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  79. 'TA': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  80. 'MA': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  81. 'SA': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  82. 'L': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  83. 'V': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  84. 'EG': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  85. 'PP': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  86. 'EB': {'has_night_session': True, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 5},
  87. 'PG': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 20},
  88. 'CY': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  89. 'SH': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 30},
  90. 'PX': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  91. # 农产品
  92. 'RM': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  93. 'OI': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  94. 'CF': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  95. 'SR': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  96. 'PF': {'has_night_session': True, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 5},
  97. 'C': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  98. 'CS': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  99. 'A': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  100. 'B': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  101. 'M': {'has_night_session': True, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 10},
  102. 'Y': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  103. 'P': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  104. 'PR': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  105. 'AD': {'has_night_session': True, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 10},
  106. # 无夜盘品种
  107. 'IF': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 300},
  108. 'IH': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 300},
  109. 'IC': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 200},
  110. 'IM': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 200},
  111. 'EC': {'has_night_session': False, 'margin_rate': {'long': 0.12, 'short': 0.12}, 'multiplier': 50},
  112. 'SF': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  113. 'SM': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  114. 'UR': {'has_night_session': False, 'margin_rate': {'long': 0.09, 'short': 0.09}, 'multiplier': 20},
  115. 'AP': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 10},
  116. 'CJ': {'has_night_session': False, 'margin_rate': {'long': 0.07, 'short': 0.07}, 'multiplier': 5},
  117. 'PK': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  118. 'JD': {'has_night_session': False, 'margin_rate': {'long': 0.08, 'short': 0.08}, 'multiplier': 5},
  119. 'LH': {'has_night_session': False, 'margin_rate': {'long': 0.1, 'short': 0.1}, 'multiplier': 16},
  120. 'SI': {'has_night_session': False, 'margin_rate': {'long': 0.13, 'short': 0.13}, 'multiplier': 5},
  121. 'LC': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 1},
  122. 'PS': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5},
  123. 'LG': {'has_night_session': False, 'margin_rate': {'long': 0.05, 'short': 0.05}, 'multiplier': 5}
  124. }
  125. # 当前策略关注的标的列表(可以根据需要调整,为空则考虑所有品种)
  126. g.strategy_focus_symbols = []
  127. # 如果关注列表为空,则使用所有配置的品种
  128. if not g.strategy_focus_symbols:
  129. g.strategy_focus_symbols = list(g.futures_config.keys())
  130. log.info("策略关注品种列表为空,将考虑所有配置的品种")
  131. # 打印配置摘要
  132. log.info(f"策略关注品种总数: {len(g.strategy_focus_symbols)}")
  133. # 交易记录和数据存储
  134. # 1. 当天临时数据(仅当天使用,当天结束后清理)
  135. g.daily_transient_data = {
  136. 'ma_cross_signals': {}, # 存储多均线穿越信号(当天信号,当天处理)
  137. 'tradable_futures': [], # 可交易期货品种(每天重新生成)
  138. 'today_trades': [] # 当日交易记录(收盘后打印并清空)
  139. }
  140. # 2. 持续数据(当天数据第二天也要用,按日期管理)
  141. g.persistent_daily_data = {
  142. 'daily_data_cache': {}, # 存储历史日线数据缓存(用于计算均线,持续更新)
  143. 'minute_data_cache': {}, # 存储分钟数据缓存(夜盘数据第二天日盘还需要)
  144. 'ma_cross_filtered_futures': {}, # 存储通过均线交叉检查的品种(按日期缓存)
  145. 'gap_check_results': {} # 存储跳空检查结果(当天计算,持仓期间使用)
  146. }
  147. # 3. 持仓数据(持仓期间要用,平仓后不用)
  148. g.position_data = {
  149. 'trade_history': {}, # 持仓信息(平仓后删除)
  150. 'ma_data_cache': {} # 存储均线数据缓存(持仓期间用于止损,平仓后可清理)
  151. }
  152. # 4. 历史数据(一直需要保留)
  153. g.historical_data = {
  154. 'margin_rate_history': {}, # 保证金比例变化历史记录(用于统计分析)
  155. 'change_fail_history': {} # 换月失败历史记录(用于统计分析)
  156. }
  157. # 保留原有变量名的兼容性映射(逐步替换)
  158. g.trade_history = g.position_data['trade_history']
  159. g.ma_cross_signals = g.daily_transient_data['ma_cross_signals']
  160. g.daily_data_cache = g.persistent_daily_data['daily_data_cache']
  161. g.minute_data_cache = g.persistent_daily_data['minute_data_cache']
  162. g.ma_data_cache = g.position_data['ma_data_cache']
  163. g.ma_cross_filtered_futures = g.persistent_daily_data['ma_cross_filtered_futures']
  164. g.gap_check_results = g.persistent_daily_data['gap_check_results']
  165. g.margin_rate_history = g.historical_data['margin_rate_history']
  166. g.today_trades = g.daily_transient_data['today_trades']
  167. # 定时任务设置 - 根据新的时间安排
  168. # 夜盘开始
  169. run_daily(main_trading_21_05, time='21:05:00', reference_security='IF1808.CCFX')
  170. run_daily(main_trading_regular, time='21:35:00', reference_security='IF1808.CCFX')
  171. run_daily(main_trading_regular, time='22:05:00', reference_security='IF1808.CCFX')
  172. run_daily(main_trading_regular, time='22:35:00', reference_security='IF1808.CCFX')
  173. # 日盘开始
  174. run_daily(main_trading_09_05, time='09:05:00', reference_security='IF1808.CCFX')
  175. run_daily(main_trading_regular, time='09:35:00', reference_security='IF1808.CCFX')
  176. run_daily(main_trading_regular, time='10:05:00', reference_security='IF1808.CCFX')
  177. run_daily(main_trading_regular, time='10:35:00', reference_security='IF1808.CCFX')
  178. run_daily(main_trading_regular, time='11:05:00', reference_security='IF1808.CCFX')
  179. run_daily(main_trading_regular, time='11:25:00', reference_security='IF1808.CCFX')
  180. run_daily(main_trading_regular, time='13:35:00', reference_security='IF1808.CCFX')
  181. run_daily(main_trading_regular, time='14:05:00', reference_security='IF1808.CCFX')
  182. # 收盘前
  183. run_daily(main_trading_before_close, time='14:35:00', reference_security='IF1808.CCFX')
  184. run_daily(main_trading_before_close, time='14:55:00', reference_security='IF1808.CCFX')
  185. # 收盘后
  186. run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
  187. ############################ 主程序执行函数 ###################################
  188. def main_trading_21_05(context):
  189. """21:05 执行任务1, 2, 3, 4, 5, 6, 9"""
  190. log.info("-" * 50)
  191. log.info("21:05 多均线穿越突破策略 - 夜盘开始")
  192. log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
  193. log.info("-" * 50)
  194. # 任务1: 获取所有可交易品种
  195. task_1_get_tradable_futures(context)
  196. # 任务2: 获取历史数据并保存到内存
  197. task_2_load_historical_data(context)
  198. # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
  199. task_3_check_ma_crosses(context)
  200. # 任务4: 获取今日分钟数据并合并均线数据
  201. task_4_update_realtime_data(context)
  202. # 任务5: 判断上穿下穿情况
  203. task_5_analyze_ma_crosses(context)
  204. # 任务6: 检查开仓条件
  205. filtered_signals = task_6_check_opening_conditions(context)
  206. # 如果任务6有满足条件的,执行任务7开仓
  207. if filtered_signals:
  208. task_7_execute_trades(context, filtered_signals)
  209. # 任务9: 检查止损止盈
  210. task_9_check_stop_loss_profit(context)
  211. def main_trading_09_05(context):
  212. """09:05 执行任务1, 2, 3, 4, 5, 6, 9"""
  213. log.info("-" * 50)
  214. log.info("09:05 多均线穿越突破策略 - 日盘开始")
  215. log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
  216. log.info("-" * 50)
  217. # 任务1: 获取所有可交易品种
  218. task_1_get_tradable_futures(context)
  219. # 任务2: 获取历史数据并保存到内存
  220. task_2_load_historical_data(context)
  221. # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
  222. task_3_check_ma_crosses(context)
  223. # 任务4: 获取今日分钟数据并合并均线数据
  224. task_4_update_realtime_data(context)
  225. # 任务5: 判断上穿下穿情况
  226. task_5_analyze_ma_crosses(context)
  227. # 任务6: 检查开仓条件
  228. filtered_signals = task_6_check_opening_conditions(context)
  229. # 如果任务6有满足条件的,执行任务7开仓
  230. if filtered_signals:
  231. task_7_execute_trades(context, filtered_signals)
  232. # 任务9: 检查止损止盈
  233. task_9_check_stop_loss_profit(context)
  234. def main_trading_regular(context):
  235. """常规时间执行任务4, 5, 6, 9"""
  236. current_time = context.current_dt.strftime('%H:%M')
  237. # log.info(f"----- {current_time} 常规检查 -----")
  238. # log.info("执行任务: 4, 5, 6, 9")
  239. # 任务4: 获取今日分钟数据并合并均线数据
  240. task_4_update_realtime_data(context)
  241. # 任务5: 判断上穿下穿情况
  242. task_5_analyze_ma_crosses(context)
  243. # 任务6: 检查开仓条件
  244. filtered_signals = task_6_check_opening_conditions(context)
  245. # 如果任务6有满足条件的,执行任务7开仓
  246. if filtered_signals:
  247. task_7_execute_trades(context, filtered_signals)
  248. # 任务9: 检查止损止盈
  249. task_9_check_stop_loss_profit(context)
  250. def main_trading_before_close(context):
  251. """收盘前执行任务4, 5, 6, 8, 9"""
  252. current_time = context.current_dt.strftime('%H:%M')
  253. # log.info(f"----- {current_time} 收盘前检查 -----")
  254. # log.info("执行任务: 4, 5, 6, 8, 9")
  255. # 任务4: 获取今日分钟数据并合并均线数据
  256. task_4_update_realtime_data(context)
  257. # 任务5: 判断上穿下穿情况
  258. task_5_analyze_ma_crosses(context)
  259. # 任务6: 检查开仓条件
  260. filtered_signals = task_6_check_opening_conditions(context)
  261. # 如果任务6有满足条件的,执行任务7开仓
  262. if filtered_signals:
  263. task_7_execute_trades(context, filtered_signals)
  264. # 任务8: 检查换月移仓
  265. task_8_check_position_switch(context)
  266. # 任务9: 检查止损止盈
  267. task_9_check_stop_loss_profit(context)
  268. ############################ 核心任务函数 ###################################
  269. def task_1_get_tradable_futures(context):
  270. """任务1: 获取所有可交易品种(分白天和晚上)"""
  271. # log.info("执行任务1: 获取可交易品种")
  272. current_time = str(context.current_dt.time())[:2]
  273. # 从策略关注列表中筛选可交易品种
  274. # 如果关注列表为空,则使用所有配置的品种
  275. focus_symbols = g.strategy_focus_symbols if g.strategy_focus_symbols else list(g.futures_config.keys())
  276. potential_icon_list = []
  277. if current_time in ('21', '22'):
  278. # 夜盘时间:只考虑有夜盘的品种
  279. for symbol in focus_symbols:
  280. if get_futures_config(symbol, 'has_night_session', False):
  281. potential_icon_list.append(symbol)
  282. log.info(f"夜盘时间,可交易品种: {potential_icon_list}")
  283. else:
  284. # 日盘时间:所有关注的品种都可以交易
  285. potential_icon_list = focus_symbols[:]
  286. log.info(f"日盘时间,可交易品种: {potential_icon_list}")
  287. potential_future_list = []
  288. for symbol in potential_icon_list:
  289. dominant_future = get_dominant_future(symbol)
  290. if dominant_future:
  291. potential_future_list.append(dominant_future)
  292. # 过滤掉已有持仓的品种
  293. existing_positions = set(g.trade_history.keys())
  294. potential_future_list = [f for f in potential_future_list if not check_symbol_prefix_match(f, existing_positions)]
  295. # 存储到新的数据结构
  296. g.daily_transient_data['tradable_futures'] = potential_future_list
  297. g.tradable_futures = potential_future_list # 保持兼容性
  298. log.info(f"最终可交易期货品种数量: {len(potential_future_list)}")
  299. return potential_future_list
  300. def task_2_load_historical_data(context):
  301. """任务2: 获取所有可交易品种和持仓品种今天之前所需的数据,并保存到内存中"""
  302. # log.info("执行任务2: 加载历史数据到内存")
  303. # 收集需要更新历史数据的品种
  304. symbols_to_update = set()
  305. # 添加可交易品种
  306. if hasattr(g, 'tradable_futures') and g.tradable_futures:
  307. symbols_to_update.update(g.tradable_futures)
  308. # 添加持仓品种(重要:确保持仓品种的历史数据也被更新)
  309. if hasattr(g, 'trade_history') and g.trade_history:
  310. symbols_to_update.update(g.trade_history.keys())
  311. if not symbols_to_update:
  312. log.info("没有需要更新历史数据的品种")
  313. return
  314. log.info(f"需要更新历史数据的品种数量: {len(symbols_to_update)} (可交易: {len(g.tradable_futures) if hasattr(g, 'tradable_futures') else 0}, 持仓: {len(g.trade_history) if hasattr(g, 'trade_history') else 0})")
  315. for future_code in symbols_to_update:
  316. try:
  317. # 获取50天历史数据(用于计算均线)
  318. data = attribute_history(future_code, 50, '1d',
  319. ['open', 'close', 'high', 'low', 'volume'],
  320. df=True)
  321. if data is not None and len(data) > 0:
  322. # 排除今天的数据
  323. today = context.current_dt.date()
  324. data = data[data.index.date < today]
  325. g.daily_data_cache[future_code] = data
  326. log.debug(f"已缓存 {future_code} 历史数据 {len(data)} 条,日期范围: {data.index[0].date()} 到 {data.index[-1].date()}")
  327. except Exception as e:
  328. log.warning(f"加载{future_code}历史数据时出错: {str(e)}")
  329. continue
  330. log.info(f"历史数据缓存完成,共缓存 {len(g.daily_data_cache)} 个品种")
  331. def task_3_check_ma_crosses(context):
  332. """任务3: 检查均线交叉数量,过滤掉交叉过多的品种"""
  333. # log.info("执行任务3: 检查均线交叉数量")
  334. if not hasattr(g, 'tradable_futures'):
  335. return
  336. # 存储通过均线交叉检查的品种
  337. today_date = context.current_dt.date()
  338. if today_date not in g.ma_cross_filtered_futures:
  339. g.ma_cross_filtered_futures[today_date] = []
  340. filtered_futures = []
  341. for future_code in g.tradable_futures:
  342. try:
  343. # 获取历史数据
  344. historical_data = g.daily_data_cache.get(future_code)
  345. if historical_data is None or len(historical_data) < 30:
  346. log.warning(f"{future_code} 历史数据不足,跳过")
  347. continue
  348. # 计算移动平均线
  349. data_with_ma = historical_data.copy()
  350. data_with_ma['MA5'] = data_with_ma['close'].rolling(window=5).mean()
  351. data_with_ma['MA10'] = data_with_ma['close'].rolling(window=10).mean()
  352. data_with_ma['MA20'] = data_with_ma['close'].rolling(window=20).mean()
  353. data_with_ma['MA30'] = data_with_ma['close'].rolling(window=30).mean()
  354. # 检查均线交叉数量
  355. ma_crosses = count_ma_crosses(data_with_ma, g.ma_cross_check_days)
  356. # 如果交叉数量在允许范围内,保留该品种
  357. if ma_crosses <= g.max_ma_crosses:
  358. filtered_futures.append(future_code)
  359. log.info(f"{future_code} 通过均线交叉检查,交叉数量: {ma_crosses}")
  360. else:
  361. log.info(f"{future_code} 均线交叉过多,被过滤,交叉数量: {ma_crosses} > {g.max_ma_crosses}")
  362. except Exception as e:
  363. log.warning(f"检查{future_code}均线交叉时出错: {str(e)}")
  364. continue
  365. # 更新可交易品种列表
  366. g.tradable_futures = filtered_futures
  367. g.ma_cross_filtered_futures[today_date] = filtered_futures
  368. log.info(f"均线交叉检查完成,剩余可交易品种数量: {len(g.tradable_futures)}")
  369. if len(g.tradable_futures) > 0:
  370. log.info(f"通过检查的品种: {g.tradable_futures}")
  371. return filtered_futures
  372. def task_4_update_realtime_data(context):
  373. """任务4: 获取所有可交易品种和持仓品种今天所需的分钟数据作为今天数据,和2中的数据合并出最新的均线数据,并保存到内存中"""
  374. log.info("执行任务4: 更新实时数据和均线")
  375. # 收集需要更新数据的品种
  376. update_symbols = set()
  377. # 添加可交易品种
  378. if hasattr(g, 'tradable_futures') and g.tradable_futures:
  379. update_symbols.update(g.tradable_futures)
  380. # 添加持仓品种(用于止损止盈)
  381. if hasattr(g, 'trade_history') and g.trade_history:
  382. update_symbols.update(g.trade_history.keys())
  383. if not update_symbols:
  384. log.info("没有需要更新的品种")
  385. return
  386. today_date = context.current_dt.date()
  387. for future_code in update_symbols:
  388. # log.info(f"任务4 future_code: {future_code}")
  389. try:
  390. # 获取今日分钟数据
  391. minute_data = get_today_minute_data(context, future_code)
  392. # log.info(f"minute_data: {minute_data}")
  393. if minute_data is None:
  394. continue
  395. # 获取历史数据,如果缓存中没有则现场获取
  396. historical_data = g.daily_data_cache.get(future_code)
  397. if historical_data is None:
  398. # 为持仓品种临时获取历史数据
  399. try:
  400. data = attribute_history(future_code, 50, '1d',
  401. ['open', 'close', 'high', 'low', 'volume'],
  402. df=True)
  403. if data is not None and len(data) > 0:
  404. # 排除今天的数据
  405. today = context.current_dt.date()
  406. data = data[data.index.date < today]
  407. g.daily_data_cache[future_code] = data
  408. historical_data = data
  409. log.info(f"为持仓品种 {future_code} 临时获取历史数据 {len(data)} 条")
  410. except Exception as e:
  411. log.warning(f"获取{future_code}历史数据失败: {str(e)}")
  412. continue
  413. if historical_data is None:
  414. continue
  415. # 检查跳空(只在第一次获取今日数据时检查)
  416. if future_code not in g.gap_check_results:
  417. gap_result = check_gap_opening(historical_data, minute_data)
  418. g.gap_check_results[future_code] = gap_result
  419. if gap_result['has_gap']:
  420. log.info(f"{future_code} 检测到跳空开盘,跳空比例: {gap_result['gap_ratio']:.3%}")
  421. # 合并数据并计算均线
  422. combined_data = combine_and_calculate_ma(historical_data, minute_data)
  423. if combined_data is not None:
  424. g.ma_data_cache[future_code] = combined_data
  425. log.debug(f"已更新 {future_code} 均线数据: {combined_data}")
  426. except Exception as e:
  427. log.warning(f"更新{future_code}实时数据时出错: {str(e)}")
  428. continue
  429. # log.debug(f"实时数据更新完成,共更新 {len(g.ma_data_cache)} 个品种(可交易: {len(g.tradable_futures) if hasattr(g, 'tradable_futures') else 0},持仓: {len(g.trade_history) if hasattr(g, 'trade_history') else 0})")
  430. def task_5_analyze_ma_crosses(context):
  431. """任务5: 根据交易品种的今天数据和均线数据,判断是否出现了上穿或者下穿的情况"""
  432. # log.info("执行任务5: 分析均线穿越")
  433. ma_cross_signals = []
  434. # 获取已持仓的品种列表
  435. existing_positions = set(g.trade_history.keys())
  436. for future_code, data in g.ma_data_cache.items():
  437. log.info(f"future_code: {future_code}")
  438. try:
  439. # 检查是否已有相似持仓,如果有则跳过分析
  440. if check_symbol_prefix_match(future_code, existing_positions):
  441. # log.(f"{future_code} 已有相似持仓,跳过均线穿越分析")
  442. continue
  443. # 检查最新的多均线穿越
  444. latest_cross = check_latest_multi_ma_cross(data, future_code)
  445. if latest_cross:
  446. ma_cross_signals.append(latest_cross)
  447. log.info(f"{future_code} 发现多均线穿越: {latest_cross['direction']}")
  448. log.info(f"开盘价格: {latest_cross['open']}, 当前价格: {latest_cross['close']}, 临界线: {latest_cross['critical_ma_name']}({latest_cross['critical_ma_value']:.2f}), 穿越数量: {latest_cross['crossed_count']}")
  449. log.info(f"MA5: {latest_cross['ma5']}, MA10: {latest_cross['ma10']}, MA20: {latest_cross['ma20']}, MA30: {latest_cross['ma30']}")
  450. except Exception as e:
  451. log.warning(f"分析{future_code}均线穿越时出错: {str(e)}")
  452. continue
  453. # 存储到全局变量
  454. g.ma_cross_signals = ma_cross_signals
  455. if len(ma_cross_signals) > 0:
  456. log.info(f"均线穿越分析完成,发现信号 {len(ma_cross_signals)} 个")
  457. log.debug(f"ma_cross_signals: {ma_cross_signals}")
  458. return ma_cross_signals
  459. def task_6_check_opening_conditions(context):
  460. """任务6: 针对那些有上穿和下穿的情况检查是否满足开仓条件"""
  461. # log.info("执行任务6: 检查开仓条件")
  462. if not hasattr(g, 'ma_cross_signals'):
  463. return []
  464. filtered_signals = []
  465. for signal in g.ma_cross_signals:
  466. # 检查是否已有相似持仓
  467. if check_symbol_prefix_match(signal['symbol'], set(g.trade_history.keys())):
  468. log.warning(f"{signal['symbol']} 已有相似持仓,跳过")
  469. continue
  470. # 检查价格位置合理性
  471. if not check_price_position(signal):
  472. log.warning(f"{signal['symbol']} 价格位置不合理,跳过")
  473. continue
  474. # 检查日内变化比例
  475. if not check_daily_change_ratio(signal):
  476. log.warning(f"{signal['symbol']} 日内变化比例不满足条件,跳过")
  477. continue
  478. filtered_signals.append(signal)
  479. log.info(f"{signal['symbol']} 满足开仓条件")
  480. if len(filtered_signals) > 0:
  481. log.info(f"开仓条件检查完成,满足条件 {len(filtered_signals)} 个")
  482. return filtered_signals
  483. def task_7_execute_trades(context, filtered_signals):
  484. """任务7: 针对满足开仓条件的标的,计算购买的金额,并发起交易请求"""
  485. # log.info("执行任务7: 执行交易")
  486. for signal in filtered_signals:
  487. symbol = signal['symbol']
  488. direction = 'long' if signal['direction'] == 'up' else 'short'
  489. # 检查资金充足性
  490. if not check_sufficient_capital(context, symbol):
  491. log.warning(f"{symbol} 资金不足,跳过开仓")
  492. continue
  493. # 计算开仓金额
  494. order_value = calculate_order_value(context, symbol, direction)
  495. log.info(f"计算开仓金额: {symbol} {direction} 金额: {order_value}")
  496. # 如果计算出的金额为0,说明资金不足,跳过开仓
  497. if order_value <= 0:
  498. log.warning(f"资金不足,跳过开仓 {symbol} {direction}")
  499. continue
  500. # 执行开仓
  501. success = open_position(context, symbol, order_value, direction, signal)
  502. if success:
  503. # 获取实际保证金(只有在开仓成功时才能获取)
  504. actual_margin = g.trade_history[symbol]['actual_margin']
  505. # 获取成交价格
  506. actual_price = g.trade_history[symbol]['entry_price']
  507. log.info(f"成功开仓 {symbol} {direction}, 成交价格: {actual_price:.2f}, 金额: {order_value}, 实际保证金: {actual_margin:.0f}")
  508. else:
  509. log.warning(f"开仓失败 {symbol} {direction}")
  510. def task_8_check_position_switch(context):
  511. """任务8: 针对已经持仓的标的,检查是否换月移仓"""
  512. # log.info("执行任务8: 检查换月移仓")
  513. switch_result = position_auto_switch(context)
  514. if switch_result:
  515. log.info(f"执行了 {len(switch_result)} 次移仓换月")
  516. for result in switch_result:
  517. log.info(f"移仓: {result['before']} -> {result['after']}")
  518. # else:
  519. # log.info("无需移仓换月")
  520. def task_9_check_stop_loss_profit(context):
  521. """任务9: 针对已经持仓的标的,检查是否止损或止盈"""
  522. # log.info("执行任务9: 检查止损止盈")
  523. # 遍历所有持仓进行止损止盈检查
  524. subportfolio = context.subportfolios[0]
  525. long_positions = list(subportfolio.long_positions.values())
  526. short_positions = list(subportfolio.short_positions.values())
  527. closed_count = 0
  528. for position in long_positions + short_positions:
  529. if check_stop_loss_profit(context, position):
  530. closed_count += 1
  531. if closed_count > 0:
  532. log.info(f"执行了 {closed_count} 次止损止盈")
  533. # else:
  534. # log.info("无需止损止盈")
  535. ############################ 数据处理辅助函数 ###################################
  536. def check_has_night_session(underlying_symbol):
  537. """检查品种是否有夜盘"""
  538. return get_futures_config(underlying_symbol, 'has_night_session', False)
  539. def get_today_minute_data(context, future_code):
  540. """获取今日分钟数据"""
  541. try:
  542. # 判断该品种是否有夜盘
  543. underlying_symbol = future_code.split('.')[0][:-4]
  544. has_night_session = check_has_night_session(underlying_symbol)
  545. end_time = context.current_dt
  546. # 获取足够的历史分钟数据
  547. minute_data = attribute_history(future_code,
  548. count=800, # 获取足够多的数据
  549. unit='1m',
  550. fields=['open', 'close', 'high', 'low', 'volume'],
  551. df=True)
  552. if minute_data is None or len(minute_data) == 0:
  553. return None
  554. # log.debug(f"原始分钟数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
  555. # 提取所有日期(年月日维度)
  556. minute_data['date'] = minute_data.index.date
  557. unique_dates = sorted(minute_data['date'].unique())
  558. # log.debug(f"数据包含的日期: {unique_dates}")
  559. if has_night_session:
  560. # 有夜盘的品种:需要找到前一交易日的21:00作为今日开盘起点
  561. today_date = end_time.date()
  562. # 找到今天之前的最后一个交易日
  563. previous_trading_dates = [d for d in unique_dates if d < today_date]
  564. # log.debug(f"夜盘标的 today_date: {today_date}, previous_trading_dates: {previous_trading_dates}")
  565. if not previous_trading_dates:
  566. log.info(f"{future_code} 没有前一交易日数据,可能是新上市品种或长假后首日")
  567. # 使用今天9:00开始的数据作为备选
  568. today_data = minute_data[minute_data['date'] == today_date]
  569. day_9_data = today_data[today_data.index.hour >= 9]
  570. if len(day_9_data) > 0:
  571. return day_9_data.drop(columns=['date'])
  572. else:
  573. return minute_data.drop(columns=['date'])
  574. previous_trading_date = max(previous_trading_dates)
  575. # log.debug(f"前一交易日: {previous_trading_date}")
  576. # 计算距离前一交易日的天数
  577. days_gap = (today_date - previous_trading_date).days
  578. # 找到前一交易日21:00:00的数据作为开盘起点
  579. previous_day_data = minute_data[minute_data['date'] == previous_trading_date]
  580. night_21_data = previous_day_data[previous_day_data.index.hour == 21]
  581. if len(night_21_data) > 0:
  582. # 从前一交易日21:00开始的所有数据
  583. start_time = night_21_data.index[0] # 21:00:00的时间点
  584. filtered_data = minute_data[minute_data.index >= start_time]
  585. # log.debug(f"夜盘品种,从{start_time}开始,数据量: {len(filtered_data)}")
  586. return filtered_data.drop(columns=['date'])
  587. else:
  588. # 如果找不到21:00的数据,判断是否是因为假期
  589. if days_gap > 3:
  590. log.info(f"{future_code} 距离前一交易日{days_gap}天,可能是长假期间,使用日盘数据")
  591. else:
  592. log.info(f"{future_code} 前一交易日无21:00夜盘数据,可能该日无夜盘交易")
  593. # 备选方案:使用今天9:00开始的数据
  594. today_data = minute_data[minute_data['date'] == today_date]
  595. day_9_data = today_data[today_data.index.hour >= 9]
  596. if len(day_9_data) > 0:
  597. return day_9_data.drop(columns=['date'])
  598. else:
  599. return minute_data.drop(columns=['date'])
  600. else:
  601. # 没有夜盘的品种:从今天9:00:00开始
  602. today_date = end_time.date()
  603. today_data = minute_data[minute_data['date'] == today_date]
  604. # 找到今天9:00:00开始的数据
  605. day_9_data = today_data[today_data.index.hour >= 9]
  606. if len(day_9_data) > 0:
  607. log.debug(f"日盘品种,从今天9:00开始,数据量: {len(day_9_data)}")
  608. return day_9_data.drop(columns=['date'])
  609. else:
  610. log.info(f"{future_code} 今天无9:00日盘数据,可能是休市日")
  611. return today_data.drop(columns=['date']) if len(today_data) > 0 else minute_data.drop(columns=['date'])
  612. except Exception as e:
  613. log.warning(f"获取{future_code}今日分钟数据时出错: {str(e)}")
  614. return None
  615. def combine_and_calculate_ma(historical_data, minute_data):
  616. """合并历史数据和分钟数据,计算均线"""
  617. try:
  618. # 将分钟数据聚合为日数据
  619. today_data = aggregate_minute_to_daily(minute_data)
  620. if today_data is None:
  621. return None
  622. # 合并历史数据和今日数据
  623. combined_data = pd.concat([historical_data, today_data])
  624. # 计算移动平均线
  625. combined_data['MA5'] = combined_data['close'].rolling(window=5).mean()
  626. combined_data['MA10'] = combined_data['close'].rolling(window=10).mean()
  627. combined_data['MA20'] = combined_data['close'].rolling(window=20).mean()
  628. combined_data['MA30'] = combined_data['close'].rolling(window=30).mean()
  629. return combined_data
  630. except Exception as e:
  631. log.warning(f"合并数据和计算均线时出错: {str(e)}")
  632. return None
  633. def aggregate_minute_to_daily(minute_data):
  634. """将分钟数据聚合为日数据
  635. 注意:传入的minute_data已经是经过过滤的今日交易数据
  636. - 对于有夜盘的品种:数据从前一交易日21:00开始
  637. - 对于无夜盘的品种:数据从当日9:00开始
  638. 开盘价(open)是第一个分钟K线的开盘价(今日交易开盘价)
  639. 收盘价(close)是当前最新的分钟K线收盘价,会随时间更新
  640. """
  641. try:
  642. if minute_data is None or len(minute_data) == 0:
  643. return None
  644. # 获取今日日期(使用最后一条数据的日期作为今日日期)
  645. today_date = minute_data.index[-1].date()
  646. # log.debug(f"聚合数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
  647. # log.debug(f"开盘价数据: {minute_data['open'].iloc[0]:.2f}")
  648. # 聚合为日数据
  649. # 开盘价:今日交易开始时的第一个分钟K线的开盘价(固定不变)
  650. # 收盘价:当前最新分钟K线的收盘价(实时更新)
  651. # 最高价:所有分钟K线中的最高价
  652. # 最低价:所有分钟K线中的最低价
  653. # 成交量:所有分钟K线成交量的总和
  654. daily_data = pd.DataFrame({
  655. 'open': [minute_data['open'].iloc[0]], # 今日交易开始时的开盘价
  656. 'close': [minute_data['close'].iloc[-1]], # 当前收盘价,实时更新
  657. 'high': [minute_data['high'].max()],
  658. 'low': [minute_data['low'].min()],
  659. 'volume': [minute_data['volume'].sum()]
  660. }, index=[pd.Timestamp(today_date)])
  661. # log.debug(f"聚合后的日数据: 开盘价={daily_data['open'].iloc[0]:.2f}, 收盘价={daily_data['close'].iloc[0]:.2f}")
  662. return daily_data
  663. except Exception as e:
  664. log.warning(f"聚合分钟数据时出错: {str(e)}")
  665. return None
  666. def check_gap_opening(historical_data, minute_data):
  667. """
  668. 检查开盘是否跳空
  669. :param historical_data: 历史日线数据
  670. :param minute_data: 今日分钟数据
  671. :return: 跳空检查结果字典
  672. """
  673. try:
  674. if historical_data is None or len(historical_data) == 0 or minute_data is None or len(minute_data) == 0:
  675. return {'has_gap': False, 'gap_ratio': 0.0}
  676. # 获取前一交易日收盘价
  677. previous_close = historical_data['close'].iloc[-1]
  678. # 获取今日开盘价
  679. today_open = minute_data['open'].iloc[0]
  680. # 计算跳空比例
  681. gap_ratio = abs(today_open - previous_close) / previous_close
  682. # 判断是否跳空
  683. has_gap = gap_ratio >= g.gap_ratio_threshold
  684. return {
  685. 'has_gap': has_gap,
  686. 'gap_ratio': gap_ratio,
  687. 'previous_close': previous_close,
  688. 'today_open': today_open
  689. }
  690. except Exception as e:
  691. log.warning(f"检查跳空开盘时出错: {str(e)}")
  692. return {'has_gap': False, 'gap_ratio': 0.0}
  693. ############################ 原有函数保持不变 ###################################
  694. def check_latest_multi_ma_cross(data, future_code):
  695. """检查最新的多均线穿越情况"""
  696. if len(data) < 2:
  697. return None
  698. # 获取最新两天的数据
  699. today = data.iloc[-1]
  700. yesterday = data.iloc[-2]
  701. # log.debug(f"today: {today}")
  702. # log.debug(f"yesterday: {yesterday}")
  703. # 检查多均线穿越
  704. cross_result = check_multi_ma_cross_single_day(today)
  705. if not cross_result:
  706. return None
  707. # TODO:验证穿越的有效性,暂时感觉没用先注释了
  708. # 验证穿越的有效性
  709. # if not validate_ma_cross(today, yesterday):
  710. # return None
  711. return {
  712. 'symbol': future_code,
  713. 'date': today.name,
  714. 'direction': cross_result['direction'],
  715. 'open': today['open'],
  716. 'close': today['close'],
  717. 'high': today['high'],
  718. 'low': today['low'],
  719. 'ma5': today['MA5'],
  720. 'ma10': today['MA10'],
  721. 'ma20': today['MA20'],
  722. 'ma30': today['MA30'],
  723. 'critical_ma_name': cross_result['critical_ma_name'],
  724. 'critical_ma_value': cross_result['critical_ma_value'],
  725. 'crossed_count': cross_result['crossed_count']
  726. }
  727. def check_multi_ma_cross_single_day(row):
  728. """检查单日K线是否穿越了至少3条均线,并返回临界线信息"""
  729. open_price = row['open']
  730. close_price = row['close']
  731. ma_values = [('MA5', row['MA5']), ('MA10', row['MA10']), ('MA20', row['MA20']), ('MA30', row['MA30'])]
  732. log.debug(f"open_price: {open_price}, close_price: {close_price}, ma_values: {ma_values}")
  733. # 检查是否有NaN值
  734. if pd.isna(row['MA5']) or pd.isna(row['MA10']) or pd.isna(row['MA20']) or pd.isna(row['MA30']):
  735. return None
  736. # 如果开盘价和收盘价相等,不可能有穿越
  737. if open_price == close_price:
  738. return None
  739. # 1. 统计开盘价和均线的高低关系
  740. open_above_count = 0 # 开盘价高于均线的数量
  741. open_below_count = 0 # 开盘价低于均线的数量
  742. open_above_mas = [] # 开盘价高于的均线列表
  743. open_below_mas = [] # 开盘价低于的均线列表
  744. for ma_name, ma_value in ma_values:
  745. if open_price > ma_value:
  746. open_above_count += 1
  747. open_above_mas.append((ma_name, ma_value))
  748. elif open_price < ma_value:
  749. open_below_count += 1
  750. open_below_mas.append((ma_name, ma_value))
  751. # 2. 统计收盘价和均线的高低关系
  752. close_above_count = 0 # 收盘价高于均线的数量
  753. close_below_count = 0 # 收盘价低于均线的数量
  754. close_above_mas = [] # 收盘价高于的均线列表
  755. close_below_mas = [] # 收盘价低于的均线列表
  756. for ma_name, ma_value in ma_values:
  757. if close_price > ma_value:
  758. close_above_count += 1
  759. close_above_mas.append((ma_name, ma_value))
  760. elif close_price < ma_value:
  761. close_below_count += 1
  762. close_below_mas.append((ma_name, ma_value))
  763. # 3. 计算穿越情况
  764. # 上穿:收盘价高于的数量比开盘价高于的数量增加了
  765. upward_cross_count = close_above_count - open_above_count
  766. # 下穿:收盘价低于的数量比开盘价低于的数量增加了
  767. downward_cross_count = close_below_count - open_below_count
  768. log.debug(f"开盘价高于均线数量: {open_above_count}, 收盘价高于均线数量: {close_above_count}")
  769. log.debug(f"开盘价低于均线数量: {open_below_count}, 收盘价低于均线数量: {close_below_count}")
  770. log.debug(f"上穿数量: {upward_cross_count}, 下穿数量: {downward_cross_count}")
  771. # 4. 判断是否满足最少穿越条件并找到临界线
  772. if upward_cross_count >= g.min_cross_mas:
  773. # 上穿:找到被穿越的均线中值最大的一条作为临界线
  774. # 被穿越的均线是那些开盘价低于但收盘价高于的均线
  775. crossed_mas = []
  776. crossed_ma_names = []
  777. for ma_name, ma_value in ma_values:
  778. if open_price <= ma_value and close_price > ma_value:
  779. crossed_mas.append((ma_name, ma_value))
  780. crossed_ma_names.append(ma_name)
  781. if len(crossed_mas) > 0:
  782. # 找到值最大的被穿越均线
  783. critical_ma = max(crossed_mas, key=lambda x: x[1])
  784. return {
  785. 'direction': 'up',
  786. 'critical_ma_name': critical_ma[0],
  787. 'critical_ma_value': critical_ma[1],
  788. 'crossed_count': upward_cross_count,
  789. 'crossed_ma_names': crossed_ma_names # 添加被穿越的均线名称列表
  790. }
  791. elif downward_cross_count >= g.min_cross_mas:
  792. # 下穿:找到被穿越的均线中值最小的一条作为临界线
  793. # 被穿越的均线是那些开盘价高于但收盘价低于的均线
  794. crossed_mas = []
  795. crossed_ma_names = []
  796. for ma_name, ma_value in ma_values:
  797. if open_price >= ma_value and close_price < ma_value:
  798. crossed_mas.append((ma_name, ma_value))
  799. crossed_ma_names.append(ma_name)
  800. if len(crossed_mas) > 0:
  801. # 找到值最小的被穿越均线
  802. critical_ma = min(crossed_mas, key=lambda x: x[1])
  803. return {
  804. 'direction': 'down',
  805. 'critical_ma_name': critical_ma[0],
  806. 'critical_ma_value': critical_ma[1],
  807. 'crossed_count': downward_cross_count,
  808. 'crossed_ma_names': crossed_ma_names # 添加被穿越的均线名称列表
  809. }
  810. return None
  811. def validate_ma_cross(today, yesterday):
  812. """验证均线穿越的有效性"""
  813. # 检查均线排列是否合理
  814. ma_today = [today['MA5'], today['MA10'], today['MA20'], today['MA30']]
  815. ma_yesterday = [yesterday['MA5'], yesterday['MA10'], yesterday['MA20'], yesterday['MA30']]
  816. # 简单的均线排列检查
  817. # 可以根据需要添加更复杂的验证逻辑
  818. return True
  819. def check_sufficient_capital(context, symbol):
  820. """检查资金是否充足"""
  821. try:
  822. # 计算单手保证金
  823. single_hand_margin = calculate_required_margin(context, symbol)
  824. # 使用实际可用资金(考虑资金使用比例)
  825. available_cash = context.portfolio.available_cash * g.usage_percentage
  826. # 检查是否有足够资金开仓至少1手
  827. return available_cash >= single_hand_margin
  828. except:
  829. return False
  830. def check_price_position(signal):
  831. """检查价格位置的合理性"""
  832. close = signal['close']
  833. critical_ma_value = signal['critical_ma_value']
  834. # 检查收盘价与临界线的偏离度
  835. deviation = abs(close - critical_ma_value) / critical_ma_value
  836. # 偏离度需要在合理范围内:大于最小偏离度且小于最大偏离度
  837. if deviation < g.price_deviation_min:
  838. log.warning(f"价格偏离度过小: {deviation:.3%} < {g.price_deviation_min:.1%}")
  839. return False
  840. elif deviation > g.price_deviation_max:
  841. log.warning(f"价格偏离度过大: {deviation:.3%} > {g.price_deviation_max:.1%}")
  842. return False
  843. else:
  844. log.info(f"价格偏离度合理: {g.price_deviation_min:.1%} <= {deviation:.3%} <= {g.price_deviation_max:.1%}")
  845. return True
  846. def check_daily_change_ratio(signal):
  847. """检查日内变化比例是否满足条件"""
  848. open_price = signal['open']
  849. close_price = signal['close']
  850. # 计算日内变化比例
  851. if open_price == 0:
  852. log.warning("开盘价为0,无法计算日内变化比例")
  853. return False
  854. daily_change_ratio = abs(close_price - open_price) / open_price
  855. # 检查是否满足最小变化比例要求
  856. if daily_change_ratio >= g.daily_change_threshold:
  857. log.info(f"日内变化比例满足条件: {daily_change_ratio:.3%} >= {g.daily_change_threshold:.1%}")
  858. return True
  859. else:
  860. log.warning(f"日内变化比例不足: {daily_change_ratio:.3%} < {g.daily_change_threshold:.1%}")
  861. return False
  862. ############################ 交易执行函数 ###################################
  863. def open_position(context, security, value, direction, signal):
  864. """开仓"""
  865. try:
  866. # 记录交易前的可用资金
  867. cash_before = context.portfolio.available_cash
  868. order = order_target_value(security, value, side=direction)
  869. log.debug(f"order: {order}")
  870. if order is not None and order.filled > 0:
  871. # 记录交易后的可用资金
  872. cash_after = context.portfolio.available_cash
  873. # 计算实际资金变化
  874. cash_change = cash_before - cash_after
  875. # 获取订单价格和数量
  876. order_price = order.avg_cost if order.avg_cost else order.price
  877. order_amount = order.filled
  878. # 计算实际保证金比例
  879. underlying_symbol = security.split('.')[0][:-4]
  880. multiplier = get_multiplier(underlying_symbol)
  881. # 单笔保证金 = 资金变化 / 数量
  882. single_margin = cash_change / order_amount if order_amount > 0 else 0
  883. # 实际保证金比例 = 单笔保证金 / (订单价格 * 合约乘数)
  884. contract_value = order_price * multiplier
  885. actual_margin_rate = single_margin / contract_value if contract_value > 0 else 0
  886. # 校准保证金比例(只有变化大于1%时才更新)
  887. current_rate = get_margin_rate(underlying_symbol, direction)
  888. rate_change = abs(actual_margin_rate - current_rate) / current_rate if current_rate > 0 else 0
  889. if rate_change > 0.01: # 变化大于1%
  890. # 记录保证金比例变化历史
  891. history_key = f"{underlying_symbol}_{direction}"
  892. if history_key not in g.margin_rate_history:
  893. g.margin_rate_history[history_key] = []
  894. g.margin_rate_history[history_key].append({
  895. 'date': context.current_dt.date(),
  896. 'time': context.current_dt.time(),
  897. 'old_rate': current_rate,
  898. 'new_rate': actual_margin_rate,
  899. 'change_pct': rate_change * 100,
  900. 'security': security
  901. })
  902. # 直接更新配置字典中的保证金比例
  903. if underlying_symbol in g.futures_config:
  904. g.futures_config[underlying_symbol]['margin_rate'][direction] = actual_margin_rate
  905. log.debug(f"保证金比例校准: {underlying_symbol}_{direction} {current_rate:.4f} -> {actual_margin_rate:.4f} (变化{rate_change*100:.1f}%)")
  906. # 记录当日交易
  907. g.today_trades.append({
  908. 'security': security, # 交易标的
  909. 'underlying_symbol': underlying_symbol, # 标的字母
  910. 'direction': direction, # 方向
  911. 'order_amount': order_amount, # 开仓数量
  912. 'order_price': order_price, # 开仓金额
  913. 'cash_change': cash_change, # 现金变化
  914. 'actual_margin_rate': actual_margin_rate, # 实际保证金率
  915. 'time': context.current_dt # 成交日期
  916. })
  917. # 记录交易信息
  918. g.trade_history[security] = {
  919. 'entry_price': order_price, # 成交价格
  920. 'position_value': value, # 开仓金额
  921. 'actual_margin': cash_change, # 实际保证金
  922. 'direction': direction, # 方向
  923. 'entry_time': context.current_dt, # 开仓时间
  924. 'signal_info': signal # 信号信息
  925. }
  926. log.debug(f"开仓成功 - 品种: {underlying_symbol}, 手数: {order_amount}, 订单价格: {order_price:.2f}")
  927. log.debug(f"资金变化: {cash_change:.0f}, 实际保证金比例: {actual_margin_rate:.4f}")
  928. return True
  929. except Exception as e:
  930. log.warning(f"开仓失败 {security}: {str(e)}")
  931. return False
  932. def close_position(context, security, direction):
  933. """平仓"""
  934. try:
  935. order = order_target_value(security, 0, side=direction)
  936. if order is not None and order.filled > 0:
  937. underlying_symbol = security.split('.')[0][:-4]
  938. # 记录当日交易(平仓)
  939. g.today_trades.append({
  940. 'security': security,
  941. 'underlying_symbol': underlying_symbol,
  942. 'direction': direction,
  943. 'order_amount': -order.filled, # 负数表示平仓
  944. 'order_price': order.avg_cost if order.avg_cost else order.price,
  945. 'cash_change': 0, # 平仓不计算保证金变化
  946. 'actual_margin_rate': 0,
  947. 'time': context.current_dt
  948. })
  949. log.info(f"平仓成功 - 品种: {underlying_symbol}, 手数: {order.filled}")
  950. # 从交易历史中移除
  951. if security in g.trade_history:
  952. del g.trade_history[security]
  953. # 清理与该持仓相关的数据
  954. clear_position_related_data(security)
  955. return True
  956. except Exception as e:
  957. log.warning(f"平仓失败 {security}: {str(e)}")
  958. return False
  959. def check_stop_loss_profit(context, position):
  960. """检查止损止盈"""
  961. security = position.security
  962. if security not in g.trade_history:
  963. return False
  964. trade_info = g.trade_history[security]
  965. # 检查固定金额止盈止损
  966. # fixed_amount_stop_result = check_fixed_amount_stop(context, security, position, trade_info)
  967. # if fixed_amount_stop_result:
  968. # return True
  969. # 跟踪均线止损止盈
  970. tracking_stop_result = check_tracking_ma_stop(context, security, position, trade_info)
  971. if tracking_stop_result:
  972. return True
  973. return False
  974. def check_fixed_amount_stop(context, security, position, trade_info):
  975. """
  976. 检查固定金额止盈止损
  977. :param context: 上下文对象
  978. :param security: 标的代码
  979. :param position: 持仓对象
  980. :param trade_info: 交易信息
  981. :return: 是否触发止损止盈
  982. """
  983. try:
  984. direction = trade_info['direction']
  985. entry_price = trade_info['entry_price']
  986. current_price = position.price
  987. # 计算当前盈亏
  988. underlying_symbol = security.split('.')[0][:-4]
  989. multiplier = get_multiplier(underlying_symbol)
  990. if direction == 'long':
  991. profit_loss = (current_price - entry_price) * multiplier * abs(position.total_amount)
  992. else:
  993. profit_loss = (entry_price - current_price) * multiplier * abs(position.total_amount)
  994. # 检查是否达到固定金额阈值
  995. if abs(profit_loss) >= g.fixed_profit_threshold:
  996. if profit_loss > 0:
  997. log.info(f"触发固定金额止盈 {security} {direction}")
  998. log.info(f"盈利金额: {profit_loss:.0f} >= {g.fixed_profit_threshold}")
  999. else:
  1000. log.info(f"触发固定金额止损 {security} {direction}")
  1001. log.info(f"亏损金额: {abs(profit_loss):.0f} >= {g.fixed_profit_threshold}")
  1002. log.info(f"开仓价格: {entry_price:.2f}, 当前价格: {current_price:.2f}")
  1003. close_position(context, security, direction)
  1004. return True
  1005. return False
  1006. except Exception as e:
  1007. log.warning(f"检查固定金额止损时出错 {security}: {str(e)}")
  1008. return False
  1009. def check_tracking_ma_stop(context, security, position, trade_info):
  1010. """
  1011. 检查跟踪均线止损止盈(简化版:默认使用MA5均线)
  1012. :param context: 上下文对象
  1013. :param security: 标的代码
  1014. :param position: 持仓对象
  1015. :param trade_info: 交易信息
  1016. :return: 是否触发止损止盈
  1017. """
  1018. try:
  1019. direction = trade_info['direction']
  1020. entry_price = trade_info['entry_price']
  1021. current_price = position.price
  1022. # 获取最新的均线数据
  1023. if security not in g.ma_data_cache:
  1024. return False
  1025. ma_data = g.ma_data_cache[security]
  1026. if len(ma_data) == 0:
  1027. return False
  1028. latest_data = ma_data.iloc[-1]
  1029. # 默认使用MA5均线作为跟踪止损线
  1030. ma5 = latest_data['MA5']
  1031. # 检查是否有NaN值
  1032. if pd.isna(ma5):
  1033. return False
  1034. # 使用MA5作为止损均线
  1035. stop_ma_price = ma5
  1036. stop_ma_name = 'MA5'
  1037. log.debug(f"使用默认跟踪均线: {stop_ma_name}({stop_ma_price:.2f})")
  1038. # 计算止损均线的收益水平
  1039. underlying_symbol = security.split('.')[0][:-4]
  1040. multiplier = get_multiplier(underlying_symbol)
  1041. if direction == 'long':
  1042. ma_profit = (stop_ma_price - entry_price) * multiplier * abs(position.total_amount)
  1043. else:
  1044. ma_profit = (entry_price - stop_ma_price) * multiplier * abs(position.total_amount)
  1045. # 获取跳空信息
  1046. gap_info = g.gap_check_results.get(security, {'has_gap': False})
  1047. has_gap = gap_info['has_gap']
  1048. # 判断是否盘尾
  1049. current_time = context.current_dt.strftime('%H:%M:%S')
  1050. is_market_close = current_time in g.market_close_times
  1051. # 确定止损比例
  1052. stop_ratio = get_tracking_stop_ratio(ma_profit, has_gap, is_market_close)
  1053. # 计算止损价格
  1054. if direction == 'long':
  1055. stop_price = stop_ma_price * (1 - stop_ratio)
  1056. should_stop = current_price <= stop_price
  1057. else:
  1058. stop_price = stop_ma_price * (1 + stop_ratio)
  1059. should_stop = current_price >= stop_price
  1060. log.debug(f"has_gap: {has_gap}, ma_profit: {ma_profit}, stop_ma_price: {stop_ma_price}, stop_ratio: {stop_ratio}, stop_price: {stop_price}, should_stop: {should_stop}")
  1061. if should_stop:
  1062. log.info(f"触发跟踪均线止损 {security} {direction}")
  1063. log.info(f"止损均线: {stop_ma_name}({stop_ma_price:.2f}), 方向: {direction}, 收益: {ma_profit:.0f}, 跳空: {has_gap}, 盘尾: {is_market_close}")
  1064. log.info(f"止损比例: {stop_ratio:.4f}, 止损价格: {stop_price:.2f}, 当前价格: {current_price:.2f}")
  1065. close_position(context, security, direction)
  1066. return True
  1067. return False
  1068. except Exception as e:
  1069. log.warning(f"检查跟踪均线止损时出错 {security}: {str(e)}")
  1070. return False
  1071. def get_tracking_stop_ratio(ma_profit, has_gap, is_market_close):
  1072. """
  1073. 根据均线收益、跳空情况、盘中盘尾确定止损比例
  1074. :param ma_profit: 止损均线的收益水平
  1075. :param has_gap: 是否跳空
  1076. :param is_market_close: 是否盘尾
  1077. :return: 止损比例
  1078. """
  1079. # 根据收益水平分区
  1080. if ma_profit < g.profit_thresholds[0]: # 收益 < 5000
  1081. if is_market_close: # 盘尾
  1082. if has_gap:
  1083. return g.stop_ratios[0] # 0.25%
  1084. else:
  1085. return g.stop_ratios[1] # 0.5%
  1086. else: # 盘中
  1087. if has_gap:
  1088. return g.stop_ratios[1] # 0.5%
  1089. else:
  1090. return g.stop_ratios[2] # 1%
  1091. elif ma_profit < g.profit_thresholds[1]: # 5000 <= 收益 < 15000
  1092. if is_market_close: # 盘尾
  1093. return g.stop_ratios[1] # 0.5%
  1094. else: # 盘中
  1095. return g.stop_ratios[2] # 1%
  1096. else: # 收益 >= 15000
  1097. if is_market_close: # 盘尾
  1098. return g.stop_ratios[2] # 1%
  1099. else: # 盘中
  1100. return g.stop_ratios[3] # 2%
  1101. ############################ 辅助函数 ###################################
  1102. def get_futures_config(underlying_symbol, config_key=None, default_value=None):
  1103. """
  1104. 获取期货品种配置信息的辅助函数
  1105. :param underlying_symbol: 品种符号,如 'AU', 'PF' 等
  1106. :param config_key: 配置键,如 'multiplier', 'has_night_session' 等
  1107. :param default_value: 默认值
  1108. :return: 配置值或整个配置字典
  1109. """
  1110. if underlying_symbol not in g.futures_config:
  1111. if config_key and default_value is not None:
  1112. return default_value
  1113. return {}
  1114. if config_key is None:
  1115. return g.futures_config[underlying_symbol]
  1116. return g.futures_config[underlying_symbol].get(config_key, default_value)
  1117. def get_margin_rate(underlying_symbol, direction, default_rate=0.10):
  1118. """
  1119. 获取保证金比例的辅助函数
  1120. :param underlying_symbol: 品种符号
  1121. :param direction: 方向 'long' 或 'short'
  1122. :param default_rate: 默认保证金比例
  1123. :return: 保证金比例
  1124. """
  1125. return g.futures_config.get(underlying_symbol, {}).get('margin_rate', {}).get(direction, default_rate)
  1126. def get_multiplier(underlying_symbol, default_multiplier=10):
  1127. """
  1128. 获取合约乘数的辅助函数
  1129. :param underlying_symbol: 品种符号
  1130. :param default_multiplier: 默认合约乘数
  1131. :return: 合约乘数
  1132. """
  1133. return g.futures_config.get(underlying_symbol, {}).get('multiplier', default_multiplier)
  1134. def calculate_order_value(context, security, direction):
  1135. """计算开仓金额"""
  1136. current_price = get_current_data()[security].last_price
  1137. underlying_symbol = security.split('.')[0][:-4]
  1138. # 使用保证金比例(已经过校准)
  1139. margin_rate = get_margin_rate(underlying_symbol, direction)
  1140. multiplier = get_multiplier(underlying_symbol)
  1141. # 计算单手保证金
  1142. single_hand_margin = current_price * multiplier * margin_rate
  1143. # 还要考虑可用资金限制
  1144. available_cash = context.portfolio.available_cash * g.usage_percentage
  1145. log.debug(f"可用资金: {available_cash:.0f}")
  1146. # 根据单个标的最大持仓保证金限制计算开仓数量
  1147. max_margin = g.max_margin_per_position
  1148. if single_hand_margin <= max_margin:
  1149. # 如果单手保证金不超过最大限制,计算最大可开仓手数
  1150. max_hands = int(max_margin / single_hand_margin)
  1151. max_hands_by_cash = int(available_cash / single_hand_margin)
  1152. # 取两者较小值
  1153. actual_hands = min(max_hands, max_hands_by_cash)
  1154. # 实际保证金金额
  1155. actual_margin = current_price * multiplier * margin_rate * actual_hands
  1156. # 计算订单金额
  1157. order_value = actual_margin
  1158. log.debug(f"单手保证金: {single_hand_margin:.0f}, 最大手数(保证金限制): {max_hands}, 最大手数(资金限制): {max_hands_by_cash}, 实际开仓手数: {actual_hands}, 实际保证金: {actual_margin:.0f}")
  1159. else:
  1160. # 如果单手保证金超过最大限制,默认开仓1手
  1161. actual_hands = 1
  1162. actual_margin = current_price * multiplier * margin_rate * actual_hands
  1163. # 计算订单金额
  1164. order_value = actual_margin
  1165. log.debug(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手, 实际保证金: {actual_margin:.0f}")
  1166. log.debug(f"计算结果 - 品种: {underlying_symbol}, 开仓手数: {actual_hands}, 订单金额: {order_value:.0f}, 实际保证金: {actual_margin:.0f}")
  1167. return order_value
  1168. def calculate_required_margin(context, symbol):
  1169. """计算所需保证金"""
  1170. current_price = get_current_data()[symbol].last_price
  1171. underlying_symbol = symbol.split('.')[0][:-4]
  1172. margin_rate = get_margin_rate(underlying_symbol, 'long')
  1173. multiplier = get_multiplier(underlying_symbol)
  1174. return current_price * multiplier * margin_rate
  1175. def check_symbol_prefix_match(symbol, hold_symbols):
  1176. """检查是否有相似的持仓品种"""
  1177. symbol_prefix = symbol[:-9]
  1178. for hold_symbol in hold_symbols:
  1179. hold_symbol_prefix = hold_symbol[:-9]
  1180. if symbol_prefix == hold_symbol_prefix:
  1181. return True
  1182. return False
  1183. def after_market_close(context):
  1184. """收盘后运行函数"""
  1185. log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
  1186. # 只有当天有交易时才打印统计信息
  1187. if g.today_trades:
  1188. print_daily_trading_summary(context)
  1189. print_margin_rate_changes(context)
  1190. # 打印内存使用报告
  1191. memory_usage_report()
  1192. # 清理当天临时数据
  1193. clear_daily_transient_data()
  1194. # 清理过期的持续数据(保留最近5天)
  1195. clear_expired_persistent_data(context, days_to_keep=5)
  1196. # 优化历史数据缓存(保留最多50个品种)
  1197. optimize_daily_data_cache(max_symbols=50)
  1198. log.info('##############################################################')
  1199. def print_daily_trading_summary(context):
  1200. """打印当日交易汇总"""
  1201. if not g.today_trades:
  1202. return
  1203. log.debug("\n=== 当日交易汇总 ===")
  1204. total_margin = 0
  1205. for trade in g.today_trades:
  1206. if trade['order_amount'] > 0: # 开仓
  1207. log.debug(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
  1208. f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f} "
  1209. f"比例:{trade['actual_margin_rate']:.4f}")
  1210. total_margin += trade['cash_change']
  1211. else: # 平仓
  1212. log.debug(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
  1213. f"价格:{trade['order_price']:.2f}")
  1214. log.debug(f"当日保证金占用: {total_margin:.0f}")
  1215. log.debug("==================\n")
  1216. def print_margin_rate_changes(context):
  1217. """打印保证金比例变化记录"""
  1218. if not g.margin_rate_history:
  1219. return
  1220. log.debug("\n=== 保证金比例变化记录 ===")
  1221. for key, history in g.margin_rate_history.items():
  1222. log.debug(f"{key}:")
  1223. for record in history:
  1224. log.debug(f" {record['date']} {record['time']}: {record['old_rate']:.4f} -> {record['new_rate']:.4f} "
  1225. f"(变化{record['change_pct']:.1f}%)")
  1226. log.debug("========================\n")
  1227. ########################## 自动移仓换月函数 #################################
  1228. def position_auto_switch(context,pindex=0,switch_func=None, callback=None):
  1229. """
  1230. 期货自动移仓换月。默认使用市价单进行开平仓。
  1231. :param context: 上下文对象
  1232. :param pindex: 子仓对象
  1233. :param switch_func: 用户自定义的移仓换月函数.
  1234. 函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
  1235. :param callback: 移仓换月完成后的回调函数。
  1236. 函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
  1237. :return: 发生移仓换月的标的。类型为列表。
  1238. """
  1239. import re
  1240. subportfolio = context.subportfolios[pindex]
  1241. symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  1242. switch_result = []
  1243. for symbol in symbols:
  1244. match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
  1245. if not match:
  1246. # raise ValueError("未知期货标的: {}".format(symbol))
  1247. raise ValueError("Unknow target: {}".format(symbol))
  1248. else:
  1249. dominant = get_dominant_future(match.groupdict()["underlying_symbol"])
  1250. cur = get_current_data()
  1251. symbol_last_price = cur[symbol].last_price
  1252. dominant_last_price = cur[dominant].last_price
  1253. log.info(f'current_hold_symbol: {symbol}, current_main_symbol: {dominant}')
  1254. if dominant > symbol:
  1255. for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
  1256. if symbol not in positions_.keys():
  1257. continue
  1258. else :
  1259. p = positions_[symbol]
  1260. if switch_func is not None:
  1261. switch_func(context, pindex, p, dominant)
  1262. else:
  1263. amount = p.total_amount
  1264. # 跌停不能开空和平多,涨停不能开多和平空。
  1265. if p.side == "long":
  1266. symbol_low_limit = cur[symbol].low_limit
  1267. dominant_high_limit = cur[dominant].high_limit
  1268. if symbol_last_price <= symbol_low_limit:
  1269. # log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
  1270. log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
  1271. continue
  1272. elif dominant_last_price >= dominant_high_limit:
  1273. # log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(symbol))
  1274. log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
  1275. continue
  1276. else:
  1277. # log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
  1278. log.info("Start the exchange: ({0},long) -> ({1},long)".format(symbol, dominant))
  1279. order_old = order_target(symbol,0,side='long')
  1280. if order_old != None and order_old.filled > 0:
  1281. order_new = order_target(dominant,amount,side='long')
  1282. if order_new != None and order_new.filled >0:
  1283. switch_result.append({"before": symbol, "after":dominant, "side": "long"})
  1284. # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
  1285. g.trade_history[dominant] = g.trade_history[symbol]
  1286. del g.trade_history[symbol]
  1287. else:
  1288. # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(domaint))
  1289. log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
  1290. # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
  1291. log.warning(f'换月多头失败{dominant}, {g.trade_history[symbol]}')
  1292. g.historical_data['change_fail_history'][dominant] = g.trade_history[symbol]
  1293. del g.trade_history[symbol]
  1294. if callback:
  1295. callback(context, pindex, p, dominant)
  1296. if p.side == "short":
  1297. symbol_high_limit = cur[symbol].high_limit
  1298. dominant_low_limit = cur[dominant].low_limit
  1299. if symbol_last_price >= symbol_high_limit:
  1300. # log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
  1301. log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
  1302. continue
  1303. elif dominant_last_price <= dominant_low_limit:
  1304. # log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(symbol))
  1305. log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
  1306. continue
  1307. else:
  1308. # log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
  1309. log.info("Start the exchange: ({0},short) -> ({1},short)".format(symbol, dominant))
  1310. order_old = order_target(symbol,0,side='short')
  1311. if order_old != None and order_old.filled > 0:
  1312. log.info(f'换月做空{dominant},数量位{amount}')
  1313. order_new = order_target(dominant,amount,side='short')
  1314. if order_new != None and order_new.filled >0:
  1315. switch_result.append({"before": symbol, "after":dominant, "side": "short"})
  1316. # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
  1317. g.trade_history[dominant] = g.trade_history[symbol]
  1318. del g.trade_history[symbol]
  1319. else:
  1320. # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(dominant))
  1321. log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
  1322. # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
  1323. log.warning(f'换月空头失败{dominant}, {g.trade_history[symbol]}')
  1324. g.historical_data['change_fail_history'][dominant] = g.trade_history[symbol]
  1325. log.warning(f'失败记录{g.historical_data["change_fail_history"]}')
  1326. del g.trade_history[symbol]
  1327. # order_target(symbol,0,side='short')
  1328. # order_target(dominant,amount,side='short')
  1329. # switch_result.append({"before": symbol, "after": dominant, "side": "short"})
  1330. if callback:
  1331. callback(context, pindex, p, dominant)
  1332. return switch_result
  1333. def count_ma_crosses(data, days):
  1334. """
  1335. 判断过去指定天数内4条MA均线的交叉次数
  1336. :param data: 包含MA5, MA10, MA20, MA30的DataFrame
  1337. :param days: 检查的天数
  1338. :return: 总交叉次数
  1339. """
  1340. if len(data) < days + 1:
  1341. return 0
  1342. # 获取最近days天的数据
  1343. recent_data = data.iloc[-days-1:]
  1344. ma5 = recent_data['MA5'].values
  1345. ma10 = recent_data['MA10'].values
  1346. ma20 = recent_data['MA20'].values
  1347. ma30 = recent_data['MA30'].values
  1348. # 检查是否有NaN值
  1349. if np.any(np.isnan([ma5, ma10, ma20, ma30])):
  1350. return 0
  1351. # 计算各均线间的交叉次数
  1352. cross_5_10 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma10[i] and ma5[i-1] < ma10[i-1]) or
  1353. (ma5[i] < ma10[i] and ma5[i-1] > ma10[i-1]))])
  1354. cross_5_20 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma20[i] and ma5[i-1] < ma20[i-1]) or
  1355. (ma5[i] < ma20[i] and ma5[i-1] > ma20[i-1]))])
  1356. cross_5_30 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma30[i] and ma5[i-1] < ma30[i-1]) or
  1357. (ma5[i] < ma30[i] and ma5[i-1] > ma30[i-1]))])
  1358. cross_10_20 = sum([1 for i in range(1, len(ma10)) if ((ma10[i] > ma20[i] and ma10[i-1] < ma20[i-1]) or
  1359. (ma10[i] < ma20[i] and ma10[i-1] > ma20[i-1]))])
  1360. cross_10_30 = sum([1 for i in range(1, len(ma10)) if ((ma10[i] > ma30[i] and ma10[i-1] < ma30[i-1]) or
  1361. (ma10[i] < ma30[i] and ma10[i-1] > ma30[i-1]))])
  1362. cross_20_30 = sum([1 for i in range(1, len(ma20)) if ((ma20[i] > ma30[i] and ma20[i-1] < ma30[i-1]) or
  1363. (ma20[i] < ma30[i] and ma20[i-1] > ma30[i-1]))])
  1364. total_crosses = cross_5_10 + cross_5_20 + cross_5_30 + cross_10_20 + cross_10_30 + cross_20_30
  1365. log.debug(f'总交叉数: {total_crosses}, MA5-MA10: {cross_5_10}, MA5-MA20: {cross_5_20}, MA5-MA30: {cross_5_30}, MA10-MA20: {cross_10_20}, MA10-MA30: {cross_10_30}, MA20-MA30: {cross_20_30}')
  1366. return total_crosses
  1367. ############################ 数据清理管理函数 ###################################
  1368. def clear_daily_transient_data():
  1369. """清理当天临时数据(每日收盘后调用)"""
  1370. log.info("清理当天临时数据")
  1371. g.daily_transient_data['ma_cross_signals'].clear()
  1372. g.daily_transient_data['tradable_futures'].clear()
  1373. g.daily_transient_data['today_trades'].clear()
  1374. # 更新兼容性映射
  1375. g.ma_cross_signals = g.daily_transient_data['ma_cross_signals']
  1376. g.tradable_futures = g.daily_transient_data['tradable_futures']
  1377. g.today_trades = g.daily_transient_data['today_trades']
  1378. def clear_expired_persistent_data(context, days_to_keep=5):
  1379. """清理过期的持续数据(保留最近N天)"""
  1380. today_date = context.current_dt.date()
  1381. cutoff_date = today_date - timedelta(days=days_to_keep)
  1382. # 清理过期的均线交叉过滤结果
  1383. expired_dates = [date for date in g.persistent_daily_data['ma_cross_filtered_futures'].keys() if date < cutoff_date]
  1384. for date in expired_dates:
  1385. del g.persistent_daily_data['ma_cross_filtered_futures'][date]
  1386. # 清理过期的分钟数据缓存(保留最近N天)
  1387. minute_cache = g.persistent_daily_data['minute_data_cache']
  1388. expired_symbols = []
  1389. for symbol, cache_data in minute_cache.items():
  1390. if isinstance(cache_data, dict) and 'date' in cache_data:
  1391. cache_date = cache_data['date']
  1392. if cache_date < cutoff_date:
  1393. expired_symbols.append(symbol)
  1394. # 如果缓存数据格式不正确,也清理掉
  1395. elif not isinstance(cache_data, dict):
  1396. expired_symbols.append(symbol)
  1397. for symbol in expired_symbols:
  1398. del minute_cache[symbol]
  1399. if expired_dates or expired_symbols:
  1400. log.info(f"清理过期数据 - 均线交叉过滤: {len(expired_dates)}天, 分钟数据缓存: {len(expired_symbols)}个品种")
  1401. def clear_position_related_data(security):
  1402. """清理与特定持仓相关的数据(平仓时调用)"""
  1403. # 清理该标的的均线数据缓存
  1404. if security in g.position_data['ma_data_cache']:
  1405. del g.position_data['ma_data_cache'][security]
  1406. log.info(f"清理平仓标的的均线数据缓存: {security}")
  1407. # 清理跳空检查结果(如果不再持仓)
  1408. if security in g.persistent_daily_data['gap_check_results']:
  1409. del g.persistent_daily_data['gap_check_results'][security]
  1410. log.info(f"清理平仓标的的跳空检查结果: {security}")
  1411. # 更新兼容性映射
  1412. g.ma_data_cache = g.position_data['ma_data_cache']
  1413. g.gap_check_results = g.persistent_daily_data['gap_check_results']
  1414. def memory_usage_report():
  1415. """内存使用情况报告"""
  1416. report = {
  1417. '当天临时数据': {
  1418. '均线穿越信号': len(g.daily_transient_data['ma_cross_signals']),
  1419. '可交易品种': len(g.daily_transient_data['tradable_futures']),
  1420. '当日交易': len(g.daily_transient_data['today_trades'])
  1421. },
  1422. '持续数据': {
  1423. '历史日线缓存': len(g.persistent_daily_data['daily_data_cache']),
  1424. '分钟数据缓存': len(g.persistent_daily_data['minute_data_cache']),
  1425. '均线交叉过滤': len(g.persistent_daily_data['ma_cross_filtered_futures']),
  1426. '跳空检查结果': len(g.persistent_daily_data['gap_check_results'])
  1427. },
  1428. '持仓数据': {
  1429. '交易历史': len(g.position_data['trade_history']),
  1430. '均线数据缓存': len(g.position_data['ma_data_cache'])
  1431. },
  1432. '历史数据': {
  1433. '保证金历史': len(g.historical_data['margin_rate_history']),
  1434. '换月失败历史': len(g.historical_data.get('change_fail_history', {}))
  1435. }
  1436. }
  1437. log.info("=== 内存使用情况报告 ===")
  1438. for category, data in report.items():
  1439. log.info(f"{category}: {data}")
  1440. log.info("========================")
  1441. return report
  1442. def optimize_daily_data_cache(max_symbols=50):
  1443. """优化历史日线数据缓存,删除不必要的数据"""
  1444. cache = g.persistent_daily_data['daily_data_cache']
  1445. if len(cache) <= max_symbols:
  1446. return
  1447. # 获取当前持仓的标的
  1448. current_positions = set(g.position_data['trade_history'].keys())
  1449. # 优先保留持仓标的的数据
  1450. symbols_to_keep = set()
  1451. symbols_to_remove = set()
  1452. for symbol in cache.keys():
  1453. if len(symbols_to_keep) < max_symbols:
  1454. # 提取标的前缀(去掉合约月份)
  1455. symbol_prefix = symbol[:-9] if len(symbol) > 9 else symbol
  1456. # 检查是否有相关持仓
  1457. has_related_position = any(pos.startswith(symbol_prefix) for pos in current_positions)
  1458. if has_related_position:
  1459. symbols_to_keep.add(symbol)
  1460. else:
  1461. symbols_to_remove.add(symbol)
  1462. else:
  1463. symbols_to_remove.add(symbol)
  1464. # 删除不需要的数据
  1465. for symbol in symbols_to_remove:
  1466. if len(symbols_to_keep) < max_symbols:
  1467. symbols_to_keep.add(symbol)
  1468. else:
  1469. del cache[symbol]
  1470. if symbols_to_remove:
  1471. log.info(f"优化历史日线缓存,删除 {len(symbols_to_remove)} 个标的的数据")
  1472. log.debug(f"删除的标的: {list(symbols_to_remove)[:10]}...") # 只显示前10个
  1473. # 更新兼容性映射
  1474. g.daily_data_cache = g.persistent_daily_data['daily_data_cache']