MultiMABreakoutStrategy_v001.py 75 KB

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