auto_report.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 创业板50指数 - 自动化交易报告系统 (独立版)
  5. 功能:
  6. 1. 获取近2个月数据
  7. 2. 运行策略回测
  8. 3. 生成详细报告
  9. 4. 发送邮件通知
  10. 执行频率:A股开盘时间每半小时(9:30-11:30, 13:00-15:00)
  11. """
  12. import pandas as pd
  13. import numpy as np
  14. import akshare as ak
  15. import warnings
  16. import os
  17. import smtplib
  18. import ssl
  19. from datetime import datetime, timedelta
  20. from email.mime.text import MIMEText
  21. from email.mime.multipart import MIMEMultipart
  22. from email.header import Header
  23. warnings.filterwarnings('ignore')
  24. # ==================== 邮件配置 ====================
  25. # 使用本地Postfix SMTP服务器发送
  26. EMAIL_CONFIG = {
  27. "smtp_server": "localhost", # 本地Postfix服务器
  28. "smtp_port": 25, # SMTP端口
  29. "sender_email": "catfly@openclaw.local", # 发件人邮箱
  30. "sender_password": "", # 本地SMTP无需密码
  31. "receiver_email": "380880504@qq.com" # 收件人邮箱
  32. }
  33. def send_email(subject, html_content, text_content=""):
  34. """发送邮件 - 使用本地Postfix"""
  35. try:
  36. msg = MIMEMultipart('alternative')
  37. msg['Subject'] = Header(subject, 'utf-8')
  38. msg['From'] = EMAIL_CONFIG['sender_email']
  39. msg['To'] = EMAIL_CONFIG['receiver_email']
  40. # 纯文本版本
  41. text_part = MIMEText(text_content, 'plain', 'utf-8')
  42. msg.attach(text_part)
  43. # HTML版本
  44. html_part = MIMEText(html_content, 'html', 'utf-8')
  45. msg.attach(html_part)
  46. # 发送邮件 - 本地Postfix无需SSL和认证
  47. with smtplib.SMTP(EMAIL_CONFIG['smtp_server'], EMAIL_CONFIG['smtp_port']) as server:
  48. server.sendmail(
  49. EMAIL_CONFIG['sender_email'],
  50. EMAIL_CONFIG['receiver_email'],
  51. msg.as_string()
  52. )
  53. print(f"✅ 邮件发送成功: {subject}")
  54. return True
  55. except Exception as e:
  56. print(f"❌ 邮件发送失败: {e}")
  57. print(f" 请检查EMAIL_CONFIG配置是否正确")
  58. return False
  59. # ==================== 数据获取 ====================
  60. class DataFetcher:
  61. """数据获取类 - 使用实时在线数据"""
  62. @staticmethod
  63. def fetch_recent_2months():
  64. """获取近2个月数据 - 使用实时在线数据(东方财富+新浪财经双数据源)"""
  65. end_date = datetime.now()
  66. start_date = end_date - timedelta(days=70) # 2个月+10天缓冲
  67. print(f"获取数据: {start_date.strftime('%Y-%m-%d')} 至 {end_date.strftime('%Y-%m-%d')}")
  68. # 尝试东方财富数据源
  69. df = DataFetcher._fetch_eastmoney_data(start_date, end_date)
  70. if df is not None:
  71. return df
  72. # 东方财富失败,尝试新浪财经
  73. print("⚠️ 东方财富数据源失败,尝试新浪财经...")
  74. df = DataFetcher._fetch_sina_data(start_date, end_date)
  75. if df is not None:
  76. return df
  77. # 所有数据源都失败
  78. raise Exception("无法获取实时数据,东方财富和新浪财经均失败。请检查网络连接或稍后重试。")
  79. @staticmethod
  80. def _fetch_eastmoney_data(start_date, end_date):
  81. """从东方财富获取数据"""
  82. try:
  83. print("[数据源1] 正在使用东方财富30分钟K线接口...")
  84. # 使用东方财富接口获取30分钟K线
  85. df = ak.index_zh_a_hist_min_em(symbol="399673", period="30")
  86. if df is not None and not df.empty and len(df) >= 50:
  87. # 标准化列名
  88. df = df.rename(columns={
  89. '时间': 'datetime',
  90. '开盘': 'open',
  91. '收盘': 'close',
  92. '最高': 'high',
  93. '最低': 'low',
  94. '成交量': 'volume'
  95. })
  96. df['datetime'] = pd.to_datetime(df['datetime'])
  97. df = df.set_index('datetime').sort_index()
  98. # 只保留最近2个月的数据用于回测
  99. backtest_start = end_date - timedelta(days=60)
  100. df_backtest = df[df.index >= backtest_start]
  101. print(f"✅ 东方财富数据获取成功: 共{len(df_backtest)}条30分钟K线")
  102. print(f" 数据区间: {df_backtest.index[0]} 至 {df_backtest.index[-1]}")
  103. # 检查数据时效性
  104. latest_time = df_backtest.index[-1]
  105. time_delay = end_date - latest_time
  106. print(f" 数据延迟: {time_delay}")
  107. return df_backtest
  108. else:
  109. print(f"⚠️ 东方财富数据不足: {len(df) if df is not None else 0}条")
  110. return None
  111. except Exception as e:
  112. print(f"❌ 东方财富数据源失败: {e}")
  113. return None
  114. @staticmethod
  115. def _fetch_sina_data(start_date, end_date):
  116. """从新浪财经获取数据"""
  117. try:
  118. print("[数据源2] 正在使用新浪财经30分钟K线接口...")
  119. import requests
  120. import json
  121. import re
  122. symbol = "sz399673"
  123. url = f"https://quotes.sina.cn/cn/api/jsonp_v2.php/var_{symbol}_30_/CN_MarketDataService.getKLineData?symbol={symbol}&scale=30&ma=no&datalen=1023"
  124. headers = {
  125. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
  126. 'Referer': 'https://finance.sina.com.cn/'
  127. }
  128. response = requests.get(url, headers=headers, timeout=15)
  129. response_text = response.text
  130. # 解析JSONP响应
  131. json_start = response_text.find('[')
  132. json_end = response_text.rfind(']') + 1
  133. if json_start >= 0 and json_end > json_start:
  134. json_str = response_text[json_start:json_end]
  135. else:
  136. raise Exception("无法解析JSONP响应")
  137. data_dict = json.loads(json_str)
  138. if data_dict and isinstance(data_dict, list) and len(data_dict) > 0:
  139. data_list = []
  140. for item in data_dict:
  141. try:
  142. data_list.append({
  143. 'datetime': item.get('day'),
  144. 'open': float(item.get('open', 0)),
  145. 'high': float(item.get('high', 0)),
  146. 'low': float(item.get('low', 0)),
  147. 'close': float(item.get('close', 0)),
  148. 'volume': float(item.get('volume', 0))
  149. })
  150. except Exception:
  151. continue
  152. if data_list:
  153. df = pd.DataFrame(data_list)
  154. df['datetime'] = pd.to_datetime(df['datetime'])
  155. df = df.set_index('datetime').sort_index()
  156. # 只保留最近2个月的数据
  157. backtest_start = end_date - timedelta(days=60)
  158. df_backtest = df[df.index >= backtest_start]
  159. print(f"✅ 新浪财经数据获取成功: 共{len(df_backtest)}条30分钟K线")
  160. print(f" 数据区间: {df_backtest.index[0]} 至 {df_backtest.index[-1]}")
  161. return df_backtest
  162. else:
  163. print("❌ 新浪财经数据解析失败")
  164. return None
  165. else:
  166. print("❌ 新浪财经返回数据格式错误")
  167. return None
  168. except Exception as e:
  169. print(f"❌ 新浪财经数据源失败: {e}")
  170. return None
  171. # ==================== 策略类 ====================
  172. class CatFlyStrategy:
  173. """cat-fly策略简化版 - 基于30分钟K线"""
  174. def __init__(self, config=None):
  175. self.config = config or {
  176. 'initial_capital': 1000000,
  177. 'position_size_pct': 1.0,
  178. 'stop_loss_pct': 0.008,
  179. 'take_profit_pct': 0.02,
  180. 'max_hold_bars': 16,
  181. 'min_signal_strength': 3
  182. }
  183. self.initial_capital = self.config['initial_capital']
  184. def calculate_indicators(self, df):
  185. """计算技术指标"""
  186. # RSI
  187. delta = df['close'].diff()
  188. gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
  189. loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
  190. rs = gain / loss
  191. df['RSI'] = 100 - (100 / (1 + rs))
  192. # 移动平均线
  193. df['MA5'] = df['close'].rolling(5).mean()
  194. df['MA20'] = df['close'].rolling(20).mean()
  195. df['MA60'] = df['close'].rolling(60).mean()
  196. # 布林带
  197. df['BB_middle'] = df['close'].rolling(20).mean()
  198. bb_std = df['close'].rolling(20).std()
  199. df['BB_upper'] = df['BB_middle'] + 2 * bb_std
  200. df['BB_lower'] = df['BB_middle'] - 2 * bb_std
  201. # MACD
  202. ema12 = df['close'].ewm(span=12).mean()
  203. ema26 = df['close'].ewm(span=26).mean()
  204. df['MACD'] = ema12 - ema26
  205. df['MACD_signal'] = df['MACD'].ewm(span=9).mean()
  206. return df
  207. def generate_signals(self, df):
  208. """生成交易信号"""
  209. df = self.calculate_indicators(df)
  210. df['signal'] = 0
  211. df['signal_strength'] = 0
  212. for i in range(60, len(df)):
  213. row = df.iloc[i]
  214. strength = 0
  215. # RSI超卖/超买
  216. if row['RSI'] < 30:
  217. strength += 1
  218. elif row['RSI'] > 70:
  219. strength -= 1
  220. # 均线多头排列/空头排列
  221. if row['close'] > row['MA5'] > row['MA20']:
  222. strength += 1
  223. elif row['close'] < row['MA5'] < row['MA20']:
  224. strength -= 1
  225. # 布林带
  226. if row['close'] < row['BB_lower']:
  227. strength += 1
  228. elif row['close'] > row['BB_upper']:
  229. strength -= 1
  230. # MACD金叉/死叉
  231. if i > 0:
  232. prev_macd = df['MACD'].iloc[i-1]
  233. prev_signal = df['MACD_signal'].iloc[i-1]
  234. curr_macd = row['MACD']
  235. curr_signal_line = row['MACD_signal']
  236. if prev_macd < prev_signal and curr_macd > curr_signal_line:
  237. strength += 1
  238. elif prev_macd > prev_signal and curr_macd < curr_signal_line:
  239. strength -= 1
  240. df.iloc[i, df.columns.get_loc('signal_strength')] = strength
  241. # 生成交易信号
  242. if strength >= self.config['min_signal_strength']:
  243. df.iloc[i, df.columns.get_loc('signal')] = 1 # 做多
  244. elif strength <= -self.config['min_signal_strength']:
  245. df.iloc[i, df.columns.get_loc('signal')] = -1 # 做空
  246. return df
  247. def backtest(self, df):
  248. """回测"""
  249. df = self.generate_signals(df)
  250. trades = []
  251. capital = self.initial_capital
  252. position = 0
  253. entry_price = 0
  254. entry_time = None
  255. holding_bars = 0
  256. for i in range(60, len(df)):
  257. current_bar = df.iloc[i]
  258. price = current_bar['close']
  259. current_time = current_bar.name
  260. # 无持仓时检查开仓信号
  261. if position == 0:
  262. if current_bar['signal'] == 1: # 做多
  263. position_size = int(capital * self.config['position_size_pct'] / price)
  264. if position_size > 0:
  265. position = position_size
  266. entry_price = price
  267. entry_time = current_time
  268. holding_bars = 0
  269. elif current_bar['signal'] == -1: # 做空
  270. position_size = int(capital * self.config['position_size_pct'] / price)
  271. if position_size > 0:
  272. position = -position_size
  273. entry_price = price
  274. entry_time = current_time
  275. holding_bars = 0
  276. # 有持仓时检查平仓
  277. else:
  278. holding_bars += 1
  279. exit_signal = False
  280. exit_reason = ""
  281. if position > 0: # 做多持仓
  282. if price <= entry_price * (1 - self.config['stop_loss_pct']):
  283. exit_signal = True
  284. exit_reason = "止损"
  285. elif price >= entry_price * (1 + self.config['take_profit_pct']):
  286. exit_signal = True
  287. exit_reason = "止盈"
  288. elif holding_bars >= self.config['max_hold_bars']:
  289. exit_signal = True
  290. exit_reason = "时间止损"
  291. elif current_bar['RSI'] > 70:
  292. exit_signal = True
  293. exit_reason = "信号消失(RSI超买)"
  294. else: # 做空持仓
  295. if price >= entry_price * (1 + self.config['stop_loss_pct']):
  296. exit_signal = True
  297. exit_reason = "止损"
  298. elif price <= entry_price * (1 - self.config['take_profit_pct']):
  299. exit_signal = True
  300. exit_reason = "止盈"
  301. elif holding_bars >= self.config['max_hold_bars']:
  302. exit_signal = True
  303. exit_reason = "时间止损"
  304. elif current_bar['RSI'] < 30:
  305. exit_signal = True
  306. exit_reason = "信号消失(RSI超卖)"
  307. # 执行平仓
  308. if exit_signal:
  309. if position > 0:
  310. pnl = (price - entry_price) * position
  311. pnl_pct = (price - entry_price) / entry_price * 100
  312. else:
  313. pnl = (entry_price - price) * abs(position)
  314. pnl_pct = (entry_price - price) / entry_price * 100
  315. capital += pnl
  316. trades.append({
  317. '方向': '做多' if position > 0 else '做空',
  318. '开仓时间': entry_time,
  319. '平仓时间': current_time,
  320. '开仓价': entry_price,
  321. '平仓价': price,
  322. '持仓数量': abs(position),
  323. '盈亏金额': pnl,
  324. '盈亏百分比': pnl_pct,
  325. '退出原因': exit_reason,
  326. '持仓周期': holding_bars,
  327. '平仓后资金': capital
  328. })
  329. position = 0
  330. entry_price = 0
  331. entry_time = None
  332. holding_bars = 0
  333. return df, pd.DataFrame(trades), capital
  334. # ==================== 报告生成 ====================
  335. def generate_report(trades_df, final_capital, initial_capital=1000000):
  336. """生成详细报告"""
  337. if len(trades_df) == 0:
  338. html = "<html><body><h1>创业板50交易报告</h1><p>近2个月无交易信号</p></body></html>"
  339. text = "近2个月无交易信号"
  340. return html, text
  341. total_return = (final_capital - initial_capital) / initial_capital * 100
  342. total_trades = len(trades_df)
  343. winning_trades = trades_df[trades_df['盈亏金额'] > 0]
  344. losing_trades = trades_df[trades_df['盈亏金额'] < 0]
  345. win_rate = len(winning_trades) / total_trades * 100 if total_trades > 0 else 0
  346. avg_profit = winning_trades['盈亏金额'].mean() if len(winning_trades) > 0 else 0
  347. avg_loss = losing_trades['盈亏金额'].mean() if len(losing_trades) > 0 else 0
  348. total_profit = winning_trades['盈亏金额'].sum() if len(winning_trades) > 0 else 0
  349. total_loss = abs(losing_trades['盈亏金额'].sum()) if len(losing_trades) > 0 else 0
  350. profit_factor = total_profit / total_loss if total_loss > 0 else 0
  351. max_profit = trades_df['盈亏金额'].max()
  352. max_loss = trades_df['盈亏金额'].min()
  353. avg_hold_time = trades_df['持仓周期'].mean()
  354. long_trades = trades_df[trades_df['方向'] == '做多']
  355. short_trades = trades_df[trades_df['方向'] == '做空']
  356. exit_reasons = trades_df['退出原因'].value_counts()
  357. # 生成HTML报告
  358. html = f"""
  359. <html>
  360. <head>
  361. <style>
  362. body {{ font-family: Arial, sans-serif; margin: 20px; }}
  363. h1 {{ color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }}
  364. h2 {{ color: #555; margin-top: 30px; }}
  365. table {{ border-collapse: collapse; width: 100%; margin: 15px 0; font-size: 14px; }}
  366. th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
  367. th {{ background-color: #007bff; color: white; }}
  368. tr:nth-child(even) {{ background-color: #f2f2f2; }}
  369. .positive {{ color: green; font-weight: bold; }}
  370. .negative {{ color: red; font-weight: bold; }}
  371. .summary {{ background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0; }}
  372. </style>
  373. </head>
  374. <body>
  375. <h1>🚀 创业板50指数交易报告</h1>
  376. <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
  377. <p>数据区间: 近2个月</p>
  378. <div class="summary">
  379. <h2>📊 总体绩效</h2>
  380. <table>
  381. <tr><th>指标</th><th>数值</th></tr>
  382. <tr><td>初始资金</td><td>{initial_capital:,.0f}元</td></tr>
  383. <tr><td>最终资金</td><td>{final_capital:,.0f}元</td></tr>
  384. <tr><td>总收益率</td><td class="{'positive' if total_return >= 0 else 'negative'}">{total_return:+.2f}%</td></tr>
  385. <tr><td>总交易次数</td><td>{total_trades}笔</td></tr>
  386. <tr><td>胜率</td><td>{win_rate:.1f}%</td></tr>
  387. <tr><td>盈亏比</td><td>{profit_factor:.2f}</td></tr>
  388. <tr><td>平均持仓时间</td><td>{avg_hold_time:.1f}周期 ({avg_hold_time*0.5:.1f}小时)</td></tr>
  389. </table>
  390. </div>
  391. <h2>📈 盈亏统计</h2>
  392. <table>
  393. <tr><th>指标</th><th>数值</th></tr>
  394. <tr><td>总盈利</td><td class="positive">+{total_profit:,.0f}元</td></tr>
  395. <tr><td>总亏损</td><td class="negative">-{total_loss:,.0f}元</td></tr>
  396. <tr><td>平均盈利</td><td class="positive">+{avg_profit:,.0f}元</td></tr>
  397. <tr><td>平均亏损</td><td class="negative">{avg_loss:,.0f}元</td></tr>
  398. <tr><td>最大单笔盈利</td><td class="positive">+{max_profit:,.0f}元</td></tr>
  399. <tr><td>最大单笔亏损</td><td class="negative">{max_loss:,.0f}元</td></tr>
  400. </table>
  401. <h2>🔄 多空统计</h2>
  402. <table>
  403. <tr><th>方向</th><th>交易次数</th><th>胜率</th><th>总盈亏</th></tr>
  404. <tr>
  405. <td>做多</td>
  406. <td>{len(long_trades)}笔</td>
  407. <td>{(len(long_trades[long_trades['盈亏金额']>0])/len(long_trades)*100 if len(long_trades)>0 else 0):.1f}%</td>
  408. <td class="{'positive' if long_trades['盈亏金额'].sum() >= 0 else 'negative'}">{long_trades['盈亏金额'].sum():+,.0f}元</td>
  409. </tr>
  410. <tr>
  411. <td>做空</td>
  412. <td>{len(short_trades)}笔</td>
  413. <td>{(len(short_trades[short_trades['盈亏金额']>0])/len(short_trades)*100 if len(short_trades)>0 else 0):.1f}%</td>
  414. <td class="{'positive' if short_trades['盈亏金额'].sum() >= 0 else 'negative'}">{short_trades['盈亏金额'].sum():+,.0f}元</td>
  415. </tr>
  416. </table>
  417. <h2>🚪 退出原因分析</h2>
  418. <table>
  419. <tr><th>退出原因</th><th>次数</th><th>占比</th></tr>
  420. """
  421. for reason, count in exit_reasons.items():
  422. pct = count / total_trades * 100
  423. html += f"<tr><td>{reason}</td><td>{count}</td><td>{pct:.1f}%</td></tr>"
  424. html += """
  425. </table>
  426. <h2>📝 最近10笔交易明细</h2>
  427. <table>
  428. <tr>
  429. <th>方向</th>
  430. <th>开仓时间</th>
  431. <th>平仓时间</th>
  432. <th>开仓价</th>
  433. <th>平仓价</th>
  434. <th>盈亏金额</th>
  435. <th>盈亏%</th>
  436. <th>退出原因</th>
  437. </tr>
  438. """
  439. recent_trades = trades_df.tail(10)
  440. for _, trade in recent_trades.iterrows():
  441. pnl_class = "positive" if trade['盈亏金额'] >= 0 else "negative"
  442. html += f"""
  443. <tr>
  444. <td>{trade['方向']}</td>
  445. <td>{trade['开仓时间']}</td>
  446. <td>{trade['平仓时间']}</td>
  447. <td>{trade['开仓价']:.2f}</td>
  448. <td>{trade['平仓价']:.2f}</td>
  449. <td class="{pnl_class}">{trade['盈亏金额']:+.0f}</td>
  450. <td class="{pnl_class}">{trade['盈亏百分比']:+.2f}%</td>
  451. <td>{trade['退出原因']}</td>
  452. </tr>
  453. """
  454. html += """
  455. </table>
  456. <hr>
  457. <p style="color: #666; font-size: 12px;">
  458. 本报告由 cat-fly 自动交易系统生成 | 策略:30分钟K线多空双向<br>
  459. 风险提示:历史回测不代表未来表现,投资有风险,入市需谨慎。
  460. </p>
  461. </body>
  462. </html>
  463. """
  464. # 生成纯文本版本
  465. text = f"""
  466. 创业板50指数交易报告
  467. 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  468. 数据区间: 近2个月
  469. 【总体绩效】
  470. 初始资金: {initial_capital:,.0f}元
  471. 最终资金: {final_capital:,.0f}元
  472. 总收益率: {total_return:+.2f}%
  473. 总交易次数: {total_trades}笔
  474. 胜率: {win_rate:.1f}%
  475. 盈亏比: {profit_factor:.2f}
  476. 平均持仓: {avg_hold_time*0.5:.1f}小时
  477. 【盈亏统计】
  478. 总盈利: +{total_profit:,.0f}元
  479. 总亏损: -{total_loss:,.0f}元
  480. 最大单笔盈利: +{max_profit:,.0f}元
  481. 最大单笔亏损: {max_loss:,.0f}元
  482. 【多空统计】
  483. 做多: {len(long_trades)}笔, 盈亏{long_trades['盈亏金额'].sum():+,.0f}元
  484. 做空: {len(short_trades)}笔, 盈亏{short_trades['盈亏金额'].sum():+,.0f}元
  485. 【退出原因】
  486. {exit_reasons.to_string()}
  487. 【最近5笔交易】
  488. {trades_df.tail(5)[['方向', '开仓时间', '平仓时间', '盈亏金额', '退出原因']].to_string(index=False)}
  489. """
  490. return html, text
  491. # ==================== 主程序 ====================
  492. def main():
  493. """主程序"""
  494. print("="*80)
  495. print("🚀 cat-fly 自动交易报告系统")
  496. print("="*80)
  497. print(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  498. # 检查是否在交易时间(可选)
  499. now = datetime.now()
  500. hour = now.hour
  501. minute = now.minute
  502. time_str = f"{hour:02d}:{minute:02d}"
  503. # A股交易时间检查
  504. is_trading_time = False
  505. if (9 <= hour <= 11) or (13 <= hour <= 15):
  506. if hour == 9 and minute < 30:
  507. is_trading_time = False
  508. elif hour == 11 and minute > 30:
  509. is_trading_time = False
  510. elif hour == 15 and minute > 0:
  511. is_trading_time = False
  512. else:
  513. is_trading_time = True
  514. print(f"当前时间: {time_str}")
  515. print(f"交易时间: {'是' if is_trading_time else '否(非交易时间也会执行)'}")
  516. # 1. 获取近2个月数据
  517. print("\n📊 步骤1: 获取近2个月数据...")
  518. df = DataFetcher.fetch_recent_2months()
  519. if df is None:
  520. print("❌ 数据获取失败,退出")
  521. return
  522. # 2. 运行策略
  523. print("\n📈 步骤2: 运行策略回测...")
  524. strategy = CatFlyStrategy()
  525. df, trades_df, final_capital = strategy.backtest(df)
  526. print(f"✅ 回测完成: 共{len(trades_df)}笔交易")
  527. print(f" 最终资金: {final_capital:,.0f}元")
  528. print(f" 收益率: {(final_capital/1000000-1)*100:+.2f}%")
  529. # 3. 生成报告
  530. print("\n📝 步骤3: 生成报告...")
  531. html_report, text_report = generate_report(trades_df, final_capital)
  532. # 4. 发送邮件
  533. print("\n📧 步骤4: 发送邮件...")
  534. subject = f"🚀 创业板50交易报告 {datetime.now().strftime('%m-%d %H:%M')} | 收益{(final_capital/1000000-1)*100:+.2f}%"
  535. send_email(subject, html_report, text_report)
  536. print("\n✅ 全部完成!")
  537. print("="*80)
  538. if __name__ == "__main__":
  539. main()