trend_report_multi.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. sys.path.insert(0, '/root/.openclaw/workspace/quant')
  10. import pandas as pd
  11. import numpy as np
  12. from datetime import datetime, timedelta
  13. import smtplib
  14. import ssl
  15. from email.mime.text import MIMEText
  16. from email.mime.multipart import MIMEMultipart
  17. from email.header import Header
  18. import warnings
  19. import requests
  20. import json
  21. import time
  22. warnings.filterwarnings('ignore')
  23. # ==================== 邮件配置 ====================
  24. EMAIL_CONFIG = {
  25. "smtp_server": "localhost",
  26. "smtp_port": 25,
  27. "sender_email": "catfly@openclaw.local",
  28. "receiver_email": "380880504@qq.com"
  29. }
  30. # ==================== 多数据源获取 ====================
  31. def fetch_sina_realtime():
  32. """新浪实时行情接口"""
  33. try:
  34. # 新浪股票代码格式: sh000001(上证), sz399673(创业板50)
  35. url = "https://hq.sinajs.cn/list=sz399673"
  36. headers = {
  37. 'Referer': 'https://finance.sina.com.cn',
  38. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  39. }
  40. response = requests.get(url, headers=headers, timeout=10)
  41. response.encoding = 'gb2312'
  42. # 解析返回数据
  43. data_str = response.text
  44. if 'var hq_str_sz399673="' in data_str:
  45. data_str = data_str.split('var hq_str_sz399673="')[1].split('"')[0]
  46. parts = data_str.split(',')
  47. if len(parts) >= 32:
  48. return {
  49. 'open': float(parts[1]),
  50. 'high': float(parts[4]),
  51. 'low': float(parts[5]),
  52. 'close': float(parts[3]),
  53. 'volume': int(parts[8]),
  54. 'name': parts[0],
  55. 'time': parts[31],
  56. 'date': parts[30]
  57. }
  58. except Exception as e:
  59. print(f"新浪实时数据获取失败: {e}")
  60. return None
  61. def fetch_tencent_realtime():
  62. """腾讯实时行情接口"""
  63. try:
  64. # 腾讯股票代码格式: sh000001, sz399673
  65. url = "https://qt.gtimg.cn/q=sz399673"
  66. headers = {
  67. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  68. }
  69. response = requests.get(url, headers=headers, timeout=10)
  70. response.encoding = 'gb2312'
  71. data_str = response.text
  72. if 'v_sz399673="' in data_str:
  73. data_str = data_str.split('v_sz399673="')[1].split('"')[0]
  74. parts = data_str.split('~')
  75. if len(parts) >= 45:
  76. return {
  77. 'name': parts[1],
  78. 'close': float(parts[3]),
  79. 'open': float(parts[5]),
  80. 'high': float(parts[33]),
  81. 'low': float(parts[34]),
  82. 'volume': int(parts[36]),
  83. 'date': parts[30]
  84. }
  85. except Exception as e:
  86. print(f"腾讯实时数据获取失败: {e}")
  87. return None
  88. def fetch_sina_hist_t1():
  89. """新浪历史数据 - T-1日"""
  90. try:
  91. # 新浪历史行情接口
  92. today = datetime.now()
  93. url = f"https://quotes.sina.cn/cn/api/quotes.php?symbol=sz399673"
  94. headers = {
  95. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  96. }
  97. response = requests.get(url, headers=headers, timeout=10)
  98. if response.status_code == 200:
  99. data = response.json()
  100. if 'data' in data and len(data['data']) > 0:
  101. item = data['data'][0]
  102. return {
  103. 'date': item.get('date'),
  104. 'open': float(item.get('open', 0)),
  105. 'high': float(item.get('high', 0)),
  106. 'low': float(item.get('low', 0)),
  107. 'close': float(item.get('close', 0)),
  108. 'volume': int(item.get('volume', 0))
  109. }
  110. except Exception as e:
  111. print(f"新浪历史数据获取失败: {e}")
  112. return None
  113. def fetch_163_hist():
  114. """网易财经历史数据接口"""
  115. try:
  116. url = "http://quotes.money.163.com/service/chddata.html"
  117. params = {
  118. 'code': '1399673', # 创业板50代码
  119. 'start': (datetime.now() - timedelta(days=30)).strftime('%Y%m%d'),
  120. 'end': datetime.now().strftime('%Y%m%d'),
  121. 'fields': 'TCLOSE;HIGH;LOW;TOPEN;CHG;PCHG;VOTURNOVER'
  122. }
  123. headers = {
  124. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  125. }
  126. response = requests.get(url, params=params, headers=headers, timeout=10)
  127. if response.status_code == 200:
  128. # 解析CSV格式数据
  129. lines = response.text.strip().split('\n')
  130. if len(lines) > 1:
  131. # 取最新一条
  132. latest = lines[-1].split(',')
  133. if len(latest) >= 6:
  134. return {
  135. 'date': latest[0],
  136. 'open': float(latest[1]),
  137. 'high': float(latest[2]),
  138. 'low': float(latest[3]),
  139. 'close': float(latest[4]),
  140. 'volume': int(float(latest[5])) if latest[5] else 0
  141. }
  142. except Exception as e:
  143. print(f"网易历史数据获取失败: {e}")
  144. return None
  145. def fetch_realtime_data():
  146. """获取实时数据,尝试多个数据源"""
  147. print("尝试获取实时数据...")
  148. # 尝试新浪实时
  149. print(" 尝试新浪实时接口...")
  150. data = fetch_sina_realtime()
  151. if data:
  152. print(f" ✅ 新浪实时数据获取成功")
  153. return data, 'sina_realtime'
  154. # 尝试腾讯实时
  155. print(" 尝试腾讯实时接口...")
  156. data = fetch_tencent_realtime()
  157. if data:
  158. print(f" ✅ 腾讯实时数据获取成功")
  159. return data, 'tencent_realtime'
  160. # 尝试获取T-1日数据
  161. print(" 尝试获取T-1历史数据...")
  162. # 网易历史数据
  163. data = fetch_163_hist()
  164. if data:
  165. print(f" ✅ 网易历史数据获取成功")
  166. return data, '163_hist'
  167. print(" ❌ 所有数据源均失败")
  168. return None, None
  169. # ==================== 趋势跟踪策略 ====================
  170. class TrendTrackingStrategy:
  171. """趋势跟踪策略 - 实时计算版"""
  172. def __init__(self):
  173. self.data = None
  174. def load_and_merge_data(self, csv_file='cyb50_baostock.csv'):
  175. """加载历史数据并合并实时数据"""
  176. try:
  177. # 加载历史数据
  178. df = pd.read_csv(f'/root/.openclaw/workspace/quant/{csv_file}')
  179. df['date'] = pd.to_datetime(df['date'])
  180. df = df.set_index('date').sort_index()
  181. # 转换数据类型
  182. for col in ['open', 'high', 'low', 'close', 'volume']:
  183. df[col] = pd.to_numeric(df[col], errors='coerce')
  184. # 获取最新历史数据日期
  185. last_hist_date = df.index[-1]
  186. today = pd.Timestamp.now().normalize()
  187. print(f"历史数据最新日期: {last_hist_date.date()}")
  188. print(f"当前日期: {today.date()}")
  189. # 如果历史数据不是最新的,尝试获取实时数据
  190. realtime_data = None
  191. source = None
  192. if last_hist_date < today:
  193. realtime_data, source = fetch_realtime_data()
  194. if realtime_data:
  195. # 处理日期格式
  196. if 'date' in realtime_data and realtime_data['date']:
  197. try:
  198. # 尝试不同日期格式
  199. date_str = str(realtime_data['date'])
  200. if len(date_str) == 8: # YYYYMMDD
  201. date = pd.Timestamp(date_str)
  202. else:
  203. date = today
  204. except:
  205. date = today
  206. else:
  207. date = today
  208. # 检查是否已有该日期数据
  209. if date > last_hist_date:
  210. # 创建新数据行
  211. new_row = pd.DataFrame({
  212. 'open': [realtime_data['open']],
  213. 'high': [realtime_data['high']],
  214. 'low': [realtime_data['low']],
  215. 'close': [realtime_data['close']],
  216. 'volume': [realtime_data['volume']]
  217. }, index=[date])
  218. # 合并数据
  219. df = pd.concat([df, new_row])
  220. print(f"✅ 已合并{source}数据: {date.date()} 收盘价 {realtime_data['close']}")
  221. else:
  222. print(f"⚠️ 获取的数据日期({date.date()})不大于历史最新日期")
  223. else:
  224. print("⚠️ 未获取到更新的实时数据,使用历史数据")
  225. else:
  226. print("✅ 历史数据已是最新")
  227. self.data = df
  228. print(f"数据范围: {df.index[0].date()} ~ {df.index[-1].date()}")
  229. return True
  230. except Exception as e:
  231. print(f"数据加载失败: {e}")
  232. return False
  233. def calculate_indicators(self):
  234. """计算技术指标"""
  235. df = self.data.copy()
  236. # 均线
  237. df['ma10'] = df['close'].rolling(window=10).mean()
  238. df['ma30'] = df['close'].rolling(window=30).mean()
  239. # 20日高低点
  240. df['high_20'] = df['high'].rolling(window=20).max()
  241. df['low_20'] = df['low'].rolling(window=20).min()
  242. # 10日涨幅
  243. df['ret_10'] = df['close'].pct_change(periods=10)
  244. # ATR
  245. tr1 = df['high'] - df['low']
  246. tr2 = abs(df['high'] - df['close'].shift(1))
  247. tr3 = abs(df['low'] - df['close'].shift(1))
  248. df['tr'] = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
  249. df['atr'] = df['tr'].rolling(window=20).mean()
  250. self.data = df
  251. return df
  252. def generate_signals(self):
  253. """生成交易信号"""
  254. df = self.data
  255. # 买入条件
  256. buy_cond = (
  257. (df['close'] > df['ma10']) &
  258. (df['ma10'] > df['ma30']) &
  259. (df['close'] >= df['high_20'] * 0.995) &
  260. (df['ret_10'] > 0.02)
  261. )
  262. # 卖出条件
  263. sell_cond = (
  264. (df['close'] < df['ma30']) |
  265. (df['close'] <= df['low_20'] * 1.005)
  266. )
  267. df['signal'] = 0
  268. df.loc[buy_cond, 'signal'] = 1
  269. df.loc[sell_cond, 'signal'] = -1
  270. return df
  271. def backtest(self, initial_capital=1000000):
  272. """回测计算"""
  273. df = self.generate_signals()
  274. position = 0
  275. entry_price = 0
  276. peak_price = 0
  277. capital = initial_capital
  278. trades = []
  279. for i in range(30, len(df)):
  280. date = df.index[i]
  281. price = df['close'].iloc[i]
  282. signal = df['signal'].iloc[i]
  283. # 移动止损检查
  284. if position > 0:
  285. if price > peak_price:
  286. peak_price = price
  287. if price < peak_price * 0.90: # 10%回撤止损
  288. signal = -1
  289. # 执行交易
  290. if signal == 1 and position == 0:
  291. position = 1
  292. entry_price = price
  293. peak_price = price
  294. trades.append({
  295. 'date': date,
  296. 'action': 'BUY',
  297. 'price': price,
  298. 'capital': capital
  299. })
  300. elif signal == -1 and position == 1:
  301. pnl = (price / entry_price - 1) * capital
  302. capital += pnl
  303. position = 0
  304. trades.append({
  305. 'date': date,
  306. 'action': 'SELL',
  307. 'price': price,
  308. 'capital': capital,
  309. 'pnl': pnl,
  310. 'return_pct': (price / entry_price - 1) * 100
  311. })
  312. # 计算当前持仓
  313. current_position = position
  314. current_price = df['close'].iloc[-1]
  315. if position == 1:
  316. unrealized_pnl = (current_price / entry_price - 1) * capital
  317. total_value = capital + unrealized_pnl
  318. else:
  319. total_value = capital
  320. total_return = (total_value / initial_capital - 1) * 100
  321. return {
  322. 'trades': trades,
  323. 'current_position': current_position,
  324. 'current_price': current_price,
  325. 'entry_price': entry_price if position == 1 else None,
  326. 'capital': capital,
  327. 'total_value': total_value,
  328. 'total_return': total_return,
  329. 'trade_count': len([t for t in trades if t['action'] == 'SELL']),
  330. 'data_end_date': df.index[-1].strftime('%Y-%m-%d')
  331. }
  332. def get_recent_indicators(self, days=20):
  333. """获取近N天指标详情"""
  334. df = self.data.tail(days).copy()
  335. indicators = []
  336. for date, row in df.iterrows():
  337. indicators.append({
  338. 'date': date.strftime('%Y-%m-%d'),
  339. 'close': round(row['close'], 2),
  340. 'ma10': round(row['ma10'], 2) if not pd.isna(row['ma10']) else '-',
  341. 'ma30': round(row['ma30'], 2) if not pd.isna(row['ma30']) else '-',
  342. 'high_20': round(row['high_20'], 2) if not pd.isna(row['high_20']) else '-',
  343. 'ret_10': f"{row['ret_10']*100:.2f}%" if not pd.isna(row['ret_10']) else '-',
  344. 'signal': '买入' if row['signal'] == 1 else ('卖出' if row['signal'] == -1 else '持有'),
  345. 'atr': round(row['atr'], 2) if not pd.isna(row['atr']) else '-'
  346. })
  347. return indicators
  348. def get_recent_trades(self, n=20):
  349. """获取近N次交易详情"""
  350. result = self.backtest()
  351. trades = result['trades'][-n:]
  352. return trades
  353. def generate_report():
  354. """生成完整报告"""
  355. strategy = TrendTrackingStrategy()
  356. if not strategy.load_and_merge_data():
  357. return None, None, None
  358. strategy.calculate_indicators()
  359. result = strategy.backtest()
  360. # 获取近期数据
  361. recent_indicators = strategy.get_recent_indicators(20)
  362. recent_trades = strategy.get_recent_trades(20)
  363. # 生成HTML报告
  364. html = f"""
  365. <html>
  366. <head>
  367. <meta charset="utf-8">
  368. <style>
  369. body {{ font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }}
  370. .container {{ max-width: 1200px; margin: 0 auto; background: white; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
  371. h1 {{ color: #333; border-bottom: 3px solid #007bff; padding-bottom: 10px; }}
  372. h2 {{ color: #555; margin-top: 30px; border-left: 4px solid #007bff; padding-left: 10px; }}
  373. .summary {{ background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0; }}
  374. .metric {{ display: inline-block; margin: 10px 20px 10px 0; }}
  375. .metric-label {{ color: #666; font-size: 12px; }}
  376. .metric-value {{ font-size: 24px; font-weight: bold; color: #333; }}
  377. .positive {{ color: #28a745; }}
  378. .negative {{ color: #dc3545; }}
  379. table {{ width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }}
  380. th {{ background: #007bff; color: white; padding: 10px; text-align: left; }}
  381. td {{ padding: 8px 10px; border-bottom: 1px solid #ddd; }}
  382. tr:nth-child(even) {{ background: #f8f9fa; }}
  383. tr:hover {{ background: #e9ecef; }}
  384. .position-yes {{ color: #28a745; font-weight: bold; }}
  385. .position-no {{ color: #666; }}
  386. .buy {{ color: #28a745; font-weight: bold; }}
  387. .sell {{ color: #dc3545; font-weight: bold; }}
  388. .data-info {{ background: #e7f3ff; padding: 10px; border-radius: 5px; margin: 10px 0; color: #004085; }}
  389. </style>
  390. </head>
  391. <body>
  392. <div class="container">
  393. <h1>🚀 创业板50趋势跟踪策略报告</h1>
  394. <p style="color: #666;">生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
  395. <div class="data-info">
  396. <strong>数据更新:</strong> 已合并历史数据与实时数据,最新数据日期: {result['data_end_date']}
  397. </div>
  398. <div class="summary">
  399. <h2>📊 总体绩效</h2>
  400. <div class="metric">
  401. <div class="metric-label">当前持仓</div>
  402. <div class="metric-value {'position-yes' if result['current_position'] == 1 else 'position-no'}">
  403. {'持有中' if result['current_position'] == 1 else '空仓'}
  404. </div>
  405. </div>
  406. <div class="metric">
  407. <div class="metric-label">当前价格</div>
  408. <div class="metric-value">{result['current_price']:.2f}</div>
  409. </div>
  410. <div class="metric">
  411. <div class="metric-label">累计收益率</div>
  412. <div class="metric-value {'positive' if result['total_return'] >= 0 else 'negative'}">
  413. {result['total_return']:+.2f}%
  414. </div>
  415. </div>
  416. <div class="metric">
  417. <div class="metric-label">总资产</div>
  418. <div class="metric-value">{result['total_value']:,.0f}元</div>
  419. </div>
  420. <div class="metric">
  421. <div class="metric-label">交易次数</div>
  422. <div class="metric-value">{result['trade_count']}</div>
  423. </div>
  424. </div>
  425. """
  426. # 持仓详情
  427. if result['current_position'] == 1:
  428. unrealized = (result['current_price'] / result['entry_price'] - 1) * 100
  429. html += f"""
  430. <div class="summary" style="background: #e8f5e9;">
  431. <h2>📈 持仓详情</h2>
  432. <p><strong>入场价格:</strong> {result['entry_price']:.2f} 元</p>
  433. <p><strong>当前浮盈:</strong> <span class="{'positive' if unrealized >= 0 else 'negative'}">{unrealized:+.2f}%</span></p>
  434. </div>
  435. """
  436. # 近20天指标
  437. html += """
  438. <h2>📅 近20天指标详情</h2>
  439. <table>
  440. <tr>
  441. <th>日期</th>
  442. <th>收盘价</th>
  443. <th>MA10</th>
  444. <th>MA30</th>
  445. <th>20日高</th>
  446. <th>10日涨幅</th>
  447. <th>信号</th>
  448. <th>ATR</th>
  449. </tr>
  450. """
  451. for ind in recent_indicators:
  452. signal_class = 'buy' if ind['signal'] == '买入' else ('sell' if ind['signal'] == '卖出' else '')
  453. html += f"""
  454. <tr>
  455. <td>{ind['date']}</td>
  456. <td>{ind['close']}</td>
  457. <td>{ind['ma10']}</td>
  458. <td>{ind['ma30']}</td>
  459. <td>{ind['high_20']}</td>
  460. <td>{ind['ret_10']}</td>
  461. <td class="{signal_class}">{ind['signal']}</td>
  462. <td>{ind['atr']}</td>
  463. </tr>
  464. """
  465. html += """
  466. </table>
  467. <h2>💼 近20次交易详情</h2>
  468. <table>
  469. <tr>
  470. <th>日期</th>
  471. <th>操作</th>
  472. <th>价格</th>
  473. <th>盈亏金额</th>
  474. <th>盈亏比例</th>
  475. <th>总资产</th>
  476. </tr>
  477. """
  478. for trade in recent_trades:
  479. action_class = 'buy' if trade['action'] == 'BUY' else 'sell'
  480. pnl = trade.get('pnl', 0)
  481. ret = trade.get('return_pct', 0)
  482. html += f"""
  483. <tr>
  484. <td>{trade['date'].strftime('%Y-%m-%d') if isinstance(trade['date'], pd.Timestamp) else trade['date']}</td>
  485. <td class="{action_class}">{trade['action']}</td>
  486. <td>{trade['price']:.2f}</td>
  487. <td>{f'{pnl:+,.0f}元' if 'pnl' in trade else '-'}</td>
  488. <td class="{'positive' if ret >= 0 else 'negative'}">{f'{ret:+.2f}%' if 'return_pct' in trade else '-'}</td>
  489. <td>{trade['capital']:,.0f}元</td>
  490. </tr>
  491. """
  492. html += """
  493. </table>
  494. <div style="margin-top: 30px; padding: 15px; background: #fff3cd; border-radius: 5px; color: #856404;">
  495. <strong>策略说明:</strong><br>
  496. • 买入条件: 价格>MA10>MA30 且 突破20日高×0.995 且 10日涨幅>2%<br>
  497. • 卖出条件: 跌破MA30 或 创20日新低 或 回撤10%止损<br>
  498. • 数据更新: 已合并历史数据与实时市场数据(支持新浪/腾讯/网易多数据源)
  499. </div>
  500. </div>
  501. </body>
  502. </html>
  503. """
  504. # 生成文本报告
  505. text = f"""
  506. 创业板50趋势跟踪策略报告
  507. 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  508. 数据最新日期: {result['data_end_date']}
  509. 【总体绩效】
  510. 当前持仓: {'持有中' if result['current_position'] == 1 else '空仓'}
  511. 当前价格: {result['current_price']:.2f}元
  512. 累计收益率: {result['total_return']:+.2f}%
  513. 总资产: {result['total_value']:,.0f}元
  514. 交易次数: {result['trade_count']}
  515. 【近20天指标】
  516. 日期 收盘价 MA10 MA30 20日高 10日涨幅 信号 ATR
  517. """
  518. for ind in recent_indicators:
  519. text += f"{ind['date']} {ind['close']:>8} {ind['ma10']:>8} {ind['ma30']:>8} {ind['high_20']:>8} {ind['ret_10']:>8} {ind['signal']:>4} {ind['atr']:>6}\n"
  520. text += "\n【近20次交易】\n"
  521. text += "日期 操作 价格 盈亏金额 盈亏比例 总资产\n"
  522. for trade in recent_trades:
  523. pnl_str = f"{trade.get('pnl', 0):+,.0f}元" if 'pnl' in trade else '-'
  524. ret_str = f"{trade.get('return_pct', 0):+.2f}%" if 'return_pct' in trade else '-'
  525. date_str = trade['date'].strftime('%Y-%m-%d') if isinstance(trade['date'], pd.Timestamp) else trade['date']
  526. text += f"{date_str} {trade['action']:>6} {trade['price']:>8.2f} {pnl_str:>12} {ret_str:>10} {trade['capital']:>12,.0f}元\n"
  527. return html, text, result
  528. def send_email(subject, html_content, text_content):
  529. """发送邮件"""
  530. try:
  531. msg = MIMEMultipart('alternative')
  532. msg['Subject'] = Header(subject, 'utf-8')
  533. msg['From'] = EMAIL_CONFIG['sender_email']
  534. msg['To'] = EMAIL_CONFIG['receiver_email']
  535. text_part = MIMEText(text_content, 'plain', 'utf-8')
  536. msg.attach(text_part)
  537. html_part = MIMEText(html_content, 'html', 'utf-8')
  538. msg.attach(html_part)
  539. with smtplib.SMTP(EMAIL_CONFIG['smtp_server'], EMAIL_CONFIG['smtp_port']) as server:
  540. server.sendmail(
  541. EMAIL_CONFIG['sender_email'],
  542. EMAIL_CONFIG['receiver_email'],
  543. msg.as_string()
  544. )
  545. print(f"✅ 邮件发送成功: {subject}")
  546. return True
  547. except Exception as e:
  548. print(f"❌ 邮件发送失败: {e}")
  549. return False
  550. def main():
  551. """主程序"""
  552. print("="*60)
  553. print("🚀 创业板50趋势跟踪实时报告 (多数据源)")
  554. print("="*60)
  555. print(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  556. # 生成报告
  557. print("\n📊 加载数据并生成报告中...")
  558. html, text, result = generate_report()
  559. if html is None:
  560. print("❌ 报告生成失败")
  561. return
  562. print(f"✅ 报告生成完成")
  563. print(f" 数据最新日期: {result['data_end_date']}")
  564. print(f" 当前持仓: {'持有中' if result['current_position'] == 1 else '空仓'}")
  565. print(f" 累计收益: {result['total_return']:+.2f}%")
  566. print(f" 交易次数: {result['trade_count']}")
  567. # 发送邮件
  568. print("\n📧 发送邮件...")
  569. position_status = "持仓" if result['current_position'] == 1 else "空仓"
  570. subject = f"🚀 创业板50趋势报告 {datetime.now().strftime('%m-%d %H:%M')} | {position_status} | 收益{result['total_return']:+.2f}%"
  571. send_email(subject, html, text)
  572. print("\n✅ 全部完成!")
  573. print("="*60)
  574. if __name__ == "__main__":
  575. main()