log
2026-07-09 18469a98f3a661b8d33419be5992f2233203f19f
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
#!/usr/bin/env python3
"""
多数据源股票数据获取模块
支持:AKShare(主)、BaoStock(备)
"""
 
import logging
import os
import time
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import pandas as pd
import numpy as np
 
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
 
 
class TushareDataSource:
    """Tushare数据源"""
 
    def __init__(self, token: str):
        self.name = "Tushare"
        self.token = token
        self.pro = None
        self.is_available = False
 
    def test_connection(self) -> bool:
        try:
            import tushare as ts
            ts.set_token(self.token)
            self.pro = ts.pro_api()
 
            # 测试获取股票列表
            df = self.pro.stock_basic(exchange='', list_status='L',
                                      fields='ts_code,symbol,name,area,industry,list_date',
                                      limit=5)
 
            self.is_available = len(df) > 0
            logger.info(f"  ✓ Tushare 连接成功")
            return True
        except Exception as e:
            logger.warning(f"  ✗ Tushare 连接失败: {e}")
            return False
 
    def get_stock_list(self) -> pd.DataFrame:
        """获取股票列表"""
        try:
            df = self.pro.stock_basic(exchange='', list_status='L',
                                      fields='ts_code,symbol,name')
            df.columns = ['ts_code', 'code', 'name']
            # 只保留A股 (上海主板、深圳主板、创业板、科创板)
            df = df[df['ts_code'].str.match(r'^(600|601|603|605|688|000|001|002|003|300)\d{3}$')]
            return df
        except Exception as e:
            logger.error(f"获取Tushare股票列表失败: {e}")
            return pd.DataFrame()
 
    def fetch_stock_history(self, stock_code: str, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
        """获取历史数据"""
        try:
            df = self.pro.daily(ts_code=stock_code, start_date=start_date, end_date=end_date)
 
            if len(df) == 0:
                return None
 
            # 标准化列名
            df.columns = [col.lower() for col in df.columns]
 
            # 添加需要的列
            if 'turnover_rate' not in df.columns:
                df['turnover_rate'] = None
 
            # 转换日期格式
            df['date'] = pd.to_datetime(df['trade_date']).dt.strftime('%Y-%m-%d')
 
            # 添加 ts_code
            df['stock_code'] = df['ts_code'].apply(lambda x: x.replace('.SZ', '').replace('.SH', ''))
 
            return df
        except Exception as e:
            logger.debug(f"  Tushare获取{stock_code}失败: {e}")
            return None
 
 
class SinaDataSource:
    """新浪财经数据源"""
    
    def __init__(self):
        self.name = "Sina"
        self.is_available = False
    
    def test_connection(self) -> bool:
        try:
            import requests
            import time
            url = f"http://hq.sinajs.cn/rn={int(time.time())}&list=sz000001"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
                'Referer': 'https://finance.sina.com.cn',
                'host': 'hq.sinajs.cn'
            }
            response = requests.get(url, headers=headers, timeout=5)
            if response.status_code == 200:
                content = response.text
                if 'var hq_str_sz000001' in content:
                    self.is_available = True
                    logger.info(f"  ✓ 新浪财经连接成功")
                    return True
        except Exception as e:
            logger.warning(f"  ✗ 新浪财经连接失败: {e}")
        return False
    
    def get_stock_realtime(self, code: str) -> Dict:
        """获取实时数据"""
        try:
            import requests
            import time
            # 转换代码格式
            if code.startswith('6'):
                sina_code = f"sh{code}"
            else:
                sina_code = f"sz{code}"
            
            url = f"http://hq.sinajs.cn/rn={int(time.time())}&list={sina_code}"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
                'Referer': 'https://finance.sina.com.cn',
                'host': 'hq.sinajs.cn'
            }
            response = requests.get(url, headers=headers, timeout=5)
            if response.status_code == 200:
                content = response.text
                if f'var hq_str_{sina_code}' in content:
                    # 解析新浪财经返回的数据
                    data_str = content.split('=')[1].strip('"\n;')
                    data = data_str.split(',')
                    if len(data) > 10:
                        return {
                            'price': float(data[3]) if data[3] else 0,
                            'open': float(data[1]) if data[1] else 0,
                            'high': float(data[4]) if data[4] else 0,
                            'low': float(data[5]) if data[5] else 0,
                            'pre_close': float(data[2]) if data[2] else 0,
                            'volume': int(data[8]) if data[8] else 0,
                            'amount': float(data[9]) if data[9] else 0
                        }
        except Exception as e:
            logger.warning(f"  新浪财经获取{code}失败: {e}")
        return {}
 
 
class TencentDataSource:
    """腾讯财经数据源"""
    
    def __init__(self):
        self.name = "Tencent"
        self.is_available = False
    
    def test_connection(self) -> bool:
        try:
            import requests
            url = "http://qt.gtimg.cn/q=sz000001"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                content = response.text
                if 'v_sz000001' in content:
                    self.is_available = True
                    logger.info(f"  ✓ 腾讯财经连接成功")
                    return True
        except Exception as e:
            logger.warning(f"  ✗ 腾讯财经连接失败: {e}")
        return False
    
    def get_stock_realtime(self, code: str) -> Dict:
        """获取实时数据"""
        try:
            import requests
            # 转换代码格式
            if code.startswith('6'):
                tencent_code = f"sh{code}"
            else:
                tencent_code = f"sz{code}"
            
            url = f"http://qt.gtimg.cn/q={tencent_code}"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                content = response.text
                if f'v_{tencent_code}' in content:
                    # 解析腾讯财经返回的数据
                    data_str = content.split('=')[1].strip('"\n;')
                    data = data_str.split('~')
                    if len(data) > 30:
                        return {
                            'price': float(data[3]) if data[3] else 0,
                            'open': float(data[5]) if data[5] else 0,
                            'high': float(data[33]) if data[33] else 0,
                            'low': float(data[34]) if data[34] else 0,
                            'pre_close': float(data[4]) if data[4] else 0,
                            'change_pct': float(data[32]) if data[32] else 0,
                            'change_amt': float(data[31]) if data[31] else 0,
                            'volume': int(data[8]) if data[8] else 0,
                            'amount': float(data[9]) if data[9] else 0,
                            'turnover_rate': float(data[37]) if data[37] else 0,
                            'pe_ttm': float(data[39]) if data[39] else 0,
                            'pb': float(data[46]) if data[46] else 0
                        }
        except Exception as e:
            logger.warning(f"  腾讯财经获取{code}失败: {e}")
        return {}
 
 
class ZhituDataSource:
    """智兔数服数据源"""
    
    def __init__(self, token: str):
        self.name = "Zhitu"
        self.token = token
        self.is_available = False
    
    def test_connection(self) -> bool:
        try:
            import requests
            url = f"https://api.zhituapi.com/hs/real/time/600519?token={self.token}"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if 'p' in data:  # 价格字段存在
                    self.is_available = True
                    logger.info(f"  ✓ 智兔数服连接成功")
                    return True
        except Exception as e:
            logger.warning(f"  ✗ 智兔数服连接失败: {e}")
        return False
    
    def get_stock_realtime(self, code: str) -> Dict:
        """获取实时数据"""
        try:
            import requests
            url = f"https://api.zhituapi.com/hs/real/time/{code}?token={self.token}"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                data = response.json()
                return {
                    'price': float(data.get('p', 0)),
                    'open': float(data.get('o', 0)),
                    'high': float(data.get('h', 0)),
                    'low': float(data.get('l', 0)),
                    'pre_close': float(data.get('yc', 0)),
                    'change_pct': float(data.get('pc', 0)),
                    'change_amt': float(data.get('ud', 0)),
                    'volume': int(data.get('v', 0)),
                    'amount': float(data.get('cje', 0)),
                    'turnover_rate': float(data.get('tr', 0)),
                    'pe_ttm': float(data.get('pe', 0)),
                    'pb': float(data.get('pb_ratio', 0)),
                    'time': data.get('t', '')
                }
        except Exception as e:
            logger.warning(f"  智兔数服获取{code}失败: {e}")
        return {}
 
 
