trend_report.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 创业板50指数 - 实时交易报告系统
  5. 基于趋势跟踪策略,生成当前时点报告
  6. """
  7. import sys
  8. sys.path.insert(0, '/root/.openclaw/workspace/cat-fly')
  9. import pandas as pd
  10. import numpy as np
  11. from datetime import datetime, timedelta
  12. import smtplib
  13. import ssl
  14. from email.mime.text import MIMEText
  15. from email.mime.multipart import MIMEMultipart
  16. from email.header import Header
  17. import warnings
  18. warnings.filterwarnings('ignore')
  19. # ==================== 邮件配置 ====================
  20. EMAIL_CONFIG = {
  21. "smtp_server": "localhost",
  22. "smtp_port": 25,
  23. "sender_email": "catfly@erwin.wang",
  24. "receiver_email": "380880504@qq.com"
  25. }
  26. # ==================== 趋势跟踪策略 ====================
  27. class TrendTrackingStrategy:
  28. """趋势跟踪策略 - 实时计算版"""
  29. def __init__(self):
  30. self.data = None
  31. self.signals = []
  32. self.trades = []
  33. def load_data(self, csv_file='cyb50_baostock.csv'):
  34. """加载历史数据"""
  35. try:
  36. df = pd.read_csv(f'/root/.openclaw/workspace/quant/{csv_file}')
  37. df['date'] = pd.to_datetime(df['date'])
  38. df = df.set_index('date').sort_index()
  39. # 转换数据类型
  40. for col in ['open', 'high', 'low', 'close', 'volume']:
  41. df[col] = pd.to_numeric(df[col], errors='coerce')
  42. self.data = df
  43. print(f"数据加载成功: {df.index[0].date()} ~ {df.index[-1].date()}")
  44. return True
  45. except Exception as e:
  46. print(f"数据加载失败: {e}")
  47. return False
  48. def calculate_indicators(self):
  49. """计算技术指标"""
  50. df = self.data.copy()
  51. # 均线
  52. df['ma10'] = df['close'].rolling(window=10).mean()
  53. df['ma30'] = df['close'].rolling(window=30).mean()
  54. # 20日高低点
  55. df['high_20'] = df['high'].rolling(window=20).max()
  56. df['low_20'] = df['low'].rolling(window=20).min()
  57. # 10日涨幅
  58. df['ret_10'] = df['close'].pct_change(periods=10)
  59. # ATR
  60. tr1 = df['high'] - df['low']
  61. tr2 = abs(df['high'] - df['close'].shift(1))
  62. tr3 = abs(df['low'] - df['close'].shift(1))
  63. df['tr'] = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
  64. df['atr'] = df['tr'].rolling(window=20).mean()
  65. self.data = df
  66. return df
  67. def generate_signals(self):
  68. """生成交易信号"""
  69. df = self.data
  70. # 买入条件
  71. buy_cond = (
  72. (df['close'] > df['ma10']) &
  73. (df['ma10'] > df['ma30']) &
  74. (df['close'] >= df['high_20'] * 0.995) &
  75. (df['ret_10'] > 0.02)
  76. )
  77. # 卖出条件
  78. sell_cond = (
  79. (df['close'] < df['ma30']) |
  80. (df['close'] <= df['low_20'] * 1.005)
  81. )
  82. df['signal'] = 0
  83. df.loc[buy_cond, 'signal'] = 1
  84. df.loc[sell_cond, 'signal'] = -1
  85. return df
  86. def backtest(self, initial_capital=1000000):
  87. """回测计算"""
  88. df = self.generate_signals()
  89. position = 0
  90. entry_price = 0
  91. peak_price = 0
  92. capital = initial_capital
  93. trades = []
  94. for i in range(30, len(df)):
  95. date = df.index[i]
  96. price = df['close'].iloc[i]
  97. signal = df['signal'].iloc[i]
  98. # 移动止损检查
  99. if position > 0:
  100. if price > peak_price:
  101. peak_price = price
  102. if price < peak_price * 0.90: # 10%回撤止损
  103. signal = -1
  104. # 执行交易
  105. if signal == 1 and position == 0:
  106. position = 1
  107. entry_price = price
  108. peak_price = price
  109. trades.append({
  110. 'date': date,
  111. 'action': 'BUY',
  112. 'price': price,
  113. 'capital': capital
  114. })
  115. elif signal == -1 and position == 1:
  116. pnl = (price / entry_price - 1) * capital
  117. capital += pnl
  118. position = 0
  119. trades.append({
  120. 'date': date,
  121. 'action': 'SELL',
  122. 'price': price,
  123. 'capital': capital,
  124. 'pnl': pnl,
  125. 'return_pct': (price / entry_price - 1) * 100
  126. })
  127. # 计算当前持仓
  128. current_position = position
  129. current_price = df['close'].iloc[-1]
  130. if position == 1:
  131. unrealized_pnl = (current_price / entry_price - 1) * capital
  132. total_value = capital + unrealized_pnl
  133. else:
  134. total_value = capital
  135. total_return = (total_value / initial_capital - 1) * 100
  136. return {
  137. 'trades': trades,
  138. 'current_position': current_position,
  139. 'current_price': current_price,
  140. 'entry_price': entry_price if position == 1 else None,
  141. 'capital': capital,
  142. 'total_value': total_value,
  143. 'total_return': total_return,
  144. 'trade_count': len([t for t in trades if t['action'] == 'SELL'])
  145. }
  146. def get_recent_indicators(self, days=20):
  147. """获取近N天指标详情"""
  148. df = self.data.tail(days).copy()
  149. indicators = []
  150. for date, row in df.iterrows():
  151. indicators.append({
  152. 'date': date.strftime('%Y-%m-%d'),
  153. 'close': round(row['close'], 2),
  154. 'ma10': round(row['ma10'], 2) if not pd.isna(row['ma10']) else '-',
  155. 'ma30': round(row['ma30'], 2) if not pd.isna(row['ma30']) else '-',
  156. 'high_20': round(row['high_20'], 2) if not pd.isna(row['high_20']) else '-',
  157. 'ret_10': f"{row['ret_10']*100:.2f}%" if not pd.isna(row['ret_10']) else '-',
  158. 'signal': '买入' if row['signal'] == 1 else ('卖出' if row['signal'] == -1 else '持有'),
  159. 'atr': round(row['atr'], 2) if not pd.isna(row['atr']) else '-'
  160. })
  161. return indicators
  162. def get_recent_trades(self, n=20):
  163. """获取近N次交易详情"""
  164. result = self.backtest()
  165. trades = result['trades'][-n:]
  166. return trades
  167. def generate_report():
  168. """生成完整报告"""
  169. strategy = TrendTrackingStrategy()
  170. if not strategy.load_data():
  171. return None, None
  172. strategy.calculate_indicators()
  173. result = strategy.backtest()
  174. # 获取近期数据
  175. recent_indicators = strategy.get_recent_indicators(20)
  176. recent_trades = strategy.get_recent_trades(20)
  177. # 生成HTML报告
  178. html = f"""
  179. <html>
  180. <head>
  181. <meta charset="utf-8">
  182. <style>
  183. body {{ font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }}
  184. .container {{ max-width: 1200px; margin: 0 auto; background: white; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
  185. h1 {{ color: #333; border-bottom: 3px solid #007bff; padding-bottom: 10px; }}
  186. h2 {{ color: #555; margin-top: 30px; border-left: 4px solid #007bff; padding-left: 10px; }}
  187. .summary {{ background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0; }}
  188. .metric {{ display: inline-block; margin: 10px 20px 10px 0; }}
  189. .metric-label {{ color: #666; font-size: 12px; }}
  190. .metric-value {{ font-size: 24px; font-weight: bold; color: #333; }}
  191. .positive {{ color: #28a745; }}
  192. .negative {{ color: #dc3545; }}
  193. table {{ width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }}
  194. th {{ background: #007bff; color: white; padding: 10px; text-align: left; }}
  195. td {{ padding: 8px 10px; border-bottom: 1px solid #ddd; }}
  196. tr:nth-child(even) {{ background: #f8f9fa; }}
  197. tr:hover {{ background: #e9ecef; }}
  198. .position-yes {{ color: #28a745; font-weight: bold; }}
  199. .position-no {{ color: #666; }}
  200. .buy {{ color: #28a745; font-weight: bold; }}
  201. .sell {{ color: #dc3545; font-weight: bold; }}
  202. </style>
  203. </head>
  204. <body>
  205. <div class="container">
  206. <h1>🚀 创业板50趋势跟踪策略报告</h1>
  207. <p style="color: #666;">生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
  208. <div class="summary">
  209. <h2>📊 总体绩效</h2>
  210. <div class="metric">
  211. <div class="metric-label">当前持仓</div>
  212. <div class="metric-value {'position-yes' if result['current_position'] == 1 else 'position-no'}">
  213. {'持有中' if result['current_position'] == 1 else '空仓'}
  214. </div>
  215. </div>
  216. <div class="metric">
  217. <div class="metric-label">当前价格</div>
  218. <div class="metric-value">{result['current_price']:.2f}</div>
  219. </div>
  220. <div class="metric">
  221. <div class="metric-label">累计收益率</div>
  222. <div class="metric-value {'positive' if result['total_return'] >= 0 else 'negative'}">
  223. {result['total_return']:+.2f}%
  224. </div>
  225. </div>
  226. <div class="metric">
  227. <div class="metric-label">总资产</div>
  228. <div class="metric-value">{result['total_value']:,.0f}元</div>
  229. </div>
  230. <div class="metric">
  231. <div class="metric-label">交易次数</div>
  232. <div class="metric-value">{result['trade_count']}</div>
  233. </div>
  234. </div>
  235. """
  236. # 持仓详情
  237. if result['current_position'] == 1:
  238. unrealized = (result['current_price'] / result['entry_price'] - 1) * 100
  239. html += f"""
  240. <div class="summary" style="background: #e8f5e9;">
  241. <h2>📈 持仓详情</h2>
  242. <p><strong>入场价格:</strong> {result['entry_price']:.2f} 元</p>
  243. <p><strong>当前浮盈:</strong> <span class="{'positive' if unrealized >= 0 else 'negative'}">{unrealized:+.2f}%</span></p>
  244. </div>
  245. """
  246. # 近20天指标
  247. html += """
  248. <h2>📅 近20天指标详情</h2>
  249. <table>
  250. <tr>
  251. <th>日期</th>
  252. <th>收盘价</th>
  253. <th>MA10</th>
  254. <th>MA30</th>
  255. <th>20日高</th>
  256. <th>10日涨幅</th>
  257. <th>信号</th>
  258. <th>ATR</th>
  259. </tr>
  260. """
  261. for ind in recent_indicators:
  262. signal_class = 'buy' if ind['signal'] == '买入' else ('sell' if ind['signal'] == '卖出' else '')
  263. html += f"""
  264. <tr>
  265. <td>{ind['date']}</td>
  266. <td>{ind['close']}</td>
  267. <td>{ind['ma10']}</td>
  268. <td>{ind['ma30']}</td>
  269. <td>{ind['high_20']}</td>
  270. <td>{ind['ret_10']}</td>
  271. <td class="{signal_class}">{ind['signal']}</td>
  272. <td>{ind['atr']}</td>
  273. </tr>
  274. """
  275. html += """
  276. </table>
  277. <h2>💼 近20次交易详情</h2>
  278. <table>
  279. <tr>
  280. <th>日期</th>
  281. <th>操作</th>
  282. <th>价格</th>
  283. <th>盈亏金额</th>
  284. <th>盈亏比例</th>
  285. <th>总资产</th>
  286. </tr>
  287. """
  288. for trade in recent_trades:
  289. action_class = 'buy' if trade['action'] == 'BUY' else 'sell'
  290. pnl = trade.get('pnl', 0)
  291. ret = trade.get('return_pct', 0)
  292. html += f"""
  293. <tr>
  294. <td>{trade['date'].strftime('%Y-%m-%d') if isinstance(trade['date'], pd.Timestamp) else trade['date']}</td>
  295. <td class="{action_class}">{trade['action']}</td>
  296. <td>{trade['price']:.2f}</td>
  297. <td>{f'{pnl:+,.0f}元' if 'pnl' in trade else '-'}</td>
  298. <td class="{'positive' if ret >= 0 else 'negative'}">{f'{ret:+.2f}%' if 'return_pct' in trade else '-'}</td>
  299. <td>{trade['capital']:,.0f}元</td>
  300. </tr>
  301. """
  302. html += """
  303. </table>
  304. <div style="margin-top: 30px; padding: 15px; background: #fff3cd; border-radius: 5px; color: #856404;">
  305. <strong>策略说明:</strong><br>
  306. • 买入条件: 价格>MA10>MA30 且 突破20日高×0.995 且 10日涨幅>2%<br>
  307. • 卖出条件: 跌破MA30 或 创20日新低 或 回撤10%止损<br>
  308. • 风险提示: 右侧交易可能错过牛市初期涨幅
  309. </div>
  310. </div>
  311. </body>
  312. </html>
  313. """
  314. # 生成文本报告
  315. text = f"""
  316. 创业板50趋势跟踪策略报告
  317. 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  318. 【总体绩效】
  319. 当前持仓: {'持有中' if result['current_position'] == 1 else '空仓'}
  320. 当前价格: {result['current_price']:.2f}元
  321. 累计收益率: {result['total_return']:+.2f}%
  322. 总资产: {result['total_value']:,.0f}元
  323. 交易次数: {result['trade_count']}
  324. 【近20天指标】
  325. 日期 收盘价 MA10 MA30 20日高 10日涨幅 信号
  326. """
  327. for ind in recent_indicators:
  328. text += f"{ind['date']} {ind['close']:>8} {ind['ma10']:>8} {ind['ma30']:>8} {ind['high_20']:>8} {ind['ret_10']:>8} {ind['signal']}\n"
  329. text += "\n【近20次交易】\n"
  330. text += "日期 操作 价格 盈亏金额 盈亏比例 总资产\n"
  331. for trade in recent_trades:
  332. pnl_str = f"{trade.get('pnl', 0):+,.0f}元" if 'pnl' in trade else '-'
  333. ret_str = f"{trade.get('return_pct', 0):+.2f}%" if 'return_pct' in trade else '-'
  334. date_str = trade['date'].strftime('%Y-%m-%d') if isinstance(trade['date'], pd.Timestamp) else trade['date']
  335. text += f"{date_str} {trade['action']:>6} {trade['price']:>8.2f} {pnl_str:>12} {ret_str:>10} {trade['capital']:>12,.0f}元\n"
  336. return html, text, result
  337. def send_email(subject, html_content, text_content):
  338. """发送邮件"""
  339. try:
  340. msg = MIMEMultipart('alternative')
  341. msg['Subject'] = Header(subject, 'utf-8')
  342. msg['From'] = EMAIL_CONFIG['sender_email']
  343. msg['To'] = EMAIL_CONFIG['receiver_email']
  344. text_part = MIMEText(text_content, 'plain', 'utf-8')
  345. msg.attach(text_part)
  346. html_part = MIMEText(html_content, 'html', 'utf-8')
  347. msg.attach(html_part)
  348. with smtplib.SMTP(EMAIL_CONFIG['smtp_server'], EMAIL_CONFIG['smtp_port']) as server:
  349. server.sendmail(
  350. EMAIL_CONFIG['sender_email'],
  351. EMAIL_CONFIG['receiver_email'],
  352. msg.as_string()
  353. )
  354. print(f"✅ 邮件发送成功: {subject}")
  355. return True
  356. except Exception as e:
  357. print(f"❌ 邮件发送失败: {e}")
  358. return False
  359. def main():
  360. """主程序"""
  361. print("="*60)
  362. print("🚀 创业板50趋势跟踪实时报告")
  363. print("="*60)
  364. print(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  365. # 生成报告
  366. print("\n📊 生成报告中...")
  367. html, text, result = generate_report()
  368. if html is None:
  369. print("❌ 报告生成失败")
  370. return
  371. print(f"✅ 报告生成完成")
  372. print(f" 当前持仓: {'持有中' if result['current_position'] == 1 else '空仓'}")
  373. print(f" 累计收益: {result['total_return']:+.2f}%")
  374. print(f" 交易次数: {result['trade_count']}")
  375. # 发送邮件
  376. print("\n📧 发送邮件...")
  377. position_status = "持仓" if result['current_position'] == 1 else "空仓"
  378. subject = f"🚀 创业板50趋势报告 {datetime.now().strftime('%m-%d %H:%M')} | {position_status} | 收益{result['total_return']:+.2f}%"
  379. send_email(subject, html, text)
  380. print("\n✅ 全部完成!")
  381. print("="*60)
  382. if __name__ == "__main__":
  383. main()