auto_report.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. max_retries = 3
  70. for attempt in range(max_retries):
  71. try:
  72. print(f"[尝试 {attempt + 1}/{max_retries}] 正在使用东方财富30分钟K线接口...")
  73. # 使用东方财富接口获取30分钟K线
  74. df = ak.index_zh_a_hist_min_em(symbol="399673", period="30")
  75. if df is not None and not df.empty and len(df) >= 50:
  76. # 标准化列名
  77. df = df.rename(columns={
  78. '时间': 'datetime',
  79. '开盘': 'open',
  80. '收盘': 'close',
  81. '最高': 'high',
  82. '最低': 'low',
  83. '成交量': 'volume'
  84. })
  85. df['datetime'] = pd.to_datetime(df['datetime'])
  86. df = df.set_index('datetime').sort_index()
  87. # 只保留最近2个月的数据用于回测
  88. backtest_start = end_date - timedelta(days=60)
  89. df_backtest = df[df.index >= backtest_start]
  90. print(f"✅ 数据获取成功: 共{len(df_backtest)}条30分钟K线")
  91. print(f" 数据区间: {df_backtest.index[0]} 至 {df_backtest.index[-1]}")
  92. # 检查数据时效性
  93. latest_time = df_backtest.index[-1]
  94. time_delay = end_date - latest_time
  95. print(f" 数据延迟: {time_delay}")
  96. return df_backtest
  97. else:
  98. print(f"⚠️ 获取到的数据不足: {len(df) if df is not None else 0}条")
  99. except Exception as e:
  100. print(f"❌ 尝试 {attempt + 1} 失败: {e}")
  101. if attempt < max_retries - 1:
  102. import time
  103. print(f" 等待3秒后重试...")
  104. time.sleep(3)
  105. # 所有尝试都失败
  106. raise Exception("无法获取实时数据,所有数据源均失败。请检查网络连接或稍后重试。")
  107. # ==================== 策略类 ====================
  108. class CatFlyStrategy:
  109. """cat-fly策略简化版 - 基于30分钟K线"""
  110. def __init__(self, config=None):
  111. self.config = config or {
  112. 'initial_capital': 1000000,
  113. 'position_size_pct': 1.0,
  114. 'stop_loss_pct': 0.008,
  115. 'take_profit_pct': 0.02,
  116. 'max_hold_bars': 16,
  117. 'min_signal_strength': 3
  118. }
  119. self.initial_capital = self.config['initial_capital']
  120. def calculate_indicators(self, df):
  121. """计算技术指标"""
  122. # RSI
  123. delta = df['close'].diff()
  124. gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
  125. loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
  126. rs = gain / loss
  127. df['RSI'] = 100 - (100 / (1 + rs))
  128. # 移动平均线
  129. df['MA5'] = df['close'].rolling(5).mean()
  130. df['MA20'] = df['close'].rolling(20).mean()
  131. df['MA60'] = df['close'].rolling(60).mean()
  132. # 布林带
  133. df['BB_middle'] = df['close'].rolling(20).mean()
  134. bb_std = df['close'].rolling(20).std()
  135. df['BB_upper'] = df['BB_middle'] + 2 * bb_std
  136. df['BB_lower'] = df['BB_middle'] - 2 * bb_std
  137. # MACD
  138. ema12 = df['close'].ewm(span=12).mean()
  139. ema26 = df['close'].ewm(span=26).mean()
  140. df['MACD'] = ema12 - ema26
  141. df['MACD_signal'] = df['MACD'].ewm(span=9).mean()
  142. return df
  143. def generate_signals(self, df):
  144. """生成交易信号"""
  145. df = self.calculate_indicators(df)
  146. df['signal'] = 0
  147. df['signal_strength'] = 0
  148. for i in range(60, len(df)):
  149. row = df.iloc[i]
  150. strength = 0
  151. # RSI超卖/超买
  152. if row['RSI'] < 30:
  153. strength += 1
  154. elif row['RSI'] > 70:
  155. strength -= 1
  156. # 均线多头排列/空头排列
  157. if row['close'] > row['MA5'] > row['MA20']:
  158. strength += 1
  159. elif row['close'] < row['MA5'] < row['MA20']:
  160. strength -= 1
  161. # 布林带
  162. if row['close'] < row['BB_lower']:
  163. strength += 1
  164. elif row['close'] > row['BB_upper']:
  165. strength -= 1
  166. # MACD金叉/死叉
  167. if i > 0:
  168. prev_macd = df['MACD'].iloc[i-1]
  169. prev_signal = df['MACD_signal'].iloc[i-1]
  170. curr_macd = row['MACD']
  171. curr_signal_line = row['MACD_signal']
  172. if prev_macd < prev_signal and curr_macd > curr_signal_line:
  173. strength += 1
  174. elif prev_macd > prev_signal and curr_macd < curr_signal_line:
  175. strength -= 1
  176. df.iloc[i, df.columns.get_loc('signal_strength')] = strength
  177. # 生成交易信号
  178. if strength >= self.config['min_signal_strength']:
  179. df.iloc[i, df.columns.get_loc('signal')] = 1 # 做多
  180. elif strength <= -self.config['min_signal_strength']:
  181. df.iloc[i, df.columns.get_loc('signal')] = -1 # 做空
  182. return df
  183. def backtest(self, df):
  184. """回测"""
  185. df = self.generate_signals(df)
  186. trades = []
  187. capital = self.initial_capital
  188. position = 0
  189. entry_price = 0
  190. entry_time = None
  191. holding_bars = 0
  192. for i in range(60, len(df)):
  193. current_bar = df.iloc[i]
  194. price = current_bar['close']
  195. current_time = current_bar.name
  196. # 无持仓时检查开仓信号
  197. if position == 0:
  198. if current_bar['signal'] == 1: # 做多
  199. position_size = int(capital * self.config['position_size_pct'] / price)
  200. if position_size > 0:
  201. position = position_size
  202. entry_price = price
  203. entry_time = current_time
  204. holding_bars = 0
  205. elif current_bar['signal'] == -1: # 做空
  206. position_size = int(capital * self.config['position_size_pct'] / price)
  207. if position_size > 0:
  208. position = -position_size
  209. entry_price = price
  210. entry_time = current_time
  211. holding_bars = 0
  212. # 有持仓时检查平仓
  213. else:
  214. holding_bars += 1
  215. exit_signal = False
  216. exit_reason = ""
  217. if position > 0: # 做多持仓
  218. if price <= entry_price * (1 - self.config['stop_loss_pct']):
  219. exit_signal = True
  220. exit_reason = "止损"
  221. elif price >= entry_price * (1 + self.config['take_profit_pct']):
  222. exit_signal = True
  223. exit_reason = "止盈"
  224. elif holding_bars >= self.config['max_hold_bars']:
  225. exit_signal = True
  226. exit_reason = "时间止损"
  227. elif current_bar['RSI'] > 70:
  228. exit_signal = True
  229. exit_reason = "信号消失(RSI超买)"
  230. else: # 做空持仓
  231. if price >= entry_price * (1 + self.config['stop_loss_pct']):
  232. exit_signal = True
  233. exit_reason = "止损"
  234. elif price <= entry_price * (1 - self.config['take_profit_pct']):
  235. exit_signal = True
  236. exit_reason = "止盈"
  237. elif holding_bars >= self.config['max_hold_bars']:
  238. exit_signal = True
  239. exit_reason = "时间止损"
  240. elif current_bar['RSI'] < 30:
  241. exit_signal = True
  242. exit_reason = "信号消失(RSI超卖)"
  243. # 执行平仓
  244. if exit_signal:
  245. if position > 0:
  246. pnl = (price - entry_price) * position
  247. pnl_pct = (price - entry_price) / entry_price * 100
  248. else:
  249. pnl = (entry_price - price) * abs(position)
  250. pnl_pct = (entry_price - price) / entry_price * 100
  251. capital += pnl
  252. trades.append({
  253. '方向': '做多' if position > 0 else '做空',
  254. '开仓时间': entry_time,
  255. '平仓时间': current_time,
  256. '开仓价': entry_price,
  257. '平仓价': price,
  258. '持仓数量': abs(position),
  259. '盈亏金额': pnl,
  260. '盈亏百分比': pnl_pct,
  261. '退出原因': exit_reason,
  262. '持仓周期': holding_bars,
  263. '平仓后资金': capital
  264. })
  265. position = 0
  266. entry_price = 0
  267. entry_time = None
  268. holding_bars = 0
  269. return df, pd.DataFrame(trades), capital
  270. # ==================== 报告生成 ====================
  271. def generate_report(trades_df, final_capital, initial_capital=1000000):
  272. """生成详细报告"""
  273. if len(trades_df) == 0:
  274. html = "<html><body><h1>创业板50交易报告</h1><p>近2个月无交易信号</p></body></html>"
  275. text = "近2个月无交易信号"
  276. return html, text
  277. total_return = (final_capital - initial_capital) / initial_capital * 100
  278. total_trades = len(trades_df)
  279. winning_trades = trades_df[trades_df['盈亏金额'] > 0]
  280. losing_trades = trades_df[trades_df['盈亏金额'] < 0]
  281. win_rate = len(winning_trades) / total_trades * 100 if total_trades > 0 else 0
  282. avg_profit = winning_trades['盈亏金额'].mean() if len(winning_trades) > 0 else 0
  283. avg_loss = losing_trades['盈亏金额'].mean() if len(losing_trades) > 0 else 0
  284. total_profit = winning_trades['盈亏金额'].sum() if len(winning_trades) > 0 else 0
  285. total_loss = abs(losing_trades['盈亏金额'].sum()) if len(losing_trades) > 0 else 0
  286. profit_factor = total_profit / total_loss if total_loss > 0 else 0
  287. max_profit = trades_df['盈亏金额'].max()
  288. max_loss = trades_df['盈亏金额'].min()
  289. avg_hold_time = trades_df['持仓周期'].mean()
  290. long_trades = trades_df[trades_df['方向'] == '做多']
  291. short_trades = trades_df[trades_df['方向'] == '做空']
  292. exit_reasons = trades_df['退出原因'].value_counts()
  293. # 生成HTML报告
  294. html = f"""
  295. <html>
  296. <head>
  297. <style>
  298. body {{ font-family: Arial, sans-serif; margin: 20px; }}
  299. h1 {{ color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }}
  300. h2 {{ color: #555; margin-top: 30px; }}
  301. table {{ border-collapse: collapse; width: 100%; margin: 15px 0; font-size: 14px; }}
  302. th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
  303. th {{ background-color: #007bff; color: white; }}
  304. tr:nth-child(even) {{ background-color: #f2f2f2; }}
  305. .positive {{ color: green; font-weight: bold; }}
  306. .negative {{ color: red; font-weight: bold; }}
  307. .summary {{ background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0; }}
  308. </style>
  309. </head>
  310. <body>
  311. <h1>🚀 创业板50指数交易报告</h1>
  312. <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
  313. <p>数据区间: 近2个月</p>
  314. <div class="summary">
  315. <h2>📊 总体绩效</h2>
  316. <table>
  317. <tr><th>指标</th><th>数值</th></tr>
  318. <tr><td>初始资金</td><td>{initial_capital:,.0f}元</td></tr>
  319. <tr><td>最终资金</td><td>{final_capital:,.0f}元</td></tr>
  320. <tr><td>总收益率</td><td class="{'positive' if total_return >= 0 else 'negative'}">{total_return:+.2f}%</td></tr>
  321. <tr><td>总交易次数</td><td>{total_trades}笔</td></tr>
  322. <tr><td>胜率</td><td>{win_rate:.1f}%</td></tr>
  323. <tr><td>盈亏比</td><td>{profit_factor:.2f}</td></tr>
  324. <tr><td>平均持仓时间</td><td>{avg_hold_time:.1f}周期 ({avg_hold_time*0.5:.1f}小时)</td></tr>
  325. </table>
  326. </div>
  327. <h2>📈 盈亏统计</h2>
  328. <table>
  329. <tr><th>指标</th><th>数值</th></tr>
  330. <tr><td>总盈利</td><td class="positive">+{total_profit:,.0f}元</td></tr>
  331. <tr><td>总亏损</td><td class="negative">-{total_loss:,.0f}元</td></tr>
  332. <tr><td>平均盈利</td><td class="positive">+{avg_profit:,.0f}元</td></tr>
  333. <tr><td>平均亏损</td><td class="negative">{avg_loss:,.0f}元</td></tr>
  334. <tr><td>最大单笔盈利</td><td class="positive">+{max_profit:,.0f}元</td></tr>
  335. <tr><td>最大单笔亏损</td><td class="negative">{max_loss:,.0f}元</td></tr>
  336. </table>
  337. <h2>🔄 多空统计</h2>
  338. <table>
  339. <tr><th>方向</th><th>交易次数</th><th>胜率</th><th>总盈亏</th></tr>
  340. <tr>
  341. <td>做多</td>
  342. <td>{len(long_trades)}笔</td>
  343. <td>{(len(long_trades[long_trades['盈亏金额']>0])/len(long_trades)*100 if len(long_trades)>0 else 0):.1f}%</td>
  344. <td class="{'positive' if long_trades['盈亏金额'].sum() >= 0 else 'negative'}">{long_trades['盈亏金额'].sum():+,.0f}元</td>
  345. </tr>
  346. <tr>
  347. <td>做空</td>
  348. <td>{len(short_trades)}笔</td>
  349. <td>{(len(short_trades[short_trades['盈亏金额']>0])/len(short_trades)*100 if len(short_trades)>0 else 0):.1f}%</td>
  350. <td class="{'positive' if short_trades['盈亏金额'].sum() >= 0 else 'negative'}">{short_trades['盈亏金额'].sum():+,.0f}元</td>
  351. </tr>
  352. </table>
  353. <h2>🚪 退出原因分析</h2>
  354. <table>
  355. <tr><th>退出原因</th><th>次数</th><th>占比</th></tr>
  356. """
  357. for reason, count in exit_reasons.items():
  358. pct = count / total_trades * 100
  359. html += f"<tr><td>{reason}</td><td>{count}</td><td>{pct:.1f}%</td></tr>"
  360. html += """
  361. </table>
  362. <h2>📝 最近10笔交易明细</h2>
  363. <table>
  364. <tr>
  365. <th>方向</th>
  366. <th>开仓时间</th>
  367. <th>平仓时间</th>
  368. <th>开仓价</th>
  369. <th>平仓价</th>
  370. <th>盈亏金额</th>
  371. <th>盈亏%</th>
  372. <th>退出原因</th>
  373. </tr>
  374. """
  375. recent_trades = trades_df.tail(10)
  376. for _, trade in recent_trades.iterrows():
  377. pnl_class = "positive" if trade['盈亏金额'] >= 0 else "negative"
  378. html += f"""
  379. <tr>
  380. <td>{trade['方向']}</td>
  381. <td>{trade['开仓时间']}</td>
  382. <td>{trade['平仓时间']}</td>
  383. <td>{trade['开仓价']:.2f}</td>
  384. <td>{trade['平仓价']:.2f}</td>
  385. <td class="{pnl_class}">{trade['盈亏金额']:+.0f}</td>
  386. <td class="{pnl_class}">{trade['盈亏百分比']:+.2f}%</td>
  387. <td>{trade['退出原因']}</td>
  388. </tr>
  389. """
  390. html += """
  391. </table>
  392. <hr>
  393. <p style="color: #666; font-size: 12px;">
  394. 本报告由 cat-fly 自动交易系统生成 | 策略:30分钟K线多空双向<br>
  395. 风险提示:历史回测不代表未来表现,投资有风险,入市需谨慎。
  396. </p>
  397. </body>
  398. </html>
  399. """
  400. # 生成纯文本版本
  401. text = f"""
  402. 创业板50指数交易报告
  403. 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  404. 数据区间: 近2个月
  405. 【总体绩效】
  406. 初始资金: {initial_capital:,.0f}元
  407. 最终资金: {final_capital:,.0f}元
  408. 总收益率: {total_return:+.2f}%
  409. 总交易次数: {total_trades}笔
  410. 胜率: {win_rate:.1f}%
  411. 盈亏比: {profit_factor:.2f}
  412. 平均持仓: {avg_hold_time*0.5:.1f}小时
  413. 【盈亏统计】
  414. 总盈利: +{total_profit:,.0f}元
  415. 总亏损: -{total_loss:,.0f}元
  416. 最大单笔盈利: +{max_profit:,.0f}元
  417. 最大单笔亏损: {max_loss:,.0f}元
  418. 【多空统计】
  419. 做多: {len(long_trades)}笔, 盈亏{long_trades['盈亏金额'].sum():+,.0f}元
  420. 做空: {len(short_trades)}笔, 盈亏{short_trades['盈亏金额'].sum():+,.0f}元
  421. 【退出原因】
  422. {exit_reasons.to_string()}
  423. 【最近5笔交易】
  424. {trades_df.tail(5)[['方向', '开仓时间', '平仓时间', '盈亏金额', '退出原因']].to_string(index=False)}
  425. """
  426. return html, text
  427. # ==================== 主程序 ====================
  428. def main():
  429. """主程序"""
  430. print("="*80)
  431. print("🚀 cat-fly 自动交易报告系统")
  432. print("="*80)
  433. print(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  434. # 检查是否在交易时间(可选)
  435. now = datetime.now()
  436. hour = now.hour
  437. minute = now.minute
  438. time_str = f"{hour:02d}:{minute:02d}"
  439. # A股交易时间检查
  440. is_trading_time = False
  441. if (9 <= hour <= 11) or (13 <= hour <= 15):
  442. if hour == 9 and minute < 30:
  443. is_trading_time = False
  444. elif hour == 11 and minute > 30:
  445. is_trading_time = False
  446. elif hour == 15 and minute > 0:
  447. is_trading_time = False
  448. else:
  449. is_trading_time = True
  450. print(f"当前时间: {time_str}")
  451. print(f"交易时间: {'是' if is_trading_time else '否(非交易时间也会执行)'}")
  452. # 1. 获取近2个月数据
  453. print("\n📊 步骤1: 获取近2个月数据...")
  454. df = DataFetcher.fetch_recent_2months()
  455. if df is None:
  456. print("❌ 数据获取失败,退出")
  457. return
  458. # 2. 运行策略
  459. print("\n📈 步骤2: 运行策略回测...")
  460. strategy = CatFlyStrategy()
  461. df, trades_df, final_capital = strategy.backtest(df)
  462. print(f"✅ 回测完成: 共{len(trades_df)}笔交易")
  463. print(f" 最终资金: {final_capital:,.0f}元")
  464. print(f" 收益率: {(final_capital/1000000-1)*100:+.2f}%")
  465. # 3. 生成报告
  466. print("\n📝 步骤3: 生成报告...")
  467. html_report, text_report = generate_report(trades_df, final_capital)
  468. # 4. 发送邮件
  469. print("\n📧 步骤4: 发送邮件...")
  470. subject = f"🚀 创业板50交易报告 {datetime.now().strftime('%m-%d %H:%M')} | 收益{(final_capital/1000000-1)*100:+.2f}%"
  471. send_email(subject, html_report, text_report)
  472. print("\n✅ 全部完成!")
  473. print("="*80)
  474. if __name__ == "__main__":
  475. main()