-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
1340 lines (1122 loc) · 47.7 KB
/
Copy pathmain.py
File metadata and controls
1340 lines (1122 loc) · 47.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. 实现低并发的线程池调度
3. 全局异常处理,确保单股失败不影响整体
4. 提供命令行入口
使用方式:
python main.py # 正常运行
python main.py --debug # 调试模式
python main.py --dry-run # 仅获取数据不分析
交易理念(已融入分析):
- 严进策略:不追高,乖离率 > 5% 不买入
- 趋势交易:只做 MA5>MA10>MA20 多头排列
- 效率优先:关注筹码集中度好的股票
- 买点偏好:缩量回踩 MA5/MA10 支撑
"""
from __future__ import annotations
import multiprocessing
import os
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from dotenv import dotenv_values
from src.config import setup_env
_INITIAL_PROCESS_ENV = dict(os.environ)
setup_env()
# 代理配置 - 通过 USE_PROXY 环境变量控制,默认关闭
# GitHub Actions 环境自动跳过代理配置
if os.getenv("GITHUB_ACTIONS") != "true" and os.getenv("USE_PROXY", "false").lower() == "true":
# 本地开发环境,启用代理(可在 .env 中配置 PROXY_HOST 和 PROXY_PORT)
proxy_host = os.getenv("PROXY_HOST", "127.0.0.1")
proxy_port = os.getenv("PROXY_PORT", "10809")
proxy_url = f"http://{proxy_host}:{proxy_port}"
os.environ["http_proxy"] = proxy_url
os.environ["https_proxy"] = proxy_url
if os.getenv("OCTOPUS_PACKAGED_INKSIFT_IMPORT_PROBE") == "1":
import importlib
import sys
try:
importlib.import_module("inksift.octopus_adapter")
except Exception as exc:
print(f"ERROR: packaged InkSift adapter import failed: {exc}", file=sys.stderr)
sys.exit(1)
print("OK: packaged InkSift adapter import succeeded")
sys.exit(0)
import argparse
import logging
import sys
import time
import uuid
from datetime import date, datetime, timezone, timedelta
from src.webui_frontend import prepare_webui_frontend_assets
from src.config import get_config, Config
from src.logging_config import setup_logging
from src.services.stock_code_utils import resolve_index_stock_code_for_analysis
logger = logging.getLogger(__name__)
_RUNTIME_ENV_FILE_KEYS = set()
_PUBLIC_BIND_HOSTS = frozenset({"0.0.0.0", "::", "[::]", "*"})
def _get_active_env_path() -> Path:
env_file = os.getenv("ENV_FILE")
if env_file:
return Path(env_file)
return Path(__file__).resolve().parent / ".env"
def _is_public_bind_host(host: str) -> bool:
return (host or "").strip().lower() in _PUBLIC_BIND_HOSTS
def _warn_if_public_webui_without_auth(host: str) -> None:
if not _is_public_bind_host(host):
return
from src.auth import is_auth_enabled
if is_auth_enabled():
return
logger.warning(
"WEBUI_HOST=%s binds the Web UI to a public interface while "
"ADMIN_AUTH_ENABLED=false. Keep this service behind a trusted network "
"boundary or enable admin authentication before exposing it.",
host,
)
def _read_active_env_values() -> Optional[Dict[str, str]]:
env_path = _get_active_env_path()
if not env_path.exists():
return {}
try:
values = dotenv_values(env_path)
except Exception as exc: # pragma: no cover - defensive branch
logger.warning("读取配置文件 %s 失败,继续沿用当前环境变量: %s", env_path, exc)
return None
return {
str(key): "" if value is None else str(value)
for key, value in values.items()
if key is not None
}
_ACTIVE_ENV_FILE_VALUES = _read_active_env_values() or {}
_RUNTIME_ENV_FILE_KEYS = {
key for key in _ACTIVE_ENV_FILE_VALUES
if key not in _INITIAL_PROCESS_ENV
}
# setup_env() already ran at import time above.
_env_bootstrapped = True
def _bootstrap_environment() -> None:
"""Load .env and apply optional local proxy settings.
Guarded to be idempotent so it can safely be called from lazy-import
paths used by API / bot consumers.
"""
global _env_bootstrapped
if _env_bootstrapped:
return
from src.config import setup_env
setup_env()
if os.getenv("GITHUB_ACTIONS") != "true" and os.getenv("USE_PROXY", "false").lower() == "true":
proxy_host = os.getenv("PROXY_HOST", "127.0.0.1")
proxy_port = os.getenv("PROXY_PORT", "10809")
proxy_url = f"http://{proxy_host}:{proxy_port}"
os.environ["http_proxy"] = proxy_url
os.environ["https_proxy"] = proxy_url
_env_bootstrapped = True
def _setup_bootstrap_logging(debug: bool = False) -> None:
"""Initialize stderr-only logging before config is loaded.
File handlers are deferred until ``config.log_dir`` is known (via the
subsequent ``setup_logging()`` call) so that healthy runs never create
log files in a hard-coded directory.
"""
level = logging.DEBUG if debug else logging.INFO
root = logging.getLogger()
root.setLevel(level)
if not any(
isinstance(h, logging.StreamHandler) and getattr(h, "stream", None) is sys.stderr
for h in root.handlers
):
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(level)
handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
)
root.addHandler(handler)
def _setup_runtime_logging(log_dir: str, debug: bool = False) -> bool:
"""Switch to configured logging, falling back to console on file I/O errors."""
try:
setup_logging(log_prefix="stock_analysis", debug=debug, log_dir=log_dir)
return True
except OSError as exc:
logger.warning(
"文件日志初始化失败,已降级为控制台日志输出;日志目录 %r 当前不可写或不可创建: %s。"
"官方 Docker 镜像启动入口会自动修复默认挂载目录权限;若仍失败,"
"请检查是否使用了 --user、只读挂载、rootless Docker 或 NFS 等限制写入的环境。",
log_dir,
exc,
)
return False
def _get_stock_analysis_pipeline():
"""Lazily import StockAnalysisPipeline for external consumers.
Also ensures env/proxy bootstrap has run so that API / bot consumers
that never call ``main()`` still get ``USE_PROXY`` applied.
"""
_bootstrap_environment()
from src.core.pipeline import StockAnalysisPipeline as _Pipeline
return _Pipeline
class _LazyPipelineDescriptor:
"""Descriptor that resolves StockAnalysisPipeline on first attribute access."""
_resolved = None
def __set_name__(self, owner, name):
self._name = name
def __get__(self, obj, objtype=None):
if self._resolved is None:
self._resolved = _get_stock_analysis_pipeline()
return self._resolved
class _ModuleExports:
StockAnalysisPipeline = _LazyPipelineDescriptor()
_exports = _ModuleExports()
def __getattr__(name: str):
if name == "StockAnalysisPipeline":
return _exports.StockAnalysisPipeline
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def _reload_env_file_values_preserving_overrides() -> None:
"""Refresh `.env`-managed env vars without clobbering process env overrides."""
global _RUNTIME_ENV_FILE_KEYS
latest_values = _read_active_env_values()
if latest_values is None:
return
managed_keys = {
key for key in latest_values
if key not in _INITIAL_PROCESS_ENV
}
for key in _RUNTIME_ENV_FILE_KEYS - managed_keys:
os.environ.pop(key, None)
for key in managed_keys:
os.environ[key] = latest_values[key]
_RUNTIME_ENV_FILE_KEYS = managed_keys
def parse_arguments() -> argparse.Namespace:
"""解析命令行参数"""
parser = argparse.ArgumentParser(
description='A股自选股智能分析系统',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
示例:
python main.py # 正常运行
python main.py --debug # 调试模式
python main.py --dry-run # 仅获取数据,不进行 AI 分析
python main.py --stocks 600519,000001 # 指定分析特定股票
python main.py --no-notify # 不发送推送通知
python main.py --check-notify # 检查通知配置,不发送通知
python main.py --single-notify # 启用单股推送模式(每分析完一只立即推送)
python main.py --schedule # 启用定时任务模式
python main.py --market-review # 仅运行大盘复盘
'''
)
parser.add_argument(
'--debug',
action='store_true',
help='启用调试模式,输出详细日志'
)
parser.add_argument(
'--dry-run',
action='store_true',
help='仅获取数据,不进行 AI 分析'
)
parser.add_argument(
'--stocks',
type=str,
help='指定要分析的股票代码,逗号分隔(覆盖配置文件)'
)
parser.add_argument(
'--no-notify',
action='store_true',
help='不发送推送通知'
)
parser.add_argument(
'--check-notify',
action='store_true',
help='只读检查通知渠道配置,不发送通知'
)
parser.add_argument(
'--single-notify',
action='store_true',
help='启用单股推送模式:每分析完一只股票立即推送,而不是汇总推送'
)
parser.add_argument(
'--workers',
type=int,
default=None,
help='并发线程数(默认使用配置值)'
)
parser.add_argument(
'--schedule',
action='store_true',
help='启用定时任务模式,每日定时执行'
)
parser.add_argument(
'--no-run-immediately',
action='store_true',
help='定时任务启动时不立即执行一次'
)
parser.add_argument(
'--market-review',
action='store_true',
help='仅运行大盘复盘分析'
)
parser.add_argument(
'--no-market-review',
action='store_true',
help='跳过大盘复盘分析'
)
parser.add_argument(
'--force-run',
action='store_true',
help='跳过交易日检查,强制执行全量分析(Issue #373)'
)
parser.add_argument(
'--webui',
action='store_true',
help='启动 Web 管理界面'
)
parser.add_argument(
'--webui-only',
action='store_true',
help='仅启动 Web 服务,不执行自动分析'
)
parser.add_argument(
'--serve',
action='store_true',
help='启动 FastAPI 后端服务(同时执行分析任务)'
)
parser.add_argument(
'--serve-only',
action='store_true',
help='仅启动 FastAPI 后端服务,不自动执行分析'
)
parser.add_argument(
'--port',
type=int,
default=8000,
help='FastAPI 服务端口(默认 8000)'
)
parser.add_argument(
'--host',
type=str,
default='0.0.0.0',
help='FastAPI 服务监听地址(默认 0.0.0.0)'
)
parser.add_argument(
'--no-context-snapshot',
action='store_true',
help='不保存分析上下文快照'
)
# === Backtest ===
parser.add_argument(
'--backtest',
action='store_true',
help='运行回测(对历史分析结果进行评估)'
)
parser.add_argument(
'--backtest-code',
type=str,
default=None,
help='仅回测指定股票代码'
)
parser.add_argument(
'--backtest-days',
type=int,
default=None,
help='回测评估窗口(交易日数,默认使用配置)'
)
parser.add_argument(
'--backtest-force',
action='store_true',
help='强制回测(即使已有回测结果也重新计算)'
)
return parser.parse_args()
def _compute_trading_day_filter(
config: Config,
args: argparse.Namespace,
stock_codes: List[str],
) -> Tuple[List[str], Optional[str], bool]:
"""
Compute filtered stock list and effective market review region (Issue #373).
Returns:
(filtered_codes, effective_region, should_skip_all)
- effective_region None = use config default (check disabled)
- effective_region '' = all relevant markets closed, skip market review
- should_skip_all: skip entire run when no stocks and no market review to run
"""
force_run = getattr(args, 'force_run', False)
if force_run or not getattr(config, 'trading_day_check_enabled', True):
return (stock_codes, None, False)
from src.core.trading_calendar import (
get_market_for_stock,
get_open_markets_today,
compute_effective_region,
)
open_markets = get_open_markets_today()
filtered_codes = []
for code in stock_codes:
mkt = get_market_for_stock(code)
if mkt in open_markets or mkt is None:
filtered_codes.append(code)
if config.market_review_enabled and not getattr(args, 'no_market_review', False):
effective_region = compute_effective_region(
getattr(config, 'market_review_region', 'cn') or 'cn', open_markets
)
else:
effective_region = None
should_skip_all = (not filtered_codes) and (effective_region or '') == ''
return (filtered_codes, effective_region, should_skip_all)
def _run_market_review_with_shared_lock(
config: Config,
run_market_review_func: Callable[..., Any],
**kwargs: Any,
) -> Any:
from src.core.market_review_lock import (
release_market_review_lock,
try_acquire_market_review_lock,
)
lock_token = try_acquire_market_review_lock(config)
if lock_token is None:
logger.warning("大盘复盘正在执行中,跳过本次大盘复盘")
return None
try:
params = dict(kwargs)
params.setdefault("config", config)
return run_market_review_func(**params)
finally:
release_market_review_lock(lock_token)
def _is_multi_market_region(region: str) -> bool:
normalized = str(region or "").strip().lower()
if not normalized:
return False
if normalized == "both":
return True
parts = {item.strip() for item in normalized.split(",") if item.strip()}
return len(parts) > 1
def _refresh_stock_index_cache_for_analysis(config: Config) -> None:
"""Best-effort stock-index refresh for CLI/scheduled analysis paths."""
try:
from src.services.stock_index_remote_service import (
refresh_remote_stock_index_cache,
settings_from_config,
)
result = refresh_remote_stock_index_cache(settings_from_config(config))
if result.refreshed:
logger.info("[stock-index] 分析前已刷新股票索引缓存: %s", result.cache_path)
elif result.error:
logger.debug("[stock-index] 分析前刷新未完成,继续使用本地索引: %s", result.error)
except Exception as exc: # noqa: BLE001 - stock index freshness must not block analysis.
logger.warning("[stock-index] 分析前刷新股票索引失败,继续执行分析: %s", exc)
def _prime_daily_market_context(
config: Config,
pipeline: Any,
*,
region: str,
no_market_review: bool,
allow_generate: bool,
force_refresh: bool = False,
target_date: Optional[date] = None,
return_full_report: bool = False,
require_current_query_match: bool = False,
) -> Union[str, Tuple[str, str]]:
"""Load/reuse the run's market context, avoiding unbounded background generation."""
if no_market_review or not region:
return ("", "") if return_full_report else ""
from src.services.daily_market_context import DailyMarketContextService
if not _is_multi_market_region(region):
service = getattr(pipeline, "_daily_market_context_service", None)
if service is None:
service = DailyMarketContextService(db_manager=pipeline.db)
pipeline._daily_market_context_service = service
else:
service = DailyMarketContextService(db_manager=pipeline.db)
get_context_kwargs = {
"region": region,
"config": config,
"notifier": pipeline.notifier,
"analyzer": pipeline.analyzer,
"search_service": pipeline.search_service,
"force_refresh": force_refresh,
"allow_generate": allow_generate,
"persist_market_review_history": False,
"target_date": target_date,
"require_query_id_match": require_current_query_match,
}
current_query_id = getattr(pipeline, "query_id", None)
if isinstance(current_query_id, str) and current_query_id.strip():
get_context_kwargs["current_query_id"] = current_query_id
context = service.get_context(**get_context_kwargs)
if context is None:
return ("", "") if return_full_report else ""
# Runtime context generation is preload-only and must not replace the full
# market review run, except the query-scoped fallback after that run fails.
if context.source != "analysis_history" and not (
require_current_query_match and context.source == "market_review_runtime"
):
return ("", "") if return_full_report else ""
summary = str(getattr(context, "summary", ""))
full_report = str(getattr(context, "full_report", "") or "")
if return_full_report:
return summary, full_report
return summary
def _can_reuse_market_context_for_review(summary: str, region: str) -> bool:
if not summary:
return False
normalized = str(region or "").strip().lower()
if normalized == "both":
return False
parts = {item.strip() for item in normalized.split(",") if item.strip()}
return len(parts) <= 1
def _resolve_daily_market_context_target_date(
region: str,
current_time: datetime,
) -> date:
normalized_region = str(region or "cn").strip().lower()
market = normalized_region if normalized_region in {"cn", "hk", "us"} else "cn"
from src.core.trading_calendar import get_effective_trading_date
return get_effective_trading_date(market, current_time=current_time)
def _market_review_report_text(review_result: Any) -> str:
if review_result is None:
return ""
report = getattr(review_result, "report", None)
if isinstance(report, str):
return report
return review_result if isinstance(review_result, str) else ""
def _save_reused_market_review_report(
notifier: Any,
market_report: str,
*,
config: Config,
trigger_source: str,
region: str,
) -> None:
body = str(market_report or "").strip()
if not body:
return
title = (
"# 🎯 Market Review"
if str(getattr(config, "report_language", "zh")).strip().lower() == "en"
else "# 🎯 大盘复盘"
)
if not any(body.startswith(item) for item in ("# 🎯 大盘复盘", "# 🎯 Market Review")):
body = f"{title}\n\n{body}"
try:
date_str = datetime.now().strftime('%Y%m%d')
report_filename = f"market_review_{date_str}.md"
filepath = notifier.save_report_to_file(body, report_filename)
logger.info(
"[MarketReview] component=market_review action=save_reused_report "
"trigger_source=%s region=%s path=%s",
trigger_source,
region,
filepath,
)
except Exception as exc:
logger.warning("复用大盘上下文保存大盘复盘报告失败: %s", exc)
def run_full_analysis(
config: Config,
args: argparse.Namespace,
stock_codes: Optional[List[str]] = None
):
"""
执行完整的分析流程(个股 + 大盘复盘)
这是定时任务调用的主函数
"""
# Import pipeline modules outside the broad try/except so that import-time
# failures propagate to the caller instead of being silently swallowed.
from src.core.market_review import run_market_review
from src.core.pipeline import StockAnalysisPipeline
try:
_refresh_stock_index_cache_for_analysis(config)
# Issue #529: Hot-reload STOCK_LIST from .env on each scheduled run
if stock_codes is None:
config.refresh_stock_list()
# Issue #373: Trading day filter (per-stock, per-market)
effective_codes = stock_codes if stock_codes is not None else config.stock_list
filtered_codes, effective_region, should_skip = _compute_trading_day_filter(
config, args, effective_codes
)
if should_skip:
logger.info(
"今日所有相关市场均为非交易日,跳过执行。可使用 --force-run 强制执行。"
)
return
if set(filtered_codes) != set(effective_codes):
skipped = set(effective_codes) - set(filtered_codes)
logger.info("今日休市股票已跳过: %s", skipped)
stock_codes = filtered_codes
# 命令行参数 --single-notify 覆盖配置(#55)
if getattr(args, 'single_notify', False):
config.single_stock_notify = True
# Issue #190: 个股与大盘复盘合并推送
merge_notification = (
getattr(config, 'merge_email_notification', False)
and config.market_review_enabled
and not getattr(args, 'no_market_review', False)
and not config.single_stock_notify
)
# 创建调度器
save_context_snapshot = None
if getattr(args, 'no_context_snapshot', False):
save_context_snapshot = False
query_id = uuid.uuid4().hex
market_review_region = (
effective_region
if effective_region is not None
else (getattr(config, 'market_review_region', 'cn') or 'cn')
)
should_run_market_review = (
config.market_review_enabled
and not args.no_market_review
and (market_review_region or '') != ''
)
should_use_daily_market_context = (
should_run_market_review
and getattr(config, 'daily_market_context_enabled', True)
)
analysis_reference_time = datetime.now(timezone.utc)
daily_market_context_target_date = None
if should_use_daily_market_context:
daily_market_context_target_date = _resolve_daily_market_context_target_date(
market_review_region,
analysis_reference_time,
)
market_report = ""
market_context_summary = ""
market_context_full_report = ""
market_context_generated_during_stock = False
pipeline = StockAnalysisPipeline(
config=config,
max_workers=args.workers,
query_id=query_id,
query_source="cli",
save_context_snapshot=save_context_snapshot,
daily_market_context_enabled=should_use_daily_market_context,
daily_market_context_allow_generate=should_use_daily_market_context,
)
if should_use_daily_market_context:
# Prompt-side context can reuse historical summaries, while full-merge
# content must avoid silently reusing unrelated historical reports.
_prime_daily_market_context(
config,
pipeline=pipeline,
region=market_review_region,
no_market_review=args.no_market_review,
allow_generate=False,
target_date=daily_market_context_target_date,
return_full_report=False,
)
(
market_context_summary,
market_context_full_report,
) = _prime_daily_market_context(
config,
pipeline=pipeline,
region=market_review_region,
no_market_review=args.no_market_review,
allow_generate=False,
target_date=daily_market_context_target_date,
return_full_report=True,
require_current_query_match=True,
)
# 1. 运行个股分析
results = pipeline.run(
stock_codes=stock_codes,
dry_run=args.dry_run,
send_notification=not args.no_notify,
merge_notification=merge_notification,
current_time=analysis_reference_time,
)
if should_use_daily_market_context and not market_context_summary:
(
market_context_summary,
market_context_full_report,
) = _prime_daily_market_context(
config,
pipeline=pipeline,
region=market_review_region,
no_market_review=args.no_market_review,
allow_generate=False,
target_date=daily_market_context_target_date,
return_full_report=True,
require_current_query_match=True,
)
market_context_generated_during_stock = bool(market_context_summary)
# Issue #128: 分析间隔 - 在个股分析和大盘分析之间添加延迟
analysis_delay = getattr(config, 'analysis_delay', 0)
# 2. 运行大盘复盘(如果启用且不是仅个股模式)
if should_run_market_review:
schedule_mode = bool(
getattr(args, 'schedule', False)
or getattr(config, 'schedule_enabled', False)
)
review_trigger_source = "schedule" if schedule_mode else "cli"
can_reuse_market_context = (
_can_reuse_market_context_for_review(
market_context_summary,
market_review_region,
)
if should_use_daily_market_context
else False
)
can_skip_market_review = (
(merge_notification or market_context_generated_during_stock)
and can_reuse_market_context
and bool(market_context_full_report or market_context_summary)
)
if can_skip_market_review:
market_report = market_context_full_report or market_context_summary
logger.info(
"复盘上下文可复用,跳过重复大盘复盘并复用上下文内容。"
)
_save_reused_market_review_report(
pipeline.notifier,
market_report,
config=config,
trigger_source=review_trigger_source,
region=market_review_region,
)
if (
market_context_generated_during_stock
and not merge_notification
and not args.no_notify
and pipeline.notifier.is_available()
):
if pipeline.notifier.send(
f"# 📈 大盘复盘\n\n{market_report}",
email_send_to_all=True,
route_type="report",
):
logger.info("复用本轮大盘上下文推送大盘复盘成功")
else:
logger.warning("复用本轮大盘上下文推送大盘复盘失败")
review_result = None
if not can_skip_market_review:
if analysis_delay > 0:
logger.info(f"等待 {analysis_delay} 秒后执行大盘复盘(避免API限流)...")
time.sleep(analysis_delay)
review_result = _run_market_review_with_shared_lock(
config,
run_market_review,
notifier=pipeline.notifier,
analyzer=pipeline.analyzer,
search_service=pipeline.search_service,
send_notification=not args.no_notify,
merge_notification=merge_notification,
override_region=market_review_region,
query_id=query_id,
trigger_source=review_trigger_source,
)
# 如果复盘仍未执行成功,再做一次复用历史/缓存读取(防止与并发运行竞态)。
if not review_result and should_use_daily_market_context:
(
market_context_summary,
market_context_full_report,
) = _prime_daily_market_context(
config,
pipeline=pipeline,
region=market_review_region,
no_market_review=args.no_market_review,
allow_generate=False,
target_date=daily_market_context_target_date,
return_full_report=True,
require_current_query_match=True,
)
can_reuse_market_context = _can_reuse_market_context_for_review(
market_context_summary,
market_review_region,
)
elif not review_result:
can_reuse_market_context = False
# 如果有结果,赋值给 market_report 用于后续飞书文档生成
if review_result:
market_report = _market_review_report_text(review_result)
elif can_reuse_market_context:
market_report = market_context_full_report or market_context_summary
# Issue #190: 合并推送(个股+大盘复盘)
if merge_notification and (results or market_report) and not args.no_notify:
parts = []
if market_report:
parts.append(f"# 📈 大盘复盘\n\n{market_report}")
if results:
dashboard_content = pipeline.notifier.generate_aggregate_report(
results,
getattr(config, 'report_type', 'simple'),
)
parts.append(f"# 🚀 个股决策仪表盘\n\n{dashboard_content}")
if parts:
combined_content = "\n\n---\n\n".join(parts)
if pipeline.notifier.is_available():
if pipeline.notifier.send(combined_content, email_send_to_all=True, route_type="report"):
logger.info("已合并推送(个股+大盘复盘)")
else:
logger.warning("合并推送失败")
# 输出摘要
if results:
logger.info("\n===== 分析结果摘要 =====")
for r in sorted(results, key=lambda x: x.sentiment_score, reverse=True):
emoji = r.get_emoji()
logger.info(
f"{emoji} {r.name}({r.code}): {r.operation_advice} | "
f"评分 {r.sentiment_score} | {r.trend_prediction}"
)
logger.info("\n任务执行完成")
# === 新增:生成飞书云文档 ===
try:
from src.feishu_doc import FeishuDocManager
feishu_doc = FeishuDocManager()
if feishu_doc.is_configured() and (results or market_report):
logger.info("正在创建飞书云文档...")
# 1. 准备标题 "01-01 13:01大盘复盘"
tz_cn = timezone(timedelta(hours=8))
now = datetime.now(tz_cn)
doc_title = f"{now.strftime('%Y-%m-%d %H:%M')} 大盘复盘"
# 2. 准备内容 (拼接个股分析和大盘复盘)
full_content = ""
# 添加大盘复盘内容(如果有)
if market_report:
full_content += f"# 📈 大盘复盘\n\n{market_report}\n\n---\n\n"
# 添加个股决策仪表盘(使用 NotificationService 生成,按 report_type 分支)
if results:
dashboard_content = pipeline.notifier.generate_aggregate_report(
results,
getattr(config, 'report_type', 'simple'),
)
full_content += f"# 🚀 个股决策仪表盘\n\n{dashboard_content}"
# 3. 创建文档
doc_url = feishu_doc.create_daily_doc(doc_title, full_content)
if doc_url:
logger.info(f"飞书云文档创建成功: {doc_url}")
# 可选:将文档链接也推送到群里
if not args.no_notify:
pipeline.notifier.send(
f"[{now.strftime('%Y-%m-%d %H:%M')}] 复盘文档创建成功: {doc_url}",
route_type="report",
)
except Exception as e:
logger.error(f"飞书文档生成失败: {e}")
# === Auto backtest ===
try:
if getattr(config, 'backtest_enabled', False):
from src.services.backtest_service import BacktestService
logger.info("开始自动回测...")
service = BacktestService()
stats = service.run_backtest(
force=False,
eval_window_days=getattr(config, 'backtest_eval_window_days', 10),
min_age_days=getattr(config, 'backtest_min_age_days', 14),
limit=200,
)
logger.info(
f"自动回测完成: processed={stats.get('processed')} saved={stats.get('saved')} "
f"completed={stats.get('completed')} insufficient={stats.get('insufficient')} errors={stats.get('errors')}"
)
except Exception as e:
logger.warning(f"自动回测失败(已忽略): {e}")
except Exception as e:
logger.exception(f"分析流程执行失败: {e}")
def start_api_server(host: str, port: int, config: Config) -> None:
"""
在后台线程启动 FastAPI 服务
Args:
host: 监听地址
port: 监听端口
config: 配置对象
"""
import socket
import threading
import uvicorn
probe = socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET, socket.SOCK_STREAM)
try:
probe.bind((host, port))
except OSError as exc:
raise RuntimeError(f"FastAPI port is not available: {host}:{port}") from exc
finally:
probe.close()
def run_server():
level_name = (config.log_level or "INFO").lower()
uvicorn.run(
"api.app:app",
host=host,
port=port,
log_level=level_name,
log_config=None,
)