future_grid_trading_analysis2.py 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667
  1. """
  2. 期货网格交易研究分析工具(带主力合约切换)
  3. 研究期货网格交易策略在不同配置下的表现,支持多种交易场景的对比分析
  4. 核心功能包括主力合约自动切换、强制平仓和重新建仓逻辑
  5. 本程序实现完整的网格交易分析流程:
  6. 1. 主力合约监控与切换 - 自动检测主力合约变化并处理切换
  7. 2. 合约选择逻辑 - 基于主力合约选择算法
  8. 3. 基础头寸交易 - 价格-数量网格配置,支持合约切换时重新建仓
  9. 4. 网格交易策略 - 限价订单网格买入卖出,合约切换时根据价格条件重新建仓
  10. 5. 统计分析对比 - 多种交易场景性能分析
  11. 主要特点:
  12. - 主力合约自动监控:每日检测主力合约变化
  13. - 强制平仓机制:合约切换时立即平掉旧合约所有头寸
  14. - 智能重新建仓:根据价格条件在新合约中重新建立头寸
  15. - 标准期货盈亏计算:使用正确的合约倍数和期货盈亏公式
  16. - 最终持仓结算:分析期结束时对所有未平仓头寸进行市值计价
  17. - 完整交易记录:记录所有交易包括合约切换引起的强制平仓
  18. 期货盈亏计算公式:
  19. - 多头:(出场价格 - 入场价格) × 合约倍数 × 数量
  20. - 空头:(入场价格 - 出场价格) × 合约倍数 × 数量
  21. 注:程序支持多个核心商品同时分析,生成详细的交易记录和统计报告
  22. 作者: jukuan研究团队
  23. 日期: 2025-09
  24. 适用平台: 聚宽在线研究平台
  25. """
  26. import pandas as pd
  27. import numpy as np
  28. from jqdata import *
  29. import datetime
  30. import warnings
  31. warnings.filterwarnings('ignore')
  32. # =====================================================================================
  33. # 分析配置参数 - 集中配置部分
  34. # =====================================================================================
  35. class GridTradingConfig:
  36. """期货网格交易分析配置参数"""
  37. # ==================== 时间范围设置 ====================
  38. START_DATE = datetime.datetime(2024, 11, 7) # 分析开始日期
  39. END_DATE = datetime.datetime(2025, 9, 19) # 分析结束日期(修正为9月19日避免数据缺失)
  40. # ==================== 期货合约倍数配置 ====================
  41. FUTURES_MULTIPLIER = {
  42. # 贵金属
  43. 'AU': 1000, # 黄金
  44. 'AG': 15, # 白银
  45. # 有色金属
  46. 'CU': 5, 'AL': 5, 'ZN': 5, 'PB': 5, 'NI': 1, 'SN': 1, 'SS': 5,
  47. # 黑色系
  48. 'RB': 10, 'HC': 10, 'I': 100, 'JM': 100, 'J': 60,
  49. # 能源化工
  50. 'SP': 10, 'FU': 10, 'BU': 10, 'RU': 10, 'BR': 5, 'SC': 1000,
  51. 'NR': 10, 'LU': 10, 'LC': 1,
  52. # 化工
  53. 'FG': 20, 'TA': 5, 'MA': 10, 'SA': 20, 'L': 5, 'V': 5, 'EG': 10,
  54. 'PP': 5, 'EB': 5, 'PG': 20, 'UR': 20,
  55. # 农产品
  56. 'RM': 10, 'OI': 10, 'CF': 5, 'SR': 10, 'PF': 5, 'C': 10, 'CS': 10,
  57. 'CY': 5, 'A': 10, 'B': 10, 'M': 10, 'Y': 10, 'P': 10,
  58. # 股指期货
  59. 'IF': 300, 'IH': 300, 'IC': 200, 'IM': 200, 'TL': 10000,
  60. # 其他
  61. 'AP': 10, 'CJ': 5, 'PK': 5, 'JD': 10, 'LH': 16
  62. }
  63. # ==================== 核心商品配置 ====================
  64. CORE_COMMODITIES = {
  65. # 'SA': ['SA2501.XZCE', 'SA2505.XZCE', 'SA2509.XZCE', 'SA2601.XZCE'], # 纯碱
  66. # 'M': ['M2501.XDCE', 'M2505.XDCE', 'M2509.XDCE', 'M2605.XDCE'], # 豆粕
  67. 'UR': ['UR2501.XZCE', 'UR2505.XZCE', 'UR2509.XZCE', 'UR2601.XZCE'], # 尿素
  68. # 'LH': ['LH2501.XDCE', 'LH2505.XDCE', 'LH2509.XDCE', 'LH2601.XDCE'], # 生猪
  69. # 'TL': ['TL2503.CCFX', 'TL2506.CCFX', 'TL2509.CCFX', 'TL2512.CCFX'] # 30年期国债
  70. }
  71. # ==================== 合约切换配置 ====================
  72. REQUIRED_TRADING_DAYS = 30 # 合约切换前需要的最少有效交易日数
  73. # ==================== 基础头寸交易配置 ====================
  74. BASE_POSITION_GRID = {
  75. 'SA': {1400: 4, 1300: 6, 1200: 8, 1100: 12, 1000: 14, 900: 16},
  76. 'M': {2800: 4, 2750: 6, 2700: 8, 2650: 12, 2600: 14, 2550: 16},
  77. 'UR': {1750: 4, 1700: 6, 1650: 8, 1600: 12, 1550: 14, 1500: 16},
  78. 'LH': {13000: 1, 12500: 1, 12000: 1, 11500: 1, 11000: 2},
  79. 'TL': {118: 1, 117: 1, 116: 1, 115: 1, 114: 2, 113: 2},
  80. }
  81. # 统一退出价格(无止损)
  82. BASE_POSITION_EXIT_PRICE = {
  83. 'SA': 1500,
  84. 'M': 3800,
  85. 'UR': 2400,
  86. 'LH': 20000,
  87. 'TL': 121,
  88. }
  89. # ==================== 网格交易配置 ====================
  90. GRID_TRADING_CONFIG = {
  91. 'SA': {
  92. 'start_price': 1250, # 开始价格
  93. 'grid_size': 50, # 网格大小
  94. 'quantity_per_grid': 5, # 每网格数量
  95. 'exit_grid_size': 50 # 退出网格大小
  96. },
  97. 'M': {
  98. 'start_price': 2800,
  99. 'grid_size': 100,
  100. 'quantity_per_grid': 10,
  101. 'exit_grid_size': 100
  102. },
  103. 'UR': {
  104. 'start_price': 1800,
  105. 'grid_size': 50,
  106. 'quantity_per_grid': 10,
  107. 'exit_grid_size': 50
  108. },
  109. 'LH': {
  110. 'start_price': 13500,
  111. 'grid_size': 500,
  112. 'quantity_per_grid': 1,
  113. 'exit_grid_size': 500
  114. },
  115. 'TL': {
  116. 'start_price': 118,
  117. 'grid_size': 1,
  118. 'quantity_per_grid': 1,
  119. 'exit_grid_size': 1
  120. },
  121. }
  122. # ==================== 输出设置 ====================
  123. OUTPUT_ENCODING = 'utf-8-sig' # 输出文件编码格式
  124. VERBOSE_LOGGING = True # 是否打印详细日志
  125. @classmethod
  126. def print_config(cls):
  127. """打印当前配置信息"""
  128. print("=== 期货网格交易分析配置 ===")
  129. print(f"分析时间范围: {cls.START_DATE.strftime('%Y-%m-%d')} 至 {cls.END_DATE.strftime('%Y-%m-%d')}")
  130. print(f"核心商品数量: {len(cls.CORE_COMMODITIES)}")
  131. print("核心商品列表:")
  132. for commodity, contracts in cls.CORE_COMMODITIES.items():
  133. print(f" {commodity}: {contracts}")
  134. print(f"\n网格交易配置:")
  135. for commodity, config in cls.GRID_TRADING_CONFIG.items():
  136. print(f" {commodity}: 起始价{config['start_price']}, 网格大小{config['grid_size']}")
  137. print(f"详细日志: {'开启' if cls.VERBOSE_LOGGING else '关闭'}")
  138. print("=" * 50)
  139. class FutureGridTradingAnalyzer:
  140. """期货网格交易分析器"""
  141. def __init__(self, config=None):
  142. """初始化分析器"""
  143. if config is None:
  144. config = GridTradingConfig
  145. self.config = config
  146. self.start_date = config.START_DATE
  147. self.end_date = config.END_DATE
  148. self.core_commodities = config.CORE_COMMODITIES
  149. self.base_position_grid = config.BASE_POSITION_GRID
  150. self.base_position_exit_price = config.BASE_POSITION_EXIT_PRICE
  151. self.grid_trading_config = config.GRID_TRADING_CONFIG
  152. self.verbose_logging = config.VERBOSE_LOGGING
  153. self.output_encoding = config.OUTPUT_ENCODING
  154. # 存储结果的字典
  155. self.selected_contracts = {} # 选中的合约
  156. self.price_data = {} # 价格数据
  157. self.dominant_contract_history = {} # 主力合约历史变化
  158. self.active_positions = { # 当前活跃头寸跟踪
  159. 'base_position': {},
  160. 'grid_trading': {}
  161. }
  162. self.trading_results = { # 交易场景的结果
  163. 'base_position': [],
  164. 'grid_trading': []
  165. }
  166. if self.verbose_logging:
  167. print("初始化期货网格交易分析器")
  168. print(f"核心商品: {list(self.core_commodities.keys())}")
  169. print(f"分析期间: {self.start_date.strftime('%Y-%m-%d')} - {self.end_date.strftime('%Y-%m-%d')}")
  170. def select_contracts(self):
  171. """
  172. 合约选择逻辑
  173. 1. 首先获取商品的主导合约
  174. 2. 如果主导合约在可用列表中,选择它
  175. 3. 如果主导合约不在列表中,选择未来到期日期最近且晚于主导合约的合约
  176. """
  177. if self.verbose_logging:
  178. print("\n=== 步骤1: 合约选择逻辑 ===")
  179. for commodity, available_contracts in self.core_commodities.items():
  180. if self.verbose_logging:
  181. print(f"\n处理商品: {commodity}")
  182. print(f"可用合约: {available_contracts}")
  183. try:
  184. # 获取商品的主导合约
  185. dominant_contract = get_dominant_future(commodity, self.start_date.date())
  186. if self.verbose_logging:
  187. print(f"主导合约: {dominant_contract}")
  188. if dominant_contract in available_contracts:
  189. # 主导合约在可用列表中,直接选择
  190. selected_contract = dominant_contract
  191. if self.verbose_logging:
  192. print(f"选择主导合约: {selected_contract}")
  193. else:
  194. # 主导合约不在列表中,选择最近的未来合约
  195. selected_contract = self._select_nearest_future_contract(
  196. commodity, dominant_contract, available_contracts
  197. )
  198. if self.verbose_logging:
  199. print(f"选择最近的未来合约: {selected_contract}")
  200. self.selected_contracts[commodity] = selected_contract
  201. except Exception as e:
  202. if self.verbose_logging:
  203. print(f"获取{commodity}主导合约失败: {str(e)}")
  204. # 默认选择第一个可用合约
  205. self.selected_contracts[commodity] = available_contracts[0]
  206. if self.verbose_logging:
  207. print(f"默认选择第一个合约: {available_contracts[0]}")
  208. if self.verbose_logging:
  209. print(f"\n合约选择完成,共选择{len(self.selected_contracts)}个合约")
  210. for commodity, contract in self.selected_contracts.items():
  211. print(f" {commodity}: {contract}")
  212. return self.selected_contracts
  213. def _select_nearest_future_contract(self, commodity, dominant_contract, available_contracts):
  214. """选择最近的未来到期合约"""
  215. if not dominant_contract:
  216. return available_contracts[0]
  217. # 解析主导合约的到期月份
  218. try:
  219. # 提取合约代码中的月份信息 (例如 SA2507 -> 2507)
  220. dominant_year_month = dominant_contract.split('.')[0][-4:] # 取最后4位
  221. dominant_year = int(dominant_year_month[:2]) + 2000 # 假设是21世纪
  222. dominant_month = int(dominant_year_month[2:])
  223. except:
  224. return available_contracts[0]
  225. # 找到最近的未来合约
  226. best_contract = available_contracts[0]
  227. best_diff = float('inf')
  228. for contract in available_contracts:
  229. try:
  230. contract_year_month = contract.split('.')[0][-4:]
  231. contract_year = int(contract_year_month[:2]) + 2000
  232. contract_month = int(contract_year_month[2:])
  233. # 计算月份差异
  234. contract_total_months = contract_year * 12 + contract_month
  235. dominant_total_months = dominant_year * 12 + dominant_month
  236. # 只选择晚于主导合约的合约
  237. if contract_total_months > dominant_total_months:
  238. diff = contract_total_months - dominant_total_months
  239. if diff < best_diff:
  240. best_diff = diff
  241. best_contract = contract
  242. except:
  243. continue
  244. return best_contract
  245. def _get_futures_multiplier(self, commodity):
  246. """获取期货合约倍数"""
  247. return self.config.FUTURES_MULTIPLIER.get(commodity, 10) # 默认倍数为10
  248. def _calculate_futures_pnl(self, entry_price, exit_price, quantity, commodity, is_long=True):
  249. """
  250. 计算期货盈亏
  251. 参数:
  252. entry_price: 入场价格
  253. exit_price: 出场价格
  254. quantity: 数量(手数)
  255. commodity: 商品代码
  256. is_long: 是否多头,True为多头,False为空头
  257. 返回:
  258. 实际盈亏金额
  259. """
  260. multiplier = self._get_futures_multiplier(commodity)
  261. if is_long:
  262. # 多头:(出场价格 - 入场价格) × 合约倍数 × 数量
  263. pnl = (exit_price - entry_price) * multiplier * quantity
  264. else:
  265. # 空头:(入场价格 - 出场价格) × 合约倍数 × 数量
  266. pnl = (entry_price - exit_price) * multiplier * quantity
  267. return pnl
  268. def build_dominant_contract_history(self):
  269. """
  270. 构建主力合约历史变化记录
  271. 为每个商品在整个分析期间构建主力合约变化的时间序列
  272. 只有当合约真正发生变化时才记录为合约切换
  273. """
  274. if self.verbose_logging:
  275. print("\n=== 步骤2:构建主力合约历史变化记录 ===")
  276. for commodity in self.core_commodities.keys():
  277. if self.verbose_logging:
  278. print(f"构建 {commodity} 主力合约历史...")
  279. contract_history = []
  280. current_date = self.start_date.date()
  281. end_date = self.end_date.date()
  282. current_selected_contract = None # 跟踪选择的合约而不是主力合约
  283. while current_date <= end_date:
  284. # 跳过非交易日
  285. if current_date.weekday() >= 5: # 周六周日
  286. current_date += datetime.timedelta(days=1)
  287. continue
  288. try:
  289. # 获取当日主力合约
  290. dominant_contract = get_dominant_future(commodity, current_date)
  291. # print(f"日期: {current_date}, 主力合约: {dominant_contract}")
  292. selected_contract = self._match_to_available_contract(commodity, dominant_contract)
  293. # 只有当选择的合约真正发生变化时才记录
  294. if selected_contract != current_selected_contract:
  295. contract_history.append({
  296. 'date': current_date,
  297. 'dominant_contract': dominant_contract,
  298. 'selected_contract': selected_contract,
  299. 'is_initial': current_selected_contract is None # 标记是否为初始合约
  300. })
  301. if self.verbose_logging:
  302. if current_selected_contract is None:
  303. print(f" {current_date}: 初始合约设置为 {selected_contract}")
  304. else:
  305. print(f" {current_date}: 合约切换 {current_selected_contract} -> {selected_contract}")
  306. current_selected_contract = selected_contract
  307. except Exception as e:
  308. if self.verbose_logging:
  309. print(f" 获取 {current_date} 的主力合约时出错: {str(e)}")
  310. current_date += datetime.timedelta(days=1)
  311. self.dominant_contract_history[commodity] = contract_history
  312. if self.verbose_logging:
  313. total_changes = sum(len(history) for history in self.dominant_contract_history.values())
  314. actual_switches = sum(
  315. sum(1 for change in history if not change.get('is_initial', False))
  316. for history in self.dominant_contract_history.values()
  317. )
  318. initial_setups = total_changes - actual_switches
  319. print(f"主力合约历史构建完成,共 {total_changes} 次记录({initial_setups} 次初始设置,{actual_switches} 次真实切换)")
  320. return self.dominant_contract_history
  321. def _match_to_available_contract(self, commodity, dominant_contract):
  322. """将主力合约匹配到可用合约列表"""
  323. available_contracts = self.core_commodities.get(commodity, [])
  324. if dominant_contract in available_contracts:
  325. return dominant_contract
  326. else:
  327. return self._select_nearest_future_contract(commodity, dominant_contract, available_contracts)
  328. def collect_price_data(self):
  329. """收集所有可能用到的合约价格数据(优化日期范围)"""
  330. if self.verbose_logging:
  331. print("\n=== 步骤3: 收集价格数据(优化日期范围) ===")
  332. # 清除之前的调整建议
  333. if hasattr(self, 'adjustment_suggestions'):
  334. self.adjustment_suggestions = []
  335. # 为每个商品创建数据存储结构
  336. for commodity in self.core_commodities.keys():
  337. print(f'收集{commodity}的价格数据:')
  338. self.price_data[commodity] = {}
  339. # 根据主力合约历史确定每个合约的数据获取范围
  340. contract_date_ranges = self._determine_contract_date_ranges(commodity)
  341. for contract, date_range in contract_date_ranges.items():
  342. start_date, end_date = date_range
  343. if self.verbose_logging:
  344. print(f"获取 {contract} 价格数据...")
  345. print(f" 优化日期范围: {start_date} 至 {end_date}")
  346. try:
  347. # 获取价格数据(使用优化的日期范围)
  348. data = get_price(
  349. contract,
  350. start_date=start_date,
  351. end_date=end_date,
  352. frequency='daily',
  353. fields=['open', 'close', 'high', 'low', 'volume'],
  354. skip_paused=False,
  355. panel=False
  356. )
  357. if data is not None and len(data) > 0:
  358. # print(f"第一条有数据的日期是: {data.index[0].date()},数据是: {data.iloc[0]}")
  359. # print(f"最后一条有数据的日期是: {data.index[-1].date()}, 数据是: {data.iloc[-1]}")
  360. self.price_data[commodity][contract] = data
  361. # 检查这个数据里有多少条空值数据
  362. empty_data = data[data.isna().any(axis=1)]
  363. # 检查有效交易日数据并收集调整建议
  364. adjustment_info = self._check_thirty_day_trading_data(commodity, contract, data, start_date, end_date)
  365. if adjustment_info and adjustment_info.get('needs_adjustment'):
  366. # 暂存调整建议,稍后统一处理
  367. if not hasattr(self, 'adjustment_suggestions'):
  368. self.adjustment_suggestions = []
  369. self.adjustment_suggestions.append(adjustment_info)
  370. if self.verbose_logging:
  371. print(f" ✅ 成功获取{len(data)}条数据记录")
  372. print(f" 空值数据: {len(empty_data)}条")
  373. print(f" 价格范围: {data['low'].min():.2f} - {data['high'].max():.2f}")
  374. print(f" 数据日期范围: {data.index[0].date()} 至 {data.index[-1].date()}")
  375. else:
  376. if self.verbose_logging:
  377. print(f" ⚠️ 未获取到{contract}的数据")
  378. # 如果优化日期范围没有数据,尝试使用更宽泛的日期范围
  379. if self.verbose_logging:
  380. print(f" 尝试使用更宽泛的日期范围获取数据...")
  381. try:
  382. fallback_data = get_price(
  383. contract,
  384. start_date=self.start_date,
  385. end_date=self.end_date,
  386. frequency='daily',
  387. fields=['open', 'close', 'high', 'low', 'volume'],
  388. skip_paused=False,
  389. panel=False
  390. )
  391. if fallback_data is not None and len(fallback_data) > 0:
  392. self.price_data[commodity][contract] = fallback_data
  393. # 检查有效交易日数据并收集调整建议(回退方案)
  394. adjustment_info = self._check_thirty_day_trading_data(commodity, contract, fallback_data, self.start_date, self.end_date)
  395. if adjustment_info and adjustment_info.get('needs_adjustment'):
  396. if not hasattr(self, 'adjustment_suggestions'):
  397. self.adjustment_suggestions = []
  398. self.adjustment_suggestions.append(adjustment_info)
  399. if self.verbose_logging:
  400. print(f" ✅ 回退方案成功获取{len(fallback_data)}条数据记录")
  401. print(f" 数据日期范围: {fallback_data.index[0].date()} 至 {fallback_data.index[-1].date()}")
  402. else:
  403. if self.verbose_logging:
  404. print(f" ❌ 回退方案也未获取到{contract}的数据")
  405. except Exception as fallback_e:
  406. if self.verbose_logging:
  407. print(f" ❌ 回退方案出错: {str(fallback_e)}")
  408. except Exception as e:
  409. if self.verbose_logging:
  410. print(f" ❌ 获取{contract}数据时出错: {str(e)}")
  411. continue
  412. # 处理动态调整建议
  413. if hasattr(self, 'adjustment_suggestions') and self.adjustment_suggestions:
  414. self._apply_dynamic_adjustments()
  415. if self.verbose_logging:
  416. total_contracts = sum(len(contracts) for contracts in self.price_data.values())
  417. print(f"价格数据收集完成,共{total_contracts}个合约")
  418. return self.price_data
  419. def _determine_contract_date_ranges(self, commodity):
  420. """
  421. 根据主力合约历史确定每个合约的最优数据获取日期范围
  422. """
  423. contract_ranges = {}
  424. if commodity not in self.dominant_contract_history:
  425. # 如果没有主力合约历史,使用全范围
  426. for contract in self.core_commodities[commodity]:
  427. contract_ranges[contract] = (self.start_date, self.end_date)
  428. return contract_ranges
  429. contract_history = self.dominant_contract_history[commodity]
  430. # 分析每个合约的活跃期间
  431. for contract in self.core_commodities[commodity]:
  432. contract_start = self.start_date
  433. contract_end = self.end_date
  434. # 查找该合约在主力合约历史中的使用时间段
  435. for i, history_record in enumerate(contract_history):
  436. if history_record['selected_contract'] == contract:
  437. # 该合约开始使用的日期
  438. if history_record.get('is_initial', False):
  439. # 初始设置的合约,从分析开始日期或历史记录日期开始
  440. contract_start = max(self.start_date.date(), history_record['date'])
  441. else:
  442. # 切换到的合约,从切换日期开始
  443. contract_start = history_record['date']
  444. # 查找该合约结束使用的日期
  445. for j in range(i + 1, len(contract_history)):
  446. next_record = contract_history[j]
  447. if next_record['selected_contract'] != contract:
  448. # 找到下一次切换,该合约在此日期结束使用
  449. contract_end = next_record['date']
  450. break
  451. else:
  452. # 该合约一直使用到分析结束
  453. contract_end = self.end_date.date()
  454. break
  455. # 转换为datetime格式并添加缓冲区
  456. if isinstance(contract_start, datetime.date):
  457. contract_start = datetime.datetime.combine(contract_start, datetime.time.min)
  458. if isinstance(contract_end, datetime.date):
  459. contract_end = datetime.datetime.combine(contract_end, datetime.time.max)
  460. # 添加缓冲期以确保有足够的历史数据满足最低交易日要求
  461. # 使用REQUIRED_TRADING_DAYS作为缓冲,保证数据充足性
  462. contract_start_buffered = contract_start - datetime.timedelta(days=self.config.REQUIRED_TRADING_DAYS)
  463. contract_end_buffered = contract_end # + datetime.timedelta(days=self.config.REQUIRED_TRADING_DAYS)
  464. # 确保不超出总体分析范围
  465. contract_start_final = max(contract_start_buffered, self.start_date)
  466. contract_end_final = min(contract_end_buffered, self.end_date)
  467. contract_ranges[contract] = (contract_start_final, contract_end_final)
  468. if self.verbose_logging:
  469. print(f" {contract}: {contract_start_final.date()} 至 {contract_end_final.date()}")
  470. return contract_ranges
  471. def _check_thirty_day_trading_data(self, commodity, contract, data, start_date, end_date):
  472. """
  473. 检查合约是否有足够的有效交易日数据并进行动态调整
  474. 返回调整建议信息
  475. """
  476. if data is None or len(data) == 0:
  477. print(f" ⚠️ {contract}: 无价格数据")
  478. return None
  479. required_days = self.config.REQUIRED_TRADING_DAYS
  480. # 检查空值数据
  481. empty_data = data[data.isna().any(axis=1)]
  482. empty_count = len(empty_data)
  483. # 过滤出非空的收盘价数据
  484. valid_close_data = data['close'].dropna()
  485. valid_count = len(valid_close_data)
  486. print(f" 📊 {contract}: 有效收盘价数据共{valid_count}天")
  487. adjustment_info = {
  488. 'contract': contract,
  489. 'commodity': commodity,
  490. 'empty_count': empty_count,
  491. 'valid_count': valid_count,
  492. 'required_days': required_days,
  493. 'needs_adjustment': False,
  494. 'suggested_switch_date': None
  495. }
  496. # 检查是否有空值数据且需要调整
  497. if empty_count > 0:
  498. print(f" ⚠️ {contract}: 检测到{empty_count}条空值数据")
  499. if valid_count >= required_days:
  500. # 找到第N个有效收盘价的日期
  501. nth_date = valid_close_data.index[required_days - 1] # 索引从0开始
  502. nth_price = valid_close_data.iloc[required_days - 1]
  503. print(f" 📍 {contract}: 第{required_days}个有效收盘价日期为{nth_date.date()},价格{nth_price:.2f}")
  504. # 检查当前切换日期是否需要调整
  505. if commodity in self.dominant_contract_history:
  506. for history_record in self.dominant_contract_history[commodity]:
  507. if (history_record['selected_contract'] == contract and
  508. not history_record.get('is_initial', False)):
  509. current_switch_date = history_record['date']
  510. # 转换日期格式进行比较
  511. if isinstance(current_switch_date, datetime.date):
  512. current_switch_datetime = datetime.datetime.combine(current_switch_date, datetime.time.min)
  513. else:
  514. current_switch_datetime = current_switch_date
  515. if nth_date > current_switch_datetime:
  516. print(f" ❌ {contract}: 切换日期过早(当前:{current_switch_date}),建议调整至{nth_date.date()}")
  517. adjustment_info.update({
  518. 'needs_adjustment': True,
  519. 'suggested_switch_date': nth_date.date(),
  520. 'current_switch_date': current_switch_date
  521. })
  522. else:
  523. print(f" ✅ {contract}: 切换日期{current_switch_date}合理,在第{required_days}个有效交易日之后")
  524. break
  525. else:
  526. print(f" ❌ {contract}: 有效交易日不足{required_days}天(仅{valid_count}天),不符合切换要求")
  527. adjustment_info['needs_adjustment'] = True
  528. else:
  529. # 没有空值数据,检查是否有足够的交易日
  530. if valid_count >= required_days:
  531. nth_date = valid_close_data.index[required_days - 1]
  532. nth_price = valid_close_data.iloc[required_days - 1]
  533. print(f" ✅ {contract}: 第{required_days}个有效收盘价日期为{nth_date.date()},价格{nth_price:.2f}")
  534. else:
  535. print(f" ❌ {contract}: 有效交易日不足{required_days}天(仅{valid_count}天)")
  536. return adjustment_info
  537. def _apply_dynamic_adjustments(self):
  538. """应用动态调整建议,更新合约切换日期并重新获取数据"""
  539. if self.verbose_logging:
  540. print(f"\n=== 应用动态调整建议(共{len(self.adjustment_suggestions)}个) ===")
  541. adjustments_applied = []
  542. for suggestion in self.adjustment_suggestions:
  543. if suggestion.get('suggested_switch_date'):
  544. commodity = suggestion['commodity']
  545. contract = suggestion['contract']
  546. new_switch_date = suggestion['suggested_switch_date']
  547. print(f"📅 调整{commodity}的{contract}切换日期至{new_switch_date}")
  548. # 更新合约历史
  549. if self._update_contract_switch_date(commodity, contract, new_switch_date):
  550. adjustments_applied.append(suggestion)
  551. # 如果有调整,重新获取相关的价格数据
  552. if adjustments_applied:
  553. print(f"✅ 完成{len(adjustments_applied)}个调整,重新获取相关价格数据")
  554. self._refresh_price_data_for_adjustments(adjustments_applied)
  555. def _update_contract_switch_date(self, commodity, contract, new_switch_date):
  556. """更新指定合约的切换日期"""
  557. if commodity not in self.dominant_contract_history:
  558. return False
  559. # 查找并更新对应的历史记录
  560. for history_record in self.dominant_contract_history[commodity]:
  561. if (history_record['selected_contract'] == contract and
  562. not history_record.get('is_initial', False)):
  563. old_date = history_record['date']
  564. history_record['date'] = new_switch_date
  565. print(f" 📝 {contract}: 切换日期从{old_date}更新为{new_switch_date}")
  566. return True
  567. return False
  568. def _refresh_price_data_for_adjustments(self, adjustments):
  569. """为调整的合约重新获取价格数据"""
  570. affected_commodities = set()
  571. for adjustment in adjustments:
  572. commodity = adjustment['commodity']
  573. affected_commodities.add(commodity)
  574. for commodity in affected_commodities:
  575. print(f"🔄 重新获取{commodity}的价格数据...")
  576. # 重新计算日期范围
  577. contract_date_ranges = self._determine_contract_date_ranges(commodity)
  578. # 重新获取每个合约的数据
  579. for contract, date_range in contract_date_ranges.items():
  580. start_date, end_date = date_range
  581. try:
  582. # 获取价格数据(使用新的日期范围)
  583. data = get_price(
  584. contract,
  585. start_date=start_date,
  586. end_date=end_date,
  587. frequency='daily',
  588. fields=['open', 'close', 'high', 'low', 'volume'],
  589. skip_paused=False,
  590. panel=False
  591. )
  592. if data is not None and len(data) > 0:
  593. self.price_data[commodity][contract] = data
  594. # 检查调整后的数据
  595. empty_data = data[data.isna().any(axis=1)]
  596. empty_count = len(empty_data)
  597. print(f" ✅ {contract}: 重新获取{len(data)}条数据记录,空值{empty_count}条")
  598. if empty_count == 0:
  599. print(f" 🎉 {contract}: 空值数据已消除")
  600. except Exception as e:
  601. print(f" ❌ 重新获取{contract}数据时出错: {str(e)}")
  602. def simulate_with_contract_switching(self):
  603. """
  604. 模拟带有主力合约切换逻辑的交易
  605. """
  606. if self.verbose_logging:
  607. print("\n=== 步骤3: 带合约切换的交易模拟 ===")
  608. # 按日期顺序处理所有交易日
  609. current_date = self.start_date.date()
  610. end_date = self.end_date.date()
  611. while current_date <= end_date:
  612. # 跳过非交易日
  613. if current_date.weekday() >= 5:
  614. current_date += datetime.timedelta(days=1)
  615. continue
  616. # 检查每个商品的主力合约切换
  617. for commodity in self.core_commodities.keys():
  618. self._check_and_handle_contract_switch(commodity, current_date)
  619. # 处理正常的交易逻辑
  620. self._process_daily_trading(current_date)
  621. current_date += datetime.timedelta(days=1)
  622. # 在交易循环结束后,计算所有未平仓头寸的最终盈亏
  623. self._calculate_final_positions_pnl()
  624. if self.verbose_logging:
  625. print("带合约切换的交易模拟完成")
  626. def _calculate_final_positions_pnl(self):
  627. """
  628. 计算分析期结束时所有未平仓头寸的最终盈亏
  629. 将这些盈亏作为最终交易记录加入结果中
  630. """
  631. if self.verbose_logging:
  632. print("\n=== 计算最终持仓盈亏 ===")
  633. final_date = self.end_date.date()
  634. final_pnl_records = []
  635. # 添加诊断信息
  636. if self.verbose_logging:
  637. print(f"分析结束日期: {final_date}")
  638. print(f"活跃头寸概览:")
  639. for strategy_name in ['base_position', 'grid_trading']:
  640. strategy_positions = self.active_positions.get(strategy_name, {})
  641. total_positions = 0
  642. open_positions = 0
  643. for commodity, positions in strategy_positions.items():
  644. commodity_total = len(positions)
  645. commodity_open = sum(1 for p in positions.values() if p['status'] == 'open')
  646. total_positions += commodity_total
  647. open_positions += commodity_open
  648. if commodity_total > 0:
  649. print(f" {strategy_name} - {commodity}: 总计 {commodity_total} 个头寸, 未平仓 {commodity_open} 个")
  650. # 详细列出所有头寸信息
  651. print(f" 详细头寸列表:")
  652. for pos_id, pos_info in positions.items():
  653. status = pos_info.get('status', 'Unknown')
  654. entry_price = pos_info.get('entry_price', 'N/A')
  655. contract = pos_info.get('contract', 'N/A')
  656. entry_date = pos_info.get('entry_date', 'N/A')
  657. quantity = pos_info.get('quantity', 'N/A')
  658. print(f" {pos_id}: 状态={status}, 合约={contract}, 开仓价格={entry_price}, 日期={entry_date}, 数量={quantity}")
  659. print(f" {strategy_name} 策略总计: {open_positions}/{total_positions} 个未平仓头寸")
  660. # 验证头寸计数的准确性
  661. actual_count = len(positions)
  662. open_count_verify = len([p for p in positions.values() if p.get('status') == 'open'])
  663. if actual_count != commodity_total or open_count_verify != commodity_open:
  664. print(f" ⚠️ 计数不匹配!实际头寸数: {actual_count}, 预期: {commodity_total}; 实际未平仓: {open_count_verify}, 预期: {commodity_open}")
  665. # 检查是否有重复的开仓价格(同一合约同一状态)
  666. open_positions_by_price = {}
  667. for pos_id, pos_info in positions.items():
  668. if pos_info.get('status') == 'open':
  669. price = pos_info.get('entry_price')
  670. contract = pos_info.get('contract')
  671. key = f"{contract}_{price}"
  672. if key not in open_positions_by_price:
  673. open_positions_by_price[key] = []
  674. open_positions_by_price[key].append(pos_id)
  675. # for key, pos_ids in open_positions_by_price.items():
  676. # if len(pos_ids) > 1:
  677. # print(f" ⚠️ 发现重复的未平仓头寸: {key} -> {pos_ids}")
  678. print(f" {strategy_name} 策略总计: {open_positions}/{total_positions} 个未平仓头寸")
  679. for strategy_name in ['base_position', 'grid_trading']:
  680. strategy_positions = self.active_positions.get(strategy_name, {})
  681. for commodity, positions in strategy_positions.items():
  682. # 获取当前合约和最终价格
  683. current_contract = self._get_current_contract(commodity, final_date)
  684. if not current_contract:
  685. if self.verbose_logging:
  686. print(f" 警告: 无法确定 {commodity} 在 {final_date} 的当前合约")
  687. continue
  688. final_price = self._get_price_on_date(commodity, current_contract, final_date, 'close')
  689. if final_price is None:
  690. if self.verbose_logging:
  691. print(f" 警告: 无法获取 {commodity} {current_contract} 在 {final_date} 的价格")
  692. continue
  693. if self.verbose_logging and len(positions) > 0:
  694. print(f" {commodity} {strategy_name}: 当前合约 {current_contract}, 结算价格 {final_price:.2f}")
  695. for position_id, position in positions.items():
  696. if self.verbose_logging:
  697. print(f" 检查头寸 {position_id}: 状态={position['status']}, 合约={position['contract']}, 开仓价格={position.get('entry_price', 'N/A')}")
  698. if position['status'] == 'open' and position['contract'] == current_contract:
  699. if self.verbose_logging:
  700. print(f" 匹配头寸进行结算: {position_id}")
  701. print(f" 头寸详情: 开仓日期={position.get('entry_date', 'N/A')}, 开仓价格={position['entry_price']}, 数量={position.get('quantity', 'N/A')}")
  702. # 计算最终盈亏(基础头寸和网格交易都是做多)
  703. profit_loss = self._calculate_futures_pnl(
  704. position['entry_price'], final_price, position['quantity'], commodity, is_long=True
  705. )
  706. profit_loss_pct = (final_price - position['entry_price']) / position['entry_price']
  707. # 计算持有天数
  708. entry_date = datetime.datetime.strptime(position['entry_date'], '%Y-%m-%d').date()
  709. days_held = (final_date - entry_date).days
  710. # 创建最终持仓盈亏记录
  711. final_record = {
  712. 'commodity': commodity,
  713. 'contract': current_contract,
  714. 'strategy': strategy_name,
  715. 'entry_date': position['entry_date'],
  716. 'exit_date': final_date.strftime('%Y-%m-%d'),
  717. 'entry_price': position['entry_price'],
  718. 'exit_price': final_price,
  719. 'quantity': position['quantity'],
  720. 'profit_loss': profit_loss,
  721. 'profit_loss_pct': profit_loss_pct,
  722. 'days_held': days_held,
  723. 'exit_reason': 'final_settlement'
  724. }
  725. if self.verbose_logging:
  726. print(f" 创建最终结算记录: 头寸ID={position_id}, 开仓价格={position['entry_price']}, 结算价格={final_price:.2f}")
  727. final_pnl_records.append(final_record)
  728. # 将头寸标记为已平仓
  729. self.active_positions[strategy_name][commodity][position_id]['status'] = 'final_settled'
  730. if self.verbose_logging:
  731. print(f" {commodity} {strategy_name} 最终结算: {position['entry_price']} -> {final_price:.2f}, 盈亏: {profit_loss:.2f}")
  732. # 将最终盈亏记录添加到交易结果中
  733. for record in final_pnl_records:
  734. strategy_name = record['strategy']
  735. self.trading_results[strategy_name].append(record)
  736. if self.verbose_logging:
  737. total_final_records = len(final_pnl_records)
  738. total_final_pnl = sum(record['profit_loss'] for record in final_pnl_records)
  739. print(f"最终持仓结算完成,共 {total_final_records} 个头寸,总未实现盈亏: {total_final_pnl:.2f}")
  740. # 显示所有最终结算记录的详情
  741. if final_pnl_records:
  742. print(f"最终结算记录详情:")
  743. for i, record in enumerate(final_pnl_records, 1):
  744. print(f" {i}. {record['commodity']} {record['strategy']}: {record['entry_price']} -> {record['exit_price']:.2f}, 盈亏: {record['profit_loss']:.2f}, 合约: {record['contract']}")
  745. def _check_and_handle_contract_switch(self, commodity, current_date):
  746. """
  747. 检查并处理主力合约切换
  748. 只有真正的合约切换才会触发平仓和重新建仓,初始设置不会
  749. """
  750. if commodity not in self.dominant_contract_history:
  751. return
  752. # 检查当天是否有合约变化
  753. contract_changes = self.dominant_contract_history[commodity]
  754. for change in contract_changes:
  755. if change['date'] == current_date:
  756. # 检查是否为初始合约设置
  757. if change.get('is_initial', False):
  758. # 初始合约设置,不需要平仓和重新建仓,只需要启动正常交易逻辑
  759. if self.verbose_logging:
  760. print(f"\n{current_date}: {commodity} 初始合约设置为 {change['selected_contract']}")
  761. return
  762. # 真正的合约切换
  763. old_contract = self._get_current_contract(commodity, current_date - datetime.timedelta(days=1))
  764. new_contract = change['selected_contract']
  765. if self.verbose_logging:
  766. print(f"\n{current_date}: {commodity} 合约切换 {old_contract} -> {new_contract}")
  767. # 平掉旧合约的所有头寸
  768. self._close_all_positions_on_switch(commodity, old_contract, current_date)
  769. # 在新合约中重新建仓
  770. self._reestablish_positions_in_new_contract(commodity, new_contract, current_date)
  771. break
  772. def _get_current_contract(self, commodity, date):
  773. """获取指定日期的当前合约"""
  774. if commodity not in self.dominant_contract_history:
  775. return None
  776. contract_changes = self.dominant_contract_history[commodity]
  777. current_contract = None
  778. for change in contract_changes:
  779. if change['date'] <= date:
  780. current_contract = change['selected_contract']
  781. else:
  782. break
  783. return current_contract
  784. def _close_all_positions_on_switch(self, commodity, old_contract, switch_date):
  785. """
  786. 在合约切换时平掉旧合约的所有头寸
  787. """
  788. if self.verbose_logging:
  789. print(f" 平掉 {old_contract} 的所有头寸")
  790. # 获取当日收盘价
  791. close_price = self._get_price_on_date(commodity, old_contract, switch_date, 'close')
  792. if close_price is None:
  793. if self.verbose_logging:
  794. print(f" 无法获取 {switch_date} 的价格数据,跳过平仓")
  795. return
  796. # 平掉基础头寸交易的头寸
  797. if commodity in self.active_positions['base_position']:
  798. positions = self.active_positions['base_position'][commodity].copy()
  799. for position_id, position in positions.items():
  800. if position['contract'] == old_contract and position['status'] == 'open':
  801. # 使用正确的期货盈亏计算公式(基础头寸都是多头)
  802. profit_loss = self._calculate_futures_pnl(
  803. position['entry_price'], close_price, position['quantity'], commodity, is_long=True
  804. )
  805. profit_loss_pct = (close_price - position['entry_price']) / position['entry_price']
  806. trade_record = {
  807. 'commodity': commodity,
  808. 'contract': old_contract,
  809. 'strategy': 'base_position',
  810. 'entry_date': position['entry_date'],
  811. 'exit_date': switch_date.strftime('%Y-%m-%d'),
  812. 'entry_price': position['entry_price'],
  813. 'exit_price': close_price,
  814. 'quantity': position['quantity'],
  815. 'profit_loss': profit_loss,
  816. 'profit_loss_pct': profit_loss_pct,
  817. 'days_held': (switch_date - datetime.datetime.strptime(position['entry_date'], '%Y-%m-%d').date()).days,
  818. 'exit_reason': 'contract_switch'
  819. }
  820. self.trading_results['base_position'].append(trade_record)
  821. self.active_positions['base_position'][commodity][position_id]['status'] = 'closed'
  822. self.active_positions['base_position'][commodity][position_id]['close_reason'] = 'contract_switch'
  823. if self.verbose_logging:
  824. print(f" 基础头寸平仓: {position['entry_price']} -> {close_price:.2f}, 盈亏: {profit_loss:.2f}")
  825. # 平掉网格交易的头寸
  826. if commodity in self.active_positions['grid_trading']:
  827. positions = self.active_positions['grid_trading'][commodity].copy()
  828. for position_id, position in positions.items():
  829. if position['contract'] == old_contract and position['status'] == 'open':
  830. # 使用正确的期货盈亏计算公式(网格交易都是多头)
  831. profit_loss = self._calculate_futures_pnl(
  832. position['entry_price'], close_price, position['quantity'], commodity, is_long=True
  833. )
  834. profit_loss_pct = (close_price - position['entry_price']) / position['entry_price']
  835. trade_record = {
  836. 'commodity': commodity,
  837. 'contract': old_contract,
  838. 'strategy': 'grid_trading',
  839. 'entry_date': position['entry_date'],
  840. 'exit_date': switch_date.strftime('%Y-%m-%d'),
  841. 'entry_price': position['entry_price'],
  842. 'exit_price': close_price,
  843. 'quantity': position['quantity'],
  844. 'profit_loss': profit_loss,
  845. 'profit_loss_pct': profit_loss_pct,
  846. 'days_held': (switch_date - datetime.datetime.strptime(position['entry_date'], '%Y-%m-%d').date()).days,
  847. 'exit_reason': 'contract_switch'
  848. }
  849. self.trading_results['grid_trading'].append(trade_record)
  850. self.active_positions['grid_trading'][commodity][position_id]['status'] = 'closed'
  851. self.active_positions['grid_trading'][commodity][position_id]['close_reason'] = 'contract_switch'
  852. if self.verbose_logging:
  853. print(f" 网格头寸平仓: {position['entry_price']} -> {close_price:.2f}, 盈亏: {profit_loss:.2f}")
  854. def _reestablish_positions_in_new_contract(self, commodity, new_contract, switch_date):
  855. """
  856. 在新合约中重新建仓
  857. """
  858. if self.verbose_logging:
  859. print(f" 在 {new_contract} 中重新建仓")
  860. # 获取当日收盘价
  861. close_price = self._get_price_on_date(commodity, new_contract, switch_date, 'close')
  862. if close_price is None:
  863. if self.verbose_logging:
  864. print(f" 无法获取 {switch_date} 的价格数据,跳过重新建仓")
  865. return
  866. # 基础头寸交易重新建仓
  867. self._reestablish_base_positions(commodity, new_contract, close_price, switch_date)
  868. # 网格交易重新建仓
  869. self._reestablish_grid_positions(commodity, new_contract, close_price, switch_date)
  870. def _reestablish_base_positions(self, commodity, new_contract, close_price, switch_date):
  871. """重新建立基础头寸"""
  872. if commodity not in self.base_position_grid:
  873. return
  874. # 获取之前被平掉的基础头寸信息(按价格水平记录)
  875. closed_positions = {} # price_level -> quantity
  876. if commodity in self.active_positions['base_position']:
  877. for position in self.active_positions['base_position'][commodity].values():
  878. if position['status'] == 'closed' and 'contract_switch' in position.get('close_reason', ''):
  879. # 只处理因合约切换而平掉的头寸
  880. original_price = position.get('original_price_level', position['entry_price'])
  881. if original_price not in closed_positions:
  882. closed_positions[original_price] = 0
  883. closed_positions[original_price] += position['quantity']
  884. if self.verbose_logging:
  885. print(f" 发现需重建的基础头寸: {original_price}水平 {position['quantity']}手 (原合约: {position['contract']})")
  886. # 根据当前价格和原始价格水平重建头寸
  887. price_grid = self.base_position_grid[commodity]
  888. reestablish_count = 0
  889. for target_price, configured_quantity in price_grid.items():
  890. # 只有当目标价格大于等于当前价格时才重建头寸
  891. # 这确保了只重建"应该持有"的价格水平头寸
  892. if target_price >= close_price:
  893. # 检查是否有该价格水平的平仓头寸需要重建
  894. if target_price in closed_positions:
  895. quantity_to_reestablish = closed_positions[target_price]
  896. if self.verbose_logging:
  897. print(f" 重建条件检查: {target_price} >= {close_price:.2f} ✓ (重建原有平仓头寸)")
  898. else:
  899. # 当前价格低于目标价格,应该建立该价格水平的头寸
  900. quantity_to_reestablish = configured_quantity
  901. if self.verbose_logging:
  902. print(f" 重建条件检查: {target_price} >= {close_price:.2f} ✓ (建立新头寸)")
  903. else:
  904. # 当前价格高于目标价格,不重建
  905. if self.verbose_logging:
  906. print(f" 重建条件检查: {target_price} >= {close_price:.2f} ✗ (跳过重建)")
  907. continue
  908. if quantity_to_reestablish > 0:
  909. position_id = f"{commodity}_{new_contract}_{switch_date}_base_reestablish_{target_price}"
  910. if commodity not in self.active_positions['base_position']:
  911. self.active_positions['base_position'][commodity] = {}
  912. self.active_positions['base_position'][commodity][position_id] = {
  913. 'contract': new_contract,
  914. 'entry_date': switch_date.strftime('%Y-%m-%d'),
  915. 'entry_price': close_price, # 实际成交价格
  916. 'original_price_level': target_price, # 原始价格水平
  917. 'quantity': quantity_to_reestablish,
  918. 'status': 'open',
  919. 'exit_target': self.base_position_exit_price.get(commodity)
  920. }
  921. if self.verbose_logging:
  922. print(f" 创建重建头寸: {position_id}")
  923. print(f" 实际成交价格: {close_price}, 原始价格水平: {target_price}, 数量: {quantity_to_reestablish}")
  924. reestablish_count += quantity_to_reestablish
  925. if self.verbose_logging:
  926. print(f" 重建基础头寸 {target_price}水平: {quantity_to_reestablish} 手 @ {close_price:.2f}")
  927. if reestablish_count > 0 and self.verbose_logging:
  928. print(f" 基础头寸重建完成,总计: {reestablish_count} 手")
  929. def _reestablish_grid_positions(self, commodity, new_contract, close_price, switch_date):
  930. """重新建立网格交易头寸"""
  931. if commodity not in self.grid_trading_config:
  932. return
  933. config = self.grid_trading_config[commodity]
  934. grid_size = config['grid_size']
  935. quantity_per_grid = config['quantity_per_grid']
  936. exit_grid_size = config['exit_grid_size']
  937. # 获取之前的网格头寸信息
  938. previous_grid_levels = set()
  939. if commodity in self.active_positions['grid_trading']:
  940. for position in self.active_positions['grid_trading'][commodity].values():
  941. if position['status'] == 'closed' and 'contract_switch' in position.get('close_reason', ''):
  942. # 只处理因合约切换而平掉的头寸
  943. previous_grid_levels.add(position['entry_price'])
  944. if self.verbose_logging:
  945. print(f" 发现需重建的网格头寸: {position['entry_price']}水平 {position['quantity']}手")
  946. # 仅在原始网格开仓价格大于等于当前价格时重新建仓
  947. # 这确保了只重建"应该持有"的网格水平头寸
  948. reestablish_count = 0
  949. for grid_level in previous_grid_levels:
  950. if grid_level >= close_price:
  951. if self.verbose_logging:
  952. print(f" 网格重建条件检查: {grid_level} >= {close_price:.2f} ✓ (重建网格头寸)")
  953. position_id = f"{commodity}_{new_contract}_{switch_date}_grid_{grid_level}"
  954. if commodity not in self.active_positions['grid_trading']:
  955. self.active_positions['grid_trading'][commodity] = {}
  956. self.active_positions['grid_trading'][commodity][position_id] = {
  957. 'contract': new_contract,
  958. 'entry_date': switch_date.strftime('%Y-%m-%d'),
  959. 'entry_price': close_price,
  960. 'original_grid_level': grid_level,
  961. 'quantity': quantity_per_grid,
  962. 'status': 'open',
  963. 'exit_target': grid_level + exit_grid_size # 保持原始退出价格
  964. }
  965. reestablish_count += 1
  966. else:
  967. if self.verbose_logging:
  968. print(f" 网格重建条件检查: {grid_level} >= {close_price:.2f} ✗ (跳过重建)")
  969. continue
  970. # 同时检查是否需要开立新的网格头寸(价格更低的情况)
  971. start_price = config['start_price']
  972. current_level = start_price
  973. while current_level > close_price:
  974. current_level -= grid_size
  975. if current_level not in previous_grid_levels and current_level > 0:
  976. # 这是一个新的网格水平
  977. position_id = f"{commodity}_{new_contract}_{switch_date}_grid_new_{current_level}"
  978. if commodity not in self.active_positions['grid_trading']:
  979. self.active_positions['grid_trading'][commodity] = {}
  980. self.active_positions['grid_trading'][commodity][position_id] = {
  981. 'contract': new_contract,
  982. 'entry_date': switch_date.strftime('%Y-%m-%d'),
  983. 'entry_price': close_price,
  984. 'original_grid_level': current_level,
  985. 'quantity': quantity_per_grid,
  986. 'status': 'open',
  987. 'exit_target': current_level + exit_grid_size
  988. }
  989. reestablish_count += 1
  990. if self.verbose_logging and reestablish_count > 0:
  991. print(f" 重建网格头寸: {reestablish_count} 个网格 @ {close_price:.2f}")
  992. def _get_price_on_date(self, commodity, contract, date, price_type='close'):
  993. """获取指定日期和合约的价格(增强NaN问题诊断)"""
  994. if commodity not in self.price_data or contract not in self.price_data[commodity]:
  995. if self.verbose_logging:
  996. print(f" ❌ 价格数据不存在: {commodity} -> {contract}")
  997. return None
  998. price_data = self.price_data[commodity][contract]
  999. # 找到日期对应的价格
  1000. target_date = date if isinstance(date, datetime.date) else date.date()
  1001. for idx, row in price_data.iterrows():
  1002. if idx.date() == target_date:
  1003. price_value = row[price_type]
  1004. if self.verbose_logging:
  1005. print(f'{price_type}的价格是: {price_value}')
  1006. # 如果价格为NaN,进行详细诊断
  1007. if pd.isna(price_value):
  1008. self._diagnose_nan_price_issue(commodity, contract, target_date, price_type, row)
  1009. return None
  1010. else:
  1011. return price_value
  1012. # 如果没有找到精确日期,尝试查找最近的交易日
  1013. if self.verbose_logging:
  1014. print(f" ⚠️ 未找到 {contract} 在 {target_date} 的数据,尝试查找最近交易日...")
  1015. return self._get_nearest_trading_day_price(commodity, contract, target_date, price_type)
  1016. def _diagnose_nan_price_issue(self, commodity, contract, date, price_type, row):
  1017. """诊断NaN价格问题的根本原因"""
  1018. if self.verbose_logging:
  1019. print(f" 🔍 NaN价格问题诊断: {commodity} {contract} {date}")
  1020. print(f" 目标价格类型: {price_type}")
  1021. print(f" 该日所有价格数据: 开盘={row['open']}, 收盘={row['close']}, 最高={row['high']}, 最低={row['low']}, 成交量={row['volume']}")
  1022. # 检查是否所有价格都是NaN
  1023. price_fields = ['open', 'close', 'high', 'low']
  1024. nan_fields = [field for field in price_fields if pd.isna(row[field])]
  1025. valid_fields = [field for field in price_fields if not pd.isna(row[field])]
  1026. if len(nan_fields) == len(price_fields):
  1027. print(f" ❌ 所有价格字段都为NaN - 可能该合约在此日期未开始交易")
  1028. else:
  1029. print(f" ⚠️ 部分价格字段为NaN: {nan_fields}")
  1030. print(f" ✅ 有效价格字段: {valid_fields}")
  1031. # 如果有有效价格,尝试使用替代方案
  1032. if valid_fields:
  1033. fallback_price = row[valid_fields[0]]
  1034. print(f" 💡 建议使用替代价格: {valid_fields[0]} = {fallback_price}")
  1035. # 检查成交量是否为0或NaN
  1036. if pd.isna(row['volume']) or row['volume'] == 0:
  1037. print(f" ⚠️ 成交量异常: {row['volume']} - 可能该合约在此日期无交易活动")
  1038. # 检查是否是合约刚上市的情况
  1039. price_data = self.price_data[commodity][contract]
  1040. first_valid_date = None
  1041. for idx, data_row in price_data.iterrows():
  1042. if not pd.isna(data_row['close']):
  1043. first_valid_date = idx.date()
  1044. break
  1045. if first_valid_date and date < first_valid_date:
  1046. print(f" 🔍 合约首次有效交易日: {first_valid_date} (查询日期 {date} 早于首次交易日)")
  1047. print(f" 💡 建议: 合约 {contract} 在 {date} 可能尚未开始交易")
  1048. # 提供解决建议
  1049. print(f" 📋 解决建议:")
  1050. print(f" 1. 检查合约 {contract} 的上市日期")
  1051. print(f" 2. 验证合约代码是否正确")
  1052. print(f" 3. 考虑调整合约切换日期")
  1053. if valid_fields:
  1054. print(f" 4. 临时使用替代价格: {valid_fields[0]} = {row[valid_fields[0]]}")
  1055. def _get_nearest_trading_day_price(self, commodity, contract, target_date, price_type):
  1056. """获取最近交易日的价格"""
  1057. price_data = self.price_data[commodity][contract]
  1058. # 查找最近的交易日(前后5天范围内)
  1059. search_range = 5
  1060. for offset in range(1, search_range + 1):
  1061. # 先查找之后的日期
  1062. future_date = target_date + datetime.timedelta(days=offset)
  1063. for idx, row in price_data.iterrows():
  1064. if idx.date() == future_date:
  1065. price_value = row[price_type]
  1066. if not pd.isna(price_value):
  1067. if self.verbose_logging:
  1068. print(f" ✅ 使用后续交易日 {future_date} 的价格: {price_value}")
  1069. return price_value
  1070. break
  1071. # 再查找之前的日期
  1072. past_date = target_date - datetime.timedelta(days=offset)
  1073. for idx, row in price_data.iterrows():
  1074. if idx.date() == past_date:
  1075. price_value = row[price_type]
  1076. if not pd.isna(price_value):
  1077. if self.verbose_logging:
  1078. print(f" ✅ 使用前期交易日 {past_date} 的价格: {price_value}")
  1079. return price_value
  1080. break
  1081. if self.verbose_logging:
  1082. print(f" ❌ 在 {search_range} 天范围内未找到有效的 {price_type} 价格")
  1083. return None
  1084. def _process_daily_trading(self, current_date):
  1085. """处理每日的正常交易逻辑"""
  1086. for commodity in self.core_commodities.keys():
  1087. current_contract = self._get_current_contract(commodity, current_date)
  1088. if not current_contract:
  1089. continue
  1090. # 获取当日价格数据
  1091. daily_prices = self._get_daily_prices(commodity, current_contract, current_date)
  1092. if not daily_prices:
  1093. continue
  1094. # 检查基础头寸入场和退出机会
  1095. self._check_base_position_trading(commodity, current_contract, current_date, daily_prices)
  1096. # 检查网格交易入场和退出机会
  1097. self._check_grid_trading(commodity, current_contract, current_date, daily_prices)
  1098. def _get_daily_prices(self, commodity, contract, date):
  1099. """获取指定日期的价格数据"""
  1100. if commodity not in self.price_data or contract not in self.price_data[commodity]:
  1101. return None
  1102. price_data = self.price_data[commodity][contract]
  1103. for idx, row in price_data.iterrows():
  1104. if idx.date() == date:
  1105. return {
  1106. 'open': row['open'],
  1107. 'close': row['close'],
  1108. 'high': row['high'],
  1109. 'low': row['low'],
  1110. 'volume': row['volume']
  1111. }
  1112. return None
  1113. def _check_base_position_trading(self, commodity, contract, current_date, daily_prices):
  1114. """检查基础头寸交易机会
  1115. 逻辑:每日主动检查所有网格水平
  1116. - 如果当前收盘价低于某个网格水平价格
  1117. - 且该网格水平没有未平仓头寸
  1118. - 则以当日收盘价在该网格水平开仓
  1119. """
  1120. if commodity not in self.base_position_grid:
  1121. return
  1122. # 检查入场机会 - 遍历所有网格水平
  1123. price_grid = self.base_position_grid[commodity]
  1124. current_close_price = daily_prices['close']
  1125. for entry_price, quantity in price_grid.items():
  1126. # 检查是否已经有这个价格水平的头寸
  1127. position_exists = False
  1128. if commodity in self.active_positions['base_position']:
  1129. for position in self.active_positions['base_position'][commodity].values():
  1130. if (position['contract'] == contract and position['status'] == 'open'):
  1131. # 检查原始价格水平
  1132. position_price_level = position.get('original_price_level', position['entry_price'])
  1133. if position_price_level == entry_price:
  1134. position_exists = True
  1135. break
  1136. # 主动开仓逻辑:当前价格低于网格水平价格 且 该水平没有头寸
  1137. if not position_exists and current_close_price < entry_price:
  1138. # 以当日收盘价建立头寸
  1139. position_id = f"{commodity}_{contract}_{current_date}_base_{entry_price}"
  1140. if commodity not in self.active_positions['base_position']:
  1141. self.active_positions['base_position'][commodity] = {}
  1142. self.active_positions['base_position'][commodity][position_id] = {
  1143. 'contract': contract,
  1144. 'entry_date': current_date.strftime('%Y-%m-%d'),
  1145. 'entry_price': current_close_price, # 使用收盘价作为入场价格
  1146. 'original_price_level': entry_price, # 记录原始网格水平
  1147. 'quantity': quantity,
  1148. 'status': 'open',
  1149. 'exit_target': self.base_position_exit_price.get(commodity)
  1150. }
  1151. if self.verbose_logging:
  1152. print(f" {current_date}: {commodity} 基础头寸入场 @ 网格{entry_price} (实际价格: {current_close_price:.2f}), 数量: {quantity},当天收盘价{current_close_price:.2f}低于网格价格{entry_price}")
  1153. # 检查退出机会
  1154. exit_target = self.base_position_exit_price.get(commodity)
  1155. if exit_target and commodity in self.active_positions['base_position']:
  1156. positions_to_close = []
  1157. for position_id, position in self.active_positions['base_position'][commodity].items():
  1158. if position['contract'] == contract and position['status'] == 'open' and daily_prices['high'] >= exit_target:
  1159. positions_to_close.append(position_id)
  1160. for position_id in positions_to_close:
  1161. position = self.active_positions['base_position'][commodity][position_id]
  1162. exit_price = min(exit_target, daily_prices['high'])
  1163. # 使用正确的期货盈亏计算公式(基础头寸都是多头)
  1164. profit_loss = self._calculate_futures_pnl(
  1165. position['entry_price'], exit_price, position['quantity'], commodity, is_long=True
  1166. )
  1167. profit_loss_pct = (exit_price - position['entry_price']) / position['entry_price']
  1168. trade_record = {
  1169. 'commodity': commodity,
  1170. 'contract': contract,
  1171. 'strategy': 'base_position',
  1172. 'entry_date': position['entry_date'],
  1173. 'exit_date': current_date.strftime('%Y-%m-%d'),
  1174. 'entry_price': position['entry_price'],
  1175. 'exit_price': exit_price,
  1176. 'quantity': position['quantity'],
  1177. 'profit_loss': profit_loss,
  1178. 'profit_loss_pct': profit_loss_pct,
  1179. 'days_held': (current_date - datetime.datetime.strptime(position['entry_date'], '%Y-%m-%d').date()).days,
  1180. 'exit_reason': 'target_reached'
  1181. }
  1182. self.trading_results['base_position'].append(trade_record)
  1183. self.active_positions['base_position'][commodity][position_id]['status'] = 'closed'
  1184. if self.verbose_logging:
  1185. print(f" {current_date}: {commodity} 基础头寸退出 {position['entry_price']} -> {exit_price:.2f}, 盈亏: {profit_loss:.2f}")
  1186. def _check_grid_trading(self, commodity, contract, current_date, daily_prices):
  1187. """检查网格交易机会"""
  1188. if commodity not in self.grid_trading_config:
  1189. return
  1190. config = self.grid_trading_config[commodity]
  1191. start_price = config['start_price']
  1192. grid_size = config['grid_size']
  1193. quantity_per_grid = config['quantity_per_grid']
  1194. exit_grid_size = config['exit_grid_size']
  1195. # 检查入场机会
  1196. current_level = start_price
  1197. while current_level > daily_prices['low'] and current_level > 0:
  1198. position_exists = False
  1199. if commodity in self.active_positions['grid_trading']:
  1200. for position in self.active_positions['grid_trading'][commodity].values():
  1201. if (position['contract'] == contract and
  1202. position.get('original_grid_level', position['entry_price']) == current_level and
  1203. position['status'] == 'open'):
  1204. position_exists = True
  1205. break
  1206. if not position_exists and daily_prices['low'] <= current_level <= daily_prices['high']:
  1207. position_id = f"{commodity}_{contract}_{current_date}_grid_{current_level}"
  1208. if commodity not in self.active_positions['grid_trading']:
  1209. self.active_positions['grid_trading'][commodity] = {}
  1210. self.active_positions['grid_trading'][commodity][position_id] = {
  1211. 'contract': contract,
  1212. 'entry_date': current_date.strftime('%Y-%m-%d'),
  1213. 'entry_price': current_level,
  1214. 'original_grid_level': current_level,
  1215. 'quantity': quantity_per_grid,
  1216. 'status': 'open',
  1217. 'exit_target': current_level + exit_grid_size
  1218. }
  1219. if self.verbose_logging:
  1220. print(f" {current_date}: {commodity} 网格入场 @ {current_level},数量:{quantity_per_grid},当天最低价为{daily_prices['low']},最高价为{daily_prices['high']}")
  1221. current_level -= grid_size
  1222. # 检查退出机会
  1223. if commodity in self.active_positions['grid_trading']:
  1224. positions_to_close = []
  1225. for position_id, position in self.active_positions['grid_trading'][commodity].items():
  1226. if position['contract'] == contract and position['status'] == 'open':
  1227. if daily_prices['high'] >= position['exit_target']:
  1228. positions_to_close.append(position_id)
  1229. for position_id in positions_to_close:
  1230. position = self.active_positions['grid_trading'][commodity][position_id]
  1231. exit_price = position['exit_target']
  1232. # 使用正确的期货盈亏计算公式(网格交易都是多头)
  1233. profit_loss = self._calculate_futures_pnl(
  1234. position['entry_price'], exit_price, position['quantity'], commodity, is_long=True
  1235. )
  1236. profit_loss_pct = (exit_price - position['entry_price']) / position['entry_price']
  1237. trade_record = {
  1238. 'commodity': commodity,
  1239. 'contract': contract,
  1240. 'strategy': 'grid_trading',
  1241. 'entry_date': position['entry_date'],
  1242. 'exit_date': current_date.strftime('%Y-%m-%d'),
  1243. 'entry_price': position['entry_price'],
  1244. 'exit_price': exit_price,
  1245. 'quantity': position['quantity'],
  1246. 'profit_loss': profit_loss,
  1247. 'profit_loss_pct': profit_loss_pct,
  1248. 'days_held': (current_date - datetime.datetime.strptime(position['entry_date'], '%Y-%m-%d').date()).days,
  1249. 'exit_reason': 'target_reached'
  1250. }
  1251. self.trading_results['grid_trading'].append(trade_record)
  1252. self.active_positions['grid_trading'][commodity][position_id]['status'] = 'closed'
  1253. if self.verbose_logging:
  1254. print(f" {current_date}: {commodity} 网格退出 {position['entry_price']} -> {exit_price:.2f}, 盈亏: {profit_loss:.2f} ({profit_loss_pct:.2%})")
  1255. def _extend_price_data_for_ma(self, commodity, contract, current_date, required_days=30):
  1256. """扩展价格数据以满足MA计算需求
  1257. 参数:
  1258. commodity: 商品代码
  1259. contract: 合约代码
  1260. current_date: 当前日期
  1261. required_days: 所需的最少数据天数
  1262. 返回:
  1263. 扩展后的价格数据DataFrame,如果获取失败则返回None
  1264. """
  1265. cache_key = f"{commodity}_{contract}"
  1266. # 检查缓存
  1267. if cache_key in self.ma_extended_data_cache:
  1268. cached_data = self.ma_extended_data_cache[cache_key]
  1269. target_date = current_date if isinstance(current_date, datetime.date) else current_date.date()
  1270. historical_data = cached_data[cached_data.index.date <= target_date]
  1271. if len(historical_data) >= required_days:
  1272. if self.verbose_logging:
  1273. print(f" ℹ️ MA过滤器:使用缓存的扩展数据,共{len(historical_data)}天")
  1274. return historical_data
  1275. # 获取现有数据
  1276. if commodity not in self.price_data or contract not in self.price_data[commodity]:
  1277. return None
  1278. existing_data = self.price_data[commodity][contract]
  1279. target_date = current_date if isinstance(current_date, datetime.date) else current_date.date()
  1280. existing_historical = existing_data[existing_data.index.date <= target_date]
  1281. if len(existing_historical) >= required_days:
  1282. return existing_historical
  1283. # 数据不足,需要扩展获取
  1284. existing_count = len(existing_historical)
  1285. shortage = required_days - existing_count
  1286. if self.verbose_logging:
  1287. print(f" 📊 MA过滤器:数据不足,开始扩展获取(当前{existing_count}天,需要{required_days}天,缺少{shortage}天)")
  1288. # 计算扩展的开始日期:从现有数据最早日期往前推至少30个交易日
  1289. if len(existing_data) > 0:
  1290. earliest_date = existing_data.index.min().date()
  1291. else:
  1292. earliest_date = target_date
  1293. # 往前推60个自然日(约等于40-45个交易日,提供充足缓冲)
  1294. extended_start_date = earliest_date - datetime.timedelta(days=60)
  1295. extended_end_date = target_date
  1296. if self.verbose_logging:
  1297. print(f" 📊 扩展日期范围: {extended_start_date} 至 {extended_end_date}")
  1298. try:
  1299. # 获取扩展的价格数据
  1300. extended_data = get_price(
  1301. contract,
  1302. start_date=extended_start_date,
  1303. end_date=extended_end_date,
  1304. frequency='daily',
  1305. fields=['open', 'close', 'high', 'low', 'volume'],
  1306. skip_paused=False,
  1307. panel=False
  1308. )
  1309. if extended_data is None or len(extended_data) == 0:
  1310. if self.verbose_logging:
  1311. print(f" ⚠️ 扩展数据获取失败:未获取到数据")
  1312. return existing_historical
  1313. # 合并数据:将扩展数据与现有数据合并,保留所有日期的数据
  1314. # 使用concat合并,然后去重并按日期排序
  1315. combined_data = pd.concat([existing_data, extended_data])
  1316. combined_data = combined_data[~combined_data.index.duplicated(keep='first')]
  1317. combined_data = combined_data.sort_index()
  1318. # 过滤到当前日期(仅用于返回给MA计算)
  1319. combined_historical = combined_data[combined_data.index.date <= target_date]
  1320. if self.verbose_logging:
  1321. print(f" ✅ 扩展数据获取成功:从{len(existing_historical)}天扩展到{len(combined_historical)}天")
  1322. print(f" 合并后完整数据范围:{combined_data.index.min().date()} 至 {combined_data.index.max().date()}(共{len(combined_data)}天)")
  1323. # 缓存扩展后的完整数据
  1324. self.ma_extended_data_cache[cache_key] = combined_data
  1325. # 更新主price_data,保留原有数据和新扩展的数据
  1326. self.price_data[commodity][contract] = combined_data
  1327. return combined_historical
  1328. except Exception as e:
  1329. if self.verbose_logging:
  1330. print(f" ⚠️ 扩展数据获取异常:{str(e)}")
  1331. return existing_historical
  1332. def simulate_base_position_trading(self):
  1333. """
  1334. 模拟基础头寸交易
  1335. 为每种商品配置价格-数量网格,以指定价格水平和数量开立多头头寸
  1336. 所有头寸使用统一的退出价格(无止损)
  1337. """
  1338. if self.verbose_logging:
  1339. print("\n=== 步骤3: 基础头寸交易模拟 ===")
  1340. base_position_results = []
  1341. for commodity in self.price_data.keys():
  1342. if commodity not in self.base_position_grid:
  1343. continue
  1344. price_grid = self.base_position_grid[commodity]
  1345. exit_price = self.base_position_exit_price[commodity]
  1346. price_data = self.price_data[commodity]['data']
  1347. contract = self.price_data[commodity]['contract']
  1348. if self.verbose_logging:
  1349. print(f"\n分析 {commodity} ({contract}) 基础头寸交易")
  1350. print(f"价格网格: {price_grid}")
  1351. print(f"退出价格: {exit_price}")
  1352. # 遍历每个价格水平
  1353. for entry_price, quantity in price_grid.items():
  1354. # 查找触发入场的日期
  1355. entry_dates = []
  1356. for date, row in price_data.iterrows():
  1357. if row['low'] <= entry_price <= row['high']:
  1358. entry_dates.append(date)
  1359. if not entry_dates:
  1360. continue
  1361. # 使用第一个触发日期作为入场点
  1362. entry_date = entry_dates[0]
  1363. # 查找退出点
  1364. exit_date = None
  1365. exit_price_actual = exit_price
  1366. # 在入场后查找价格达到退出价格的日期
  1367. for date, row in price_data.iterrows():
  1368. if date > entry_date and row['high'] >= exit_price:
  1369. exit_date = date
  1370. exit_price_actual = min(exit_price, row['high'])
  1371. break
  1372. # 如果没有达到退出价格,使用最后一日的收盘价退出
  1373. if exit_date is None:
  1374. exit_date = price_data.index[-1]
  1375. exit_price_actual = price_data.iloc[-1]['close']
  1376. # 计算盈亏
  1377. profit_loss = (exit_price_actual - entry_price) * quantity
  1378. profit_loss_pct = (exit_price_actual - entry_price) / entry_price
  1379. trade_record = {
  1380. 'commodity': commodity,
  1381. 'contract': contract,
  1382. 'strategy': 'base_position',
  1383. 'entry_date': entry_date.strftime('%Y-%m-%d'),
  1384. 'exit_date': exit_date.strftime('%Y-%m-%d'),
  1385. 'entry_price': entry_price,
  1386. 'exit_price': exit_price_actual,
  1387. 'quantity': quantity,
  1388. 'profit_loss': profit_loss,
  1389. 'profit_loss_pct': profit_loss_pct,
  1390. 'days_held': (exit_date - entry_date).days
  1391. }
  1392. base_position_results.append(trade_record)
  1393. if self.verbose_logging:
  1394. print(f" 入场: {entry_date.strftime('%Y-%m-%d')} @ {entry_price}, 数量: {quantity}")
  1395. print(f" 出场: {exit_date.strftime('%Y-%m-%d')} @ {exit_price_actual:.2f}")
  1396. print(f" 盈亏: {profit_loss:.2f} ({profit_loss_pct:.2%})")
  1397. self.trading_results['base_position'] = base_position_results
  1398. if self.verbose_logging:
  1399. print(f"\n基础头寸交易模拟完成,共{len(base_position_results)}笔交易")
  1400. return base_position_results
  1401. def simulate_grid_trading(self):
  1402. """
  1403. 模拟网格交易策略
  1404. 从start_price开始,每次价格下降grid_size时买入quantity_per_grid
  1405. 当价格从入场价格上涨exit_grid_size时退出
  1406. """
  1407. if self.verbose_logging:
  1408. print("\n=== 步骤4: 网格交易策略模拟 ===")
  1409. grid_trading_results = []
  1410. for commodity in self.price_data.keys():
  1411. if commodity not in self.grid_trading_config:
  1412. continue
  1413. config = self.grid_trading_config[commodity]
  1414. start_price = config['start_price']
  1415. grid_size = config['grid_size']
  1416. quantity_per_grid = config['quantity_per_grid']
  1417. exit_grid_size = config['exit_grid_size']
  1418. price_data = self.price_data[commodity]['data']
  1419. contract = self.price_data[commodity]['contract']
  1420. if self.verbose_logging:
  1421. print(f"\n分析 {commodity} ({contract}) 网格交易")
  1422. print(f"起始价格: {start_price}, 网格大小: {grid_size}")
  1423. print(f"每网格数量: {quantity_per_grid}, 退出网格大小: {exit_grid_size}")
  1424. # 生成网格价格水平
  1425. grid_levels = []
  1426. current_level = start_price
  1427. min_price = price_data['low'].min()
  1428. while current_level > min_price:
  1429. grid_levels.append(current_level)
  1430. current_level -= grid_size
  1431. # 模拟每个网格水平的交易
  1432. for entry_price in grid_levels:
  1433. exit_price = entry_price + exit_grid_size
  1434. # 查找入场机会
  1435. entry_date = None
  1436. for date, row in price_data.iterrows():
  1437. if row['low'] <= entry_price <= row['high']:
  1438. entry_date = date
  1439. break
  1440. if entry_date is None:
  1441. continue
  1442. # 查找退出机会
  1443. exit_date = None
  1444. exit_price_actual = exit_price
  1445. for date, row in price_data.iterrows():
  1446. if date > entry_date and row['high'] >= exit_price:
  1447. exit_date = date
  1448. exit_price_actual = exit_price
  1449. break
  1450. # 如果没有达到退出价格,使用最后一日收盘价
  1451. if exit_date is None:
  1452. exit_date = price_data.index[-1]
  1453. exit_price_actual = price_data.iloc[-1]['close']
  1454. # 计算盈亏
  1455. profit_loss = (exit_price_actual - entry_price) * quantity_per_grid
  1456. profit_loss_pct = (exit_price_actual - entry_price) / entry_price
  1457. trade_record = {
  1458. 'commodity': commodity,
  1459. 'contract': contract,
  1460. 'strategy': 'grid_trading',
  1461. 'entry_date': entry_date.strftime('%Y-%m-%d'),
  1462. 'exit_date': exit_date.strftime('%Y-%m-%d'),
  1463. 'entry_price': entry_price,
  1464. 'exit_price': exit_price_actual,
  1465. 'quantity': quantity_per_grid,
  1466. 'profit_loss': profit_loss,
  1467. 'profit_loss_pct': profit_loss_pct,
  1468. 'days_held': (exit_date - entry_date).days
  1469. }
  1470. grid_trading_results.append(trade_record)
  1471. if self.verbose_logging:
  1472. print(f" 网格 {entry_price}: {entry_date.strftime('%Y-%m-%d')} -> {exit_date.strftime('%Y-%m-%d')}")
  1473. print(f" 盈亏: {profit_loss:.2f} ({profit_loss_pct:.2%})")
  1474. self.trading_results['grid_trading'] = grid_trading_results
  1475. if self.verbose_logging:
  1476. print(f"\n网格交易模拟完成,共{len(grid_trading_results)}笔交易")
  1477. return grid_trading_results
  1478. def calculate_performance_statistics(self):
  1479. """
  1480. 计算多品种多级聚合的性能统计
  1481. 包括品种-策略级、品种级、策略级和总体级统计
  1482. """
  1483. if self.verbose_logging:
  1484. print("\n=== 步骤6: 多级性能统计分析 ===")
  1485. # 多级统计结构
  1486. performance_stats = {
  1487. 'by_commodity_strategy': {}, # 品种-策略级统计
  1488. 'by_commodity': {}, # 品种级汇总
  1489. 'by_strategy': {}, # 策略级汇总
  1490. 'overall': {} # 总体汇总
  1491. }
  1492. if self.verbose_logging:
  1493. print("\n--- 第一级:品种-策略级统计 ---")
  1494. # 第一步:计算品种-策略级统计
  1495. for strategy_name, results in self.trading_results.items():
  1496. if strategy_name not in performance_stats['by_commodity_strategy']:
  1497. performance_stats['by_commodity_strategy'][strategy_name] = {}
  1498. # 按品种分组交易结果
  1499. commodity_results = {}
  1500. for result in results:
  1501. commodity = result['commodity']
  1502. if commodity not in commodity_results:
  1503. commodity_results[commodity] = []
  1504. commodity_results[commodity].append(result)
  1505. # 为每个品种计算统计
  1506. for commodity in self.core_commodities.keys():
  1507. comm_results = commodity_results.get(commodity, [])
  1508. stats = self._calculate_single_strategy_stats(strategy_name, comm_results, commodity)
  1509. performance_stats['by_commodity_strategy'][strategy_name][commodity] = stats
  1510. if self.verbose_logging:
  1511. print(f"\n{commodity}-{strategy_name} 策略统计:")
  1512. self._print_strategy_stats(stats)
  1513. if self.verbose_logging:
  1514. print("\n--- 第二级:品种级汇总统计 ---")
  1515. # 第二步:计算品种级汇总统计
  1516. for commodity in self.core_commodities.keys():
  1517. commodity_stats = self._calculate_commodity_summary(commodity, performance_stats['by_commodity_strategy'])
  1518. performance_stats['by_commodity'][commodity] = commodity_stats
  1519. if self.verbose_logging:
  1520. print(f"\n{commodity} 品种汇总统计:")
  1521. self._print_strategy_stats(commodity_stats)
  1522. if self.verbose_logging:
  1523. print("\n--- 第三级:策略级汇总统计 ---")
  1524. # 第三步:计算策略级汇总统计
  1525. for strategy_name in self.trading_results.keys():
  1526. strategy_stats = self._calculate_strategy_summary(strategy_name, performance_stats['by_commodity_strategy'])
  1527. performance_stats['by_strategy'][strategy_name] = strategy_stats
  1528. if self.verbose_logging:
  1529. print(f"\n{strategy_name} 策略汇总统计:")
  1530. self._print_strategy_stats(strategy_stats)
  1531. if self.verbose_logging:
  1532. print("\n--- 第四级:整体汇总统计 ---")
  1533. # 第四步:计算总体统计
  1534. overall_stats = self._calculate_overall_summary(performance_stats['by_strategy'])
  1535. performance_stats['overall'] = overall_stats
  1536. if self.verbose_logging:
  1537. print(f"\n整体汇总统计:")
  1538. self._print_strategy_stats(overall_stats)
  1539. return performance_stats
  1540. def _calculate_single_strategy_stats(self, strategy_name, results, commodity):
  1541. """计算单个策略在特定品种下的统计数据"""
  1542. # 计算已平仓交易的盈亏
  1543. closed_profit_loss = sum(r['profit_loss'] for r in results) if results else 0.0
  1544. # 计算未平仓头寸的未实现盈亏(特定品种)
  1545. unrealized_profit_loss = self._calculate_unrealized_pnl_for_commodity(strategy_name, commodity)
  1546. # 总盈亏 = 已实现盈亏 + 未实现盈亏
  1547. total_profit_loss = closed_profit_loss + unrealized_profit_loss
  1548. if not results and unrealized_profit_loss == 0:
  1549. return {
  1550. 'total_trades': 0,
  1551. 'open_positions': 0,
  1552. 'profitable_trades': 0,
  1553. 'losing_trades': 0,
  1554. 'win_rate': 0.0,
  1555. 'closed_profit_loss': 0.0,
  1556. 'unrealized_profit_loss': 0.0,
  1557. 'total_profit_loss': 0.0,
  1558. 'avg_profit_loss': 0.0,
  1559. 'avg_profit_loss_pct': 0.0,
  1560. 'max_profit': 0.0,
  1561. 'max_loss': 0.0,
  1562. 'avg_holding_days': 0.0,
  1563. 'profit_factor': 0.0
  1564. }
  1565. # 基本统计
  1566. total_trades = len(results)
  1567. open_positions = self._count_open_positions_for_commodity(strategy_name, commodity)
  1568. profitable_trades = sum(1 for r in results if r['profit_loss'] > 0)
  1569. losing_trades = sum(1 for r in results if r['profit_loss'] < 0)
  1570. win_rate = profitable_trades / total_trades if total_trades > 0 else 0
  1571. # 平均盈亏(基于已平仓交易)
  1572. avg_profit_loss = closed_profit_loss / total_trades if total_trades > 0 else 0
  1573. avg_profit_loss_pct = sum(r['profit_loss_pct'] for r in results) / total_trades if total_trades > 0 else 0
  1574. # 最大盈亏(基于已平仓交易)
  1575. profit_losses = [r['profit_loss'] for r in results]
  1576. max_profit = max(profit_losses) if profit_losses else 0
  1577. max_loss = min(profit_losses) if profit_losses else 0
  1578. # 平均持有天数
  1579. avg_holding_days = sum(r['days_held'] for r in results) / total_trades if total_trades > 0 else 0
  1580. # 盈亏比(基于已平仓交易)
  1581. total_profits = sum(r['profit_loss'] for r in results if r['profit_loss'] > 0)
  1582. total_losses = abs(sum(r['profit_loss'] for r in results if r['profit_loss'] < 0))
  1583. profit_factor = total_profits / total_losses if total_losses > 0 else float('inf') if total_profits > 0 else 0
  1584. return {
  1585. 'total_trades': total_trades,
  1586. 'open_positions': open_positions,
  1587. 'profitable_trades': profitable_trades,
  1588. 'losing_trades': losing_trades,
  1589. 'win_rate': win_rate,
  1590. 'closed_profit_loss': closed_profit_loss,
  1591. 'unrealized_profit_loss': unrealized_profit_loss,
  1592. 'total_profit_loss': total_profit_loss,
  1593. 'avg_profit_loss': avg_profit_loss,
  1594. 'avg_profit_loss_pct': avg_profit_loss_pct,
  1595. 'max_profit': max_profit,
  1596. 'max_loss': max_loss,
  1597. 'avg_holding_days': avg_holding_days,
  1598. 'profit_factor': profit_factor
  1599. }
  1600. def _print_strategy_stats(self, stats):
  1601. """打印策略统计信息"""
  1602. print(f" 已平仓交易: {stats['total_trades']}")
  1603. print(f" 未平仓头寸: {stats['open_positions']}")
  1604. print(f" 盈利交易: {stats['profitable_trades']}")
  1605. print(f" 亏损交易: {stats['losing_trades']}")
  1606. print(f" 胜率: {stats['win_rate']:.2%}")
  1607. print(f" 已实现盈亏: {stats['closed_profit_loss']:.2f}")
  1608. print(f" 未实现盈亏: {stats['unrealized_profit_loss']:.2f}")
  1609. print(f" 总盈亏: {stats['total_profit_loss']:.2f}")
  1610. print(f" 平均盈亏: {stats['avg_profit_loss']:.2f}")
  1611. print(f" 平均盈亏率: {stats['avg_profit_loss_pct']:.2%}")
  1612. print(f" 最大盈利: {stats['max_profit']:.2f}")
  1613. print(f" 最大亏损: {stats['max_loss']:.2f}")
  1614. print(f" 平均持有天数: {stats['avg_holding_days']:.1f}")
  1615. profit_factor_str = f"{stats['profit_factor']:.2f}" if stats['profit_factor'] != float('inf') else "∞"
  1616. print(f" 盈亏比: {profit_factor_str}")
  1617. def _calculate_commodity_summary(self, commodity, by_commodity_strategy):
  1618. """计算品种级汇总统计"""
  1619. total_stats = {
  1620. 'total_trades': 0,
  1621. 'open_positions': 0,
  1622. 'profitable_trades': 0,
  1623. 'losing_trades': 0,
  1624. 'closed_profit_loss': 0.0,
  1625. 'unrealized_profit_loss': 0.0,
  1626. 'total_profit_loss': 0.0,
  1627. 'max_profit': 0.0,
  1628. 'max_loss': 0.0,
  1629. 'total_holding_days': 0.0,
  1630. 'total_profits': 0.0,
  1631. 'total_losses': 0.0,
  1632. 'all_pct': []
  1633. }
  1634. for strategy_name, commodity_stats in by_commodity_strategy.items():
  1635. if commodity in commodity_stats:
  1636. stats = commodity_stats[commodity]
  1637. total_stats['total_trades'] += stats['total_trades']
  1638. total_stats['open_positions'] += stats['open_positions']
  1639. total_stats['profitable_trades'] += stats['profitable_trades']
  1640. total_stats['losing_trades'] += stats['losing_trades']
  1641. total_stats['closed_profit_loss'] += stats['closed_profit_loss']
  1642. total_stats['unrealized_profit_loss'] += stats['unrealized_profit_loss']
  1643. total_stats['total_profit_loss'] += stats['total_profit_loss']
  1644. total_stats['max_profit'] = max(total_stats['max_profit'], stats['max_profit'])
  1645. total_stats['max_loss'] = min(total_stats['max_loss'], stats['max_loss'])
  1646. total_stats['total_holding_days'] += stats['avg_holding_days'] * stats['total_trades']
  1647. if stats['profit_factor'] != float('inf'):
  1648. profits = stats['closed_profit_loss'] if stats['closed_profit_loss'] > 0 else 0
  1649. losses = abs(stats['closed_profit_loss']) if stats['closed_profit_loss'] < 0 else 0
  1650. total_stats['total_profits'] += profits
  1651. total_stats['total_losses'] += losses
  1652. # 收集所有百分比数据
  1653. if stats['total_trades'] > 0:
  1654. total_stats['all_pct'].extend([stats['avg_profit_loss_pct']] * stats['total_trades'])
  1655. # 计算汇总指标
  1656. win_rate = total_stats['profitable_trades'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1657. avg_profit_loss = total_stats['closed_profit_loss'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1658. avg_profit_loss_pct = sum(total_stats['all_pct']) / len(total_stats['all_pct']) if total_stats['all_pct'] else 0
  1659. avg_holding_days = total_stats['total_holding_days'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1660. profit_factor = total_stats['total_profits'] / total_stats['total_losses'] if total_stats['total_losses'] > 0 else float('inf') if total_stats['total_profits'] > 0 else 0
  1661. return {
  1662. 'total_trades': total_stats['total_trades'],
  1663. 'open_positions': total_stats['open_positions'],
  1664. 'profitable_trades': total_stats['profitable_trades'],
  1665. 'losing_trades': total_stats['losing_trades'],
  1666. 'win_rate': win_rate,
  1667. 'closed_profit_loss': total_stats['closed_profit_loss'],
  1668. 'unrealized_profit_loss': total_stats['unrealized_profit_loss'],
  1669. 'total_profit_loss': total_stats['total_profit_loss'],
  1670. 'avg_profit_loss': avg_profit_loss,
  1671. 'avg_profit_loss_pct': avg_profit_loss_pct,
  1672. 'max_profit': total_stats['max_profit'],
  1673. 'max_loss': total_stats['max_loss'],
  1674. 'avg_holding_days': avg_holding_days,
  1675. 'profit_factor': profit_factor
  1676. }
  1677. def _calculate_strategy_summary(self, strategy_name, by_commodity_strategy):
  1678. """计算策略级汇总统计"""
  1679. if strategy_name not in by_commodity_strategy:
  1680. return self._get_empty_stats()
  1681. strategy_stats = by_commodity_strategy[strategy_name]
  1682. total_stats = {
  1683. 'total_trades': 0,
  1684. 'open_positions': 0,
  1685. 'profitable_trades': 0,
  1686. 'losing_trades': 0,
  1687. 'closed_profit_loss': 0.0,
  1688. 'unrealized_profit_loss': 0.0,
  1689. 'total_profit_loss': 0.0,
  1690. 'max_profit': 0.0,
  1691. 'max_loss': 0.0,
  1692. 'total_holding_days': 0.0,
  1693. 'total_profits': 0.0,
  1694. 'total_losses': 0.0,
  1695. 'all_pct': []
  1696. }
  1697. for commodity, stats in strategy_stats.items():
  1698. total_stats['total_trades'] += stats['total_trades']
  1699. total_stats['open_positions'] += stats['open_positions']
  1700. total_stats['profitable_trades'] += stats['profitable_trades']
  1701. total_stats['losing_trades'] += stats['losing_trades']
  1702. total_stats['closed_profit_loss'] += stats['closed_profit_loss']
  1703. total_stats['unrealized_profit_loss'] += stats['unrealized_profit_loss']
  1704. total_stats['total_profit_loss'] += stats['total_profit_loss']
  1705. total_stats['max_profit'] = max(total_stats['max_profit'], stats['max_profit'])
  1706. total_stats['max_loss'] = min(total_stats['max_loss'], stats['max_loss'])
  1707. total_stats['total_holding_days'] += stats['avg_holding_days'] * stats['total_trades']
  1708. if stats['profit_factor'] != float('inf'):
  1709. profits = stats['closed_profit_loss'] if stats['closed_profit_loss'] > 0 else 0
  1710. losses = abs(stats['closed_profit_loss']) if stats['closed_profit_loss'] < 0 else 0
  1711. total_stats['total_profits'] += profits
  1712. total_stats['total_losses'] += losses
  1713. # 收集所有百分比数据
  1714. if stats['total_trades'] > 0:
  1715. total_stats['all_pct'].extend([stats['avg_profit_loss_pct']] * stats['total_trades'])
  1716. # 计算汇总指标
  1717. win_rate = total_stats['profitable_trades'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1718. avg_profit_loss = total_stats['closed_profit_loss'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1719. avg_profit_loss_pct = sum(total_stats['all_pct']) / len(total_stats['all_pct']) if total_stats['all_pct'] else 0
  1720. avg_holding_days = total_stats['total_holding_days'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1721. profit_factor = total_stats['total_profits'] / total_stats['total_losses'] if total_stats['total_losses'] > 0 else float('inf') if total_stats['total_profits'] > 0 else 0
  1722. return {
  1723. 'total_trades': total_stats['total_trades'],
  1724. 'open_positions': total_stats['open_positions'],
  1725. 'profitable_trades': total_stats['profitable_trades'],
  1726. 'losing_trades': total_stats['losing_trades'],
  1727. 'win_rate': win_rate,
  1728. 'closed_profit_loss': total_stats['closed_profit_loss'],
  1729. 'unrealized_profit_loss': total_stats['unrealized_profit_loss'],
  1730. 'total_profit_loss': total_stats['total_profit_loss'],
  1731. 'avg_profit_loss': avg_profit_loss,
  1732. 'avg_profit_loss_pct': avg_profit_loss_pct,
  1733. 'max_profit': total_stats['max_profit'],
  1734. 'max_loss': total_stats['max_loss'],
  1735. 'avg_holding_days': avg_holding_days,
  1736. 'profit_factor': profit_factor
  1737. }
  1738. def _calculate_overall_summary(self, by_strategy):
  1739. """计算总体汇总统计"""
  1740. total_stats = {
  1741. 'total_trades': 0,
  1742. 'open_positions': 0,
  1743. 'profitable_trades': 0,
  1744. 'losing_trades': 0,
  1745. 'closed_profit_loss': 0.0,
  1746. 'unrealized_profit_loss': 0.0,
  1747. 'total_profit_loss': 0.0,
  1748. 'max_profit': 0.0,
  1749. 'max_loss': 0.0,
  1750. 'total_holding_days': 0.0,
  1751. 'total_profits': 0.0,
  1752. 'total_losses': 0.0,
  1753. 'all_pct': []
  1754. }
  1755. for strategy_name, stats in by_strategy.items():
  1756. total_stats['total_trades'] += stats['total_trades']
  1757. total_stats['open_positions'] += stats['open_positions']
  1758. total_stats['profitable_trades'] += stats['profitable_trades']
  1759. total_stats['losing_trades'] += stats['losing_trades']
  1760. total_stats['closed_profit_loss'] += stats['closed_profit_loss']
  1761. total_stats['unrealized_profit_loss'] += stats['unrealized_profit_loss']
  1762. total_stats['total_profit_loss'] += stats['total_profit_loss']
  1763. total_stats['max_profit'] = max(total_stats['max_profit'], stats['max_profit'])
  1764. total_stats['max_loss'] = min(total_stats['max_loss'], stats['max_loss'])
  1765. total_stats['total_holding_days'] += stats['avg_holding_days'] * stats['total_trades']
  1766. if stats['profit_factor'] != float('inf'):
  1767. profits = stats['closed_profit_loss'] if stats['closed_profit_loss'] > 0 else 0
  1768. losses = abs(stats['closed_profit_loss']) if stats['closed_profit_loss'] < 0 else 0
  1769. total_stats['total_profits'] += profits
  1770. total_stats['total_losses'] += losses
  1771. # 收集所有百分比数据
  1772. if stats['total_trades'] > 0:
  1773. total_stats['all_pct'].extend([stats['avg_profit_loss_pct']] * stats['total_trades'])
  1774. # 计算汇总指标
  1775. win_rate = total_stats['profitable_trades'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1776. avg_profit_loss = total_stats['closed_profit_loss'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1777. avg_profit_loss_pct = sum(total_stats['all_pct']) / len(total_stats['all_pct']) if total_stats['all_pct'] else 0
  1778. avg_holding_days = total_stats['total_holding_days'] / total_stats['total_trades'] if total_stats['total_trades'] > 0 else 0
  1779. profit_factor = total_stats['total_profits'] / total_stats['total_losses'] if total_stats['total_losses'] > 0 else float('inf') if total_stats['total_profits'] > 0 else 0
  1780. return {
  1781. 'total_trades': total_stats['total_trades'],
  1782. 'open_positions': total_stats['open_positions'],
  1783. 'profitable_trades': total_stats['profitable_trades'],
  1784. 'losing_trades': total_stats['losing_trades'],
  1785. 'win_rate': win_rate,
  1786. 'closed_profit_loss': total_stats['closed_profit_loss'],
  1787. 'unrealized_profit_loss': total_stats['unrealized_profit_loss'],
  1788. 'total_profit_loss': total_stats['total_profit_loss'],
  1789. 'avg_profit_loss': avg_profit_loss,
  1790. 'avg_profit_loss_pct': avg_profit_loss_pct,
  1791. 'max_profit': total_stats['max_profit'],
  1792. 'max_loss': total_stats['max_loss'],
  1793. 'avg_holding_days': avg_holding_days,
  1794. 'profit_factor': profit_factor
  1795. }
  1796. def _get_empty_stats(self):
  1797. """返回空的统计数据"""
  1798. return {
  1799. 'total_trades': 0,
  1800. 'open_positions': 0,
  1801. 'profitable_trades': 0,
  1802. 'losing_trades': 0,
  1803. 'win_rate': 0.0,
  1804. 'closed_profit_loss': 0.0,
  1805. 'unrealized_profit_loss': 0.0,
  1806. 'total_profit_loss': 0.0,
  1807. 'avg_profit_loss': 0.0,
  1808. 'avg_profit_loss_pct': 0.0,
  1809. 'max_profit': 0.0,
  1810. 'max_loss': 0.0,
  1811. 'avg_holding_days': 0.0,
  1812. 'profit_factor': 0.0
  1813. }
  1814. def _calculate_unrealized_pnl_for_commodity(self, strategy_name, commodity):
  1815. """计算特定品种未平仓头寸的未实现盈亏"""
  1816. unrealized_pnl = 0.0
  1817. strategy_positions = self.active_positions.get(strategy_name, {})
  1818. if commodity in strategy_positions:
  1819. current_contract = self._get_current_contract(commodity, self.end_date.date())
  1820. if not current_contract:
  1821. return 0.0
  1822. end_price = self._get_price_on_date(commodity, current_contract, self.end_date.date(), 'close')
  1823. if end_price is None:
  1824. return 0.0
  1825. positions = strategy_positions[commodity]
  1826. for position_id, position in positions.items():
  1827. if position['status'] == 'open' and position['contract'] == current_contract:
  1828. # 基础头寸和网格交易都是做多
  1829. pnl = self._calculate_futures_pnl(
  1830. position['entry_price'], end_price, position['quantity'], commodity, is_long=True
  1831. )
  1832. unrealized_pnl += pnl
  1833. return unrealized_pnl
  1834. def _count_open_positions_for_commodity(self, strategy_name, commodity):
  1835. """计算特定品种的未平仓头寸数量"""
  1836. count = 0
  1837. strategy_positions = self.active_positions.get(strategy_name, {})
  1838. if commodity in strategy_positions:
  1839. positions = strategy_positions[commodity]
  1840. for position_id, position in positions.items():
  1841. if position['status'] == 'open':
  1842. count += 1
  1843. return count
  1844. def _calculate_unrealized_pnl(self, strategy_name):
  1845. """
  1846. 计算未平仓头寸的未实现盈亏
  1847. """
  1848. unrealized_pnl = 0.0
  1849. # 获取策略对应的头寸字典
  1850. strategy_positions = self.active_positions.get(strategy_name, {})
  1851. for commodity, positions in strategy_positions.items():
  1852. # 获取当前合约和最新价格
  1853. current_contract = self._get_current_contract(commodity, self.end_date.date())
  1854. if not current_contract:
  1855. continue
  1856. # 获取结束日期的收盘价
  1857. end_price = self._get_price_on_date(commodity, current_contract, self.end_date.date(), 'close')
  1858. if end_price is None:
  1859. continue
  1860. for position_id, position in positions.items():
  1861. if position['status'] == 'open' and position['contract'] == current_contract:
  1862. # 基础头寸和网格交易都是做多
  1863. pnl = self._calculate_futures_pnl(
  1864. position['entry_price'], end_price, position['quantity'], commodity, is_long=True
  1865. )
  1866. unrealized_pnl += pnl
  1867. return unrealized_pnl
  1868. def _count_open_positions(self, strategy_name):
  1869. """
  1870. 计算未平仓头寸数量
  1871. """
  1872. count = 0
  1873. strategy_positions = self.active_positions.get(strategy_name, {})
  1874. for commodity, positions in strategy_positions.items():
  1875. for position_id, position in positions.items():
  1876. if position['status'] == 'open':
  1877. count += 1
  1878. return count
  1879. def generate_comparison_report(self, performance_stats):
  1880. """
  1881. 生成多级聚合的对比报告
  1882. 包括品种-策略级、品种级、策略级和总体级报告
  1883. """
  1884. if self.verbose_logging:
  1885. print("\n=== 多级聚合对比分析报告 ===")
  1886. strategies = ['base_position', 'grid_trading']
  1887. strategy_names = {
  1888. 'base_position': '基础头寸交易',
  1889. 'grid_trading': '网格交易'
  1890. }
  1891. all_comparison_data = {
  1892. 'by_commodity_strategy': [],
  1893. 'by_commodity': [],
  1894. 'by_strategy': [],
  1895. 'overall': []
  1896. }
  1897. # 1. 品种-策略级对比报告
  1898. if self.verbose_logging:
  1899. print("\n--- 品种-策略级对比 ---")
  1900. by_comm_strategy_data = []
  1901. for strategy in strategies:
  1902. for commodity in self.core_commodities.keys():
  1903. stats = performance_stats['by_commodity_strategy'].get(strategy, {}).get(commodity, {})
  1904. if stats.get('total_trades', 0) > 0 or stats.get('open_positions', 0) > 0:
  1905. by_comm_strategy_data.append({
  1906. '品种': commodity,
  1907. '策略': strategy_names[strategy],
  1908. '已平仓': stats.get('total_trades', 0),
  1909. '未平仓': stats.get('open_positions', 0),
  1910. '胜率': f"{stats.get('win_rate', 0):.2%}",
  1911. '已实现': f"{stats.get('closed_profit_loss', 0):.2f}",
  1912. '未实现': f"{stats.get('unrealized_profit_loss', 0):.2f}",
  1913. '总盈亏': f"{stats.get('total_profit_loss', 0):.2f}",
  1914. '平均盈亏': f"{stats.get('avg_profit_loss', 0):.2f}",
  1915. '最大盈利': f"{stats.get('max_profit', 0):.2f}",
  1916. '最大亏损': f"{stats.get('max_loss', 0):.2f}",
  1917. '平均天数': f"{stats.get('avg_holding_days', 0):.1f}",
  1918. '盈亏比': f"{stats.get('profit_factor', 0):.2f}" if stats.get('profit_factor', 0) != float('inf') else "∞"
  1919. })
  1920. if by_comm_strategy_data and self.verbose_logging:
  1921. df_comm_strategy = pd.DataFrame(by_comm_strategy_data)
  1922. print(df_comm_strategy.to_string(index=False))
  1923. all_comparison_data['by_commodity_strategy'] = by_comm_strategy_data
  1924. # 2. 品种级汇总对比报告
  1925. if self.verbose_logging:
  1926. print("\n--- 品种级汇总对比 ---")
  1927. by_commodity_data = []
  1928. for commodity in self.core_commodities.keys():
  1929. stats = performance_stats['by_commodity'].get(commodity, {})
  1930. if stats.get('total_trades', 0) > 0 or stats.get('open_positions', 0) > 0:
  1931. by_commodity_data.append({
  1932. '品种': commodity,
  1933. '已平仓': stats.get('total_trades', 0),
  1934. '未平仓': stats.get('open_positions', 0),
  1935. '胜率': f"{stats.get('win_rate', 0):.2%}",
  1936. '已实现': f"{stats.get('closed_profit_loss', 0):.2f}",
  1937. '未实现': f"{stats.get('unrealized_profit_loss', 0):.2f}",
  1938. '总盈亏': f"{stats.get('total_profit_loss', 0):.2f}",
  1939. '平均盈亏': f"{stats.get('avg_profit_loss', 0):.2f}",
  1940. '最大盈利': f"{stats.get('max_profit', 0):.2f}",
  1941. '最大亏损': f"{stats.get('max_loss', 0):.2f}",
  1942. '平均天数': f"{stats.get('avg_holding_days', 0):.1f}",
  1943. '盈亏比': f"{stats.get('profit_factor', 0):.2f}" if stats.get('profit_factor', 0) != float('inf') else "∞"
  1944. })
  1945. if by_commodity_data and self.verbose_logging:
  1946. df_commodity = pd.DataFrame(by_commodity_data)
  1947. print(df_commodity.to_string(index=False))
  1948. all_comparison_data['by_commodity'] = by_commodity_data
  1949. # 3. 策略级汇总对比报告
  1950. if self.verbose_logging:
  1951. print("\n--- 策略级汇总对比 ---")
  1952. by_strategy_data = []
  1953. for strategy in strategies:
  1954. stats = performance_stats['by_strategy'].get(strategy, {})
  1955. by_strategy_data.append({
  1956. '策略': strategy_names[strategy],
  1957. '已平仓': stats.get('total_trades', 0),
  1958. '未平仓': stats.get('open_positions', 0),
  1959. '胜率': f"{stats.get('win_rate', 0):.2%}",
  1960. '已实现': f"{stats.get('closed_profit_loss', 0):.2f}",
  1961. '未实现': f"{stats.get('unrealized_profit_loss', 0):.2f}",
  1962. '总盈亏': f"{stats.get('total_profit_loss', 0):.2f}",
  1963. '平均盈亏': f"{stats.get('avg_profit_loss', 0):.2f}",
  1964. '最大盈利': f"{stats.get('max_profit', 0):.2f}",
  1965. '最大亏损': f"{stats.get('max_loss', 0):.2f}",
  1966. '平均天数': f"{stats.get('avg_holding_days', 0):.1f}",
  1967. '盈亏比': f"{stats.get('profit_factor', 0):.2f}" if stats.get('profit_factor', 0) != float('inf') else "∞"
  1968. })
  1969. if by_strategy_data and self.verbose_logging:
  1970. df_strategy = pd.DataFrame(by_strategy_data)
  1971. print(df_strategy.to_string(index=False))
  1972. all_comparison_data['by_strategy'] = by_strategy_data
  1973. # 4. 总体汇总报告
  1974. if self.verbose_logging:
  1975. print("\n--- 整体汇总 ---")
  1976. overall_data = []
  1977. stats = performance_stats['overall']
  1978. overall_data.append({
  1979. '项目': '整体表现',
  1980. '已平仓': stats.get('total_trades', 0),
  1981. '未平仓': stats.get('open_positions', 0),
  1982. '胜率': f"{stats.get('win_rate', 0):.2%}",
  1983. '已实现': f"{stats.get('closed_profit_loss', 0):.2f}",
  1984. '未实现': f"{stats.get('unrealized_profit_loss', 0):.2f}",
  1985. '总盈亏': f"{stats.get('total_profit_loss', 0):.2f}",
  1986. '平均盈亏': f"{stats.get('avg_profit_loss', 0):.2f}",
  1987. '最大盈利': f"{stats.get('max_profit', 0):.2f}",
  1988. '最大亏损': f"{stats.get('max_loss', 0):.2f}",
  1989. '平均天数': f"{stats.get('avg_holding_days', 0):.1f}",
  1990. '盈亏比': f"{stats.get('profit_factor', 0):.2f}" if stats.get('profit_factor', 0) != float('inf') else "∞"
  1991. })
  1992. if overall_data and self.verbose_logging:
  1993. df_overall = pd.DataFrame(overall_data)
  1994. print(df_overall.to_string(index=False))
  1995. all_comparison_data['overall'] = overall_data
  1996. return all_comparison_data
  1997. def generate_csv_output(self, performance_stats):
  1998. """
  1999. 生成CSV输出文件
  2000. """
  2001. if self.verbose_logging:
  2002. print("\n=== 步骤8: 生成CSV输出文件 ===")
  2003. timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
  2004. # 1. 生成交易记录CSV
  2005. all_trades = []
  2006. for strategy_name, trades in self.trading_results.items():
  2007. all_trades.extend(trades)
  2008. if all_trades:
  2009. df_trades = pd.DataFrame(all_trades)
  2010. # 添加列顺序,确保合约切换相关字段在前面
  2011. column_order = ['commodity', 'contract', 'strategy', 'entry_date', 'exit_date',
  2012. 'entry_price', 'exit_price', 'quantity', 'profit_loss', 'profit_loss_pct',
  2013. 'days_held', 'exit_reason']
  2014. # 重新排列DataFrame的列顺序
  2015. existing_columns = [col for col in column_order if col in df_trades.columns]
  2016. other_columns = [col for col in df_trades.columns if col not in column_order]
  2017. df_trades = df_trades[existing_columns + other_columns]
  2018. trades_filename = f'grid_trading_records_{timestamp}.csv'
  2019. df_trades.to_csv(trades_filename, index=False, encoding=self.output_encoding)
  2020. if self.verbose_logging:
  2021. print(f"交易记录已保存至: {trades_filename}")
  2022. # 2. 生成多级性能统计CSV
  2023. csv_files = []
  2024. # 2.1 品种-策略级统计CSV
  2025. by_comm_strategy_data = []
  2026. for strategy, commodity_data in performance_stats['by_commodity_strategy'].items():
  2027. for commodity, stats in commodity_data.items():
  2028. stats_record = {
  2029. '品种': commodity,
  2030. '策略': strategy,
  2031. **stats
  2032. }
  2033. by_comm_strategy_data.append(stats_record)
  2034. if by_comm_strategy_data:
  2035. df_comm_strategy = pd.DataFrame(by_comm_strategy_data)
  2036. comm_strategy_filename = f'grid_trading_by_commodity_strategy_{timestamp}.csv'
  2037. df_comm_strategy.to_csv(comm_strategy_filename, index=False, encoding=self.output_encoding)
  2038. csv_files.append(comm_strategy_filename)
  2039. if self.verbose_logging:
  2040. print(f"品种-策略级统计已保存至: {comm_strategy_filename}")
  2041. # 2.2 品种级汇总统计CSV
  2042. by_commodity_data = []
  2043. for commodity, stats in performance_stats['by_commodity'].items():
  2044. stats_record = {
  2045. '品种': commodity,
  2046. **stats
  2047. }
  2048. by_commodity_data.append(stats_record)
  2049. if by_commodity_data:
  2050. df_commodity = pd.DataFrame(by_commodity_data)
  2051. commodity_filename = f'grid_trading_by_commodity_{timestamp}.csv'
  2052. df_commodity.to_csv(commodity_filename, index=False, encoding=self.output_encoding)
  2053. csv_files.append(commodity_filename)
  2054. if self.verbose_logging:
  2055. print(f"品种级汇总统计已保存至: {commodity_filename}")
  2056. # 2.3 策略级汇总统计CSV
  2057. by_strategy_data = []
  2058. for strategy, stats in performance_stats['by_strategy'].items():
  2059. stats_record = {
  2060. '策略': strategy,
  2061. **stats
  2062. }
  2063. by_strategy_data.append(stats_record)
  2064. if by_strategy_data:
  2065. df_strategy = pd.DataFrame(by_strategy_data)
  2066. strategy_filename = f'grid_trading_by_strategy_{timestamp}.csv'
  2067. df_strategy.to_csv(strategy_filename, index=False, encoding=self.output_encoding)
  2068. csv_files.append(strategy_filename)
  2069. if self.verbose_logging:
  2070. print(f"策略级汇总统计已保存至: {strategy_filename}")
  2071. # 2.4 整体汇总统计CSV
  2072. overall_data = [{
  2073. '项目': '整体汇总',
  2074. **performance_stats['overall']
  2075. }]
  2076. if overall_data:
  2077. df_overall = pd.DataFrame(overall_data)
  2078. overall_filename = f'grid_trading_overall_{timestamp}.csv'
  2079. df_overall.to_csv(overall_filename, index=False, encoding=self.output_encoding)
  2080. csv_files.append(overall_filename)
  2081. if self.verbose_logging:
  2082. print(f"整体汇总统计已保存至: {overall_filename}")
  2083. return trades_filename if all_trades else None, csv_files
  2084. def run_complete_analysis(self):
  2085. """执行完整的网格交易分析流程(带主力合约切换)"""
  2086. if self.verbose_logging:
  2087. print("开始执行期货网格交易分析(带主力合约切换)")
  2088. print("=" * 60)
  2089. try:
  2090. # 步骤1: 合约选择
  2091. self.select_contracts()
  2092. if not self.selected_contracts:
  2093. if self.verbose_logging:
  2094. print("未选择到有效合约,分析终止")
  2095. return None
  2096. # 步骤2: 构建主力合约历史变化
  2097. self.build_dominant_contract_history()
  2098. if not self.dominant_contract_history:
  2099. if self.verbose_logging:
  2100. print("未获取到主力合约历史,分析终止")
  2101. return None
  2102. # 步骤3: 收集价格数据
  2103. self.collect_price_data()
  2104. if not self.price_data:
  2105. if self.verbose_logging:
  2106. print("未获取到有效价格数据,分析终止")
  2107. return None
  2108. # 步骤4: 带合约切换的交易模拟
  2109. self.simulate_with_contract_switching()
  2110. # 步骤5: 性能统计分析
  2111. performance_stats = self.calculate_performance_statistics()
  2112. # 步骤6: 生成对比报告
  2113. comparison_report = self.generate_comparison_report(performance_stats)
  2114. # 步骤8: 生成CSV输出
  2115. # trades_file, stats_files = self.generate_csv_output(performance_stats)
  2116. # 分析汇总
  2117. total_commodities = len(self.selected_contracts)
  2118. total_trades = sum(len(trades) for trades in self.trading_results.values())
  2119. contract_switches = sum(len(history) for history in self.dominant_contract_history.values())
  2120. if self.verbose_logging:
  2121. print("\n" + "=" * 60)
  2122. print("分析完成汇总:")
  2123. print(f"分析商品数: {total_commodities}")
  2124. print(f"合约切换次数: {contract_switches}")
  2125. print(f"总交易笔数: {total_trades}")
  2126. # print(f"交易记录文件: {trades_file}")
  2127. # print(f"性能统计文件: {stats_file}")
  2128. return {
  2129. 'selected_contracts': self.selected_contracts,
  2130. 'dominant_contract_history': self.dominant_contract_history,
  2131. 'price_data': self.price_data,
  2132. 'trading_results': self.trading_results,
  2133. 'performance_stats': performance_stats,
  2134. 'comparison_report': comparison_report,
  2135. # 'output_files': {
  2136. # 'trades_file': trades_file,
  2137. # 'stats_files': stats_files
  2138. # },
  2139. 'summary': {
  2140. 'total_commodities': total_commodities,
  2141. 'contract_switches': contract_switches,
  2142. 'total_trades': total_trades
  2143. }
  2144. }
  2145. except Exception as e:
  2146. if self.verbose_logging:
  2147. print(f"分析过程中出现错误: {str(e)}")
  2148. import traceback
  2149. traceback.print_exc()
  2150. return None
  2151. # =====================================================================================
  2152. # 主程序入口
  2153. # =====================================================================================
  2154. def run_grid_trading_analysis(config=None):
  2155. """运行期货网格交易分析"""
  2156. if config is None:
  2157. config = GridTradingConfig
  2158. # 打印配置信息
  2159. config.print_config()
  2160. # 创建分析器并运行
  2161. analyzer = FutureGridTradingAnalyzer(config)
  2162. results = analyzer.run_complete_analysis()
  2163. return results
  2164. # 执行分析
  2165. if __name__ == "__main__":
  2166. print("期货网格交易研究分析工具(带主力合约切换)")
  2167. print("研究期货网格交易策略在不同配置下的表现")
  2168. print("核心功能包括主力合约自动切换、强制平仓和重新建仓逻辑")
  2169. print("")
  2170. print("支持两种独立交易策略的分析:")
  2171. print(" 1. 基础头寸交易 - 价格-数量网格配置")
  2172. print(" 2. 网格交易策略 - 限价订单网格买入卖出")
  2173. print("")
  2174. print("主要特点:")
  2175. print(" - 主力合约自动监控:每日检测主力合约变化")
  2176. print(" - 强制平仓机制:合约切换时立即平掉旧合约所有头寸")
  2177. print(" - 智能重新建仓:根据价格条件在新合约中重新建立头寸")
  2178. print(" - 完整交易记录:记录所有交易包括合约切换引起的强制平仓")
  2179. print("")
  2180. print("适用于聚宽在线研究平台")
  2181. results = run_grid_trading_analysis()
  2182. if results:
  2183. print("\n✅ 分析执行成功!")
  2184. summary = results['summary']
  2185. print(f"📊 结果摘要:")
  2186. print(f" - 分析商品数: {summary['total_commodities']}")
  2187. print(f" - 合约切换次数: {summary['contract_switches']}")
  2188. print(f" - 总交易笔数: {summary['total_trades']}")
  2189. print(f" - 整体总盈亏: {results['performance_stats']['overall']['total_profit_loss']:.2f}")
  2190. print(f" - 整体胜率: {results['performance_stats']['overall']['win_rate']:.2%}")
  2191. print(f" - 未平仓头寸: {results['performance_stats']['overall']['open_positions']}")
  2192. print(f"📂 输出文件:")
  2193. print(f" - 交易记录文件: {results['output_files']['trades_file']}")
  2194. for i, stats_file in enumerate(results['output_files']['stats_files'], 1):
  2195. print(f" - 统计文件{i}: {stats_file}")
  2196. print(f"\n📈 多级汇总:")
  2197. # 品种级汇总简要显示
  2198. print(f" 品种表现:")
  2199. for commodity in ['SA', 'M']:
  2200. comm_stats = results['performance_stats']['by_commodity'].get(commodity, {})
  2201. if comm_stats.get('total_trades', 0) > 0 or comm_stats.get('open_positions', 0) > 0:
  2202. print(f" {commodity}: 交易{comm_stats.get('total_trades', 0)}笔, 盈亏{comm_stats.get('total_profit_loss', 0):.2f}, 胜率{comm_stats.get('win_rate', 0):.2%}")
  2203. # 策略级汇总简要显示
  2204. print(f" 策略表现:")
  2205. strategy_names = {
  2206. 'base_position': '基础头寸',
  2207. 'grid_trading': '网格交易'
  2208. }
  2209. for strategy, name in strategy_names.items():
  2210. strat_stats = results['performance_stats']['by_strategy'].get(strategy, {})
  2211. print(f" {name}: 交易{strat_stats.get('total_trades', 0)}笔, 盈亏{strat_stats.get('total_profit_loss', 0):.2f}, 胜率{strat_stats.get('win_rate', 0):.2%}")
  2212. else:
  2213. print("\n❌ 分析执行失败,请检查错误信息")