class EastMoneyDataSource:
    """东方财富数据源"""
    
    def __init__(self):
        self.name = "EastMoney"
        self.is_available = False
    
    def test_connection(self) -> bool:
        try:
            import requests
            url = "http://push2.eastmoney.com/api/qt/stock/get?secid=1.600519&fields=f43,f44,f45,f46,f51,f52"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if 'data' in data:
                    self.is_available = True
                    logger.info(f"  ✓ 东方财富连接成功")
                    return True
        except Exception as e:
            logger.warning(f"  ✗ 东方财富连接失败: {e}")
        return False
    
    def get_stock_realtime(self, code: str) -> Dict:
        """获取实时数据"""
        try:
            import requests
            # 转换代码格式
            if code.startswith('6'):
                secid = f"1.{code}"
            else:
                secid = f"0.{code}"
            
            url = f"http://push2.eastmoney.com/api/qt/stock/get?secid={secid}&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f20,f21,f22,f23,f24,f25,f26,f27,f28,f29,f30,f31,f32,f33,f34,f35,f36,f37,f38,f39,f40,f41,f42,f43,f44,f45,f46,f47,f48,f49,f50,f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if 'data' in data:
                    data = data['data']
                    return {
                        'price': float(data.get('f2', 0)),
                        'open': float(data.get('f17', 0)),
                        'high': float(data.get('f15', 0)),
                        'low': float(data.get('f16', 0)),
                        'pre_close': float(data.get('f18', 0)),
                        'change_pct': float(data.get('f3', 0)),
                        'change_amt': float(data.get('f4', 0)),
                        'volume': int(data.get('f5', 0)),
                        'amount': float(data.get('f6', 0)),
                        'turnover_rate': float(data.get('f8', 0)),
                        'pe_ttm': float(data.get('f9', 0)),
                        'pb': float(data.get('f23', 0)),
                        'market_cap': float(data.get('f20', 0)) / 100000000 if data.get('f20') else 0
                    }
        except Exception as e:
            logger.warning(f"  东方财富获取{code}失败: {e}")
        return {}
 
 
