forked from azmove/jin-ce-zhi-suan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3197 lines (2959 loc) · 136 KB
/
Copy pathserver.py
File metadata and controls
3197 lines (2959 loc) · 136 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
import asyncio
import argparse
import json
import os
import importlib
import sys
import traceback
import math
import numbers
import re
import urllib.request
import urllib.error
import io
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.lines as mlines
from matplotlib import font_manager
from datetime import datetime
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, BackgroundTasks, HTTPException
from fastapi.responses import HTMLResponse, StreamingResponse, Response, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Dict, List, Any
from src.core.live_cabinet import LiveCabinet
from src.core.backtest_cabinet import BacktestCabinet
from src.utils.config_loader import ConfigLoader
import src.strategies.strategy_factory as strategy_factory_module
from src.strategies.strategy_manager_repo import (
list_all_strategy_meta,
next_custom_strategy_id,
build_fallback_strategy_code,
add_custom_strategy,
update_custom_strategy,
delete_strategy,
set_strategy_enabled,
list_strategy_dependents,
is_builtin_strategy_id
)
from src.strategy_intent.intent_engine import StrategyIntentEngine
from src.utils.stock_manager import stock_manager
from src.utils.data_provider import DataProvider
from src.utils.tushare_provider import TushareProvider
from src.utils.akshare_provider import AkshareProvider
from src.utils.mysql_provider import MysqlProvider
from src.utils.postgres_provider import PostgresProvider
from src.utils.history_sync_service import HistoryDiffSyncService, TABLE_INTERVAL_MAP, DEFAULT_SYNC_TABLES
from src.utils.backtest_baseline import apply_backtest_baseline
from src.utils.webhook_notifier import WebhookNotifier
import logging
def _configure_matplotlib_font():
font_candidates = [
"Microsoft YaHei",
"SimHei",
]
available_fonts = {f.name for f in font_manager.fontManager.ttflist}
chosen_font = next((name for name in font_candidates if name in available_fonts), None)
if chosen_font:
matplotlib.rcParams["font.family"] = "sans-serif"
matplotlib.rcParams["font.sans-serif"] = [chosen_font, "DejaVu Sans"]
matplotlib.rcParams["axes.unicode_minus"] = False
_configure_matplotlib_font()
# Configure Logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger("CabinetServer")
app = FastAPI(title="三省六部 AI 交易决策控制台")
@app.middleware("http")
async def log_requests(request, call_next):
logger.info(f"Incoming Request: {request.method} {request.url.path}")
response = await call_next(request)
logger.info(f"Response Status: {response.status_code}")
return response
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global variables
active_connections = []
cabinet_task = None
current_cabinet = None
live_tasks: Dict[str, asyncio.Task] = {}
live_cabinets: Dict[str, LiveCabinet] = {}
live_strategy_profiles: Dict[str, Any] = {}
live_last_error: Optional[Dict[str, Any]] = None
current_provider_source = None
latest_backtest_result = None
latest_strategy_reports = {}
current_backtest_report = None
current_backtest_progress = {"progress": 0, "current_date": None}
current_backtest_trades = []
kline_daily_cache = {}
report_strategy_kline_cache = {}
report_ai_review_cache = {}
strategy_score_cache = {}
report_detail_cache = {}
report_history_mtime = None
AI_REVIEW_SCHEMA_VERSION = 2
report_history = []
REPORTS_DIR = os.path.join("data", "reports")
REPORTS_FILE = os.path.join(REPORTS_DIR, "backtest_reports.json")
PATTERN_THUMB_DIR = os.path.join(REPORTS_DIR, "pattern_thumbs")
CLASSIC_PATTERN_ITEMS = [
{"stock": "688585", "start": "2025-07-09", "end": "2025-12-31"},
{"stock": "301030", "start": "2025-01-02", "end": "2025-06-30"},
{"stock": "600376", "start": "2025-07-01", "end": "2025-12-31"},
{"stock": "601888", "start": "2025-01-02", "end": "2025-06-30"},
{"stock": "300450", "start": "2025-04-01", "end": "2025-09-30"},
{"stock": "603083", "start": "2025-03-03", "end": "2025-08-29"},
{"stock": "600941", "start": "2025-07-01", "end": "2025-12-31"},
{"stock": "601857", "start": "2025-01-02", "end": "2025-06-30"},
{"stock": "300118", "start": "2025-06-02", "end": "2025-11-28"},
{"stock": "002475", "start": "2025-09-01", "end": "2025-12-31"}
]
# Config
config = ConfigLoader()
intent_engine = StrategyIntentEngine()
history_sync_service = HistoryDiffSyncService()
history_sync_scheduler_task = None
startup_server_host = None
startup_server_port = None
webhook_notifier = WebhookNotifier()
SECRET_CONFIG_PATHS = set(ConfigLoader._default_private_override_paths)
SECRET_MASK = "********"
LIVE_FUND_POOL_DIR = os.path.join("data", "live_fund_pool")
def _system_mode(cfg=None):
c = cfg if cfg is not None else ConfigLoader.reload()
mode = str(c.get("system.mode", "backtest") or "backtest").strip().lower()
return mode if mode in {"backtest", "live"} else "backtest"
def _apply_log_level(cfg=None):
c = cfg if cfg is not None else ConfigLoader.reload()
level_name = str(c.get("system.log_level", "INFO") or "INFO").strip().upper()
level = getattr(logging, level_name, logging.INFO)
logging.getLogger().setLevel(level)
logger.setLevel(level)
return level_name
def _server_host(cfg=None):
c = cfg if cfg is not None else ConfigLoader.reload()
env_host = str(os.environ.get("SERVER_HOST", "") or "").strip()
if env_host:
return env_host
cfg_host = str(c.get("system.server_host", "0.0.0.0") or "").strip()
return cfg_host or "0.0.0.0"
def _server_port(cfg=None):
c = cfg if cfg is not None else ConfigLoader.reload()
env_port = str(os.environ.get("SERVER_PORT", "") or "").strip()
raw_port = env_port if env_port else str(c.get("system.server_port", 8000) or "").strip()
try:
port = int(raw_port)
if 1 <= port <= 65535:
return port
except (TypeError, ValueError):
pass
logger.warning("Invalid server port '%s', fallback to 8000", raw_port)
return 8000
def _resolve_server_bind(cfg=None, argv=None):
c = cfg if cfg is not None else ConfigLoader.reload()
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--host", type=str, default=None)
parser.add_argument("--port", type=int, default=None)
parser.add_argument("--prot", type=int, default=None)
args, _ = parser.parse_known_args(argv if argv is not None else sys.argv[1:])
host = _server_host(c)
port = _server_port(c)
cli_host = str(args.host or "").strip()
if cli_host:
host = cli_host
cli_port = args.prot if args.prot is not None else args.port
if cli_port is not None:
if 1 <= int(cli_port) <= 65535:
port = int(cli_port)
else:
logger.warning("Invalid cli port '%s', keep port=%s", cli_port, port)
return host, port
def _default_target_code(cfg=None):
c = cfg if cfg is not None else ConfigLoader.reload()
targets = c.get("targets", [])
if isinstance(targets, list):
for item in targets:
code = str(item or "").strip()
if code:
return code
return "600036.SH"
def _normalize_live_codes(stock_code=None, stock_codes=None, cfg=None, use_default=True):
out = []
seen = set()
c = cfg if cfg is not None else ConfigLoader.reload()
values = []
if isinstance(stock_codes, list):
values.extend(stock_codes)
if stock_code is not None:
values.append(stock_code)
if (not values) and use_default:
targets = c.get("targets", [])
if isinstance(targets, list):
values.extend(targets)
if (not values) and use_default:
values.append(_default_target_code(c))
for item in values:
code = str(item or "").strip()
if not code:
continue
code_upper = code.upper()
if code_upper in seen:
continue
seen.add(code_upper)
out.append(code_upper)
if out:
return out
if use_default:
return [_default_target_code(c)]
return []
def _live_running_codes():
return [code for code, task in live_tasks.items() if task and (not task.done())]
async def _stop_live_tasks(stock_codes=None, clear_profile=False):
global current_cabinet
targets = _normalize_live_codes(stock_codes=stock_codes, use_default=False) if isinstance(stock_codes, list) else list(live_tasks.keys())
stopped = []
for code in targets:
task = live_tasks.get(code)
if task and not task.done():
task.cancel()
stopped.append(code)
live_tasks.pop(code, None)
live_cabinets.pop(code, None)
if clear_profile:
live_strategy_profiles.pop(code, None)
if (not live_tasks) and (current_cabinet is not None):
current_cabinet = None
return stopped
def _normalize_strategy_selection(strategy_id=None, strategy_ids=None):
if isinstance(strategy_ids, list):
out = []
seen = set()
for item in strategy_ids:
sid = str(item or "").strip()
if (not sid) or sid in seen:
continue
seen.add(sid)
out.append(sid)
if out:
return out
sid = str(strategy_id or "").strip()
if sid:
return sid
return None
def _normalize_stock_strategy_map(stock_strategy_map):
if not isinstance(stock_strategy_map, dict):
return {}
out = {}
for raw_code, raw_ids in stock_strategy_map.items():
code = str(raw_code or "").strip().upper()
if not code:
continue
selection = _normalize_strategy_selection(strategy_ids=raw_ids if isinstance(raw_ids, list) else None)
if selection is None:
continue
out[code] = selection
return out
def _profile_snapshot(codes=None):
target_codes = codes if isinstance(codes, list) else _live_running_codes()
out = {}
for code in target_codes:
profile = live_strategy_profiles.get(code)
if profile is None:
cab = live_cabinets.get(code)
if cab is not None:
profile = getattr(cab, "active_strategy_ids", None)
if profile is not None:
out[code] = profile
return out
def _format_live_start_summary(codes=None):
target_codes = codes if isinstance(codes, list) else _live_running_codes()
profile_map = _profile_snapshot(target_codes)
summary_parts = []
for code in target_codes:
profile = profile_map.get(code)
if isinstance(profile, list):
ids_text = "、".join([str(x) for x in profile if str(x)])
else:
ids_text = str(profile) if profile is not None else "全部"
if not ids_text:
ids_text = "全部"
summary_parts.append(f"{code}[{ids_text}]")
return ";".join(summary_parts) if summary_parts else ",".join(target_codes)
def _live_fund_pool_file(stock_code):
code = str(stock_code or "").strip().upper()
return os.path.join(LIVE_FUND_POOL_DIR, f"{code}.json")
def _empty_live_fund_pool_state(stock_code, initial_capital):
cap = float(initial_capital or 0.0)
return {
"version": 1,
"state": {
"stock_code": str(stock_code or "").strip().upper(),
"updated_at": datetime.now().isoformat(timespec="seconds"),
"initial_capital": cap,
"cash": cap,
"holdings_value": 0.0,
"fund_value": cap,
"position_count": 0,
"positions": [],
"trade_count": 0,
"trade_details": [],
"realized_pnl": 0.0,
"fee_summary": {
"total_cost": 0.0,
"total_commission": 0.0,
"total_stamp_duty": 0.0,
"total_transfer_fee": 0.0
},
"peak_fund_value": cap
},
"positions_state": {},
"transactions_all": []
}
def _load_live_fund_pool_snapshot(stock_code, include_transactions=False, tx_limit=200):
code = str(stock_code or "").strip().upper()
cab = live_cabinets.get(code)
if cab is not None:
return cab.get_fund_pool_snapshot(include_transactions=bool(include_transactions), tx_limit=int(tx_limit or 200))
file_path = _live_fund_pool_file(code)
if not os.path.exists(file_path):
return None
try:
with open(file_path, "r", encoding="utf-8") as f:
payload = json.load(f)
state = payload.get("state", {}) if isinstance(payload, dict) else {}
if not isinstance(state, dict):
return None
trades = state.get("trade_details", [])
if isinstance(trades, list):
if include_transactions:
all_trades = payload.get("transactions_all", [])
if isinstance(all_trades, list) and all_trades:
state["trade_details"] = all_trades[-max(1, int(tx_limit or 1)):]
else:
state["trade_details"] = trades[-max(1, int(tx_limit or 1)):]
else:
state["trade_details"] = trades[-20:]
return state
except Exception:
return None
def _collect_live_fund_pools(codes=None, include_transactions=False, tx_limit=200):
target = []
seen = set()
if isinstance(codes, list):
for item in codes:
code = str(item or "").strip().upper()
if code and code not in seen:
seen.add(code)
target.append(code)
else:
for code in _live_running_codes():
code_u = str(code or "").strip().upper()
if code_u and code_u not in seen:
seen.add(code_u)
target.append(code_u)
if os.path.isdir(LIVE_FUND_POOL_DIR):
for fn in os.listdir(LIVE_FUND_POOL_DIR):
if not str(fn).lower().endswith(".json"):
continue
code_u = str(fn[:-5] or "").strip().upper()
if code_u and code_u not in seen:
seen.add(code_u)
target.append(code_u)
out = {}
for code in target:
snap = _load_live_fund_pool_snapshot(code, include_transactions=include_transactions, tx_limit=tx_limit)
if isinstance(snap, dict):
out[code] = snap
return out
def _set_live_last_error(stock_code, stage, err, tb_text=None):
global live_last_error
err_type = type(err).__name__ if err is not None else "Exception"
err_msg = str(err) if err is not None else ""
stack_text = tb_text if isinstance(tb_text, str) and tb_text.strip() else traceback.format_exc()
live_last_error = {
"time": datetime.now().isoformat(timespec="seconds"),
"stock_code": str(stock_code or "").upper() or None,
"stage": str(stage or "").strip() or None,
"error_type": err_type,
"error_msg": err_msg,
"stack": stack_text
}
def _clear_live_last_error():
global live_last_error
live_last_error = None
def _project_root():
return os.path.dirname(os.path.abspath(__file__))
def _secret_config_paths(payload=None):
try:
if isinstance(payload, dict):
return ConfigLoader.resolve_private_override_paths(payload)
cfg = ConfigLoader.reload()
return ConfigLoader.resolve_private_override_paths(cfg.to_dict())
except Exception:
return set(SECRET_CONFIG_PATHS)
def _private_config_path():
override = str(os.environ.get("CONFIG_PRIVATE_PATH", "") or "").strip()
if override:
return override
try:
cfg = ConfigLoader.reload()
cfg_override = str(cfg.get("system.private_config_path", "") or "").strip()
if cfg_override:
return cfg_override if os.path.isabs(cfg_override) else os.path.join(_project_root(), cfg_override)
except Exception:
pass
return os.path.join(_project_root(), "config.private.json")
def _custom_private_strategy_path():
override = str(os.environ.get("CUSTOM_STRATEGIES_PRIVATE_PATH", "") or "").strip()
if override:
return override
try:
cfg = ConfigLoader.reload()
cfg_override = str(cfg.get("system.private_strategy_path", "") or "").strip()
if cfg_override:
return cfg_override if os.path.isabs(cfg_override) else os.path.join(_project_root(), cfg_override)
except Exception:
pass
return os.path.join(_project_root(), "data", "strategies", "custom_strategies.private.json")
def _startup_private_data_check(cfg=None):
c = cfg if cfg is not None else ConfigLoader.reload()
private_path = _private_config_path()
strategy_private_path = _custom_private_strategy_path()
required_paths = [
"data_provider.default_api_key",
"data_provider.tushare_token",
]
missing_secrets = []
for p in required_paths:
val = str(c.get(p, "") or "").strip()
if not val:
missing_secrets.append(p)
if (not os.path.exists(private_path)) or missing_secrets:
logger.warning("私有配置检查: CONFIG_PRIVATE_PATH=%s", private_path)
if not os.path.exists(private_path):
logger.warning("未找到私有配置文件 config.private.json,密钥不会随代码仓库同步。")
if missing_secrets:
logger.warning("以下关键密钥为空: %s", ",".join(missing_secrets))
logger.warning("建议:在目标机器创建私有目录并设置环境变量 CONFIG_PRIVATE_PATH/CUSTOM_STRATEGIES_PRIVATE_PATH。")
if not os.path.exists(strategy_private_path):
logger.warning("未找到私有策略文件: %s", strategy_private_path)
logger.warning("若需私有策略持久化,请创建该文件并设置 CUSTOM_STRATEGIES_WRITE_PRIVATE=1。")
def _load_json_with_comments(file_path, silent=False):
import re
if not os.path.exists(file_path):
return {}
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
pattern = r'("[^"]*")|(\/\/.*)'
def replace(match):
if match.group(1):
return match.group(1)
return ""
content = re.sub(pattern, replace, content)
payload = json.loads(content)
return payload if isinstance(payload, dict) else {}
except Exception as e:
if not silent:
logger.error(f"load json failed: {file_path}, {e}")
return {}
def _deep_merge_dict(base, override):
if not isinstance(base, dict):
return override if override is not None else base
if not isinstance(override, dict):
return dict(base)
merged = dict(base)
for k, v in override.items():
if isinstance(v, dict) and isinstance(merged.get(k), dict):
merged[k] = _deep_merge_dict(merged[k], v)
else:
merged[k] = v
return merged
def _path_exists(payload, path):
if not isinstance(payload, dict):
return False
cur = payload
for key in str(path).split("."):
if not isinstance(cur, dict) or key not in cur:
return False
cur = cur.get(key)
return True
def _get_path_value(payload, path, default=None):
if not isinstance(payload, dict):
return default
cur = payload
for key in str(path).split("."):
if not isinstance(cur, dict) or key not in cur:
return default
cur = cur.get(key)
return cur
def _set_path_value(payload, path, value):
if not isinstance(payload, dict):
return
keys = str(path).split(".")
cur = payload
for key in keys[:-1]:
nxt = cur.get(key)
if not isinstance(nxt, dict):
nxt = {}
cur[key] = nxt
cur = nxt
cur[keys[-1]] = value
def _delete_path_value(payload, path):
if not isinstance(payload, dict):
return
keys = str(path).split(".")
chain = []
cur = payload
for key in keys:
if not isinstance(cur, dict) or key not in cur:
return
chain.append((cur, key))
cur = cur.get(key)
parent, last_key = chain[-1]
parent.pop(last_key, None)
for parent, key in reversed(chain[:-1]):
child = parent.get(key)
if isinstance(child, dict) and not child:
parent.pop(key, None)
else:
break
def _mask_secret_value(value):
text = str(value or "").strip()
return SECRET_MASK if text else ""
def _mask_secret_config(payload):
masked = json.loads(json.dumps(payload, ensure_ascii=False))
for path in _secret_config_paths(masked):
val = _get_path_value(masked, path, "")
if _path_exists(masked, path):
_set_path_value(masked, path, _mask_secret_value(val))
return masked
def _is_secret_mask_value(value):
return str(value or "").strip() == SECRET_MASK
def _write_json_file(file_path, payload):
folder = os.path.dirname(file_path)
if folder:
os.makedirs(folder, exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
def _save_split_config(incoming):
incoming_dict = incoming if isinstance(incoming, dict) else {}
current_cfg = ConfigLoader.reload().to_dict()
merged_cfg = _deep_merge_dict(current_cfg, incoming_dict)
secret_paths = _secret_config_paths(merged_cfg)
secret_updates = {}
for path in secret_paths:
if not _path_exists(incoming_dict, path):
continue
val = _get_path_value(incoming_dict, path, "")
if isinstance(val, str) and _is_secret_mask_value(val):
continue
secret_updates[path] = val
public_cfg = json.loads(json.dumps(merged_cfg, ensure_ascii=False))
for path in secret_paths:
_set_path_value(public_cfg, path, "")
cfg = ConfigLoader.reload()
cfg._config = public_cfg
cfg.save("config.json")
private_path = _private_config_path()
private_exists = os.path.exists(private_path)
if secret_updates:
private_cfg = _load_json_with_comments(private_path, silent=True)
if not isinstance(private_cfg, dict):
private_cfg = {}
private_changed = False
for path, val in secret_updates.items():
text = str(val or "")
old_val = _get_path_value(private_cfg, path, "")
if not text.strip():
if _path_exists(private_cfg, path):
_delete_path_value(private_cfg, path)
private_changed = True
continue
if str(old_val) != text:
_set_path_value(private_cfg, path, text)
private_changed = True
if private_changed or private_exists:
_write_json_file(private_path, private_cfg)
return ConfigLoader.reload()
def is_live_enabled():
cfg = ConfigLoader.reload()
return bool(cfg.get("system.enable_live", True)) and _system_mode(cfg) == "live"
def load_report_history(force=False):
global report_history, latest_backtest_result, latest_strategy_reports, report_history_mtime, report_detail_cache
os.makedirs(REPORTS_DIR, exist_ok=True)
if not os.path.exists(REPORTS_FILE):
report_history = []
report_history_mtime = None
report_detail_cache = {}
return
try:
mtime = os.path.getmtime(REPORTS_FILE)
if (not force) and (report_history_mtime is not None) and (abs(float(mtime) - float(report_history_mtime)) < 1e-9):
return
with open(REPORTS_FILE, "r", encoding="utf-8") as f:
payload = json.load(f)
report_history = payload.get("reports", [])
report_history_mtime = float(mtime)
report_detail_cache = {}
if report_history:
latest = report_history[0]
latest_backtest_result = latest.get("summary")
latest_strategy_reports = latest.get("strategy_reports", {})
_rebuild_strategy_score_cache()
except Exception as e:
logger.error(f"Failed to load report history: {e}")
report_history = []
report_history_mtime = None
report_detail_cache = {}
_rebuild_strategy_score_cache()
def persist_report_history():
global report_history_mtime, report_detail_cache
os.makedirs(REPORTS_DIR, exist_ok=True)
with open(REPORTS_FILE, "w", encoding="utf-8") as f:
json.dump({"reports": report_history}, f, ensure_ascii=False, indent=2, default=str)
report_history_mtime = os.path.getmtime(REPORTS_FILE) if os.path.exists(REPORTS_FILE) else None
report_detail_cache = {}
def _score_grade(score):
s = float(score or 0.0)
if s >= 90:
return "S"
if s >= 75:
return "A"
if s >= 60:
return "B"
return "C"
def _sample_size_penalty_points(count):
c = int(count or 0)
if c >= 12:
return 0.0
if c >= 8:
return 1.0
if c >= 5:
return 3.0
if c >= 3:
return 5.0
if c >= 2:
return 8.0
return 12.0
def _sample_size_confidence(count):
c = int(count or 0)
if c >= 12:
return 1.0
if c >= 8:
return 0.9
if c >= 5:
return 0.75
if c >= 3:
return 0.6
if c >= 2:
return 0.45
return 0.3
def _rebuild_strategy_score_cache():
global strategy_score_cache
stats = {}
for rep in report_history if isinstance(report_history, list) else []:
if not isinstance(rep, dict):
continue
summary = rep.get("summary") if isinstance(rep.get("summary"), dict) else {}
ranking = summary.get("ranking", []) if isinstance(summary, dict) else []
if not isinstance(ranking, list):
continue
for row in ranking:
if not isinstance(row, dict):
continue
sid = str(row.get("strategy_id", "")).strip()
if not sid:
continue
score = row.get("score_total", None)
if not isinstance(score, numbers.Number):
continue
score = float(score)
annual = float(row.get("annualized_roi", 0.0) or 0.0)
dd = float(row.get("max_dd", 0.0) or 0.0)
tr = float(row.get("total_trades", 0.0) or 0.0)
x = stats.get(sid)
if x is None:
stats[sid] = {
"count": 1,
"score_sum": score,
"annual_sum": annual,
"dd_sum": dd,
"trades_sum": tr,
"score_total_latest": score,
"rating_latest": str(row.get("rating", "")).strip() or _score_grade(score)
}
else:
x["count"] += 1
x["score_sum"] += score
x["annual_sum"] += annual
x["dd_sum"] += dd
x["trades_sum"] += tr
out = {}
for sid, x in stats.items():
cnt = max(1, int(x.get("count", 1)))
avg_score = float(x.get("score_sum", 0.0)) / cnt
penalty = _sample_size_penalty_points(cnt)
confidence = _sample_size_confidence(cnt)
adjusted = max(0.0, avg_score - penalty)
out[sid] = {
"score_total": avg_score,
"rating": _score_grade(adjusted),
"score_total_adjusted": adjusted,
"score_penalty_points": penalty,
"score_confidence": confidence,
"score_backtest_count": cnt,
"score_total_latest": float(x.get("score_total_latest", 0.0)),
"rating_latest": str(x.get("rating_latest", "C")),
"score_annualized_roi_avg": float(x.get("annual_sum", 0.0)) / cnt,
"score_max_dd_avg": float(x.get("dd_sum", 0.0)) / cnt,
"score_trades_avg": float(x.get("trades_sum", 0.0)) / cnt
}
strategy_score_cache = out
def _safe_json_obj(obj):
try:
return json.loads(json.dumps(obj, ensure_ascii=False, default=str))
except Exception:
return None
def _sanitize_non_finite(obj):
if isinstance(obj, dict):
return {k: _sanitize_non_finite(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_sanitize_non_finite(v) for v in obj]
if isinstance(obj, tuple):
return [_sanitize_non_finite(v) for v in obj]
if isinstance(obj, bool):
return obj
if isinstance(obj, numbers.Integral):
return int(obj)
if isinstance(obj, numbers.Real):
v = float(obj)
return v if math.isfinite(v) else 0.0
return obj
def start_new_backtest_report(stock_code, strategy_id, request_payload=None):
global current_backtest_report, latest_backtest_result, latest_strategy_reports, current_backtest_progress, current_backtest_trades
report_id = f"{int(datetime.now().timestamp() * 1000)}-{os.urandom(2).hex()}"
current_backtest_report = {
"report_id": report_id,
"created_at": datetime.now().isoformat(timespec="seconds"),
"stock_code": stock_code,
"strategy_id": strategy_id,
"status": "running",
"error_msg": None,
"request": request_payload if isinstance(request_payload, dict) else {},
"summary": None,
"ranking": [],
"strategy_reports": {}
}
latest_backtest_result = None
latest_strategy_reports = {}
current_backtest_progress = {"progress": 0, "current_date": None}
current_backtest_trades = []
return report_id
def finalize_current_backtest_report():
global report_history, current_backtest_report
if not current_backtest_report:
return
if not current_backtest_report.get("finished_at"):
current_backtest_report["finished_at"] = datetime.now().isoformat(timespec="seconds")
report_history = [r for r in report_history if r.get("report_id") != current_backtest_report.get("report_id")]
report_history.insert(0, current_backtest_report)
persist_report_history()
_rebuild_strategy_score_cache()
def fail_current_backtest_report(msg):
global current_backtest_report
if not current_backtest_report:
return
current_backtest_report["status"] = "failed"
current_backtest_report["error_msg"] = str(msg)
current_backtest_report["finished_at"] = datetime.now().isoformat(timespec="seconds")
finalize_current_backtest_report()
def cancel_current_backtest_report(msg="backtest cancelled"):
global current_backtest_report
if not current_backtest_report:
return
current_backtest_report["status"] = "cancelled"
current_backtest_report["error_msg"] = str(msg)
current_backtest_report["finished_at"] = datetime.now().isoformat(timespec="seconds")
finalize_current_backtest_report()
# --- WebSocket Manager ---
async def connect(websocket: WebSocket):
await websocket.accept()
active_connections.append(websocket)
def disconnect(websocket: WebSocket):
active_connections.remove(websocket)
async def broadcast(message: dict):
# print(f"Broadcasting: {message}")
for connection in active_connections:
try:
await connection.send_json(message)
except Exception:
pass
# --- Event Callback for LiveCabinet ---
async def cabinet_event_handler(event_type, data):
"""
Bridge between LiveCabinet and WebSocket clients.
"""
payload = {
"type": event_type,
"data": data,
"timestamp": asyncio.get_event_loop().time()
}
await broadcast(payload)
# --- Models for API ---
class BacktestRequest(BaseModel):
stock_code: str = "600036.SH"
strategy_id: str = "all"
strategy_ids: Optional[list[str]] = None
strategy_mode: Optional[str] = None
start: Optional[str] = None
end: Optional[str] = None
capital: Optional[float] = None
class LiveRequest(BaseModel):
stock_code: Optional[str] = None
stock_codes: Optional[list[str]] = None
strategy_id: Optional[str] = None
strategy_ids: Optional[list[str]] = None
stock_strategy_map: Optional[dict[str, list[str]]] = None
replace_existing: bool = True
class StrategySwitchRequest(BaseModel):
strategy_id: Optional[str] = None
strategy_ids: Optional[list[str]] = None
stock_codes: Optional[list[str]] = None
stock_strategy_map: Optional[dict[str, list[str]]] = None
class SourceSwitchRequest(BaseModel):
source: str
class LiveFundPoolResetRequest(BaseModel):
stock_code: str
initial_capital: Optional[float] = None
class WebhookRetryRequest(BaseModel):
event_ids: Optional[list[str]] = None
limit: int = 20
class WebhookDeleteRequest(BaseModel):
event_ids: Optional[list[str]] = None
class ConfigUpdateRequest(BaseModel):
config: dict
class StrategyToggleRequest(BaseModel):
strategy_id: str
enabled: bool
class StrategyAnalyzeRequest(BaseModel):
template_text: str
strategy_name: Optional[str] = None
code_template: Optional[str] = None
kline_type: Optional[str] = None
class StrategyMarketAnalyzeRequest(BaseModel):
market_state: dict
strategy_name: Optional[str] = None
code_template: Optional[str] = None
kline_type: Optional[str] = None
class StrategyAddRequest(BaseModel):
strategy_id: str
strategy_name: str
class_name: Optional[str] = None
code: str
template_text: Optional[str] = None
analysis_text: Optional[str] = None
strategy_intent: Optional[dict] = None
source: Optional[str] = None
kline_type: Optional[str] = None
raw_requirement_title: Optional[str] = None
raw_requirement: Optional[str] = None
depends_on: Optional[list[str]] = None
protect_level: Optional[str] = None
immutable: Optional[bool] = None
class StrategyUpdateRequest(BaseModel):
strategy_id: str
strategy_name: Optional[str] = None
class_name: Optional[str] = None
code: Optional[str] = None
analysis_text: Optional[str] = None
source: Optional[str] = None
kline_type: Optional[str] = None
raw_requirement_title: Optional[str] = None
raw_requirement: Optional[str] = None
depends_on: Optional[list[str]] = None
protect_level: Optional[str] = None
immutable: Optional[bool] = None
class StrategyDeleteRequest(BaseModel):
strategy_id: str
force: bool = False
class ReportDeleteRequest(BaseModel):
report_id: str
class HistorySyncRunRequest(BaseModel):
codes: Optional[list[str]] = None
tables: Optional[list[str]] = None
start_time: Optional[str] = None
end_time: Optional[str] = None
time_mode: Optional[str] = None
custom_start_time: Optional[str] = None
custom_end_time: Optional[str] = None
session_only: Optional[bool] = None
intraday_mode: Optional[bool] = None
lookback_days: int = 10
max_codes: int = 10000
batch_size: int = 500
dry_run: bool = False
on_duplicate: str = "ignore"
write_mode: Optional[str] = None