Repository navigation
Expand file tree
/
Copy pathdata_manager.py
More file actions
2559 lines (2210 loc) · 106 KB
/
Copy pathdata_manager.py
File metadata and controls
2559 lines (2210 loc) · 106 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 os
import pandas as pd
import re
import sqlite3
import time
from collections import defaultdict, deque
from datetime import datetime, timedelta
import threading
import xtquant.xtdata as xt
import Methods
import config
from logger import get_logger, suppress_stdout_stderr
# from realtime_data_manager import get_realtime_data_manager
# 获取logger
logger = get_logger("data_manager")
def _create_xtdata():
"""
工厂函数:根据 config.ENABLE_XTQUANT_MANAGER 返回行情接口对象。
Returns:
XtDataAdapter: ENABLE_XTQUANT_MANAGER=True 时,返回 HTTP 适配器
xtquant.xtdata module: ENABLE_XTQUANT_MANAGER=False 时,返回原始模块
"""
if getattr(config, "ENABLE_XTQUANT_MANAGER", False):
from xtquant_manager.client import XtQuantClient, ClientConfig, XtDataAdapter
account_config = config.get_account_config()
client = XtQuantClient(
config=ClientConfig(
base_url=getattr(config, "XTQUANT_MANAGER_URL", "http://127.0.0.1:8888"),
account_id=account_config.get("account_id", ""),
api_token=getattr(config, "XTQUANT_MANAGER_TOKEN", ""),
)
)
return XtDataAdapter(client)
else:
import xtquant.xtdata as _xtdata
return _xtdata
class MarketDataHealthTracker:
"""内存版行情源健康评分器,不落库,重启即清空。"""
def __init__(self):
self._events = defaultdict(
lambda: deque(maxlen=getattr(config, "MARKET_HEALTH_MAX_EVENTS", 100))
)
self._lock = threading.Lock()
def record(self, source, purpose, stock_code, ok, latency_ms=0, reason="", data_quality_ok=True):
if not getattr(config, "MARKET_HEALTH_ENABLED", True):
return
key = (
str(source or "unknown"),
str(purpose or "unknown"),
self._normalize_stock_code(stock_code),
)
event = {
"ts": time.time(),
"ok": bool(ok),
"latency_ms": max(0, int(latency_ms or 0)),
"reason": str(reason or ("success" if ok else "unknown")),
"data_quality_ok": bool(data_quality_ok),
}
with self._lock:
self._events[key].append(event)
def get_score(self, source=None, purpose=None, stock_code=None):
events = self._collect_events(source, purpose, stock_code)
return self._score_events(events)
def snapshot(self):
generated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with self._lock:
keys = list(self._events.keys())
overall = self.get_score()
sources = {}
stocks = {}
for source in sorted({k[0] for k in keys}):
sources[source] = self.get_score(source=source)
for stock_code in sorted({k[2] for k in keys}):
stock_entry = stocks.setdefault(stock_code, {})
for purpose in sorted({k[1] for k in keys if k[2] == stock_code}):
purpose_entry = self.get_score(purpose=purpose, stock_code=stock_code)
purpose_entry["sources"] = {}
for source in sorted({k[0] for k in keys if k[1] == purpose and k[2] == stock_code}):
purpose_entry["sources"][source] = self.get_score(
source=source,
purpose=purpose,
stock_code=stock_code,
)
stock_entry[purpose] = purpose_entry
return {
"enabled": getattr(config, "MARKET_HEALTH_ENABLED", True),
"observe_only": getattr(config, "MARKET_HEALTH_OBSERVE_ONLY", True),
"generated_at": generated_at,
"overall": overall,
"sources": sources,
"stocks": stocks,
"trading": {
"min_score": getattr(config, "MARKET_HEALTH_TRADING_MIN_SCORE", 70),
"allow_mootdx": getattr(config, "MARKET_HEALTH_ALLOW_MOOTDX_FOR_TRADING", False),
},
}
def format_summary(self):
snapshot = self.snapshot()
sources = snapshot.get("sources", {})
if not sources:
return "行情健康: 暂无样本"
parts = []
bad_stocks = []
unstable_score = getattr(config, "MARKET_HEALTH_UNSTABLE_SCORE", 40)
for source, info in sorted(sources.items()):
score = info.get("score")
if source in ("Mootdx", "Tushare") and score is None:
parts.append(f"{source}=idle")
continue
score_text = "unknown" if score is None else str(score)
parts.append(f"{source}={info.get('status', 'unknown')}({score_text})")
for stock_code, purposes in snapshot.get("stocks", {}).items():
realtime = purposes.get("realtime", {})
score = realtime.get("score")
if score is not None and score < unstable_score:
bad_stocks.append(stock_code)
if bad_stocks:
parts.append("异常股票:" + ",".join(bad_stocks[:5]))
return "行情健康: " + " | ".join(parts)
def _collect_events(self, source=None, purpose=None, stock_code=None):
stock_code = self._normalize_stock_code(stock_code) if stock_code else None
now = time.time()
window_seconds = getattr(config, "MARKET_HEALTH_WINDOW_SECONDS", 300)
events = []
with self._lock:
for key, values in self._events.items():
key_source, key_purpose, key_stock = key
if source and key_source != source:
continue
if purpose and key_purpose != purpose:
continue
if stock_code and key_stock != stock_code:
continue
events.extend(event for event in values if now - event["ts"] <= window_seconds)
events.sort(key=lambda event: event["ts"])
return events
def _score_events(self, events):
if not events:
return {
"score": None,
"status": "unknown",
"event_count": 0,
"success_count": 0,
"failure_count": 0,
"consecutive_failures": 0,
"last_success_at": None,
"last_event_at": None,
"avg_latency_ms": None,
"last_reason": None,
}
total = len(events)
success_events = [event for event in events if event["ok"] and event["data_quality_ok"]]
success_count = len(success_events)
failure_count = total - success_count
if success_events:
avg_latency = sum(event["latency_ms"] for event in success_events) / success_count
last_success_ts = success_events[-1]["ts"]
last_success_at = datetime.fromtimestamp(last_success_ts).strftime("%Y-%m-%d %H:%M:%S")
else:
avg_latency = None
last_success_at = None
consecutive_failures = 0
for event in reversed(events):
if event["ok"] and event["data_quality_ok"]:
break
consecutive_failures += 1
base_result = {
"event_count": total,
"success_count": success_count,
"failure_count": failure_count,
"consecutive_failures": consecutive_failures,
"last_success_at": last_success_at,
"last_event_at": datetime.fromtimestamp(events[-1]["ts"]).strftime("%Y-%m-%d %H:%M:%S"),
"avg_latency_ms": None if avg_latency is None else int(round(avg_latency)),
"last_reason": events[-1]["reason"],
}
min_events = max(1, int(getattr(config, "MARKET_HEALTH_MIN_EVENTS", 3) or 1))
if total < min_events:
return {
"score": None,
"status": "unknown",
**base_result,
}
success_rate_score = 100 * success_count / total
quality_score = 100 * sum(1 for event in events if event["data_quality_ok"]) / total
if success_events:
latency_score = max(0, 100 - (avg_latency / 30))
age = max(0, time.time() - success_events[-1]["ts"])
window_seconds = max(1, getattr(config, "MARKET_HEALTH_WINDOW_SECONDS", 300))
freshness_score = max(0, 100 - (age / window_seconds * 100))
else:
latency_score = 0
freshness_score = 0
consecutive_score = max(0, 100 - consecutive_failures * 25)
score = (
success_rate_score * 0.45
+ latency_score * 0.20
+ freshness_score * 0.20
+ quality_score * 0.10
+ consecutive_score * 0.05
)
score = int(round(max(0, min(100, score))))
return {
"score": score,
"status": self._status_for_score(score),
**base_result,
}
def _status_for_score(self, score):
if score is None:
return "unknown"
if score >= getattr(config, "MARKET_HEALTH_HEALTHY_SCORE", 80):
return "healthy"
if score >= getattr(config, "MARKET_HEALTH_DEGRADED_SCORE", 60):
return "degraded"
if score >= getattr(config, "MARKET_HEALTH_UNSTABLE_SCORE", 40):
return "unstable"
return "down"
def _normalize_stock_code(self, stock_code):
if not stock_code:
return "unknown"
return str(stock_code).upper()
class DataManager:
"""数据管理类,处理历史行情数据的获取与存储"""
def __init__(self):
"""初始化数据管理器"""
# 创建数据目录
if not os.path.exists(config.DATA_DIR):
os.makedirs(config.DATA_DIR)
# 连接数据库
self.conn = self._connect_db()
# 数据库操作锁,防止多线程并发访问同一连接导致事务冲突
self._db_lock = threading.Lock()
# 创建表结构
self._create_tables()
# 已订阅的股票代码列表
self.subscribed_stocks = []
# 股票名称缓存(在 __init__ 中预先创建,避免运行时懒加载触发 baostock)
self.stock_names_cache = {}
# baostock 连续失败冷却机制(防止网络异常时反复阻塞)
self._bs_consecutive_failures = 0
self._bs_cooldown_until = 0.0 # 冷却截止时间戳
# Tushare 客户端惰性初始化与冷却机制(与 baostock 机制对称)
self._tushare_pro = None
self._tushare_token_attempted = False
self._ts_consecutive_failures = 0
self._ts_cooldown_until = 0.0 # 冷却截止时间戳
# 行情源健康评分(仅内存,不持久化)
self.market_health = MarketDataHealthTracker()
# 历史数据更新节流与告警降噪状态
self._history_update_attempts = {}
self._history_invalid_date_warnings = {}
self._history_no_data_warnings = {}
# xtdata断连自动重连控制
self._xtdata_reconnect_lock = threading.Lock()
self._xtdata_last_reconnect_time = 0.0
self._xtdata_reconnect_errors = 0
self._xtdata_reconnect_threshold = getattr(config, "XTQUANT_DATA_RECONNECT_ON_ERRORS", 3)
self._xtdata_reconnect_interval = getattr(config, "XTQUANT_DATA_RECONNECT_INTERVAL", 60)
# # 初始化行情接口
self._init_xtquant()
# self.realtime_manager = get_realtime_data_manager()
# 数据更新线程
self.update_thread = None
self.stop_flag = False
def _init_xtquant(self):
"""初始化行情接口(根据 ENABLE_XTQUANT_MANAGER 选择本地或 HTTP 适配器)"""
try:
self.xt = _create_xtdata()
if self.xt.connect():
logger.info("行情服务连接成功")
else:
logger.error("行情服务连接失败")
self.xt = None
return
# 验证连接状态
self._verify_connection()
# 订阅股票池,确保交易时段 get_full_tick 返回实时价格
self._subscribe_stocks_to_xtdata(config.STOCK_POOL)
except Exception as e:
logger.error(f"初始化行情接口出错: {str
10BC8
(e)}")
self.xt = None
def reinit_xtquant(self):
"""重新初始化行情接口。
用于 ENABLE_XTQUANT_MANAGER=True 时的延迟重连:
web_server.py 模块加载时 XtQuantManager HTTP 服务尚未启动,导致首次连接失败。
main.py 在 HTTP 服务启动后调用此方法补充初始化。
"""
if self.xt is not None:
return # 已成功初始化,无需重连
logger.info("行情接口重新初始化(XtQuantManager 服务已就绪)")
self._init_xtquant()
def _subscribe_stocks_to_xtdata(self, stock_list):
"""订阅股票池到 xtdata,保证交易时段 get_full_tick 返回实时推送价格。
subscribe_quote(count=0) 表示只订阅实时推送,不拉取历史数据。
注册 _on_xtdata_tick 回调,xtdata 推送的实时 tick 直接写入 _tick_cache,
供 get_latest_data 在盘中优先读取(避免每轮轮询 get_full_tick 的线程池开销)。
"""
if not self.xt or not stock_list:
return
ok, fail = 0, 0
for stock in stock_list:
code = self._adjust_stock(stock)
try:
self.xt.subscribe_quote(
code,
period='tick',
start_time='',
end_time='',
count=0,
callback=self._on_xtdata_tick,
)
if code not in self.subscribed_stocks:
self.subscribed_stocks.append(code)
ok += 1
except Exception as e:
logger.warning(f"xtdata subscribe_quote 失败: {code} - {e}")
fail += 1
logger.info(f"xtdata 订阅股票池完成: 成功 {ok} 只,失败 {fail} 只,共 {ok+fail} 只")
def _on_xtdata_tick(self, data):
"""xtdata tick 订阅回调:把 xtdata 推送的实时行情写入内存缓存。
xtdata 在交易时段持续推送,盘中 get_latest_data 优先从此缓存读取,
避免每轮轮询 get_full_tick 的线程池开销;缓存不可用时自动降级到原有轮询路径。
"""
if not data or not isinstance(data, dict):
return
if not getattr(self, '_tick_cache', None):
self._tick_cache = {}
for stock_code, tick in data.items():
if tick and isinstance(tick, dict):
self._tick_cache[stock_code] = tick
def _get_tick_from_cache(self, stock_code):
"""从 xtdata 推送缓存获取 tick 数据。
缓存命中且 lastPrice > 0(有效价格)时直接返回,记录健康评分并重置 xtdata 失败计数。
缓存命中但 lastPrice = 0 时清掉脏缓存让上层降级。
缓存未命中返回 None。
"""
cache = getattr(self, '_tick_cache', {}) or {}
tick = cache.get(stock_code)
if not tick or not isinstance(tick, dict):
return None
if tick.get('lastPrice', 0) <= 0:
cache.pop(stock_code, None)
return None
self._record_market_health("xtdata", "realtime", stock_code, True, 0, reason="tick_cache")
self._reset_xtdata_failure()
return self._decorate_quote(tick, "xtdata", "realtime", stock_code, 0)
def ensure_subscribed(self, stock_code):
"""确保股票已订阅到 xtdata 实时推送。
盘中新持仓加入时调用,保证下一个心跳就能拿到实时价格。
已订阅则直接返回;未订阅则立即订阅并追踪到 subscribed_stocks。
"""
if not self.xt:
return
code = self._adjust_stock(stock_code)
if code in self.subscribed_stocks:
return # 已订阅,无需重复操作
try:
self.xt.subscribe_quote(
code,
period='tick',
start_time='',
end_time='',
count=0,
callback=self._on_xtdata_tick,
)
self.subscribed_stocks.append(code)
logger.info(f"xtdata 动态订阅新股票: {code}")
except Exception as e:
logger.warning(f"xtdata 动态订阅失败: {code} - {e}")
def prune_untracked_stocks(self, active_stock_codes):
"""移除已不在运行态股票池中的订阅和 tick 缓存记录。"""
active_codes = {
self._adjust_stock(code)
for code in (active_stock_codes or [])
if code is not None and str(code).strip()
}
before = list(getattr(self, 'subscribed_stocks', []) or [])
kept = [code for code in before if self._adjust_stock(code) in active_codes]
removed = [code for code in before if self._adjust_stock(code) not in active_codes]
if removed:
self.subscribed_stocks = kept
cache = getattr(self, '_tick_cache', None)
if isinstance(cache, dict):
for code in removed:
cache.pop(code, None)
cache.pop(str(code).split('.')[0], None)
logger.info(f"已清理运行态股票池外的行情订阅缓存: {removed}")
return removed
def _verify_connection(self):
"""验证连接状态"""
try:
# 使用一个简单的测试来验证连接
test_codes = ['000001.SZ'] # 测试股票
test_data = self.xt.get_full_tick(test_codes)
if test_data:
logger.debug("xtquant连接状态验证成功")
return True
else:
logger.warning("xtquant连接状态验证失败")
return False
except Exception as e:
logger.warning(f"xtquant连接验证出错: {str(e)}")
return False
def _record_xtdata_failure(self, reason=""):
"""记录xtdata失败并按阈值触发重连"""
self._xtdata_reconnect_errors += 1
if self._xtdata_reconnect_errors >= self._xtdata_reconnect_threshold:
if self._attempt_xtdata_reconnect(reason):
self._xtdata_reconnect_errors = 0
def _reset_xtdata_failure(self):
"""重置xtdata失败计数"""
self._xtdata_reconnect_errors = 0
def _attempt_xtdata_reconnect(self, reason=""):
"""尝试重连xtdata并恢复订阅"""
if not self.xt:
return False
with self._xtdata_reconnect_lock:
now = time.time()
if now - self._xtdata_last_reconnect_time < self._xtdata_reconnect_interval:
return False
self._xtdata_last_reconnect_time = now
try:
reconnect_ok = False
if hasattr(self.xt, "reconnect"):
reconnect_ok = self.xt.reconnect()
elif hasattr(self.xt, "connect"):
reconnect_ok = self.xt.connect()
if reconnect_ok:
# 复订阅:优先使用已订阅列表,否则用股票池
stocks = list(dict.fromkeys(self.subscribed_stocks)) if self.subscribed_stocks else list(config.STOCK_POOL)
if stocks:
self._subscribe_stocks_to_xtdata(stocks)
return True
return False
except Exception as e:
logger.warning(f"xtdata重连失败: {e}")
return False
def _get_market_health(self):
if not hasattr(self, "market_health") or self.market_health is None:
self.market_health = MarketDataHealthTracker()
return self.market_health
def _record_market_health(self, source, purpose, stock_code, ok, latency_ms=0,
reason="", data_quality_ok=True):
self._get_market_health().record(
source=source,
purpose=purpose,
stock_code=stock_code,
ok=ok,
latency_ms=latency_ms,
reason=reason,
data_quality_ok=data_quality_ok,
)
def get_market_health_snapshot(self):
return self._get_market_health().snapshot()
def format_market_health_summary(self):
return self._get_market_health().format_summary()
def is_quote_tradable(self, stock_code, quote):
if not getattr(config, "MARKET_HEALTH_ENABLED", True):
return True
if getattr(config, "MARKET_HEALTH_OBSERVE_ONLY", True):
return True
if not quote:
return False
source = quote.get("_source")
if source == "Mootdx" and not getattr(config, "MARKET_HEALTH_ALLOW_MOOTDX_FOR_TRADING", False):
return False
score = quote.get("_health_score")
if score is None:
health = self._get_market_health().get_score(
source=source,
purpose=quote.get("_purpose", "realtime"),
stock_code=stock_code,
)
score = health.get("score")
if score is None:
return False
return score >= getattr(config, "MARKET_HEALTH_TRADING_MIN_SCORE", 70)
def _decorate_quote(self, quote, source, purpose, stock_code, latency_ms=0):
if not isinstance(quote, dict):
return quote
decorated = dict(quote)
decorated["_source"] = source
decorated["_purpose"] = purpose
decorated["_latency_ms"] = int(max(0, latency_ms or 0))
decorated["_health_score"] = self._get_market_health().get_score(
source=source,
purpose=purpose,
stock_code=stock_code,
).get("score")
return decorated
def _connect_db(self):
"""连接SQLite数据库"""
try:
# ⭐ 超时优化:添加30秒超时和WAL模式
conn = sqlite3.connect(
config.DB_PATH,
timeout=30.0, # 30秒超时(默认5秒)
check_same_thread=False
)
# 启用WAL模式,允许读写并发(减少锁冲突)
conn.execute('PRAGMA journal_mode=WAL')
logger.info(f"已连接数据库: {config.DB_PATH}")
return conn
except Exception as e:
logger.error(f"连接数据库失败: {str(e)}")
raise
def _create_tables(self):
"""创建数据表结构"""
cursor = self.conn.cursor()
# 创建股票历史数据表
cursor.execute('''
CREATE TABLE IF NOT EXISTS stock_daily_data (
stock_code TEXT,
stock_name TEXT,
date TEXT,
open REAL,
high REAL,
low REAL,
close REAL,
volume REAL,
amount REAL,
PRIMARY KEY (stock_code, date)
)
''')
# 创建指标数据表
# ⚠️ 列名与通用MACD术语的映射(历史遗留,勿按字面理解):
# macd → DIF = EMA(C,12) - EMA(C,26)
# macd_signal → DEA = EMA(DIF,9)
# macd_hist → MACD柱 = (DIF - DEA) * 2
cursor.execute('''
CREATE TABLE IF NOT EXISTS stock_indicators (
stock_code TEXT,
date TEXT,
ma10 REAL,
ma20 REAL,
ma30 REAL,
ma60 REAL,
macd REAL,
macd_signal REAL,
macd_hist REAL,
PRIMARY KEY (stock_code, date)
)
''')
# 创建交易记录表
cursor.execute('''
CREATE TABLE IF NOT EXISTS trade_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stock_code TEXT,
stock_name TEXT,
trade_time TIMESTAMP,
trade_type TEXT, -- BUY, SELL
price REAL,
volume INTEGER,
amount REAL,
trade_id TEXT,
commission REAL,
strategy TEXT
)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_trade_records_identity
ON trade_records(trade_id, stock_code, trade_type, trade_time, price, volume, amount)
''')
# 创建持仓表
cursor.execute('''
CREATE TABLE IF NOT EXISTS positions (
stock_code TEXT PRIMARY KEY,
stock_name TEXT,
volume INTEGER,
available REAL,
cost_price REAL,
base_cost_price REAL,
current_price REAL,
market_value REAL,
profit_ratio REAL,
last_update TIMESTAMP,
open_date TIMESTAMP,
profit_triggered BOOLEAN DEFAULT FALSE,
highest_price REAL,
stop_loss_price REAL,
profit_breakout_triggered BOOLEAN DEFAULT FALSE,
breakout_highest_price REAL,
stop_profit_enabled INTEGER DEFAULT 1
)
''')
# 创建网格交易表
cursor.execute('''
CREATE TABLE IF NOT EXISTS grid_trades (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stock_code TEXT,
grid_level INTEGER,
buy_price REAL,
sell_price REAL,
volume INTEGER,
status TEXT, -- PENDING, ACTIVE, COMPLETED
create_time TIMESTAMP,
update_time TIMESTAMP
)
''')
# 盘前同步调度持久化(premarket_sync.PreMarketSyncScheduler 读写)
cursor.execute('''
CREATE TABLE IF NOT EXISTS premarket_schedule (
id INTEGER PRIMARY KEY CHECK (id = 1),
next_sync_time TIMESTAMP NOT NULL,
last_sync_time TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 盘前同步历史(premarket_sync.record_sync_history 写入)
cursor.execute('''
CREATE TABLE IF NOT EXISTS premarket_sync_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sync_time TIMESTAMP NOT NULL,
configs_synced INTEGER DEFAULT 0,
switches_synced INTEGER DEFAULT 0,
xtdata_reconnected BOOLEAN DEFAULT 0,
xttrader_reconnected BOOLEAN DEFAULT 0,
connection_status TEXT,
positions_synced BOOLEAN DEFAULT 0,
errors TEXT,
execution_time_ms INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
self.conn.commit()
logger.info("数据表结构已创建")
# 兼容老 DB:缺失列幂等补齐(CREATE TABLE IF NOT EXISTS 不会改已有表的 schema)
self._migrate_legacy_schema()
# 启动时修复可能损坏的索引(机器强制重启后可能出现索引损坏)
self._repair_indexes_if_needed()
def _migrate_legacy_schema(self):
"""幂等地为旧版 DB 补齐缺失字段。
历史上 positions 表分批添加过 profit_breakout_triggered /
breakout_highest_price,多账号下新建 data_<account_id>/trading.db
如果首次创建时代码已有这两列就 OK;但已经在更早版本上创建过的
老 DB(包括用户在跑的两个账号 DB),仍缺这两列,会导致
position_manager 同步线程持续报 "no such column" 错误。
"""
try:
cursor = self.conn.cursor()
cursor.execute("PRAGMA table_info(positions)")
existing_cols = {row[1] for row in cursor.fetchall()}
added_cols = set()
migrations = [
('base_cost_price', 'REAL'),
('profit_breakout_triggered', 'BOOLEAN DEFAULT FALSE'),
('breakout_highest_price', 'REAL'),
('stop_profit_enabled', 'INTEGER DEFAULT 1'),
]
for col, typedef in migrations:
if col not in existing_cols:
cursor.execute(f"ALTER TABLE positions ADD COLUMN {col} {typedef}")
added_cols.add(col)
logger.info(f"DB迁移: positions 表已补齐字段 {col}")
if 'base_cost_price' in existing_cols or 'base_cost_price' in added_cols:
cursor.execute("""
UPDATE positions
SET base_cost_price=cost_price
WHERE base_cost_price IS NULL AND cost_price IS NOT NULL AND cost_price > 0
""")
self.conn.commit()
except Exception as e:
logger.error(f"DB迁移失败(不影响运行,但会持续报字段缺失): {e}")
# quick_check 报告里定位受损 B-tree 的行格式: "Tree 3 page 528 cell 49: ..."
_CORRUPT_TREE_RE = re.compile(r'^Tree (\d+) page', re.MULTILINE)
def _repair_indexes_if_needed(self):
"""检查并修复损坏的数据库结构(快速完整性检查)。
区分两类损坏,用不同手段修复:
- **索引** B-tree 损坏 → REINDEX 即可重建。
- **表** B-tree 损坏(rowid out of order)→ REINDEX 和 VACUUM 都**无效**,
必须导出数据后重建整张表。
历史缺陷:早期实现对所有损坏一律 REINDEX。当受损的是 stock_daily_data
表自身时,REINDEX 会因扫描到乱序 rowid 而误报
"UNIQUE constraint failed",随后的去重逻辑又统计不到任何真实重复
(表里本来就没有重复),于是直接 raise —— 修复从未生效,
每次启动都重复刷同一条 WARNING。
该损坏并非只是噪音:受损表上 `SELECT COUNT(*)` 与实际全表扫描
读到的行数会不一致(B-tree 乱序导致部分数据被重复遍历)。
"""
try:
result = self.conn.execute("PRAGMA quick_check").fetchone()
if not result or result[0] == 'ok':
logger.debug("数据库完整性检查通过")
return
report = result[0]
corrupt_tables = self._find_corrupt_tables(report)
first_line = report.split('\n')[0]
if corrupt_tables:
logger.warning(
f"检测到数据表结构损坏: {first_line} "
f"(受损表: {', '.join(corrupt_tables)}),执行表重建修复..."
)
for table in corrupt_tables:
self._rebuild_table(table)
else:
logger.warning(f"检测到数据库索引异常: {first_line},执行 REINDEX 修复...")
self.conn.execute("REINDEX")
self.conn.commit()
result2 = self.conn.execute("PRAGMA quick_check").fetchone()
if result2 and result2[0] == 'ok':
logger.info("数据库完整性修复成功")
else:
# 仍未修好时给出可操作的指引,而不是每次静默重复告警
logger.error(
f"数据库修复后仍有异常: "
f"{result2[0].split(chr(10))[0] if result2 else '未知'}。"
f"建议停止系统后手动执行: "
f"sqlite3 {self.db_path} \".recover\" | sqlite3 recovered.db"
)
except Exception as e:
logger.warning(f"数据库完整性检查失败(不影响运行): {str(e)}")
def _find_corrupt_tables(self, report):
"""从 quick_check 报告中解析出受损的**表**名(排除索引)。
报告用 rootpage 号标识受损 B-tree("Tree 3 page ..."),
通过 sqlite_master.rootpage 反查它属于表还是索引。
"""
tables = []
try:
cursor = self.conn.cursor()
for rootpage in set(self._CORRUPT_TREE_RE.findall(report)):
rows = cursor.execute(
"SELECT type, name FROM sqlite_master WHERE rootpage=?",
(int(rootpage),)
).fetchall()
for obj_type, name in rows:
if obj_type == 'table' and name not in tables:
tables.append(name)
except Exception as e:
logger.warning(f"解析受损对象失败: {e}")
return tables
def _rebuild_table(self, table):
"""导出数据 → 重建表 → 回填,修复表 B-tree 损坏。
受损表的全表扫描可能读出重复行(同一批数据被重复遍历),
因此回填用 INSERT OR REPLACE 依赖主键天然去重。
"""
try:
cursor = self.conn.cursor()
ddl_row = cursor.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name=?",
(table,)
).fetchone()
if not ddl_row or not ddl_row[0]:
logger.error(f"无法获取表 {table} 的 DDL,跳过重建")
return
ddl = ddl_row[0]
indexes = [
r[0] for r in cursor.execute(
"SELECT sql FROM sqlite_master WHERE type='index' "
"AND tbl_name=? AND sql IS NOT NULL", (table,)
).fetchall()
]
cols = [r[1] for r in cursor.execute(f"PRAGMA table_info({table})").fetchall()]
col_list = ', '.join(f'"{c}"' for c in cols)
rows = cursor.execute(f"SELECT {col_list} FROM {table}").fetchall()
tmp_name = f"{table}__rebuild_tmp"
cursor.execute(f"DROP TABLE IF EXISTS {tmp_name}")
cursor.execute(f"DROP TABLE {table}")
cursor.execute(ddl)
placeholders = ','.join('?' * len(cols))
cursor.executemany(
f"INSERT OR REPLACE INTO {table} ({col_list}) VALUES ({placeholders})",
rows
)
for idx_sql in indexes:
try:
cursor.execute(idx_sql)
except Exception as e:
logger.warning(f"重建索引失败({table}): {e}")
self.conn.commit()
kept = cursor.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
dropped = len(rows) - kept
msg = f"表 {table} 已重建, 保留 {kept} 行"
if dropped > 0:
msg += f"(扫描到 {len(rows)} 行,去除 {dropped} 行损坏导致的重复遍历结果)"
logger.info(msg)
except Exception as e:
self.conn.rollback()
logger.error(f"重建表 {table} 失败: {e}")
def _deduplicate_stock_daily_data(self):
"""清理 stock_daily_data 中违反 (stock_code, date) 唯一性的重复日线记录。
注意:此方法解决"真实存在的重复数据",不用于修复 B-tree 损坏。
B-tree 损坏时表本身没有重复,COUNT 只是被乱序 rowid 骗了;
该场景现在由 _rebuild_table 处理。
"""
try:
cursor = self.conn.cursor()
duplicate_count = cursor.execute("""
SELECT COALESCE(SUM(cnt - 1), 0)
FROM (
SELECT COUNT(*) AS cnt
FROM stock_daily_data
GROUP BY stock_code, date
HAVING COUNT(*) > 1
)
""").fetchone()[0] or 0
if duplicate_count <= 0:
return 0
cursor.execute("""
DELETE FROM stock_daily_data
WHERE rowid NOT IN (
SELECT MAX(rowid)
FROM stock_daily_data
GROUP BY stock_code, date
)
""")
self.conn.commit()
return int(duplicate_count)
except Exception as e:
logger.warning(f"清理 stock_daily_data 重复记录失败: {e}")
return 0
return 0
# def _init_xtquant(self):
# """初始化迅投行情接口"""
# try:
# # 根据文档,首先调用connect连接到行情服务器
# if not xt.connect():
# logger.error("行情服务连接失败")
# return
# logger.info("行情服务连接成功")
# # 根据测试结果,我们不使用subscribe_quote方法(会失败)
# # 改为验证股票代码是否可以通过get_full_tick获取数据
# valid_stocks = []
# for stock_code in config.STOCK_POOL:
# try:
# stock_code = self._adjust_stock(stock_code)
# # 尝试adjust_stock(stock_code)
# # 尝试获取Tick数据验证股票代码有效性
# tick_data = xt.get_full_tick([stock_code])
# if tick_data and stock_code in tick_data:
# valid_stocks.append(stock_code)
# logger.info(f"股票 {stock_code} 数据获取成功")
# else:
# logger.warning(f"无法获取 {stock_code} 的Tick数据")
# except Exception as e:
# logger.warning(f"获取 {stock_code} 的Tick数据失败: {str(e)}")
# self.subscribed_stocks = valid_stocks
# if self.subscribed_stocks:
# logger.info(f"成功验证 {len(self.subscribed_stocks)} 只股票可获取数据")
# else:
# logger.warning("没有有效的股票,请检查股票代码格式")
# except Exception as e:
# logger.error(f"初始化迅投行情接口出错: {str(e)}")
# # 股票代码转换
# def _select_data_type(self, stock='600031'):
# '''
# 选择数据类型
# '''
# return Methods.select_data_type(stock)
def _adjust_stock(self, stock='600031.SH'):
'''
调整代码
'''
stock = str(stock).strip()
lower_stock = stock.lower()
if lower_stock.startswith('sh.'):
return f"{stock.split('.', 1)[1].upper()}.SH"
if lower_stock.startswith('sz.'):
return f"{stock.split('.', 1)[1].upper()}.SZ"
if lower_stock.startswith('bj.'):
return f"{stock.split('.', 1)[1].upper()}.BJ"
return Methods.add_xt_suffix(stock)
def _normalize_date_arg(self, value):
"""把外部日期参数统一为 YYYY-MM-DD,便于比较和过滤。"""
if value is None:
return None
text = str(value).strip()
if not text:
return None
compact = pd.Series([text]).str.replace(r'\D', '', regex=True).iloc[0]
if len(compact) >= 8:
parsed = pd.to_datetime(compact[:8], format='%Y%m%d', errors='coerce')
else:
parsed = pd.to_datetime(text, errors='coerce')
if pd.isna(parsed):