class MultiSourceStockFetcher:
    """多数据源股票数据获取器"""
    
    INDUSTRY_MAPPING = {
        'J66货币金融服务': '银行',
        'J67资本市场服务': '证券',
        'J68保险业': '保险',
        'K70房地产业': '房地产',
        'C26化学原料和化学制品制造业': '化工',
        'C27医药制造业': '医药',
        'C34通用设备制造业': '机械',
        'C35专用设备制造业': '机械',
        'C36汽车制造业': '汽车',
        'C39计算机、通信和其他电子设备制造业': '电子',
        'D44电力、热力生产和供应业': '电力',
        'D45燃气生产和供应业': '燃气',
        'D46水的生产和供应业': '水务',
        'B06煤炭开采和洗选业': '煤炭',
        'B07石油和天然气开采业': '石油石化',
        'B08黑色金属矿采选业': '钢铁',
        'B09有色金属矿采选业': '有色金属',
        'B11开采专业及辅助性活动': '采掘服务',
        'C13农副食品加工业': '食品',
        'C14食品制造业': '食品',
        'C15酒、饮料和精制茶制造业': '白酒',
        'C17纺织业': '纺织',
        'C18纺织服装、服饰业': '服装',
        'C19皮革、毛皮、羽毛及其制品和制鞋业': '轻工制造',
        'C20木材加工和木、竹、藤、棕、草制品业': '轻工制造',
        'C21家具制造业': '轻工制造',
        'C22造纸和纸制品业': '轻工制造',
        'C23印刷和记录媒介复制业': '轻工制造',
        'C24文教、工美、体育和娱乐用品制造业': '轻工制造',
        'C29橡胶和塑料制品业': '化工',
        'C30非金属矿物制品业': '建材',
        'C31黑色金属冶炼和压延加工业': '钢铁',
        'C32有色金属冶炼和压延加工业': '有色金属',
        'C33金属制品业': '金属',
        'C41其他制造业': '其他制造',
        'C42废弃资源综合利用业': '环保',
        'C43金属制品、机械和设备修理业': '机械',
        'F51批发业': '商业贸易',
        'F52零售业': '商业贸易',
        'G53铁路运输业': '交通运输',
        'G54道路运输业': '交通运输',
        'G55水上运输业': '交通运输',
        'G56航空运输业': '交通运输',
        'G57管道运输业': '交通运输',
        'G58多式联运和运输代理业': '交通运输',
        'G59装卸搬运和仓储业': '交通运输',
        'H61住宿业': '酒店旅游',
        'H62餐饮业': '酒店旅游',
        'I63电信、广播电视和卫星传输服务': '通信',
        'I64互联网和相关服务': '互联网',
        'I65软件和信息技术服务业': '计算机',
        'J69货币金融服务': '银行',
        'L72商务服务业': '商业服务',
        'M73研究和试验发展': '科研服务',
        'M74专业技术服务业': '专业服务',
        'N75水利管理业': '水务',
        'N76生态保护和环境治理业': '环保',
        'N77公共设施管理业': '公用事业',
        'O78居民服务业': '居民服务',
        'P80教育': '教育',
        'Q81卫生': '医疗',
        'R86广播、电视、电影和影视录音制作业': '传媒',
        'R87文化艺术业': '传媒',
        'R88体育': '体育',
        'R89娱乐业': '娱乐',
        'S90综合': '综合',
    }
    
    def __init__(self):
        self.akshare_available = self._check_akshare()
        self.baostock_available = self._check_baostock()
        self.tushare_available = False
        self.zhitu_available = False
        self.tencent_available = False
        self.sina_available = False
        self.eastmoney_available = False
        self.tushare_source = None
        self.zhitu_source = None
        self.tencent_source = None
        self.sina_source = None
        self.eastmoney_source = None
        self.bs = None
        self._stock_info_cache = {}
        self._industry_cache = {}
        self._realtime_data_cache = {}  # 实时数据缓存
        self._cache_expiry = 60  # 缓存过期时间(秒)
        self.metadata = {
            'source': 'multi_source',
            'fetch_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'sources_tested': [],
            'active_source': None
        }
        
        if self.baostock_available:
            try:
                import baostock as bs
                self.bs = bs
                lg = bs.login()
                if lg.error_code != '0':
                    logger.warning(f"BaoStock登录失败: {lg.error_msg}")
                    self.baostock_available = False
                else:
                    logger.info("✓ BaoStock登录成功")
                    self._load_stock_info()
            except Exception as e:
                logger.warning(f"BaoStock初始化失败: {e}")
                self.baostock_available = False
        
        # 初始化Tushare
        self._init_tushare()
        
        # 初始化智兔数服
        self._init_zhitu()
        
        # 初始化腾讯财经
        self._init_tencent()
        
        # 初始化新浪财经
        self._init_sina()
        
        # 初始化东方财富
        self._init_eastmoney()
        
    def _init_tushare(self):
        """初始化Tushare数据源"""
        try:
            tushare_token = os.environ.get("TUSHARE_TOKEN", "")
            if not tushare_token:
                logger.warning("TUSHARE_TOKEN 环境变量未设置,跳过Tushare数据源")
                self.tushare_available = False
                return
            self.tushare_source = TushareDataSource(tushare_token)
            self.tushare_available = self.tushare_source.test_connection()
            self.metadata['sources_tested'].append({
                'name': "Tushare",
                'available': self.tushare_available
            })
        except Exception as e:
            logger.warning(f"Tushare初始化失败: {e}")
            self.tushare_available = False
    
    def _init_zhitu(self):
        """初始化智兔数服数据源"""
        try:
            zhitu_token = os.environ.get("ZHITU_TOKEN", "")
            if not zhitu_token:
                logger.warning("ZHITU_TOKEN 环境变量未设置,跳过智兔数服数据源")
                self.zhitu_available = False
                return
            self.zhitu_source = ZhituDataSource(zhitu_token)
            self.zhitu_available = self.zhitu_source.test_connection()
            self.metadata['sources_tested'].append({
                'name': "Zhitu",
                'available': self.zhitu_available
            })
        except Exception as e:
            logger.warning(f"智兔数服初始化失败: {e}")
            self.zhitu_available = False
    
    def _init_tencent(self):
        """初始化腾讯财经数据源"""
        try:
            self.tencent_source = TencentDataSource()
            self.tencent_available = self.tencent_source.test_connection()
            self.metadata['sources_tested'].append({
                'name': "Tencent",
                'available': self.tencent_available
            })
        except Exception as e:
            logger.warning(f"腾讯财经初始化失败: {e}")
            self.tencent_available = False
    
    def _init_sina(self):
        """初始化新浪财经数据源"""
        try:
            self.sina_source = SinaDataSource()
            self.sina_available = self.sina_source.test_connection()
            self.metadata['sources_tested'].append({
                'name': "Sina",
                'available': self.sina_available
            })
        except Exception as e:
            logger.warning(f"新浪财经初始化失败: {e}")
            self.sina_available = False
    
    def _init_eastmoney(self):
        """初始化东方财富数据源"""
        try:
            self.eastmoney_source = EastMoneyDataSource()
            self.eastmoney_available = self.eastmoney_source.test_connection()
            self.metadata['sources_tested'].append({
                'name': "EastMoney",
                'available': self.eastmoney_available
            })
        except Exception as e:
            logger.warning(f"东方财富初始化失败: {e}")
            self.eastmoney_available = False
    
    def get_stock_list(self) -> pd.DataFrame:
        """获取股票列表"""
        # 尝试从Tushare获取
        if self.tushare_available and self.tushare_source:
            try:
                df = self.tushare_source.get_stock_list()
                if len(df) > 0:
                    self.metadata['active_source'] = "Tushare"
                    return df
            except Exception as e:
                logger.warning(f"从Tushare获取股票列表失败: {e}")
        
        # 尝试从AKShare获取
        if self.akshare_available:
            try:
                import akshare as ak
                df = ak.stock_info_a_code_name()
                if len(df) > 0:
                    self.metadata['active_source'] = "AKShare"
                    return df
            except Exception as e:
                logger.warning(f"从AKShare获取股票列表失败: {e}")
        
        # 从缓存获取
        if self._stock_info_cache:
            df = pd.DataFrame([{
                'code': info['code'],
                'name': info['name']
            } for code, info in self._stock_info_cache.items()])
            if len(df) > 0:
                self.metadata['active_source'] = "Cache"
                return df
        
        try:
            from code.config import DEFAULT_STOCK_NAMES
            MAJOR_STOCKS = [(code.lstrip('sh').lstrip('sz'), name) for code, name in DEFAULT_STOCK_NAMES.items()]
            logger.info("使用配置文件中的股票列表")
        except ImportError:
            MAJOR_STOCKS = [
                ('000001', '平安银行'), ('000002', '万科A'), ('000063', '中兴通讯'),
                ('000333', '美的集团'), ('000651', '格力电器'), ('000725', '京东方A'),
                ('000858', '五粮液'), ('002594', '比亚迪'), ('002415', '海康威视'),
                ('600000', '浦发银行'), ('600036', '招商银行'), ('600519', '贵州茅台'),
                ('600900', '长江电力'), ('601318', '中国平安'), ('601888', '中国中免'),
                ('601939', '建设银行'), ('603259', '药明康德')
            ]
            logger.info("使用默认股票列表")
        
        df = pd.DataFrame(MAJOR_STOCKS, columns=['code', 'name'])
        self.metadata['active_source'] = "Config"
        return df
    
    def _check_akshare(self) -> bool:
        """检查AKShare是否可用"""
        try:
            import akshare
            return True
        except ImportError:
            return False
    
    def _check_baostock(self) -> bool:
        """检查BaoStock是否可用"""
        try:
            import baostock
            return True
        except ImportError:
            return False
    
    def _load_stock_info(self):
        """加载股票基本信息和行业分类"""
        if not self.bs:
            return
        
        try:
            # 尝试最近几个交易日的数据
            dates_to_try = []
            today = datetime.now()
            for i in range(10):
                d = today - timedelta(days=i)
                if d.weekday() < 5:  # 只尝试工作日
                    dates_to_try.append(d.strftime('%Y-%m-%d'))
            
            # 获取所有股票列表
            for date in dates_to_try:
                rs = self.bs.query_all_stock(day=date)
                if rs.error_code == '0':
                    while rs.next():
                        row = rs.get_row_data()
                        # row[0] 格式: 'sh.600000' 或 'sz.000001'
                        raw_code = row[0] if len(row) > 0 else ''
                        # 提取纯代码
                        if '.' in raw_code:
                            pure_code = raw_code.split('.')[1]
                        else:
                            pure_code = raw_code
                        
                        # 只保留沪深A股
                        if raw_code.startswith('sh.6') or raw_code.startswith('sz.0') or raw_code.startswith('sz.3'):
                            self._stock_info_cache[pure_code] = {
                                'code': pure_code,
                                'name': row[2] if len(row) > 2 else '',
                                'trade_status': row[1] if len(row) > 1 else ''
                            }
                    
                    if len(self._stock_info_cache) > 0:
                        logger.info(f"✓ 加载{len(self._stock_info_cache)}只股票基本信息(日期:{date})")
                        break
            
            if len(self._stock_info_cache) == 0:
                logger.warning("无法从BaoStock获取股票列表,使用行业分类数据")
                # 从行业分类数据中提取股票代码
                rs2 = self.bs.query_stock_industry()
                if rs2.error_code == '0':
                    while rs2.next():
                        row = rs2.get_row_data()
                        raw_code = row[1] if len(row) > 1 else ''
                        if '.' in raw_code:
                            pure_code = raw_code.split('.')[1]
                        else:
                            pure_code = raw_code
                        
                        if pure_code and pure_code not in self._stock_info_cache:
                            self._stock_info_cache[pure_code] = {
                                'code': pure_code,
                                'name': row[2] if len(row) > 2 else '',
                                'trade_status': ''
                            }
                    logger.info(f"✓ 从行业分类加载{len(self._stock_info_cache)}只股票基本信息")
            
            # 获取行业分类
            rs2 = self.bs.query_stock_industry()
            if rs2.error_code == '0':
                while rs2.next():
                    row = rs2.get_row_data()
                    # row[1] 格式: 'sh.600000' 或 'sz.000001'
                    raw_code = row[1] if len(row) > 1 else ''
                    if '.' in raw_code:
                        code = raw_code.split('.')[1]
                    else:
                        code = raw_code
                    raw_industry = row[3] if len(row) > 3 else ''
                    industry = self._map_industry(raw_industry)
                    self._industry_cache[code] = {
                        'name': row[2] if len(row) > 2 else '',
                        'industry': industry,
                        'raw_industry': raw_industry
                    }
                logger.info(f"✓ 加载{len(self._industry_cache)}只股票行业分类")
        except Exception as e:
            logger.warning(f"加载股票信息失败: {e}")
    
    def _map_industry(self, raw_industry: str) -> str:
        """映射行业名称"""
        if not raw_industry:
            return '其他'
        if raw_industry in self.INDUSTRY_MAPPING:
            return self.INDUSTRY_MAPPING[raw_industry]
        for key, value in self.INDUSTRY_MAPPING.items():
            if key in raw_industry or raw_industry in key:
                return value
        return raw_industry if raw_industry else '其他'
    
    def get_index_data(self) -> Dict:
        """获取主要指数数据"""
        result = {
            'sh': {'name': '上证指数', 'price': 0, 'change_pct': 0, 'volume': 0},
            'sz': {'name': '深证成指', 'price': 0, 'change_pct': 0, 'volume': 0},
            'cyb': {'name': '创业板指', 'price': 0, 'change_pct': 0, 'volume': 0},
            'hs300': {'name': '沪深300', 'price': 0, 'change_pct': 0, 'volume': 0}
        }
        
        if self.akshare_available:
            try:
                import akshare as ak
                df = ak.stock_zh_index_spot_em()
                if df is not None and len(df) > 0:
                    index_mapping = {
                        '上证指数': 'sh',
                        '深证成指': 'sz',
                        '创业板指': 'cyb',
                        '沪深300': 'hs300'
                    }
                    for _, row in df.iterrows():
                        name = row.get('名称', '')
                        if name in index_mapping:
                            key = index_mapping[name]
                            result[key]['price'] = float(row.get('最新价', 0) or 0)
                            result[key]['change_pct'] = float(row.get('涨跌幅', 0) or 0)
                            result[key]['volume'] = float(row.get('成交量', 0) or 0)
                    if result['sh']['price'] > 0:
                        logger.info("✓ AKShare获取指数数据成功")
                        return result
            except Exception as e:
                logger.warning(f"AKShare获取指数失败: {e}")
        
        if self.baostock_available and self.bs:
            try:
                today = datetime.now().strftime('%Y-%m-%d')
                index_codes = {
                    'sh': 'sh.000001',
                    'sz': 'sz.399001',
                    'cyb': 'sz.399006',
                    'hs300': 'sh.000300'
                }
                for key, code in index_codes.items():
                    rs = self.bs.query_history_k_data_plus(
                        code, "date,code,open,high,low,close,volume",
                        start_date=(datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'),
                        end_date=today, frequency="d", adjustflag="3"
                    )
                    if rs.error_code == '0':
                        data_list = []
                        while (rs.error_code == '0') & rs.next():
                            data_list.append(rs.get_row_data())
                        if len(data_list) >= 1:
                            latest = data_list[-1]
                            prev = data_list[-2] if len(data_list) > 1 else data_list[-1]
                            close = float(latest[5]) if latest[5] else 0
                            prev_close = float(prev[5]) if prev[5] else 0
                            result[key]['price'] = close
                            if prev_close > 0:
                                result[key]['change_pct'] = round((close - prev_close) / prev_close * 100, 2)
                            result[key]['volume'] = float(latest[6]) if latest[6] else 0
                if result['sh']['price'] > 0:
                    logger.info("✓ BaoStock获取指数数据成功")
                    return result
            except Exception as e:
                logger.warning(f"BaoStock获取指数失败: {e}")
        
        logger.warning("所有数据源获取失败,使用参考数据")
        result = {
            'sh': {'name': '上证指数', 'price': 4182.59, 'change_pct': 0.47, 'volume': 0},
            'sz': {'name': '深证成指', 'price': 14465.79, 'change_pct': -0.20, 'volume': 0},
            'cyb': {'name': '创业板指', 'price': 3294.16, 'change_pct': -0.49, 'volume': 0},
            'hs300': {'name': '沪深300', 'price': 3950.23, 'change_pct': 0.15, 'volume': 0}
        }
        return result
    
    def get_stock_realtime(self, code: str) -> Dict:
        """获取个股实时数据"""
        result = {
            'code': code,
            'name': '',
            'price': 0,
            'change_pct': 0,
            'change_amt': 0,
            'open': 0,
            'high': 0,
            'low': 0,
            'pre_close': 0,
            'volume': 0,
            'amount': 0,
            'turnover_rate': 0,
            'pe_ttm': None,
            'pb': None,
            'roe': None,
            'market_cap': None,
            'industry': '其他'
        }
        
        pure_code = code.replace('sh', '').replace('sz', '')
        
        # 检查缓存
        cache_key = f"realtime_{pure_code}"
        current_time = time.time()
        if cache_key in self._realtime_data_cache:
            cached_data = self._realtime_data_cache[cache_key]
            if current_time - cached_data['timestamp'] < self._cache_expiry:
                logger.info(f"✓ 从缓存获取{pure_code}数据")
                cached_result = cached_data['data']
                # 从缓存获取名称和行业
                if pure_code in self._stock_info_cache:
                    cached_result['name'] = self._stock_info_cache[pure_code].get('name', '')
                if pure_code in self._industry_cache:
                    cached_result['industry'] = self._industry_cache[pure_code].get('industry', '其他')
                    if not cached_result['name']:
                        cached_result['name'] = self._industry_cache[pure_code].get('name', '')
                return cached_result
        
        # 从缓存获取名称和行业
        if pure_code in self._stock_info_cache:
            result['name'] = self._stock_info_cache[pure_code].get('name', '')
        if pure_code in self._industry_cache:
            result['industry'] = self._industry_cache[pure_code].get('industry', '其他')
            if not result['name']:
                result['name'] = self._industry_cache[pure_code].get('name', '')
        
        # 尝试智兔数服
        if self.zhitu_available and self.zhitu_source:
            try:
                zhitu_data = self.zhitu_source.get_stock_realtime(pure_code)
                if zhitu_data.get('price', 0) > 0:
                    result['price'] = zhitu_data['price']
                    result['open'] = zhitu_data['open']
                    result['high'] = zhitu_data['high']
                    result['low'] = zhitu_data['low']
                    result['pre_close'] = zhitu_data['pre_close']
                    result['change_pct'] = zhitu_data['change_pct']
                    result['change_amt'] = zhitu_data['change_amt']
                    result['volume'] = zhitu_data['volume']
                    result['amount'] = zhitu_data['amount']
                    result['turnover_rate'] = zhitu_data['turnover_rate']
                    result['pe_ttm'] = zhitu_data['pe_ttm']
                    result['pb'] = zhitu_data['pb']
                    logger.info(f"✓ 智兔数服获取{pure_code}成功: {result['price']}元")
                    # 缓存数据
                    self._realtime_data_cache[cache_key] = {
                        'timestamp': current_time,
                        'data': result.copy()
                    }
                    return result
            except Exception as e:
                logger.warning(f"智兔数服获取{code}失败: {e}")
        
        # 尝试腾讯财经
        if self.tencent_available and self.tencent_source:
            try:
                tencent_data = self.tencent_source.get_stock_realtime(pure_code)
                if tencent_data.get('price', 0) > 0:
                    result['price'] = tencent_data['price']
                    result['open'] = tencent_data['open']
                    result['high'] = tencent_data['high']
                    result['low'] = tencent_data['low']
                    result['pre_close'] = tencent_data['pre_close']
                    result['change_pct'] = tencent_data['change_pct']
                    result['change_amt'] = tencent_data['change_amt']
                    result['volume'] = tencent_data['volume']
                    result['amount'] = tencent_data['amount']
                    result['turnover_rate'] = tencent_data['turnover_rate']
                    result['pe_ttm'] = tencent_data['pe_ttm']
                    result['pb'] = tencent_data['pb']
                    logger.info(f"✓ 腾讯财经获取{pure_code}成功: {result['price']}元")
                    # 缓存数据
                    self._realtime_data_cache[cache_key] = {
                        'timestamp': current_time,
                        'data': result.copy()
                    }
                    return result
            except Exception as e:
                logger.warning(f"腾讯财经获取{code}失败: {e}")
        
        # 尝试新浪财经
        if self.sina_available and self.sina_source:
            try:
                sina_data = self.sina_source.get_stock_realtime(pure_code)
                if sina_data.get('price', 0) > 0:
                    result['price'] = sina_data['price']
                    result['open'] = sina_data['open']
                    result['high'] = sina_data['high']
                    result['low'] = sina_data['low']
                    result['pre_close'] = sina_data['pre_close']
                    result['volume'] = sina_data['volume']
                    result['amount'] = sina_data['amount']
                    # 计算涨跌幅和涨跌额
                    if result['pre_close'] > 0:
                        result['change_amt'] = round(result['price'] - result['pre_close'], 2)
                        result['change_pct'] = round((result['price'] - result['pre_close']) / result['pre_close'] * 100, 2)
                    logger.info(f"✓ 新浪财经获取{pure_code}成功: {result['price']}元")
                    # 缓存数据
                    self._realtime_data_cache[cache_key] = {
                        'timestamp': current_time,
                        'data': result.copy()
                    }
                    return result
            except Exception as e:
                logger.warning(f"新浪财经获取{code}失败: {e}")
        
        # 尝试东方财富
        if self.eastmoney_available and self.eastmoney_source:
            try:
                eastmoney_data = self.eastmoney_source.get_stock_realtime(pure_code)
                if eastmoney_data.get('price', 0) > 0:
                    result['price'] = eastmoney_data['price']
                    result['open'] = eastmoney_data['open']
                    result['high'] = eastmoney_data['high']
                    result['low'] = eastmoney_data['low']
                    result['pre_close'] = eastmoney_data['pre_close']
                    result['change_pct'] = eastmoney_data['change_pct']
                    result['change_amt'] = eastmoney_data['change_amt']
                    result['volume'] = eastmoney_data['volume']
                    result['amount'] = eastmoney_data['amount']
                    result['turnover_rate'] = eastmoney_data['turnover_rate']
                    result['pe_ttm'] = eastmoney_data['pe_ttm']
                    result['pb'] = eastmoney_data['pb']
                    result['market_cap'] = eastmoney_data['market_cap']
                    logger.info(f"✓ 东方财富获取{pure_code}成功: {result['price']}元")
                    # 缓存数据
                    self._realtime_data_cache[cache_key] = {
                        'timestamp': current_time,
                        'data': result.copy()
                    }
                    return result
            except Exception as e:
                logger.warning(f"东方财富获取{code}失败: {e}")
        
        # 尝试AKShare
        if self.akshare_available:
            try:
                import akshare as ak
                df = ak.stock_zh_a_spot_em()
                if df is not None and len(df) > 0:
                    stock_row = df[df['代码'] == pure_code]
                    if len(stock_row) > 0:
                        row = stock_row.iloc[0]
                        result['name'] = str(row.get('名称', result['name']))
                        result['price'] = float(row.get('最新价', 0) or 0)
                        result['change_pct'] = float(row.get('涨跌幅', 0) or 0)
                        result['change_amt'] = float(row.get('涨跌额', 0) or 0)
                        result['open'] = float(row.get('今开', 0) or 0)
                        result['high'] = float(row.get('最高', 0) or 0)
                        result['low'] = float(row.get('最低', 0) or 0)
                        result['pre_close'] = float(row.get('昨收', 0) or 0)
                        result['volume'] = float(row.get('成交量', 0) or 0)
                        result['amount'] = float(row.get('成交额', 0) or 0)
                        result['turnover_rate'] = float(row.get('换手率', 0) or 0)
                if result['price'] > 0:
                    logger.info(f"✓ AKShare获取{pure_code}成功: {result['price']}元")
                    # 缓存数据
                    self._realtime_data_cache[cache_key] = {
                        'timestamp': current_time,
                        'data': result.copy()
                    }
            except Exception as e:
                logger.warning(f"AKShare获取{code}失败: {e}")
        
        # 如果AKShare失败,尝试BaoStock
        if result['price'] == 0 and self.baostock_available and self.bs:
            try:
                if code.startswith('sh') or code.startswith('6'):
                    bs_code = f"sh.{pure_code}"
                else:
                    bs_code = f"sz.{pure_code}"
                
                today = datetime.now().strftime('%Y-%m-%d')
                rs = self.bs.query_history_k_data_plus(
                    bs_code,
                    "date,code,open,high,low,close,volume,amount,turn",
                    start_date=(datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'),
                    end_date=today, frequency="d", adjustflag="3"
                )
                if rs.error_code == '0':
                    data_list = []
                    while (rs.error_code == '0') & rs.next():
                        data_list.append(rs.get_row_data())
                    if len(data_list) >= 1:
                        latest = data_list[-1]
                        prev = data_list[-2] if len(data_list) > 1 else data_list[-1]
                        result['open'] = float(latest[2]) if latest[2] else 0
                        result['high'] = float(latest[3]) if latest[3] else 0
                        result['low'] = float(latest[4]) if latest[4] else 0
                        result['price'] = float(latest[5]) if latest[5] else 0
                        result['volume'] = float(latest[6]) if latest[6] else 0
                        result['amount'] = float(latest[7]) if latest[7] else 0
                        result['turnover_rate'] = float(latest[8]) if latest[8] else 0
                        prev_close = float(prev[5]) if prev[5] else 0
                        result['pre_close'] = prev_close
                        if prev_close > 0:
                            result['change_pct'] = round((result['price'] - prev_close) / prev_close * 100, 2)
                            result['change_amt'] = round(result['price'] - prev_close, 2)
                if result['price'] > 0:
                    logger.info(f"✓ BaoStock获取{pure_code}成功: {result['price']}元")
                    # 缓存数据
                    self._realtime_data_cache[cache_key] = {
                        'timestamp': current_time,
                        'data': result.copy()
                    }
            except Exception as e:
                logger.warning(f"BaoStock获取{code}失败: {e}")
        
        return result
    
    def get_financial_data(self, code: str) -> Dict:
        """获取财务指标数据"""
        result = {
            'pe_ttm': None,
            'pb': None,
            'roe': None,
            'roa': None,
            'gross_margin': None,
            'net_margin': None,
            'market_cap': None
        }
        
        pure_code = code.replace('sh', '').replace('sz', '')
        
        # 使用BaoStock获取财务数据
        if self.baostock_available and self.bs:
            try:
                if code.startswith('sh') or code.startswith('6'):
                    bs_code = f"sh.{pure_code}"
                else:
                    bs_code = f"sz.{pure_code}"
                
                # 获取盈利能力数据(ROE等)
                current_year = datetime.now().year
                for year in [current_year - 1, current_year - 2]:
                    for quarter in [3, 2, 1]:
                        rs = self.bs.query_profit_data(code=bs_code, year=year, quarter=quarter)
                        if rs.error_code == '0' and rs.next():
                            row = rs.get_row_data()
                            roe = float(row[3]) if row[3] else None
                            if roe:
                                result['roe'] = round(roe * 100, 2)
                            net_margin = float(row[4]) if row[4] else None
                            if net_margin:
                                result['net_margin'] = round(net_margin * 100, 2)
                            break
                    if result['roe']:
                        break
                
                # 获取估值数据
                rs = self.bs.query_history_k_data_plus(
                    bs_code, "date,close,peTTM,pbMRQ",
                    start_date=(datetime.now() - timedelta(days=5)).strftime('%Y-%m-%d'),
                    end_date=datetime.now().strftime('%Y-%m-%d'),
                    frequency="d", adjustflag="3"
                )
                if rs.error_code == '0':
                    data_list = []
                    while (rs.error_code == '0') & rs.next():
                        data_list.append(rs.get_row_data())
                    if data_list:
                        latest = data_list[-1]
                        if latest[2]:
                            result['pe_ttm'] = round(float(latest[2]), 2)
                        if latest[3]:
                            result['pb'] = round(float(latest[3]), 2)
                
                # 计算市值
                if result['pe_ttm'] and result['pe_ttm'] > 0:
                    # 从行情数据获取总股本
                    stock_info = self.get_stock_realtime(code)
                    if stock_info.get('price', 0) > 0:
                        # 使用BaoStock获取总股本
                        rs2 = self.bs.query_profit_data(code=bs_code, year=current_year-1, quarter=3)
                        if rs2.error_code == '0' and rs2.next():
                            row = rs2.get_row_data()
                            total_share = float(row[9]) if len(row) > 9 and row[9] else 0
                            if total_share > 0 and stock_info['price'] > 0:
                                result['market_cap'] = round(total_share * stock_info['price'] / 100000000, 2)
                
                if result['roe'] or result['pe_ttm']:
                    logger.info(f"✓ BaoStock获取{pure_code}财务数据: PE={result['pe_ttm']}, ROE={result['roe']}%")
            except Exception as e:
                logger.warning(f"BaoStock获取{code}财务数据失败: {e}")
        
        return result
    
    def get_market_sentiment(self) -> Dict:
        """获取市场情绪数据"""
        result = {
            'up_count': 0,
            'down_count': 0,
            'total_volume': 0,
            'north_flow': 0
        }
        
        if self.akshare_available:
            try:
                import akshare as ak
                df = ak.stock_zh_a_spot_em()
                if df is not None and len(df) > 0:
                    df['涨跌幅'] = pd.to_numeric(df.get('涨跌幅', 0), errors='coerce').fillna(0)
                    df['成交量'] = pd.to_numeric(df.get('成交量', 0), errors='coerce').fillna(0)
                    result['up_count'] = int((df['涨跌幅'] >= 9.8).sum())
                    result['down_count'] = int((df['涨跌幅'] <= -9.8).sum())
                    result['total_volume'] = float(df['成交量'].sum() / 100000000)
                try:
                    north_data = ak.stock_hsgt_hist_em(symbol='北向资金')
                    if north_data is not None and len(north_data) > 0:
                        latest = north_data.iloc[-1]
                        north_flow = latest.get('当日成交净买额', 0)
                        if pd.notna(north_flow):
                            result['north_flow'] = float(north_flow)
                except Exception:
                    pass
                if result['up_count'] > 0 or result['down_count'] > 0:
                    logger.info(f"✓ AKShare获取市场情绪成功: 涨停{result['up_count']}只")
                    return result
            except Exception as e:
                logger.warning(f"AKShare获取市场情绪失败: {e}")
        
        logger.warning("使用参考市场情绪数据")
        result = {
            'up_count': 99,
            'down_count': 25,
            'total_volume': 30200,
            'north_flow': 80.5
        }
        return result
    
    def get_stock_full_info(self, code: str) -> Dict:
        """获取股票完整信息"""
        base_info = self.get_stock_realtime(code)
        financial = self.get_financial_data(code)
        
        # 合并财务数据
        base_info['pe_ttm'] = financial.get('pe_ttm')
        base_info['pb'] = financial.get('pb')
        base_info['roe'] = financial.get('roe')
        base_info['roa'] = financial.get('roa')
        base_info['gross_margin'] = financial.get('gross_margin')
        base_info['net_margin'] = financial.get('net_margin')
        base_info['market_cap'] = financial.get('market_cap')
        
        return base_info
    
    def get_stock_history(self, code: str, days: int = 60) -> List[Dict]:
        """
        获取股票历史数据
        
        Args:
            code: 股票代码
            days: 天数
            
        Returns:
            历史数据列表 [{'date': xxx, 'close': xxx, 'volume': xxx}, ...]
        """
        pure_code = code.replace('sh', '').replace('sz', '')
        history = []
        
        if self.baostock_available and self.bs:
            try:
                if code.startswith('sh') or code.startswith('6'):
                    bs_code = f"sh.{pure_code}"
                else:
                    bs_code = f"sz.{pure_code}"
                
                end_date = datetime.now().strftime('%Y-%m-%d')
                start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y-%m-%d')
                
                rs = self.bs.query_history_k_data_plus(
                    bs_code,
                    "date,open,high,low,close,volume",
                    start_date=start_date,
                    end_date=end_date,
                    frequency="d",
                    adjustflag="2"  # 前复权
                )
                
                if rs.error_code == '0':
                    while (rs.error_code == '0') & rs.next():
                        row = rs.get_row_data()
                        if row[4]:  # close price exists
                            history.append({
                                'date': row[0],
                                'open': float(row[1]) if row[1] else 0,
                                'high': float(row[2]) if row[2] else 0,
                                'low': float(row[3]) if row[3] else 0,
                                'close': float(row[4]) if row[4] else 0,
                                'volume': float(row[5]) if row[5] else 0
                            })
                    
                    # 取最近N天
                    history = history[-days:] if len(history) > days else history
                    logger.info(f"✓ 获取{pure_code}历史数据: {len(history)}天")
            except Exception as e:
                logger.warning(f"获取{code}历史数据失败: {e}")
        
        return history
    
    def get_index_history(self, days: int = 60) -> Dict[str, List[Dict]]:
        """
        获取指数历史数据
        
        Args:
            days: 天数
            
        Returns:
            {指数代码: [历史数据...]}
        """
        result = {}
        
        if self.baostock_available and self.bs:
            index_codes = {
                'sh': 'sh.000001',
                'hs300': 'sh.000300'
            }
            
            for key, code in index_codes.items():
                try:
                    end_date = datetime.now().strftime('%Y-%m-%d')
                    start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y-%m-%d')
                    
                    rs = self.bs.query_history_k_data_plus(
                        code,
                        "date,close",
                        start_date=start_date,
                        end_date=end_date,
                        frequency="d",
                        adjustflag="3"
                    )
                    
                    if rs.error_code == '0':
                        history = []
                        while (rs.error_code == '0') & rs.next():
                            row = rs.get_row_data()
                            if row[1]:
                                history.append({
                                    'date': row[0],
                                    'close': float(row[1])
                                })
                        result[key] = history[-days:] if len(history) > days else history
                except Exception as e:
                    logger.warning(f"获取{code}历史数据失败: {e}")
        
        return result
    
    def calculate_volatility(self, history: List[Dict]) -> float:
        """
        计算年化波动率
        
        Args:
            history: 历史数据列表
            
        Returns:
            年化波动率(百分比)
        """
        if len(history) < 10:
            return 0.0
        
        closes = [h['close'] for h in history if h['close'] > 0]
        if len(closes) < 10:
            return 0.0
        
        # 计算日收益率
        returns = []
        for i in range(1, len(closes)):
            if closes[i-1] > 0:
                ret = (closes[i] - closes[i-1]) / closes[i-1]
                returns.append(ret)
        
        if len(returns) < 5:
            return 0.0
        
        # 计算标准差并年化
        std = np.std(returns, ddof=1)
        annualized = std * np.sqrt(252) * 100  # 转换为百分比
        
        return round(annualized, 2)
    
    def calculate_max_drawdown(self, history: List[Dict]) -> Tuple[float, float]:
        """
        计算最大回撤和当前回撤
        
        Args:
            history: 历史数据列表
            
        Returns:
            (最大回撤百分比, 当前回撤百分比)
        """
        if len(history) < 2:
            return 0.0, 0.0
        
        closes = [h['close'] for h in history if h['close'] > 0]
        if len(closes) < 2:
            return 0.0, 0.0
        
        # 计算累计最大值
        cumulative_max = []
        max_val = closes[0]
        for c in closes:
            if c > max_val:
                max_val = c
            cumulative_max.append(max_val)
        
        # 计算回撤
        drawdowns = [(cumulative_max[i] - closes[i]) / cumulative_max[i] * 100 
                     for i in range(len(closes))]
        
        max_dd = max(drawdowns) if drawdowns else 0.0
        current_dd = drawdowns[-1] if drawdowns else 0.0
        
        return round(max_dd, 2), round(current_dd, 2)
    
    def calculate_var(self, history: List[Dict], confidence: float = 0.95) -> float:
        """
        计算VaR(在险价值)
        
        Args:
            history: 历史数据列表
            confidence: 置信水平
            
        Returns:
            VaR值(百分比)
        """
        if len(history) < 20:
            return 0.0
        
        closes = [h['close'] for h in history if h['close'] > 0]
        if len(closes) < 20:
            return 0.0
        
        # 计算日收益率
        returns = []
        for i in range(1, len(closes)):
            if closes[i-1] > 0:
                ret = (closes[i] - closes[i-1]) / closes[i-1]
                returns.append(ret)
        
        if len(returns) < 10:
            return 0.0
        
        # 历史模拟法计算VaR
        sorted_returns = sorted(returns)
        index = int((1 - confidence) * len(sorted_returns))
        var = abs(sorted_returns[index] * 100) if index < len(sorted_returns) else 0.0
        
        return round(var, 2)
    
    def calculate_beta(self, stock_history: List[Dict], index_history: List[Dict]) -> float:
        """
        计算Beta值
        
        Args:
            stock_history: 股票历史数据
            index_history: 指数历史数据
            
        Returns:
            Beta值
        """
        if len(stock_history) < 20 or len(index_history) < 20:
            return 1.0
        
        # 按日期匹配
        stock_dict = {h['date']: h['close'] for h in stock_history if h['close'] > 0}
        index_dict = {h['date']: h['close'] for h in index_history if h['close'] > 0}
        
        common_dates = sorted(set(stock_dict.keys()) & set(index_dict.keys()))
        if len(common_dates) < 20:
            return 1.0
        
        # 计算收益率
        stock_returns = []
        index_returns = []
        for i in range(1, len(common_dates)):
            d_prev, d_curr = common_dates[i-1], common_dates[i]
            if stock_dict[d_prev] > 0 and index_dict[d_prev] > 0:
                stock_returns.append((stock_dict[d_curr] - stock_dict[d_prev]) / stock_dict[d_prev])
                index_returns.append((index_dict[d_curr] - index_dict[d_prev]) / index_dict[d_prev])
        
        if len(stock_returns) < 10:
            return 1.0
        
        # 计算协方差和方差
        stock_returns = np.array(stock_returns)
        index_returns = np.array(index_returns)
        
        covariance = np.cov(stock_returns, index_returns)[0, 1]
        variance = np.var(index_returns, ddof=1)
        
        if variance == 0:
            return 1.0
        
        beta = covariance / variance
        return round(beta, 2)
    
    def calculate_factor_ic(self, factor_values: List[float], returns: List[float]) -> float:
        """
        计算因子IC(信息系数)
        
        Args:
            factor_values: 因子值列表
            returns: 对应的收益率列表
            
        Returns:
            IC值
        """
        if len(factor_values) < 10 or len(returns) < 10:
            return 0.0
        
        # 使用斯皮尔曼相关系数
        from scipy.stats import spearmanr
        correlation, _ = spearmanr(factor_values, returns)
        
        return round(correlation, 4) if not np.isnan(correlation) else 0.0
    
    def calculate_technical_factors(self, df: pd.DataFrame) -> pd.DataFrame:
        """计算技术因子(只使用历史数据)"""
        if len(df) < 60:
            return df
 
        df = df.sort_values('date').copy()
 
        # 移动均线
        df['ma5'] = df['close'].rolling(5).mean()
        df['ma10'] = df['close'].rolling(10).mean()
        df['ma20'] = df['close'].rolling(20).mean()
        df['ma60'] = df['close'].rolling(60).mean()
 
        # 动量
        df['momentum_5'] = df['close'].pct_change(5)
        df['momentum_10'] = df['close'].pct_change(10)
        df['momentum_20'] = df['close'].pct_change(20)
        df['momentum_60'] = df['close'].pct_change(60)
 
        # 波动率
        df['volatility_5'] = df['close'].pct_change().rolling(5).std()
        df['volatility_10'] = df['close'].pct_change().rolling(10).std()
        df['volatility_20'] = df['close'].pct_change().rolling(20).std()
 
        # 换手率均值
        if 'turnover' in df.columns and df['turnover'].notna().any():
            df['turnover_ma5'] = df['turnover'].rolling(5).mean()
            df['turnover_ma20'] = df['turnover'].rolling(20).mean()
        else:
            df['turnover_ma5'] = None
            df['turnover_ma20'] = None
 
        # 成交额均值
        df['amount_ma5'] = df['amount'].rolling(5).mean()
        df['amount_ma20'] = df['amount'].rolling(20).mean()
 
        # 价格相对位置
        df['price_to_ma20'] = df['close'] / df['ma20'] - 1
        df['price_to_ma60'] = df['close'] / df['ma60'] - 1
 
        return df
    
    def remove_future_leakage(self, df: pd.DataFrame) -> pd.DataFrame:
        """消除未来函数"""
        factor_cols = [
            'ma5', 'ma10', 'ma20', 'ma60',
            'momentum_5', 'momentum_10', 'momentum_20', 'momentum_60',
            'volatility_5', 'volatility_10', 'volatility_20',
            'turnover_ma5', 'turnover_ma20',
            'amount_ma5', 'amount_ma20',
            'price_to_ma20', 'price_to_ma60'
        ]
 
        for col in factor_cols:
            if col in df.columns:
                df[col] = df[col].shift(1)
 
        return df
    
    def apply_liquidity_filter(self, df: pd.DataFrame, min_amount: float = 1000000) -> pd.DataFrame:
        """流动性过滤"""
        initial_count = len(df)
        if 'amount' in df.columns:
            df = df[df['amount'] >= min_amount].copy()
 
        removed = initial_count - len(df)
        logger.info(f"  💧 流动性过滤: 去除 {removed} 条记录 ({removed/initial_count*100:.2f}%)")
        return df
    
    def process_all_stocks(self, limit: int = None, start_date: str = '20190101', end_date: str = '20241231', min_amount: float = 1000000) -> Optional[pd.DataFrame]:
        """处理所有股票数据"""
        logger.info("=" * 70)
        logger.info("开始获取A股历史数据")
        logger.info("=" * 70)
 
        # 获取股票列表
        stock_list = self.get_stock_list()
 
        if limit:
            stock_list = stock_list.head(limit)
            logger.info(f"⚠️ 测试模式:只处理前 {limit} 只股票")
 
        logger.info(f"共需处理 {len(stock_list)} 只股票")
 
        all_data = []
        success_count = 0
        no_data_count = 0
 
        for idx, stock in stock_list.iterrows():
            stock_code = stock.get('code') or stock.get('ts_code', '').split('.')[0] or stock.get('ts_code')
            stock_name = stock.get('name', '')
 
            if not stock_code:
                continue
 
            if (idx + 1) % 10 == 0:
                logger.info(f"  进度: [{idx+1}/{len(stock_list)}] 成功: {success_count}")
 
            # 获取数据
            hist_data = self.fetch_stock_history(stock_code, days=730)  # 2年数据
 
            if hist_data is not None and len(hist_data) > 0:
                # 添加股票名称
                hist_data['stock_name'] = stock_name
 
                # 标准化列名
                hist_data = self._standardize_columns(hist_data)
 
                # 日期过滤
                hist_data = self._filter_by_date(hist_data, start_date, end_date)
 
                if len(hist_data) < 50:
                    no_data_count += 1
                    continue
 
                # 计算技术因子
                hist_data = self.calculate_technical_factors(hist_data)
 
                # 消除未来函数
                hist_data = self.remove_future_leakage(hist_data)
 
                all_data.append(hist_data)
                success_count += 1
            else:
                no_data_count += 1
 
            # 控制请求频率
            time.sleep(0.3)
 
        if not all_data:
            logger.error("✗ 没有成功获取任何数据")
            return None
 
        # 合并数据
        combined_data = pd.concat(all_data, ignore_index=True)
 
        logger.info(f"\n✓ 数据获取完成: 成功={success_count}, 无数据={no_data_count}")
 
        # 添加月份列
        combined_data['date_dt'] = pd.to_datetime(combined_data['date'])
        combined_data['month'] = combined_data['date_dt'].dt.strftime('%Y-%m')
 
        # 流动性过滤
        combined_data = self.apply_liquidity_filter(combined_data, min_amount)
 
        # 更新元数据
        self.metadata['versions'] = [{
            'step': 'process_all_stocks',
            'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'success_count': success_count,
            'no_data_count': no_data_count,
            'total_records': len(combined_data),
            'unique_stocks': int(combined_data['stock_code'].nunique()),
            'date_range': f"{combined_data['date'].min()} to {combined_data['date'].max()}"
        }]
 
        return combined_data
    
    def _standardize_columns(self, df: pd.DataFrame) -> pd.DataFrame:
        """标准化列名"""
        # 确保所有必须的列存在
        required_cols = ['date', 'stock_code', 'open', 'close', 'high', 'low', 'volume', 'amount', 'turnover']
 
        for col in required_cols:
            if col not in df.columns and col == 'turnover':
                if 'turnover_rate' in df.columns:
                    df['turnover'] = df['turnover_rate']
                else:
                    df['turnover'] = None
 
        return df
    
    def _filter_by_date(self, df: pd.DataFrame, start_date: str, end_date: str) -> pd.DataFrame:
        """过滤日期范围"""
        if 'date' not in df.columns:
            return df
 
        start = start_date[:4] + '-' + start_date[4:6] + '-' + start_date[6:]
        end = end_date[:4] + '-' + end_date[4:6] + '-' + end_date[6:]
        mask = (df['date'] >= start) & (df['date'] <= end)
        return df[mask].copy()
    
    def save_data(self, data: pd.DataFrame, filepath: str):
        """保存数据"""
        logger.info(f"\n💾 保存数据到 {filepath}...")
 
        os.makedirs(os.path.dirname(filepath), exist_ok=True)
 
        with open(filepath, 'wb') as f:
            pickle.dump(data, f)
 
        # 保存元数据
        metadata_file = filepath.replace('.pkl', '_metadata.json')
        with open(metadata_file, 'w', encoding='utf-8') as f:
            json.dump(self.metadata, f, ensure_ascii=False, indent=2)
 
        logger.info(f"  ✓ 数据已保存 ({len(data)} 条记录)")
        logger.info(f"  ✓ 元数据已保存")
    
    def generate_quality_report(self, data: pd.DataFrame, output_file: str):
        """生成数据质量报告"""
        logger.info(f"\n📊 生成数据质量报告...")
 
        report_lines = [
            "# A股真实数据质量报告",
            "",
            f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
            f"数据源: {self.metadata.get('active_source', 'multi_source')}",
            "",
            "## 数据源测试结果",
            ""
        ]
 
        for src in self.metadata.get('sources_tested', []):
            status = "✓" if src['available'] else "✗"
            report_lines.append(f"- {status} **{src['name']}**: {'可用' if src['available'] else '不可用'}")
 
        report_lines.extend([
            "",
            "## 数据概览",
            "",
            f"- **总记录数**: {len(data):,}",
            f"- **股票数量**: {data['stock_code'].nunique()}",
            f"- **时间范围**: {data['date'].min()} 至 {data['date'].max()}",
            f"- **月份数量**: {data['month'].nunique()}",
            "",
            "## 数据统计特征",
            ""
        ])
 
        # 价格统计
        for col in ['open', 'close', 'high', 'low']:
            if col in data.columns:
                report_lines.append(f"- **{col}**: 均值={data[col].mean():.2f}, 中位数={data[col].median():.2f}")
 
        report_lines.append("")
 
        # 涨跌幅
        if 'change_pct' in data.columns:
            change_data = data['change_pct'].dropna()
            report_lines.extend([
                f"- **涨跌幅**: 均值={change_data.mean():.2f}%, 中位数={change_data.median():.2f}%",
                f"- **涨跌幅范围**: {change_data.min():.2f}% ~ {change_data.max():.2f}%",
                ""
            ])
 
        report_lines.extend([
            "## 技术因子统计",
            "",
            "| 因子 | 均值 | 标准差 |",
            "|------|------|--------|"
        ])
 
        factor_cols = ['ma20', 'momentum_20', 'volatility_20', 'turnover_ma20']
        for col in factor_cols:
            if col in data.columns:
                report_lines.append(f"| {col} | {data[col].mean():.4f} | {data[col].std():.4f} |")
 
        report_lines.extend([
            "",
            "## 数据处理说明",
            "",
            "✓ 标准化列名和数据格式",
            "✓ 筛选日期范围 (2019-2024)",
            "✓ 计算技术因子(移动均线、动量、波动率等)",
            "✓ 消除未来函数(因子下移一行)",
            "✓ 流动性过滤(成交额>=100万)",
            "",
            f"---\n*报告生成于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*"
        ])
 
        os.makedirs(os.path.dirname(output_file), exist_ok=True)
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(report_lines))
 
        logger.info(f"  ✓ 报告已保存到 {output_file}")
    
    def close(self):
        """关闭连接"""
        if self.bs:
            try:
                self.bs.logout()
            except Exception:
                pass
 
 
if __name__ == "__main__":
    fetcher = MultiSourceStockFetcher()
    
    print("=" * 60)
    print("多数据源股票数据获取测试")
    print("=" * 60)
    
    print("\n【指数数据】")
    index_data = fetcher.get_index_data()
    for key, data in index_data.items():
        print(f"  {data['name']}: {data['price']:.2f}点, {data['change_pct']:+.2f}%")
    
    print("\n【个股完整数据】")
    try:
        from code.config import TEST_STOCK_CODES
        test_codes = TEST_STOCK_CODES
    except ImportError:
        test_codes = ['sh600000', 'sh601899', 'sz002703']
    for code in test_codes:
        info = fetcher.get_stock_full_info(code)
        print(f"\n  {info.get('name', 'N/A')}({code}):")
        print(f"    价格: {info['price']}元, 涨跌: {info['change_pct']:+.2f}%")
        print(f"    PE_TTM: {info['pe_ttm']}, PB: {info['pb']}")
        print(f"    ROE: {info['roe']}%, 市值: {info['market_cap']}亿")
        print(f"    行业: {info['industry']}")
    
    print("\n【市场情绪】")
    sentiment = fetcher.get_market_sentiment()
    print(f"  涨停: {sentiment['up_count']}只")
    print(f"  跌停: {sentiment['down_count']}只")
    
    fetcher.close()