forked from ZhuLinsen/daily_stock_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification.py
More file actions
2568 lines (2114 loc) · 94.7 KB
/
notification.py
File metadata and controls
2568 lines (2114 loc) · 94.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
===================================
A股自选股智能分析系统 - 通知层
===================================
职责:
1. 汇总分析结果生成日报
2. 支持 Markdown 格式输出
3. 多渠道推送(自动识别):
- 企业微信 Webhook
- 飞书 Webhook
- Telegram Bot
- 邮件 SMTP
- Pushover(手机/桌面推送)
"""
import logging
import json
import smtplib
import re
from datetime import datetime
from typing import List, Dict, Any, Optional
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from enum import Enum
import requests
from config import get_config
from analyzer import AnalysisResult
logger = logging.getLogger(__name__)
class NotificationChannel(Enum):
"""通知渠道类型"""
WECHAT = "wechat" # 企业微信
FEISHU = "feishu" # 飞书
TELEGRAM = "telegram" # Telegram
EMAIL = "email" # 邮件
PUSHOVER = "pushover" # Pushover(手机/桌面推送)
CUSTOM = "custom" # 自定义 Webhook
UNKNOWN = "unknown" # 未知
# SMTP 服务器配置(自动识别)
SMTP_CONFIGS = {
# QQ邮箱
"qq.com": {"server": "smtp.qq.com", "port": 465, "ssl": True},
"foxmail.com": {"server": "smtp.qq.com", "port": 465, "ssl": True},
# 网易邮箱
"163.com": {"server": "smtp.163.com", "port": 465, "ssl": True},
"126.com": {"server": "smtp.126.com", "port": 465, "ssl": True},
# Gmail
"gmail.com": {"server": "smtp.gmail.com", "port": 587, "ssl": False},
# Outlook
"outlook.com": {"server": "smtp-mail.outlook.com", "port": 587, "ssl": False},
"hotmail.com": {"server": "smtp-mail.outlook.com", "port": 587, "ssl": False},
"live.com": {"server": "smtp-mail.outlook.com", "port": 587, "ssl": False},
# 新浪
"sina.com": {"server": "smtp.sina.com", "port": 465, "ssl": True},
# 搜狐
"sohu.com": {"server": "smtp.sohu.com", "port": 465, "ssl": True},
# 阿里云
"aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "ssl": True},
# 139邮箱
"139.com": {"server": "smtp.139.com", "port": 465, "ssl": True},
}
class ChannelDetector:
"""
渠道检测器 - 简化版
根据配置直接判断渠道类型(不再需要 URL 解析)
"""
@staticmethod
def get_channel_name(channel: NotificationChannel) -> str:
"""获取渠道中文名称"""
names = {
NotificationChannel.WECHAT: "企业微信",
NotificationChannel.FEISHU: "飞书",
NotificationChannel.TELEGRAM: "Telegram",
NotificationChannel.EMAIL: "邮件",
NotificationChannel.PUSHOVER: "Pushover",
NotificationChannel.CUSTOM: "自定义Webhook",
NotificationChannel.UNKNOWN: "未知渠道",
}
return names.get(channel, "未知渠道")
class NotificationService:
"""
通知服务
职责:
1. 生成 Markdown 格式的分析日报
2. 向所有已配置的渠道推送消息(多渠道并发)
3. 支持本地保存日报
支持的渠道:
- 企业微信 Webhook
- 飞书 Webhook
- Telegram Bot
- 邮件 SMTP
- Pushover(手机/桌面推送)
注意:所有已配置的渠道都会收到推送
"""
def __init__(self):
"""
初始化通知服务
检测所有已配置的渠道,推送时会向所有渠道发送
"""
config = get_config()
# 各渠道的 Webhook URL
self._wechat_url = config.wechat_webhook_url
self._feishu_url = getattr(config, 'feishu_webhook_url', None)
# Telegram 配置
self._telegram_config = {
'bot_token': getattr(config, 'telegram_bot_token', None),
'chat_id': getattr(config, 'telegram_chat_id', None),
}
# 邮件配置
self._email_config = {
'sender': config.email_sender,
'password': config.email_password,
'receivers': config.email_receivers or ([config.email_sender] if config.email_sender else []),
}
# Pushover 配置
self._pushover_config = {
'user_key': getattr(config, 'pushover_user_key', None),
'api_token': getattr(config, 'pushover_api_token', None),
}
# 自定义 Webhook 配置
self._custom_webhook_urls = getattr(config, 'custom_webhook_urls', []) or []
self._custom_webhook_bearer_token = getattr(config, 'custom_webhook_bearer_token', None)
# 消息长度限制(字节)
self._feishu_max_bytes = getattr(config, 'feishu_max_bytes', 20000)
self._wechat_max_bytes = getattr(config, 'wechat_max_bytes', 4000)
# 检测所有已配置的渠道
self._available_channels = self._detect_all_channels()
if not self._available_channels:
logger.warning("未配置有效的通知渠道,将不发送推送通知")
else:
channel_names = [ChannelDetector.get_channel_name(ch) for ch in self._available_channels]
logger.info(f"已配置 {len(self._available_channels)} 个通知渠道:{', '.join(channel_names)}")
def _detect_all_channels(self) -> List[NotificationChannel]:
"""
检测所有已配置的渠道
Returns:
已配置的渠道列表
"""
channels = []
# 企业微信
if self._wechat_url:
channels.append(NotificationChannel.WECHAT)
# 飞书
if self._feishu_url:
channels.append(NotificationChannel.FEISHU)
# Telegram
if self._is_telegram_configured():
channels.append(NotificationChannel.TELEGRAM)
# 邮件
if self._is_email_configured():
channels.append(NotificationChannel.EMAIL)
# Pushover
if self._is_pushover_configured():
channels.append(NotificationChannel.PUSHOVER)
# 自定义 Webhook
if self._custom_webhook_urls:
channels.append(NotificationChannel.CUSTOM)
return channels
def _is_telegram_configured(self) -> bool:
"""检查 Telegram 配置是否完整"""
return bool(self._telegram_config['bot_token'] and self._telegram_config['chat_id'])
def _is_email_configured(self) -> bool:
"""检查邮件配置是否完整(只需邮箱和授权码)"""
return bool(self._email_config['sender'] and self._email_config['password'])
def _is_pushover_configured(self) -> bool:
"""检查 Pushover 配置是否完整"""
return bool(self._pushover_config['user_key'] and self._pushover_config['api_token'])
def is_available(self) -> bool:
"""检查通知服务是否可用(至少有一个渠道)"""
return len(self._available_channels) > 0
def get_available_channels(self) -> List[NotificationChannel]:
"""获取所有已配置的渠道"""
return self._available_channels
def get_channel_names(self) -> str:
"""获取所有已配置渠道的名称"""
return ', '.join([ChannelDetector.get_channel_name(ch) for ch in self._available_channels])
def generate_daily_report(
self,
results: List[AnalysisResult],
report_date: Optional[str] = None
) -> str:
"""
生成 Markdown 格式的日报(详细版)
Args:
results: 分析结果列表
report_date: 报告日期(默认今天)
Returns:
Markdown 格式的日报内容
"""
if report_date is None:
report_date = datetime.now().strftime('%Y-%m-%d')
# 标题
report_lines = [
f"# 📅 {report_date} A股自选股智能分析报告",
"",
f"> 共分析 **{len(results)}** 只股票 | 报告生成时间:{datetime.now().strftime('%H:%M:%S')}",
"",
"---",
"",
]
# 按评分排序(高分在前)
sorted_results = sorted(
results,
key=lambda x: x.sentiment_score,
reverse=True
)
# 统计信息
buy_count = sum(1 for r in results if r.operation_advice in ['买入', '加仓', '强烈买入'])
sell_count = sum(1 for r in results if r.operation_advice in ['卖出', '减仓', '强烈卖出'])
hold_count = sum(1 for r in results if r.operation_advice in ['持有', '观望'])
avg_score = sum(r.sentiment_score for r in results) / len(results) if results else 0
report_lines.extend([
"## 📊 操作建议汇总",
"",
f"| 指标 | 数值 |",
f"|------|------|",
f"| 🟢 建议买入/加仓 | **{buy_count}** 只 |",
f"| 🟡 建议持有/观望 | **{hold_count}** 只 |",
f"| 🔴 建议减仓/卖出 | **{sell_count}** 只 |",
f"| 📈 平均看多评分 | **{avg_score:.1f}** 分 |",
"",
"---",
"",
"## 📈 个股详细分析",
"",
])
# 逐个股票的详细分析
for result in sorted_results:
emoji = result.get_emoji()
confidence_stars = result.get_confidence_stars() if hasattr(result, 'get_confidence_stars') else '⭐⭐'
report_lines.extend([
f"### {emoji} {result.name} ({result.code})",
"",
f"**操作建议:{result.operation_advice}** | **综合评分:{result.sentiment_score}分** | **趋势预测:{result.trend_prediction}** | **置信度:{confidence_stars}**",
"",
])
# 核心看点
if hasattr(result, 'key_points') and result.key_points:
report_lines.extend([
f"**🎯 核心看点**:{result.key_points}",
"",
])
# 买入/卖出理由
if hasattr(result, 'buy_reason') and result.buy_reason:
report_lines.extend([
f"**💡 操作理由**:{result.buy_reason}",
"",
])
# 走势分析
if hasattr(result, 'trend_analysis') and result.trend_analysis:
report_lines.extend([
"#### 📉 走势分析",
f"{result.trend_analysis}",
"",
])
# 短期/中期展望
outlook_lines = []
if hasattr(result, 'short_term_outlook') and result.short_term_outlook:
outlook_lines.append(f"- **短期(1-3日)**:{result.short_term_outlook}")
if hasattr(result, 'medium_term_outlook') and result.medium_term_outlook:
outlook_lines.append(f"- **中期(1-2周)**:{result.medium_term_outlook}")
if outlook_lines:
report_lines.extend([
"#### 🔮 市场展望",
*outlook_lines,
"",
])
# 技术面分析
tech_lines = []
if result.technical_analysis:
tech_lines.append(f"**综合**:{result.technical_analysis}")
if hasattr(result, 'ma_analysis') and result.ma_analysis:
tech_lines.append(f"**均线**:{result.ma_analysis}")
if hasattr(result, 'volume_analysis') and result.volume_analysis:
tech_lines.append(f"**量能**:{result.volume_analysis}")
if hasattr(result, 'pattern_analysis') and result.pattern_analysis:
tech_lines.append(f"**形态**:{result.pattern_analysis}")
if tech_lines:
report_lines.extend([
"#### 📊 技术面分析",
*tech_lines,
"",
])
# 基本面分析
fund_lines = []
if hasattr(result, 'fundamental_analysis') and result.fundamental_analysis:
fund_lines.append(result.fundamental_analysis)
if hasattr(result, 'sector_position') and result.sector_position:
fund_lines.append(f"**板块地位**:{result.sector_position}")
if hasattr(result, 'company_highlights') and result.company_highlights:
fund_lines.append(f"**公司亮点**:{result.company_highlights}")
if fund_lines:
report_lines.extend([
"#### 🏢 基本面分析",
*fund_lines,
"",
])
# 消息面/情绪面
news_lines = []
if result.news_summary:
news_lines.append(f"**新闻摘要**:{result.news_summary}")
if hasattr(result, 'market_sentiment') and result.market_sentiment:
news_lines.append(f"**市场情绪**:{result.market_sentiment}")
if hasattr(result, 'hot_topics') and result.hot_topics:
news_lines.append(f"**相关热点**:{result.hot_topics}")
if news_lines:
report_lines.extend([
"#### 📰 消息面/情绪面",
*news_lines,
"",
])
# 综合分析
if result.analysis_summary:
report_lines.extend([
"#### 📝 综合分析",
result.analysis_summary,
"",
])
# 风险提示
if hasattr(result, 'risk_warning') and result.risk_warning:
report_lines.extend([
f"⚠️ **风险提示**:{result.risk_warning}",
"",
])
# 数据来源说明
if hasattr(result, 'search_performed') and result.search_performed:
report_lines.append(f"*🔍 已执行联网搜索*")
if hasattr(result, 'data_sources') and result.data_sources:
report_lines.append(f"*📋 数据来源:{result.data_sources}*")
# 错误信息(如果有)
if not result.success and result.error_message:
report_lines.extend([
"",
f"❌ **分析异常**:{result.error_message[:100]}",
])
report_lines.extend([
"",
"---",
"",
])
# 底部信息(去除免责声明)
report_lines.extend([
"",
f"*报告生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*",
])
return "\n".join(report_lines)
def _get_signal_level(self, result: AnalysisResult) -> tuple:
"""
根据操作建议获取信号等级和颜色
Returns:
(信号文字, emoji, 颜色标记)
"""
advice = result.operation_advice
score = result.sentiment_score
if advice in ['强烈买入'] or score >= 80:
return ('强烈买入', '💚', '强买')
elif advice in ['买入', '加仓'] or score >= 65:
return ('买入', '🟢', '买入')
elif advice in ['持有'] or 55 <= score < 65:
return ('持有', '🟡', '持有')
elif advice in ['观望'] or 45 <= score < 55:
return ('观望', '⚪', '观望')
elif advice in ['减仓'] or 35 <= score < 45:
return ('减仓', '🟠', '减仓')
elif advice in ['卖出', '强烈卖出'] or score < 35:
return ('卖出', '🔴', '卖出')
else:
return ('观望', '⚪', '观望')
def generate_dashboard_report(
self,
results: List[AnalysisResult],
report_date: Optional[str] = None
) -> str:
"""
生成决策仪表盘格式的日报(详细版)
格式:市场概览 + 重要信息 + 核心结论 + 数据透视 + 作战计划
Args:
results: 分析结果列表
report_date: 报告日期(默认今天)
Returns:
Markdown 格式的决策仪表盘日报
"""
if report_date is None:
report_date = datetime.now().strftime('%Y-%m-%d')
# 按评分排序(高分在前)
sorted_results = sorted(results, key=lambda x: x.sentiment_score, reverse=True)
# 统计信息
buy_count = sum(1 for r in results if r.operation_advice in ['买入', '加仓', '强烈买入'])
sell_count = sum(1 for r in results if r.operation_advice in ['卖出', '减仓', '强烈卖出'])
hold_count = sum(1 for r in results if r.operation_advice in ['持有', '观望'])
report_lines = [
f"# 🎯 {report_date} 决策仪表盘",
"",
f"> 共分析 **{len(results)}** 只股票 | 🟢买入:{buy_count} 🟡观望:{hold_count} 🔴卖出:{sell_count}",
"",
"---",
"",
]
# 逐个股票的决策仪表盘
for result in sorted_results:
signal_text, signal_emoji, signal_tag = self._get_signal_level(result)
dashboard = result.dashboard if hasattr(result, 'dashboard') and result.dashboard else {}
# 股票名称(优先使用 dashboard 或 result 中的名称)
stock_name = result.name if result.name and not result.name.startswith('股票') else f'股票{result.code}'
report_lines.extend([
f"## {signal_emoji} {stock_name} ({result.code})",
"",
])
# ========== 舆情与基本面概览(放在最前面)==========
intel = dashboard.get('intelligence', {}) if dashboard else {}
if intel:
report_lines.extend([
"### 📰 重要信息速览",
"",
])
# 舆情情绪总结
if intel.get('sentiment_summary'):
report_lines.append(f"**💭 舆情情绪**: {intel['sentiment_summary']}")
# 业绩预期
if intel.get('earnings_outlook'):
report_lines.append(f"**📊 业绩预期**: {intel['earnings_outlook']}")
# 风险警报(醒目显示)
risk_alerts = intel.get('risk_alerts', [])
if risk_alerts:
report_lines.append("")
report_lines.append("**🚨 风险警报**:")
for alert in risk_alerts:
report_lines.append(f"- {alert}")
# 利好催化
catalysts = intel.get('positive_catalysts', [])
if catalysts:
report_lines.append("")
report_lines.append("**✨ 利好催化**:")
for cat in catalysts:
report_lines.append(f"- {cat}")
# 最新消息
if intel.get('latest_news'):
report_lines.append("")
report_lines.append(f"**📢 最新动态**: {intel['latest_news']}")
report_lines.append("")
# ========== 核心结论 ==========
core = dashboard.get('core_conclusion', {}) if dashboard else {}
one_sentence = core.get('one_sentence', result.analysis_summary)
time_sense = core.get('time_sensitivity', '本周内')
pos_advice = core.get('position_advice', {})
report_lines.extend([
"### 📌 核心结论",
"",
f"**{signal_emoji} {signal_text}** | {result.trend_prediction}",
"",
f"> **一句话决策**: {one_sentence}",
"",
f"⏰ **时效性**: {time_sense}",
"",
])
# 持仓分类建议
if pos_advice:
report_lines.extend([
"| 持仓情况 | 操作建议 |",
"|---------|---------|",
f"| 🆕 **空仓者** | {pos_advice.get('no_position', result.operation_advice)} |",
f"| 💼 **持仓者** | {pos_advice.get('has_position', '继续持有')} |",
"",
])
# ========== 数据透视 ==========
data_persp = dashboard.get('data_perspective', {}) if dashboard else {}
if data_persp:
trend_data = data_persp.get('trend_status', {})
price_data = data_persp.get('price_position', {})
vol_data = data_persp.get('volume_analysis', {})
chip_data = data_persp.get('chip_structure', {})
report_lines.extend([
"### 📊 数据透视",
"",
])
# 趋势状态
if trend_data:
is_bullish = "✅ 是" if trend_data.get('is_bullish', False) else "❌ 否"
report_lines.extend([
f"**均线排列**: {trend_data.get('ma_alignment', 'N/A')} | 多头排列: {is_bullish} | 趋势强度: {trend_data.get('trend_score', 'N/A')}/100",
"",
])
# 价格位置
if price_data:
bias_status = price_data.get('bias_status', 'N/A')
bias_emoji = "✅" if bias_status == "安全" else ("⚠️" if bias_status == "警戒" else "🚨")
report_lines.extend([
"| 价格指标 | 数值 |",
"|---------|------|",
f"| 当前价 | {price_data.get('current_price', 'N/A')} |",
f"| MA5 | {price_data.get('ma5', 'N/A')} |",
f"| MA10 | {price_data.get('ma10', 'N/A')} |",
f"| MA20 | {price_data.get('ma20', 'N/A')} |",
f"| 乖离率(MA5) | {price_data.get('bias_ma5', 'N/A')}% {bias_emoji}{bias_status} |",
f"| 支撑位 | {price_data.get('support_level', 'N/A')} |",
f"| 压力位 | {price_data.get('resistance_level', 'N/A')} |",
"",
])
# 量能分析
if vol_data:
report_lines.extend([
f"**量能**: 量比 {vol_data.get('volume_ratio', 'N/A')} ({vol_data.get('volume_status', '')}) | 换手率 {vol_data.get('turnover_rate', 'N/A')}%",
f"💡 *{vol_data.get('volume_meaning', '')}*",
"",
])
# 筹码结构
if chip_data:
chip_health = chip_data.get('chip_health', 'N/A')
chip_emoji = "✅" if chip_health == "健康" else ("⚠️" if chip_health == "一般" else "🚨")
report_lines.extend([
f"**筹码**: 获利比例 {chip_data.get('profit_ratio', 'N/A')} | 平均成本 {chip_data.get('avg_cost', 'N/A')} | 集中度 {chip_data.get('concentration', 'N/A')} {chip_emoji}{chip_health}",
"",
])
# 舆情情报已移至顶部显示
# ========== 作战计划 ==========
battle = dashboard.get('battle_plan', {}) if dashboard else {}
if battle:
report_lines.extend([
"### 🎯 作战计划",
"",
])
# 狙击点位
sniper = battle.get('sniper_points', {})
if sniper:
report_lines.extend([
"**📍 狙击点位**",
"",
"| 点位类型 | 价格 |",
"|---------|------|",
f"| 🎯 理想买入点 | {sniper.get('ideal_buy', 'N/A')} |",
f"| 🔵 次优买入点 | {sniper.get('secondary_buy', 'N/A')} |",
f"| 🛑 止损位 | {sniper.get('stop_loss', 'N/A')} |",
f"| 🎊 目标位 | {sniper.get('take_profit', 'N/A')} |",
"",
])
# 仓位策略
position = battle.get('position_strategy', {})
if position:
report_lines.extend([
f"**💰 仓位建议**: {position.get('suggested_position', 'N/A')}",
f"- 建仓策略: {position.get('entry_plan', 'N/A')}",
f"- 风控策略: {position.get('risk_control', 'N/A')}",
"",
])
# 检查清单
checklist = battle.get('action_checklist', [])
if checklist:
report_lines.extend([
"**✅ 检查清单**",
"",
])
for item in checklist:
report_lines.append(f"- {item}")
report_lines.append("")
# 如果没有 dashboard,显示传统格式
if not dashboard:
# 操作理由
if result.buy_reason:
report_lines.extend([
f"**💡 操作理由**: {result.buy_reason}",
"",
])
# 风险提示
if result.risk_warning:
report_lines.extend([
f"**⚠️ 风险提示**: {result.risk_warning}",
"",
])
# 技术面分析
if result.ma_analysis or result.volume_analysis:
report_lines.extend([
"### 📊 技术面",
"",
])
if result.ma_analysis:
report_lines.append(f"**均线**: {result.ma_analysis}")
if result.volume_analysis:
report_lines.append(f"**量能**: {result.volume_analysis}")
report_lines.append("")
# 消息面
if result.news_summary:
report_lines.extend([
"### 📰 消息面",
f"{result.news_summary}",
"",
])
report_lines.extend([
"---",
"",
])
# 底部(去除免责声明)
report_lines.extend([
"",
f"*报告生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*",
])
return "\n".join(report_lines)
def generate_wechat_dashboard(self, results: List[AnalysisResult]) -> str:
"""
生成企业微信决策仪表盘精简版(控制在4000字符内)
只保留核心结论和狙击点位
Args:
results: 分析结果列表
Returns:
精简版决策仪表盘
"""
report_date = datetime.now().strftime('%Y-%m-%d')
# 按评分排序
sorted_results = sorted(results, key=lambda x: x.sentiment_score, reverse=True)
# 统计
buy_count = sum(1 for r in results if r.operation_advice in ['买入', '加仓', '强烈买入'])
sell_count = sum(1 for r in results if r.operation_advice in ['卖出', '减仓', '强烈卖出'])
hold_count = sum(1 for r in results if r.operation_advice in ['持有', '观望'])
lines = [
f"## 🎯 {report_date} 决策仪表盘",
"",
f"> {len(results)}只股票 | 🟢买入:{buy_count} 🟡观望:{hold_count} 🔴卖出:{sell_count}",
"",
]
for result in sorted_results:
signal_text, signal_emoji, _ = self._get_signal_level(result)
dashboard = result.dashboard if hasattr(result, 'dashboard') and result.dashboard else {}
core = dashboard.get('core_conclusion', {}) if dashboard else {}
battle = dashboard.get('battle_plan', {}) if dashboard else {}
intel = dashboard.get('intelligence', {}) if dashboard else {}
# 股票名称
stock_name = result.name if result.name and not result.name.startswith('股票') else f'股票{result.code}'
# 标题行:信号等级 + 股票名称
lines.append(f"### {signal_emoji} **{signal_text}** | {stock_name}({result.code})")
lines.append("")
# 核心决策(一句话)
one_sentence = core.get('one_sentence', result.analysis_summary) if core else result.analysis_summary
if one_sentence:
lines.append(f"📌 **{one_sentence[:80]}**")
lines.append("")
# 重要信息区(舆情+基本面)
info_lines = []
# 业绩预期
if intel.get('earnings_outlook'):
outlook = intel['earnings_outlook'][:60]
info_lines.append(f"📊 业绩: {outlook}")
# 舆情情绪
if intel.get('sentiment_summary'):
sentiment = intel['sentiment_summary'][:50]
info_lines.append(f"💭 舆情: {sentiment}")
if info_lines:
lines.extend(info_lines)
lines.append("")
# 风险警报(最重要,醒目显示)
risks = intel.get('risk_alerts', []) if intel else []
if risks:
lines.append("🚨 **风险**:")
for risk in risks[:2]: # 最多显示2条
risk_text = risk[:50] + "..." if len(risk) > 50 else risk
lines.append(f" • {risk_text}")
lines.append("")
# 利好催化
catalysts = intel.get('positive_catalysts', []) if intel else []
if catalysts:
lines.append("✨ **利好**:")
for cat in catalysts[:2]: # 最多显示2条
cat_text = cat[:50] + "..." if len(cat) > 50 else cat
lines.append(f" • {cat_text}")
lines.append("")
# 狙击点位
sniper = battle.get('sniper_points', {}) if battle else {}
if sniper:
ideal_buy = sniper.get('ideal_buy', '')
stop_loss = sniper.get('stop_loss', '')
take_profit = sniper.get('take_profit', '')
points = []
if ideal_buy:
points.append(f"🎯买点:{ideal_buy[:15]}")
if stop_loss:
points.append(f"🛑止损:{stop_loss[:15]}")
if take_profit:
points.append(f"🎊目标:{take_profit[:15]}")
if points:
lines.append(" | ".join(points))
lines.append("")
# 持仓建议
pos_advice = core.get('position_advice', {}) if core else {}
if pos_advice:
no_pos = pos_advice.get('no_position', '')
has_pos = pos_advice.get('has_position', '')
if no_pos:
lines.append(f"🆕 空仓者: {no_pos[:50]}")
if has_pos:
lines.append(f"💼 持仓者: {has_pos[:50]}")
lines.append("")
# 检查清单简化版
checklist = battle.get('action_checklist', []) if battle else []
if checklist:
# 只显示不通过的项目
failed_checks = [c for c in checklist if c.startswith('❌') or c.startswith('⚠️')]
if failed_checks:
lines.append("**检查未通过项**:")
for check in failed_checks[:3]:
lines.append(f" {check[:40]}")
lines.append("")
lines.append("---")
lines.append("")
# 底部
lines.append(f"*生成时间: {datetime.now().strftime('%H:%M')}*")
content = "\n".join(lines)
return content
def generate_wechat_summary(self, results: List[AnalysisResult]) -> str:
"""
生成企业微信精简版日报(控制在4000字符内)
Args:
results: 分析结果列表
Returns:
精简版 Markdown 内容
"""
report_date = datetime.now().strftime('%Y-%m-%d')
# 按评分排序
sorted_results = sorted(results, key=lambda x: x.sentiment_score, reverse=True)
# 统计
buy_count = sum(1 for r in results if r.operation_advice in ['买入', '加仓', '强烈买入'])
sell_count = sum(1 for r in results if r.operation_advice in ['卖出', '减仓', '强烈卖出'])
hold_count = sum(1 for r in results if r.operation_advice in ['持有', '观望'])
avg_score = sum(r.sentiment_score for r in results) / len(results) if results else 0
lines = [
f"## 📅 {report_date} A股分析报告",
"",
f"> 共 **{len(results)}** 只 | 🟢买入:{buy_count} 🟡持有:{hold_count} 🔴卖出:{sell_count} | 均分:{avg_score:.0f}",
"",
]
# 每只股票精简信息(控制长度)
for result in sorted_results:
emoji = result.get_emoji()
# 核心信息行
lines.append(f"### {emoji} {result.name}({result.code})")
lines.append(f"**{result.operation_advice}** | 评分:{result.sentiment_score} | {result.trend_prediction}")
# 操作理由(截断)
if hasattr(result, 'buy_reason') and result.buy_reason:
reason = result.buy_reason[:80] + "..." if len(result.buy_reason) > 80 else result.buy_reason
lines.append(f"💡 {reason}")
# 核心看点
if hasattr(result, 'key_points') and result.key_points:
points = result.key_points[:60] + "..." if len(result.key_points) > 60 else result.key_points
lines.append(f"🎯 {points}")
# 风险提示(截断)
if hasattr(result, 'risk_warning') and result.risk_warning:
risk = result.risk_warning[:50] + "..." if len(result.risk_warning) > 50 else result.risk_warning
lines.append(f"⚠️ {risk}")
lines.append("")
# 底部
lines.extend([
"---",
"*AI生成,仅供参考,不构成投资建议*",
f"*详细报告见 reports/report_{report_date.replace('-', '')}.md*"
])
content = "\n".join(lines)
return content
def generate_single_stock_report(self, result: AnalysisResult) -> str:
"""
生成单只股票的分析报告(用于单股推送模式 #55)
格式精简但信息完整,适合每分析完一只股票立即推送
Args:
result: 单只股票的分析结果
Returns:
Markdown 格式的单股报告
"""
report_date = datetime.now().strftime('%Y-%m-%d %H:%M')
signal_text, signal_emoji, _ = self._get_signal_level(result)
dashboard = result.dashboard if hasattr(result, 'dashboard') and result.dashboard else {}
core = dashboard.get('core_conclusion', {}) if dashboard else {}
battle = dashboard.get('battle_plan', {}) if dashboard else {}
intel = dashboard.get('intelligence', {}) if dashboard else {}
# 股票名称
stock_name = result.name if result.name and not result.name.startswith('股票') else f'股票{result.code}'
lines = [
f"## {signal_emoji} {stock_name} ({result.code})",
"",
f"> {report_date} | 评分: **{result.sentiment_score}** | {result.trend_prediction}",
"",
]
# 核心决策(一句话)
one_sentence = core.get('one_sentence', result.analysis_summary) if core else result.analysis_summary
if one_sentence:
lines.extend([
"### 📌 核心结论",
"",
f"**{signal_text}**: {one_sentence}",
"",
])
# 重要信息(舆情+基本面)
info_added = False
if intel:
if intel.get('earnings_outlook'):
if not info_added:
lines.append("### 📰 重要信息")
lines.append("")
info_added = True
lines.append(f"📊 **业绩预期**: {intel['earnings_outlook'][:100]}")
if intel.get('sentiment_summary'):
if not info_added:
lines.append("### 📰 重要信息")
lines.append("")
info_added = True
lines.append(f"💭 **舆情情绪**: {intel['sentiment_summary'][:80]}")
# 风险警报
risks = intel.get('risk_alerts', [])
if risks:
if not info_added:
lines.append("### 📰 重要信息")
lines.append("")
info_added = True
lines.append("")
lines.append("🚨 **风险警报**:")
for risk in risks[:3]:
lines.append(f"- {risk[:60]}")
# 利好催化
catalysts = intel.get('positive_catalysts', [])
if catalysts:
lines.append("")
lines.append("✨ **利好催化**:")
for cat in catalysts[:3]:
lines.append(f"- {cat[:60]}")
if info_added:
lines.append("")
# 狙击点位
sniper = battle.get('sniper_points', {}) if battle else {}
if sniper:
lines.extend([
"### 🎯 操作点位",
"",
"| 买点 | 止损 | 目标 |",
"|------|------|------|",
])
ideal_buy = sniper.get('ideal_buy', '-')
stop_loss = sniper.get('stop_loss', '-')
take_profit = sniper.get('take_profit', '-')
lines.append(f"| {ideal_buy} | {stop_loss} | {take_profit} |")
lines.append("")
# 持仓建议
pos_advice = core.get('position_advice', {}) if core else {}
if pos_advice: