MultiMABreakoutStrategy_v001.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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.margin_rates = {
  41. 'long': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
  42. 'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
  43. 'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
  44. 'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22,
  45. 'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
  46. 'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
  47. 'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
  48. 'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
  49. 'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
  50. 'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05},
  51. 'short': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
  52. 'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
  53. 'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
  54. 'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22,
  55. 'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
  56. 'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
  57. 'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
  58. 'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
  59. 'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
  60. 'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05}
  61. }
  62. g.multiplier = {
  63. 'A': 10, 'AG': 15, 'AL': 5, 'AO': 20, 'AP': 10, 'AU': 1000, 'B': 10,
  64. 'BC': 5, 'BR': 5, 'BU': 10, 'C': 10, 'CF': 5, 'CJ': 5, 'CS': 10,
  65. 'CU': 5, 'CY': 5, 'EB': 5, 'EC': 50, 'EG': 10, 'FG': 20, 'FU': 10,
  66. 'HC': 10, 'I': 100, 'J': 60, 'JD': 5, 'JM': 100,
  67. 'L': 5, 'LC': 1, 'LH': 16, 'LR': 0.05, 'LU': 10, 'M': 10, 'MA': 10, 'NI': 1, 'NR': 10, 'OI': 10,
  68. 'P': 10, 'PB': 5, 'PF': 5, 'PG': 20, 'PK': 5,
  69. 'PP': 5, 'RB': 10, 'RI': 0.05, 'RM': 10, 'RU': 10,
  70. 'SA': 20, 'SC': 1000, 'SF': 5, 'SH': 30, 'SI': 5, 'SM': 5, 'SN': 1, 'SP': 10, 'SR': 10,
  71. 'SS': 5, 'TA': 5, 'UR': 20, 'V': 5,
  72. 'Y': 10, 'ZC': 0.05, 'ZN': 5
  73. }
  74. # 交易记录和数据存储
  75. g.trade_history = {}
  76. g.ma_cross_signals = {} # 存储多均线穿越信号
  77. g.daily_data_cache = {} # 存储历史日线数据缓存
  78. g.minute_data_cache = {} # 存储今日分钟数据缓存
  79. g.ma_data_cache = {} # 存储均线数据缓存
  80. g.ma_cross_filtered_futures = {} # 存储通过均线交叉检查的品种(每日缓存)
  81. # 保证金比例管理(g.margin_rates会根据实际交易校准)
  82. g.margin_rate_history = {} # 保证金比例变化历史记录
  83. g.today_trades = [] # 当日交易记录
  84. # 定时任务设置 - 根据新的时间安排
  85. # 夜盘开始
  86. run_daily(main_trading_21_05, time='21:05:00', reference_security='IF1808.CCFX')
  87. run_daily(main_trading_regular, time='21:35:00', reference_security='IF1808.CCFX')
  88. run_daily(main_trading_regular, time='22:05:00', reference_security='IF1808.CCFX')
  89. run_daily(main_trading_regular, time='22:35:00', reference_security='IF1808.CCFX')
  90. # 日盘开始
  91. run_daily(main_trading_09_05, time='09:05:00', reference_security='IF1808.CCFX')
  92. run_daily(main_trading_regular, time='09:35:00', reference_security='IF1808.CCFX')
  93. run_daily(main_trading_regular, time='10:05:00', reference_security='IF1808.CCFX')
  94. run_daily(main_trading_regular, time='10:35:00', reference_security='IF1808.CCFX')
  95. run_daily(main_trading_regular, time='11:05:00', reference_security='IF1808.CCFX')
  96. run_daily(main_trading_regular, time='11:25:00', reference_security='IF1808.CCFX')
  97. run_daily(main_trading_regular, time='13:35:00', reference_security='IF1808.CCFX')
  98. run_daily(main_trading_regular, time='14:05:00', reference_security='IF1808.CCFX')
  99. # 收盘前
  100. run_daily(main_trading_before_close, time='14:35:00', reference_security='IF1808.CCFX')
  101. run_daily(main_trading_before_close, time='14:55:00', reference_security='IF1808.CCFX')
  102. # 收盘后
  103. run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
  104. ############################ 主程序执行函数 ###################################
  105. def main_trading_21_05(context):
  106. """21:05 执行任务1, 2, 3, 4, 5, 6, 9"""
  107. log.info("-" * 50)
  108. log.info("21:05 多均线穿越突破策略 - 夜盘开始")
  109. log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
  110. log.info("-" * 50)
  111. # 任务1: 获取所有可交易品种
  112. task_1_get_tradable_futures(context)
  113. # 任务2: 获取历史数据并保存到内存
  114. task_2_load_historical_data(context)
  115. # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
  116. task_3_check_ma_crosses(context)
  117. # 任务4: 获取今日分钟数据并合并均线数据
  118. task_4_update_realtime_data(context)
  119. # 任务5: 判断上穿下穿情况
  120. task_5_analyze_ma_crosses(context)
  121. # 任务6: 检查开仓条件
  122. filtered_signals = task_6_check_opening_conditions(context)
  123. # 如果任务6有满足条件的,执行任务7开仓
  124. if filtered_signals:
  125. task_7_execute_trades(context, filtered_signals)
  126. # 任务9: 检查止损止盈
  127. task_9_check_stop_loss_profit(context)
  128. def main_trading_09_05(context):
  129. """09:05 执行任务1, 2, 3, 4, 5, 6, 9"""
  130. log.info("-" * 50)
  131. log.info("09:05 多均线穿越突破策略 - 日盘开始")
  132. log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
  133. log.info("-" * 50)
  134. # 任务1: 获取所有可交易品种
  135. task_1_get_tradable_futures(context)
  136. # 任务2: 获取历史数据并保存到内存
  137. task_2_load_historical_data(context)
  138. # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
  139. task_3_check_ma_crosses(context)
  140. # 任务4: 获取今日分钟数据并合并均线数据
  141. task_4_update_realtime_data(context)
  142. # 任务5: 判断上穿下穿情况
  143. task_5_analyze_ma_crosses(context)
  144. # 任务6: 检查开仓条件
  145. filtered_signals = task_6_check_opening_conditions(context)
  146. # 如果任务6有满足条件的,执行任务7开仓
  147. if filtered_signals:
  148. task_7_execute_trades(context, filtered_signals)
  149. # 任务9: 检查止损止盈
  150. task_9_check_stop_loss_profit(context)
  151. def main_trading_regular(context):
  152. """常规时间执行任务4, 5, 6, 9"""
  153. current_time = context.current_dt.strftime('%H:%M')
  154. # log.info(f"----- {current_time} 常规检查 -----")
  155. # log.info("执行任务: 4, 5, 6, 9")
  156. # 任务4: 获取今日分钟数据并合并均线数据
  157. task_4_update_realtime_data(context)
  158. # 任务5: 判断上穿下穿情况
  159. task_5_analyze_ma_crosses(context)
  160. # 任务6: 检查开仓条件
  161. filtered_signals = task_6_check_opening_conditions(context)
  162. # 如果任务6有满足条件的,执行任务7开仓
  163. if filtered_signals:
  164. task_7_execute_trades(context, filtered_signals)
  165. # 任务9: 检查止损止盈
  166. task_9_check_stop_loss_profit(context)
  167. def main_trading_before_close(context):
  168. """收盘前执行任务4, 5, 6, 8, 9"""
  169. current_time = context.current_dt.strftime('%H:%M')
  170. # log.info(f"----- {current_time} 收盘前检查 -----")
  171. # log.info("执行任务: 4, 5, 6, 8, 9")
  172. # 任务4: 获取今日分钟数据并合并均线数据
  173. task_4_update_realtime_data(context)
  174. # 任务5: 判断上穿下穿情况
  175. task_5_analyze_ma_crosses(context)
  176. # 任务6: 检查开仓条件
  177. filtered_signals = task_6_check_opening_conditions(context)
  178. # 如果任务6有满足条件的,执行任务7开仓
  179. if filtered_signals:
  180. task_7_execute_trades(context, filtered_signals)
  181. # 任务8: 检查换月移仓
  182. task_8_check_position_switch(context)
  183. # 任务9: 检查止损止盈
  184. task_9_check_stop_loss_profit(context)
  185. ############################ 核心任务函数 ###################################
  186. def task_1_get_tradable_futures(context):
  187. """任务1: 获取所有可交易品种(分白天和晚上)"""
  188. # log.info("执行任务1: 获取可交易品种")
  189. # 夜盘品种
  190. # potential_night_list = ['NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM', 'RB', 'HC', 'I', 'J', 'JM']
  191. potential_night_list = ['PF', 'Y', 'SN']
  192. # 日盘品种
  193. potential_day_list = ['PK']
  194. # potential_day_list = ['JD', 'UR', 'AP', 'CJ', 'PK']
  195. current_time = str(context.current_dt.time())[:2]
  196. if current_time in ('21', '22'):
  197. potential_icon_list = potential_night_list
  198. log.info(f"夜盘时间,可交易品种: {potential_night_list}")
  199. else:
  200. potential_icon_list = potential_day_list + potential_night_list
  201. log.info(f"日盘时间,可交易品种: {potential_icon_list}")
  202. potential_future_list = []
  203. for symbol in potential_icon_list:
  204. dominant_future = get_dominant_future(symbol)
  205. if dominant_future:
  206. potential_future_list.append(dominant_future)
  207. # 过滤掉已有持仓的品种
  208. existing_positions = set(g.trade_history.keys())
  209. potential_future_list = [f for f in potential_future_list if not check_symbol_prefix_match(f, existing_positions)]
  210. # 存储到全局变量
  211. g.tradable_futures = potential_future_list
  212. log.info(f"最终可交易期货品种数量: {len(potential_future_list)}")
  213. return potential_future_list
  214. def task_2_load_historical_data(context):
  215. """任务2: 获取所有可交易品种今天之前所需的数据,并保存到内存中"""
  216. # log.info("执行任务2: 加载历史数据到内存")
  217. if not hasattr(g, 'tradable_futures'):
  218. return
  219. for future_code in g.tradable_futures:
  220. try:
  221. # 获取50天历史数据(用于计算均线)
  222. data = attribute_history(future_code, 50, '1d',
  223. ['open', 'close', 'high', 'low', 'volume'],
  224. df=True)
  225. if data is not None and len(data) > 0:
  226. # 排除今天的数据
  227. today = context.current_dt.date()
  228. data = data[data.index.date < today]
  229. g.daily_data_cache[future_code] = data
  230. # log.info(f"已缓存 {future_code} 历史数据 {len(data)} 条")
  231. except Exception as e:
  232. log.warning(f"加载{future_code}历史数据时出错: {str(e)}")
  233. continue
  234. log.info(f"历史数据缓存完成,共缓存 {len(g.daily_data_cache)} 个品种")
  235. def task_3_check_ma_crosses(context):
  236. """任务3: 检查均线交叉数量,过滤掉交叉过多的品种"""
  237. # log.info("执行任务3: 检查均线交叉数量")
  238. if not hasattr(g, 'tradable_futures'):
  239. return
  240. # 存储通过均线交叉检查的品种
  241. today_date = context.current_dt.date()
  242. if today_date not in g.ma_cross_filtered_futures:
  243. g.ma_cross_filtered_futures[today_date] = []
  244. filtered_futures = []
  245. for future_code in g.tradable_futures:
  246. try:
  247. # 获取历史数据
  248. historical_data = g.daily_data_cache.get(future_code)
  249. if historical_data is None or len(historical_data) < 30:
  250. log.warning(f"{future_code} 历史数据不足,跳过")
  251. continue
  252. # 计算移动平均线
  253. data_with_ma = historical_data.copy()
  254. data_with_ma['MA5'] = data_with_ma['close'].rolling(window=5).mean()
  255. data_with_ma['MA10'] = data_with_ma['close'].rolling(window=10).mean()
  256. data_with_ma['MA20'] = data_with_ma['close'].rolling(window=20).mean()
  257. data_with_ma['MA30'] = data_with_ma['close'].rolling(window=30).mean()
  258. # 检查均线交叉数量
  259. ma_crosses = count_ma_crosses(data_with_ma, g.ma_cross_check_days)
  260. # 如果交叉数量在允许范围内,保留该品种
  261. if ma_crosses <= g.max_ma_crosses:
  262. filtered_futures.append(future_code)
  263. log.info(f"{future_code} 通过均线交叉检查,交叉数量: {ma_crosses}")
  264. else:
  265. log.info(f"{future_code} 均线交叉过多,被过滤,交叉数量: {ma_crosses} > {g.max_ma_crosses}")
  266. except Exception as e:
  267. log.warning(f"检查{future_code}均线交叉时出错: {str(e)}")
  268. continue
  269. # 更新可交易品种列表
  270. g.tradable_futures = filtered_futures
  271. g.ma_cross_filtered_futures[today_date] = filtered_futures
  272. log.info(f"均线交叉检查完成,剩余可交易品种数量: {len(g.tradable_futures)}")
  273. if len(g.tradable_futures) > 0:
  274. log.info(f"通过检查的品种: {g.tradable_futures}")
  275. return filtered_futures
  276. def task_4_update_realtime_data(context):
  277. """任务4: 获取所有可交易品种今天所需的分钟数据作为今天数据,和2中的数据合并出最新的均线数据,并保存到内存中"""
  278. # log.info("执行任务4: 更新实时数据和均线")
  279. if not hasattr(g, 'tradable_futures'):
  280. return
  281. for future_code in g.tradable_futures:
  282. log.info(f"任务4 future_code: {future_code}")
  283. try:
  284. # 获取今日分钟数据
  285. minute_data = get_today_minute_data(context, future_code)
  286. # log.info(f"minute_data: {minute_data}")
  287. if minute_data is None:
  288. continue
  289. # 获取历史数据
  290. historical_data = g.daily_data_cache.get(future_code)
  291. if historical_data is None:
  292. continue
  293. # 合并数据并计算均线
  294. combined_data = combine_and_calculate_ma(historical_data, minute_data)
  295. if combined_data is not None:
  296. g.ma_data_cache[future_code] = combined_data
  297. # log.info(f"已更新 {future_code} 均线数据")
  298. except Exception as e:
  299. log.warning(f"更新{future_code}实时数据时出错: {str(e)}")
  300. continue
  301. # log.info(f"实时数据更新完成,共更新 {len(g.ma_data_cache)} 个品种")
  302. def task_5_analyze_ma_crosses(context):
  303. """任务5: 根据交易品种的今天数据和均线数据,判断是否出现了上穿或者下穿的情况"""
  304. # log.info("执行任务5: 分析均线穿越")
  305. ma_cross_signals = []
  306. # 获取已持仓的品种列表
  307. existing_positions = set(g.trade_history.keys())
  308. for future_code, data in g.ma_data_cache.items():
  309. log.info(f"future_code: {future_code}")
  310. try:
  311. # 检查是否已有相似持仓,如果有则跳过分析
  312. if check_symbol_prefix_match(future_code, existing_positions):
  313. # log.(f"{future_code} 已有相似持仓,跳过均线穿越分析")
  314. continue
  315. # 检查最新的多均线穿越
  316. latest_cross = check_latest_multi_ma_cross(data, future_code)
  317. if latest_cross:
  318. ma_cross_signals.append(latest_cross)
  319. log.info(f"{future_code} 发现多均线穿越: {latest_cross['direction']}")
  320. log.info(f"开盘价格: {latest_cross['open']}, 当前价格: {latest_cross['close']}, 临界线: {latest_cross['critical_ma_name']}({latest_cross['critical_ma_value']:.2f}), 穿越数量: {latest_cross['crossed_count']}")
  321. log.info(f"MA5: {latest_cross['ma5']}, MA10: {latest_cross['ma10']}, MA20: {latest_cross['ma20']}, MA30: {latest_cross['ma30']}")
  322. except Exception as e:
  323. log.warning(f"分析{future_code}均线穿越时出错: {str(e)}")
  324. continue
  325. # 存储到全局变量
  326. g.ma_cross_signals = ma_cross_signals
  327. if len(ma_cross_signals) > 0:
  328. log.info(f"均线穿越分析完成,发现信号 {len(ma_cross_signals)} 个")
  329. log.debug(f"ma_cross_signals: {ma_cross_signals}")
  330. return ma_cross_signals
  331. def task_6_check_opening_conditions(context):
  332. """任务6: 针对那些有上穿和下穿的情况检查是否满足开仓条件"""
  333. # log.info("执行任务6: 检查开仓条件")
  334. if not hasattr(g, 'ma_cross_signals'):
  335. return []
  336. filtered_signals = []
  337. for signal in g.ma_cross_signals:
  338. # 检查是否已有相似持仓
  339. if check_symbol_prefix_match(signal['symbol'], set(g.trade_history.keys())):
  340. log.warning(f"{signal['symbol']} 已有相似持仓,跳过")
  341. continue
  342. # 检查价格位置合理性
  343. if not check_price_position(signal):
  344. log.warning(f"{signal['symbol']} 价格位置不合理,跳过")
  345. continue
  346. filtered_signals.append(signal)
  347. log.info(f"{signal['symbol']} 满足开仓条件")
  348. if len(filtered_signals) > 0:
  349. log.info(f"开仓条件检查完成,满足条件 {len(filtered_signals)} 个")
  350. return filtered_signals
  351. def task_7_execute_trades(context, filtered_signals):
  352. """任务7: 针对满足开仓条件的标的,计算购买的金额,并发起交易请求"""
  353. # log.info("执行任务7: 执行交易")
  354. for signal in filtered_signals:
  355. symbol = signal['symbol']
  356. direction = 'long' if signal['direction'] == 'up' else 'short'
  357. # 检查资金充足性
  358. if not check_sufficient_capital(context, symbol):
  359. log.warning(f"{symbol} 资金不足,跳过开仓")
  360. continue
  361. # 计算开仓金额
  362. order_value = calculate_order_value(context, symbol, direction)
  363. log.info(f"计算开仓金额: {symbol} {direction} 金额: {order_value}")
  364. # 如果计算出的金额为0,说明资金不足,跳过开仓
  365. if order_value <= 0:
  366. log.warning(f"资金不足,跳过开仓 {symbol} {direction}")
  367. continue
  368. # 执行开仓
  369. success = open_position(context, symbol, order_value, direction, signal)
  370. if success:
  371. # 获取实际保证金(只有在开仓成功时才能获取)
  372. actual_margin = g.trade_history[symbol]['actual_margin']
  373. log.info(f"成功开仓 {symbol} {direction} 金额: {order_value}, 实际保证金: {actual_margin:.0f}")
  374. else:
  375. log.warning(f"开仓失败 {symbol} {direction}")
  376. def task_8_check_position_switch(context):
  377. """任务8: 针对已经持仓的标的,检查是否换月移仓"""
  378. # log.info("执行任务8: 检查换月移仓")
  379. switch_result = position_auto_switch(context)
  380. if switch_result:
  381. log.info(f"执行了 {len(switch_result)} 次移仓换月")
  382. for result in switch_result:
  383. log.info(f"移仓: {result['before']} -> {result['after']}")
  384. # else:
  385. # log.info("无需移仓换月")
  386. def task_9_check_stop_loss_profit(context):
  387. """任务9: 针对已经持仓的标的,检查是否止损或止盈"""
  388. # log.info("执行任务9: 检查止损止盈")
  389. # 遍历所有持仓进行止损止盈检查
  390. subportfolio = context.subportfolios[0]
  391. long_positions = list(subportfolio.long_positions.values())
  392. short_positions = list(subportfolio.short_positions.values())
  393. closed_count = 0
  394. for position in long_positions + short_positions:
  395. if check_stop_loss_profit(context, position):
  396. closed_count += 1
  397. if closed_count > 0:
  398. log.info(f"执行了 {closed_count} 次止损止盈")
  399. # else:
  400. # log.info("无需止损止盈")
  401. ############################ 数据处理辅助函数 ###################################
  402. def check_has_night_session(underlying_symbol):
  403. """检查品种是否有夜盘"""
  404. # 有夜盘的品种列表
  405. night_session_symbols = {
  406. 'NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM', 'RB', 'HC', 'I', 'J', 'JM',
  407. 'A', 'AG', 'AL', 'AU', 'BU', 'C', 'CU', 'FU', 'L', 'P', 'PB', 'RU',
  408. 'SC', 'SP', 'SS', 'TA', 'V', 'ZC', 'ZN', 'MA', 'SR', 'OI', 'CF', 'RM',
  409. 'FG', 'SA', 'UR', 'NR', 'LU', 'BC', 'EC', 'PP', 'EB', 'EG', 'PG'
  410. }
  411. return underlying_symbol in night_session_symbols
  412. def get_today_minute_data(context, future_code):
  413. """获取今日分钟数据"""
  414. try:
  415. # 判断该品种是否有夜盘
  416. underlying_symbol = future_code.split('.')[0][:-4]
  417. has_night_session = check_has_night_session(underlying_symbol)
  418. end_time = context.current_dt
  419. # 获取足够的历史分钟数据
  420. minute_data = attribute_history(future_code,
  421. count=800, # 获取足够多的数据
  422. unit='1m',
  423. fields=['open', 'close', 'high', 'low', 'volume'],
  424. df=True)
  425. if minute_data is None or len(minute_data) == 0:
  426. return None
  427. # log.debug(f"原始分钟数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
  428. # 提取所有日期(年月日维度)
  429. minute_data['date'] = minute_data.index.date
  430. unique_dates = sorted(minute_data['date'].unique())
  431. # log.debug(f"数据包含的日期: {unique_dates}")
  432. if has_night_session:
  433. # 有夜盘的品种:需要找到前一交易日的21:00作为今日开盘起点
  434. today_date = end_time.date()
  435. # 找到今天之前的最后一个交易日
  436. previous_trading_dates = [d for d in unique_dates if d < today_date]
  437. # log.debug(f"夜盘标的 today_date: {today_date}, previous_trading_dates: {previous_trading_dates}")
  438. if not previous_trading_dates:
  439. # log.warning(f"找不到{future_code}的前一交易日数据")
  440. return minute_data
  441. previous_trading_date = max(previous_trading_dates)
  442. # log.debug(f"前一交易日: {previous_trading_date}")
  443. # 找到前一交易日21:00:00的数据作为开盘起点
  444. previous_day_data = minute_data[minute_data['date'] == previous_trading_date]
  445. night_21_data = previous_day_data[previous_day_data.index.hour == 21]
  446. if len(night_21_data) > 0:
  447. # 从前一交易日21:00开始的所有数据
  448. start_time = night_21_data.index[0] # 21:00:00的时间点
  449. filtered_data = minute_data[minute_data.index >= start_time]
  450. # log.debug(f"夜盘品种,从{start_time}开始,数据量: {len(filtered_data)}")
  451. return filtered_data.drop(columns=['date'])
  452. else:
  453. # log.warning(f"找不到{future_code}前一交易日21:00的数据")
  454. # 备选方案:使用今天9:00开始的数据
  455. today_data = minute_data[minute_data['date'] == today_date]
  456. day_9_data = today_data[today_data.index.hour >= 9]
  457. if len(day_9_data) > 0:
  458. return day_9_data.drop(columns=['date'])
  459. else:
  460. return minute_data.drop(columns=['date'])
  461. else:
  462. # 没有夜盘的品种:从今天9:00:00开始
  463. today_date = end_time.date()
  464. today_data = minute_data[minute_data['date'] == today_date]
  465. # 找到今天9:00:00开始的数据
  466. day_9_data = today_data[today_data.index.hour >= 9]
  467. if len(day_9_data) > 0:
  468. # log.debug(f"日盘品种,从今天9:00开始,数据量: {len(day_9_data)}")
  469. return day_9_data.drop(columns=['date'])
  470. else:
  471. # log.warning(f"找不到{future_code}今天9:00的数据")
  472. return today_data.drop(columns=['date']) if len(today_data) > 0 else minute_data.drop(columns=['date'])
  473. except Exception as e:
  474. log.warning(f"获取{future_code}今日分钟数据时出错: {str(e)}")
  475. return None
  476. def combine_and_calculate_ma(historical_data, minute_data):
  477. """合并历史数据和分钟数据,计算均线"""
  478. try:
  479. # 将分钟数据聚合为日数据
  480. today_data = aggregate_minute_to_daily(minute_data)
  481. if today_data is None:
  482. return None
  483. # 合并历史数据和今日数据
  484. combined_data = pd.concat([historical_data, today_data])
  485. # 计算移动平均线
  486. combined_data['MA5'] = combined_data['close'].rolling(window=5).mean()
  487. combined_data['MA10'] = combined_data['close'].rolling(window=10).mean()
  488. combined_data['MA20'] = combined_data['close'].rolling(window=20).mean()
  489. combined_data['MA30'] = combined_data['close'].rolling(window=30).mean()
  490. return combined_data
  491. except Exception as e:
  492. log.warning(f"合并数据和计算均线时出错: {str(e)}")
  493. return None
  494. def aggregate_minute_to_daily(minute_data):
  495. """将分钟数据聚合为日数据
  496. 注意:传入的minute_data已经是经过过滤的今日交易数据
  497. - 对于有夜盘的品种:数据从前一交易日21:00开始
  498. - 对于无夜盘的品种:数据从当日9:00开始
  499. 开盘价(open)是第一个分钟K线的开盘价(今日交易开盘价)
  500. 收盘价(close)是当前最新的分钟K线收盘价,会随时间更新
  501. """
  502. try:
  503. if minute_data is None or len(minute_data) == 0:
  504. return None
  505. # 获取今日日期(使用最后一条数据的日期作为今日日期)
  506. today_date = minute_data.index[-1].date()
  507. # log.debug(f"聚合数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
  508. # log.debug(f"开盘价数据: {minute_data['open'].iloc[0]:.2f}")
  509. # 聚合为日数据
  510. # 开盘价:今日交易开始时的第一个分钟K线的开盘价(固定不变)
  511. # 收盘价:当前最新分钟K线的收盘价(实时更新)
  512. # 最高价:所有分钟K线中的最高价
  513. # 最低价:所有分钟K线中的最低价
  514. # 成交量:所有分钟K线成交量的总和
  515. daily_data = pd.DataFrame({
  516. 'open': [minute_data['open'].iloc[0]], # 今日交易开始时的开盘价
  517. 'close': [minute_data['close'].iloc[-1]], # 当前收盘价,实时更新
  518. 'high': [minute_data['high'].max()],
  519. 'low': [minute_data['low'].min()],
  520. 'volume': [minute_data['volume'].sum()]
  521. }, index=[pd.Timestamp(today_date)])
  522. # log.debug(f"聚合后的日数据: 开盘价={daily_data['open'].iloc[0]:.2f}, 收盘价={daily_data['close'].iloc[0]:.2f}")
  523. return daily_data
  524. except Exception as e:
  525. log.warning(f"聚合分钟数据时出错: {str(e)}")
  526. return None
  527. ############################ 原有函数保持不变 ###################################
  528. def check_latest_multi_ma_cross(data, future_code):
  529. """检查最新的多均线穿越情况"""
  530. if len(data) < 2:
  531. return None
  532. # 获取最新两天的数据
  533. today = data.iloc[-1]
  534. yesterday = data.iloc[-2]
  535. # log.info(f"today: {today}")
  536. # log.info(f"yesterday: {yesterday}")
  537. # 检查多均线穿越
  538. cross_result = check_multi_ma_cross_single_day(today)
  539. if not cross_result:
  540. return None
  541. # TODO:验证穿越的有效性,暂时感觉没用先注释了
  542. # 验证穿越的有效性
  543. # if not validate_ma_cross(today, yesterday):
  544. # return None
  545. return {
  546. 'symbol': future_code,
  547. 'date': today.name,
  548. 'direction': cross_result['direction'],
  549. 'open': today['open'],
  550. 'close': today['close'],
  551. 'high': today['high'],
  552. 'low': today['low'],
  553. 'ma5': today['MA5'],
  554. 'ma10': today['MA10'],
  555. 'ma20': today['MA20'],
  556. 'ma30': today['MA30'],
  557. 'critical_ma_name': cross_result['critical_ma_name'],
  558. 'critical_ma_value': cross_result['critical_ma_value'],
  559. 'crossed_count': cross_result['crossed_count']
  560. }
  561. def check_multi_ma_cross_single_day(row):
  562. """检查单日K线是否穿越了至少3条均线,并返回临界线信息"""
  563. open_price = row['open']
  564. close_price = row['close']
  565. ma_values = [('MA5', row['MA5']), ('MA10', row['MA10']), ('MA20', row['MA20']), ('MA30', row['MA30'])]
  566. log.debug(f"open_price: {open_price}, close_price: {close_price}, ma_values: {ma_values}")
  567. # 检查是否有NaN值
  568. if pd.isna(row['MA5']) or pd.isna(row['MA10']) or pd.isna(row['MA20']) or pd.isna(row['MA30']):
  569. return None
  570. # 如果开盘价和收盘价相等,不可能有穿越
  571. if open_price == close_price:
  572. return None
  573. crossed_mas = []
  574. # 上涨(阳线),检查上穿
  575. if close_price > open_price:
  576. for ma_name, ma_value in ma_values:
  577. if open_price < ma_value and close_price > ma_value:
  578. crossed_mas.append((ma_name, ma_value))
  579. if len(crossed_mas) >= g.min_cross_mas:
  580. # 找到最大的穿越线作为临界线
  581. critical_ma = max(crossed_mas, key=lambda x: x[1])
  582. return {
  583. 'direction': 'up',
  584. 'critical_ma_name': critical_ma[0],
  585. 'critical_ma_value': critical_ma[1],
  586. 'crossed_count': len(crossed_mas)
  587. }
  588. # 下跌(阴线),检查下穿
  589. elif open_price > close_price:
  590. for ma_name, ma_value in ma_values:
  591. if open_price > ma_value and close_price < ma_value:
  592. crossed_mas.append((ma_name, ma_value))
  593. if len(crossed_mas) >= g.min_cross_mas:
  594. # 找到最小的穿越线作为临界线
  595. critical_ma = min(crossed_mas, key=lambda x: x[1])
  596. return {
  597. 'direction': 'down',
  598. 'critical_ma_name': critical_ma[0],
  599. 'critical_ma_value': critical_ma[1],
  600. 'crossed_count': len(crossed_mas)
  601. }
  602. return None
  603. def validate_ma_cross(today, yesterday):
  604. """验证均线穿越的有效性"""
  605. # 检查均线排列是否合理
  606. ma_today = [today['MA5'], today['MA10'], today['MA20'], today['MA30']]
  607. ma_yesterday = [yesterday['MA5'], yesterday['MA10'], yesterday['MA20'], yesterday['MA30']]
  608. # 简单的均线排列检查
  609. # 可以根据需要添加更复杂的验证逻辑
  610. return True
  611. def check_sufficient_capital(context, symbol):
  612. """检查资金是否充足"""
  613. try:
  614. # 计算单手保证金
  615. single_hand_margin = calculate_required_margin(context, symbol)
  616. # 使用实际可用资金(考虑资金使用比例)
  617. available_cash = context.portfolio.available_cash * g.usage_percentage
  618. # 检查是否有足够资金开仓至少1手
  619. return available_cash >= single_hand_margin
  620. except:
  621. return False
  622. def check_price_position(signal):
  623. """检查价格位置的合理性"""
  624. close = signal['close']
  625. critical_ma_value = signal['critical_ma_value']
  626. # 检查收盘价与临界线的偏离度
  627. deviation = abs(close - critical_ma_value) / critical_ma_value
  628. # 偏离度需要在合理范围内:大于最小偏离度且小于最大偏离度
  629. if deviation < g.price_deviation_min:
  630. log.warning(f"价格偏离度过小: {deviation:.3%} < {g.price_deviation_min:.1%}")
  631. return False
  632. elif deviation > g.price_deviation_max:
  633. log.warning(f"价格偏离度过大: {deviation:.3%} > {g.price_deviation_max:.1%}")
  634. return False
  635. else:
  636. log.info(f"价格偏离度合理: {g.price_deviation_min:.1%} <= {deviation:.3%} <= {g.price_deviation_max:.1%}")
  637. return True
  638. ############################ 交易执行函数 ###################################
  639. def open_position(context, security, value, direction, signal):
  640. """开仓"""
  641. try:
  642. # 记录交易前的可用资金
  643. cash_before = context.portfolio.available_cash
  644. order = order_target_value(security, value, side=direction)
  645. log.info(f"order: {order}")
  646. if order is not None and order.filled > 0:
  647. # 记录交易后的可用资金
  648. cash_after = context.portfolio.available_cash
  649. # 计算实际资金变化
  650. cash_change = cash_before - cash_after
  651. # 获取订单价格和数量
  652. order_price = order.avg_cost if order.avg_cost else order.price
  653. order_amount = order.filled
  654. # 计算实际保证金比例
  655. underlying_symbol = security.split('.')[0][:-4]
  656. multiplier = g.multiplier.get(underlying_symbol, 10)
  657. # 单笔保证金 = 资金变化 / 数量
  658. single_margin = cash_change / order_amount if order_amount > 0 else 0
  659. # 实际保证金比例 = 单笔保证金 / (订单价格 * 合约乘数)
  660. contract_value = order_price * multiplier
  661. actual_margin_rate = single_margin / contract_value if contract_value > 0 else 0
  662. # 校准保证金比例(只有变化大于1%时才更新)
  663. current_rate = g.margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
  664. rate_change = abs(actual_margin_rate - current_rate) / current_rate if current_rate > 0 else 0
  665. if rate_change > 0.01: # 变化大于1%
  666. # 记录保证金比例变化历史
  667. history_key = f"{underlying_symbol}_{direction}"
  668. if history_key not in g.margin_rate_history:
  669. g.margin_rate_history[history_key] = []
  670. g.margin_rate_history[history_key].append({
  671. 'date': context.current_dt.date(),
  672. 'time': context.current_dt.time(),
  673. 'old_rate': current_rate,
  674. 'new_rate': actual_margin_rate,
  675. 'change_pct': rate_change * 100,
  676. 'security': security
  677. })
  678. # 直接更新默认保证金比例
  679. g.margin_rates[direction][underlying_symbol] = actual_margin_rate
  680. log.info(f"保证金比例校准: {underlying_symbol}_{direction} {current_rate:.4f} -> {actual_margin_rate:.4f} (变化{rate_change*100:.1f}%)")
  681. # 记录当日交易
  682. g.today_trades.append({
  683. 'security': security,
  684. 'underlying_symbol': underlying_symbol,
  685. 'direction': direction,
  686. 'order_amount': order_amount,
  687. 'order_price': order_price,
  688. 'cash_change': cash_change,
  689. 'actual_margin_rate': actual_margin_rate,
  690. 'time': context.current_dt
  691. })
  692. # 记录交易信息
  693. g.trade_history[security] = {
  694. 'entry_price': order_price,
  695. 'position_value': value,
  696. 'actual_margin': cash_change,
  697. 'direction': direction,
  698. 'entry_time': context.current_dt,
  699. 'signal_info': signal
  700. }
  701. log.info(f"开仓成功 - 品种: {underlying_symbol}, 手数: {order_amount}, 订单价格: {order_price:.2f}")
  702. log.info(f"资金变化: {cash_change:.0f}, 实际保证金比例: {actual_margin_rate:.4f}")
  703. return True
  704. except Exception as e:
  705. log.warning(f"开仓失败 {security}: {str(e)}")
  706. return False
  707. def close_position(context, security, direction):
  708. """平仓"""
  709. try:
  710. order = order_target_value(security, 0, side=direction)
  711. if order is not None and order.filled > 0:
  712. underlying_symbol = security.split('.')[0][:-4]
  713. # 记录当日交易(平仓)
  714. g.today_trades.append({
  715. 'security': security,
  716. 'underlying_symbol': underlying_symbol,
  717. 'direction': direction,
  718. 'order_amount': -order.filled, # 负数表示平仓
  719. 'order_price': order.avg_cost if order.avg_cost else order.price,
  720. 'cash_change': 0, # 平仓不计算保证金变化
  721. 'actual_margin_rate': 0,
  722. 'time': context.current_dt
  723. })
  724. log.info(f"平仓成功 - 品种: {underlying_symbol}, 手数: {order.filled}")
  725. # 从交易历史中移除
  726. if security in g.trade_history:
  727. del g.trade_history[security]
  728. return True
  729. except Exception as e:
  730. log.warning(f"平仓失败 {security}: {str(e)}")
  731. return False
  732. def check_stop_loss_profit(context, position):
  733. """检查止损止盈"""
  734. security = position.security
  735. if security not in g.trade_history:
  736. return False
  737. trade_info = g.trade_history[security]
  738. entry_price = trade_info['entry_price']
  739. current_price = position.price
  740. direction = trade_info['direction']
  741. # 计算盈亏
  742. if direction == 'long':
  743. pnl_ratio = (current_price - entry_price) / entry_price
  744. else:
  745. pnl_ratio = (entry_price - current_price) / entry_price
  746. # 止损条件
  747. stop_loss_ratio = -0.03 # 3%止损
  748. # 止盈条件
  749. take_profit_ratio = 0.05 # 5%止盈
  750. if pnl_ratio <= stop_loss_ratio:
  751. log.info(f"触发止损 {security} 盈亏比例: {pnl_ratio:.2%}")
  752. close_position(context, security, direction)
  753. return True
  754. elif pnl_ratio >= take_profit_ratio:
  755. log.info(f"触发止盈 {security} 盈亏比例: {pnl_ratio:.2%}")
  756. close_position(context, security, direction)
  757. return True
  758. return False
  759. ############################ 辅助函数 ###################################
  760. def calculate_order_value(context, security, direction):
  761. """计算开仓金额"""
  762. current_price = get_current_data()[security].last_price
  763. underlying_symbol = security.split('.')[0][:-4]
  764. # 使用保证金比例(已经过校准)
  765. margin_rate = g.margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
  766. multiplier = g.multiplier.get(underlying_symbol, 10)
  767. # 计算单手保证金
  768. single_hand_margin = current_price * multiplier * margin_rate
  769. # 还要考虑可用资金限制
  770. available_cash = context.portfolio.available_cash * g.usage_percentage
  771. log.info(f"可用资金: {available_cash:.0f}")
  772. # 根据单个标的最大持仓保证金限制计算开仓数量
  773. max_margin = g.max_margin_per_position
  774. if single_hand_margin <= max_margin:
  775. # 如果单手保证金不超过最大限制,计算最大可开仓手数
  776. max_hands = int(max_margin / single_hand_margin)
  777. max_hands_by_cash = int(available_cash / single_hand_margin)
  778. # 取两者较小值
  779. actual_hands = min(max_hands, max_hands_by_cash)
  780. # 实际保证金金额
  781. actual_margin = current_price * multiplier * margin_rate * actual_hands
  782. # 计算订单金额
  783. order_value = actual_margin
  784. log.info(f"单手保证金: {single_hand_margin:.0f}, 最大手数(保证金限制): {max_hands}, 最大手数(资金限制): {max_hands_by_cash}, 实际开仓手数: {actual_hands}, 实际保证金: {actual_margin:.0f}")
  785. else:
  786. # 如果单手保证金超过最大限制,默认开仓1手
  787. actual_hands = 1
  788. actual_margin = current_price * multiplier * margin_rate * actual_hands
  789. # 计算订单金额
  790. order_value = actual_margin
  791. log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手, 实际保证金: {actual_margin:.0f}")
  792. log.info(f"计算结果 - 品种: {underlying_symbol}, 开仓手数: {actual_hands}, 订单金额: {order_value:.0f}, 实际保证金: {actual_margin:.0f}")
  793. return order_value
  794. def calculate_required_margin(context, symbol):
  795. """计算所需保证金"""
  796. current_price = get_current_data()[symbol].last_price
  797. underlying_symbol = symbol.split('.')[0][:-4]
  798. margin_rate = g.margin_rates.get('long', {}).get(underlying_symbol, 0.10)
  799. multiplier = g.multiplier.get(underlying_symbol, 10)
  800. return current_price * multiplier * margin_rate
  801. def check_symbol_prefix_match(symbol, hold_symbols):
  802. """检查是否有相似的持仓品种"""
  803. symbol_prefix = symbol[:-9]
  804. for hold_symbol in hold_symbols:
  805. hold_symbol_prefix = hold_symbol[:-9]
  806. if symbol_prefix == hold_symbol_prefix:
  807. return True
  808. return False
  809. def after_market_close(context):
  810. """收盘后运行函数"""
  811. log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
  812. # 只有当天有交易时才打印统计信息
  813. if g.today_trades:
  814. print_daily_trading_summary(context)
  815. print_margin_rate_changes(context)
  816. # 清空当日交易记录
  817. g.today_trades = []
  818. log.info('A day ends')
  819. log.info('##############################################################')
  820. def print_daily_trading_summary(context):
  821. """打印当日交易汇总"""
  822. if not g.today_trades:
  823. return
  824. log.info("\n=== 当日交易汇总 ===")
  825. total_margin = 0
  826. for trade in g.today_trades:
  827. if trade['order_amount'] > 0: # 开仓
  828. log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
  829. f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f} "
  830. f"比例:{trade['actual_margin_rate']:.4f}")
  831. total_margin += trade['cash_change']
  832. else: # 平仓
  833. log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
  834. f"价格:{trade['order_price']:.2f}")
  835. log.info(f"当日保证金占用: {total_margin:.0f}")
  836. log.info("==================\n")
  837. def print_margin_rate_changes(context):
  838. """打印保证金比例变化记录"""
  839. if not g.margin_rate_history:
  840. return
  841. log.info("\n=== 保证金比例变化记录 ===")
  842. for key, history in g.margin_rate_history.items():
  843. log.info(f"{key}:")
  844. for record in history:
  845. log.info(f" {record['date']} {record['time']}: {record['old_rate']:.4f} -> {record['new_rate']:.4f} "
  846. f"(变化{record['change_pct']:.1f}%)")
  847. log.info("========================\n")
  848. ########################## 自动移仓换月函数 #################################
  849. def position_auto_switch(context,pindex=0,switch_func=None, callback=None):
  850. """
  851. 期货自动移仓换月。默认使用市价单进行开平仓。
  852. :param context: 上下文对象
  853. :param pindex: 子仓对象
  854. :param switch_func: 用户自定义的移仓换月函数.
  855. 函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
  856. :param callback: 移仓换月完成后的回调函数。
  857. 函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
  858. :return: 发生移仓换月的标的。类型为列表。
  859. """
  860. import re
  861. subportfolio = context.subportfolios[pindex]
  862. symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
  863. switch_result = []
  864. for symbol in symbols:
  865. match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
  866. if not match:
  867. # raise ValueError("未知期货标的: {}".format(symbol))
  868. raise ValueError("Unknow target: {}".format(symbol))
  869. else:
  870. dominant = get_dominant_future(match.groupdict()["underlying_symbol"])
  871. cur = get_current_data()
  872. symbol_last_price = cur[symbol].last_price
  873. dominant_last_price = cur[dominant].last_price
  874. log.info(f'current_hold_symbol: {symbol}, current_main_symbol: {dominant}')
  875. if dominant > symbol:
  876. for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
  877. if symbol not in positions_.keys():
  878. continue
  879. else :
  880. p = positions_[symbol]
  881. if switch_func is not None:
  882. switch_func(context, pindex, p, dominant)
  883. else:
  884. amount = p.total_amount
  885. # 跌停不能开空和平多,涨停不能开多和平空。
  886. if p.side == "long":
  887. symbol_low_limit = cur[symbol].low_limit
  888. dominant_high_limit = cur[dominant].high_limit
  889. if symbol_last_price <= symbol_low_limit:
  890. # log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
  891. log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
  892. continue
  893. elif dominant_last_price >= dominant_high_limit:
  894. # log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(symbol))
  895. log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
  896. continue
  897. else:
  898. # log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
  899. log.info("Start the exchange: ({0},long) -> ({1},long)".format(symbol, dominant))
  900. order_old = order_target(symbol,0,side='long')
  901. if order_old != None and order_old.filled > 0:
  902. order_new = order_target(dominant,amount,side='long')
  903. if order_new != None and order_new.filled >0:
  904. switch_result.append({"before": symbol, "after":dominant, "side": "long"})
  905. # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
  906. g.trade_history[dominant] = g.trade_history[symbol]
  907. del g.trade_history[symbol]
  908. else:
  909. # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(domaint))
  910. log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
  911. # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
  912. log.warning(f'换月多头失败{dominant}, {g.trade_history[symbol]}')
  913. g.change_fail_history[domaint] = g.trade_history[symbol]
  914. del g.trade_history[symbol]
  915. if callback:
  916. callback(context, pindex, p, dominant)
  917. if p.side == "short":
  918. symbol_high_limit = cur[symbol].high_limit
  919. dominant_low_limit = cur[dominant].low_limit
  920. if symbol_last_price >= symbol_high_limit:
  921. # log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
  922. log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
  923. continue
  924. elif dominant_last_price <= dominant_low_limit:
  925. # log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(symbol))
  926. log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
  927. continue
  928. else:
  929. # log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
  930. log.info("Start the exchange: ({0},short) -> ({1},short)".format(symbol, dominant))
  931. order_old = order_target(symbol,0,side='short')
  932. if order_old != None and order_old.filled > 0:
  933. log.info(f'换月做空{dominant},数量位{amount}')
  934. order_new = order_target(dominant,amount,side='short')
  935. if order_new != None and order_new.filled >0:
  936. switch_result.append({"before": symbol, "after":dominant, "side": "short"})
  937. # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
  938. g.trade_history[dominant] = g.trade_history[symbol]
  939. del g.trade_history[symbol]
  940. else:
  941. # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(dominant))
  942. log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
  943. # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
  944. log.warning(f'换月空头失败{dominant}, {g.trade_history[symbol]}')
  945. g.change_fail_history[dominant] = g.trade_history[symbol]
  946. log.warning(f'失败记录{g.change_fail_history}')
  947. del g.trade_history[symbol]
  948. # order_target(symbol,0,side='short')
  949. # order_target(dominant,amount,side='short')
  950. # switch_result.append({"before": symbol, "after": dominant, "side": "short"})
  951. if callback:
  952. callback(context, pindex, p, dominant)
  953. return switch_result
  954. def count_ma_crosses(data, days):
  955. """
  956. 判断过去指定天数内4条MA均线的交叉次数
  957. :param data: 包含MA5, MA10, MA20, MA30的DataFrame
  958. :param days: 检查的天数
  959. :return: 总交叉次数
  960. """
  961. if len(data) < days + 1:
  962. return 0
  963. # 获取最近days天的数据
  964. recent_data = data.iloc[-days-1:]
  965. ma5 = recent_data['MA5'].values
  966. ma10 = recent_data['MA10'].values
  967. ma20 = recent_data['MA20'].values
  968. ma30 = recent_data['MA30'].values
  969. # 检查是否有NaN值
  970. if np.any(np.isnan([ma5, ma10, ma20, ma30])):
  971. return 0
  972. # 计算各均线间的交叉次数
  973. 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
  974. (ma5[i] < ma10[i] and ma5[i-1] > ma10[i-1]))])
  975. 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
  976. (ma5[i] < ma20[i] and ma5[i-1] > ma20[i-1]))])
  977. 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
  978. (ma5[i] < ma30[i] and ma5[i-1] > ma30[i-1]))])
  979. 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
  980. (ma10[i] < ma20[i] and ma10[i-1] > ma20[i-1]))])
  981. 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
  982. (ma10[i] < ma30[i] and ma10[i-1] > ma30[i-1]))])
  983. 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
  984. (ma20[i] < ma30[i] and ma20[i-1] > ma30[i-1]))])
  985. total_crosses = cross_5_10 + cross_5_20 + cross_5_30 + cross_10_20 + cross_10_30 + cross_20_30
  986. 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}')
  987. return total_crosses