log
2026-07-10 9ed88e8d947856aae52cffefbce3e11ac11dcfa2
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
#!/usr/bin/env python3
"""
数据更新脚本V3 - 使用真实数据源
任务:从AKShare获取真实A股数据
执行时机:每日开盘前(7:00)和收盘后(16:00)
"""
 
import sys
import os
from pathlib import Path
 
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
 
from datetime import datetime, timedelta
import logging
import pandas as pd
import numpy as np
import pickle
import json
import argparse
import time
import socket
 
os.makedirs('logs', exist_ok=True)
 
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/data_update_v3.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)
 
 
def fetch_real_stock_data_from_akshare(n_stocks=500, days=365):
    """优先使用AKShare,失败时由BaoStock和腾讯行情共同兜底。"""
    stock_list = fetch_stock_list_from_akshare(n_stocks=n_stocks)
 
    df = fetch_real_stock_data_from_akshare_only(
        n_stocks=n_stocks,
        days=days,
        stock_list=stock_list,
    )
    if df is not None and len(df) > 0:
        df.attrs['source'] = 'akshare_real'
        return df
 
    logger.warning("⚠️ AKShare未获取到有效数据,尝试切换到备用数据源")
    baostock_df = fetch_real_stock_data_from_baostock(
        n_stocks=n_stocks,
        days=days,
        stock_list=stock_list,
    )
    tencent_df = fetch_real_stock_data_from_tencent_bse(
        n_stocks=n_stocks,
        days=days,
        stock_list=stock_list,
    )
 
    frames = [
        frame for frame in (baostock_df, tencent_df)
        if frame is not None and len(frame) > 0
    ]
    if not frames:
        return None
 
    df = pd.concat(frames, ignore_index=True)
    if baostock_df is not None and tencent_df is not None:
        df.attrs['source'] = 'baostock_tencent_real'
    elif tencent_df is not None:
        df.attrs['source'] = 'tencent_real'
    else:
        df.attrs['source'] = 'baostock_real'
    return df
 
 
def fallback_stock_pool():
    """内置精选股票池,作为所有在线股票列表接口失败时的最后兜底。"""
    return pd.DataFrame([
        {'代码': '000001', '名称': '平安银行'}, {'代码': '600519', '名称': '贵州茅台'},
        {'代码': '000858', '名称': '五粮液'}, {'代码': '300750', '名称': '宁德时代'},
        {'代码': '601318', '名称': '中国平安'}, {'代码': '002594', '名称': '比亚迪'},
        {'代码': '600036', '名称': '招商银行'}, {'代码': '601888', '名称': '中国中免'},
        {'代码': '600276', '名称': '恒瑞医药'}, {'代码': '600900', '名称': '长江电力'},
    ])
 
 
def fetch_akshare_stock_list(ak):
    """优先用交易所股票列表,避免依赖东方财富push2实时行情列表。"""
    try:
        stock_list = ak.stock_info_a_code_name()
        stock_list = stock_list.rename(columns={'code': '代码', 'name': '名称'})
        stock_list['代码'] = stock_list['代码'].astype(str).str.zfill(6)
        stock_list = stock_list[['代码', '名称']]
        logger.info(f"✓ 从交易所股票列表获取到 {len(stock_list)} 只股票")
        return stock_list
    except Exception as e:
        logger.warning(f"⚠️ 交易所股票列表获取失败,尝试东方财富实时列表: {e}")
 
    try:
        stock_list = ak.stock_zh_a_spot_em()
        logger.info(f"✓ 从东方财富实时列表获取到 {len(stock_list)} 只股票")
        return stock_list[['代码', '名称']]
    except Exception as e:
        logger.warning(f"⚠️ 无法获取完整股票列表,可能是东方财富接口限制: {e}")
        logger.info("ℹ️ 启用备用精选股票池...")
        return fallback_stock_pool()
 
 
def fetch_stock_list_from_akshare(n_stocks=None):
    """获取AKShare股票列表,供AKShare和BaoStock历史行情路径共用。"""
    try:
        import akshare as ak
    except ImportError:
        logger.warning("⚠️ AKShare未安装,无法使用AKShare股票列表")
        return None
 
    stock_list = fetch_akshare_stock_list(ak)
    if stock_list is None or len(stock_list) == 0:
        return None
 
    if n_stocks is not None:
        stock_list = stock_list.head(n_stocks)
    return stock_list
 
 
def fetch_real_stock_data_from_akshare_only(
    n_stocks=500,
    days=365,
    max_consecutive_failures=10,
    stock_list=None,
):
    """从AKShare获取真实股票历史数据"""
    logger.info("="*60)
    logger.info("从AKShare获取真实A股数据")
    logger.info("="*60)
    
    try:
        import akshare as ak
        logger.info("✓ AKShare导入成功")
    except ImportError:
        logger.error("❌ AKShare未安装,请运行: pip install akshare")
        return None
    
    all_data = []
    end_date = datetime.now().strftime('%Y-%m-%d')
    start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y-%m-%d')
    
    try:
        if stock_list is None:
            logger.info("📥 获取A股股票列表...")
            stock_list = fetch_akshare_stock_list(ak)
 
        if n_stocks is not None:
            stock_list = stock_list.head(n_stocks)
        
        consecutive_failures = 0
 
        for position, (_, row) in enumerate(stock_list.iterrows(), start=1):
            stock_code = row['代码']
            stock_name = row['名称']
            
            try:
                logger.info(f"  [{position}/{len(stock_list)}] 获取 {stock_name}({stock_code})...")
                
                df = ak.stock_zh_a_hist(
                    symbol=stock_code,
                    period="daily",
                    start_date=start_date.replace('-', ''),
                    end_date=end_date.replace('-', ''),
                    adjust="qfq"
                )
                
                if df is not None and len(df) > 0:
                    # AKShare返回12列:日期、股票代码、开盘、收盘、最高、最低、成交量、成交额、振幅、涨跌幅、涨跌额、换手率
                    df.columns = ['date', 'stock_code_api', 'open', 'close', 'high', 'low',
                                  'volume', 'amount', 'amplitude', 'change_pct', 'change_amount', 'turnover']
 
                    df['stock_code'] = stock_code
                    df['stock_name'] = stock_name
                    df['date'] = pd.to_datetime(df['date'])
                    
                    df = calculate_technical_factors(df)
 
                    all_data.append(df)
                    consecutive_failures = 0
                    logger.info(f"    ✓ 获取 {len(df)} 条记录")
                else:
                    logger.warning(f"    ⚠️ 无数据")
                    
            except Exception as e:
                consecutive_failures += 1
                logger.warning(f"    ⚠️ 获取失败: {e}")
                if (
                    max_consecutive_failures
                    and consecutive_failures >= max_consecutive_failures
                ):
                    logger.error(
                        f"❌ AKShare历史行情连续失败 {consecutive_failures} 次,"
                        "提前停止并切换备用数据源"
                    )
                    if not all_data:
                        return None
                    break
                continue
        
        if all_data:
            combined = pd.concat(all_data, ignore_index=True)
            logger.info(f"\n✓ 总计获取 {len(combined)} 条记录,{combined['stock_code'].nunique()} 只股票")
            return combined
        else:
            logger.error("❌ 未获取到任何数据")
            return None
            
    except Exception as e:
        logger.error(f"❌ 获取数据失败: {e}", exc_info=True)
        return None
 
 
def normalize_baostock_code(code):
    """将BaoStock代码格式 sh.600519 转成 600519。"""
    return str(code).split('.')[-1]
 
 
def to_baostock_code(stock_code):
    """将6位A股代码转换为BaoStock代码格式。"""
    code = str(stock_code).strip().zfill(6)
    if is_bse_stock_code(code):
        return None
    if code.startswith('6'):
        return f"sh.{code}"
    if code.startswith(('0', '2', '3')):
        return f"sz.{code}"
    return None
 
 
def is_bse_stock_code(stock_code):
    """识别北交所现行及历史股票代码段。"""
    code = str(stock_code).strip().zfill(6)
    return code.startswith(('4', '8', '92'))
 
 
def to_tencent_code(stock_code):
    """将6位A股代码转换为腾讯行情接口的带市场代码。"""
    code = str(stock_code).strip().zfill(6)
    if is_bse_stock_code(code):
        return f"bj{code}"
    if code.startswith('6'):
        return f"sh{code}"
    if code.startswith(('0', '2', '3')):
        return f"sz{code}"
    return None
 
 
def normalize_external_stock_list(stock_list):
    """把AKShare股票列表标准化为BaoStock历史行情可用的字段。"""
    if stock_list is None or len(stock_list) == 0:
        return None
 
    normalized = stock_list.rename(
        columns={'code': '代码', 'name': '名称', 'code_name': '名称'}
    ).copy()
    if '代码' not in normalized.columns or '名称' not in normalized.columns:
        return None
 
    normalized['代码'] = normalized['代码'].astype(str).str.strip().str.zfill(6)
    normalized['名称'] = normalized['名称'].astype(str)
    normalized['bs_code'] = normalized['代码'].map(to_baostock_code)
    normalized = normalized.dropna(subset=['bs_code'])
    return normalized[['bs_code', '代码', '名称']]
 
 
def baostock_result_to_dataframe(result):
    """使用BaoStock迭代接口构建DataFrame,避开旧版get_data()对pandas.append的依赖。"""
    if not all(hasattr(result, attr) for attr in ('fields', 'next', 'get_row_data')):
        return result.get_data()
 
    rows = []
    while result.next():
        rows.append(result.get_row_data())
    return pd.DataFrame(rows, columns=result.fields)
 
 
def convert_baostock_history(df, stock_code, stock_name):
    """将BaoStock历史行情转换为现有AKShare数据字段格式。"""
    if df is None or len(df) == 0:
        return None
 
    converted = df.copy()
    converted['stock_code_api'] = converted['code']
    converted['stock_code'] = stock_code
    converted['stock_name'] = stock_name
    converted['date'] = pd.to_datetime(converted['date'])
 
    numeric_cols = ['open', 'high', 'low', 'close', 'preclose', 'volume', 'amount', 'turn', 'pctChg']
    for col in numeric_cols:
        converted[col] = pd.to_numeric(converted[col], errors='coerce')
 
    converted['turnover'] = converted['turn']
    converted['change_pct'] = converted['pctChg']
    converted['change_amount'] = converted['close'] - converted['preclose']
    converted['amplitude'] = np.where(
        converted['preclose'] > 0,
        (converted['high'] - converted['low']) / converted['preclose'] * 100,
        np.nan
    )
 
    columns = [
        'date', 'stock_code_api', 'open', 'close', 'high', 'low',
        'volume', 'amount', 'amplitude', 'change_pct', 'change_amount',
        'turnover', 'stock_code', 'stock_name'
    ]
    return converted[columns]
 
 
def convert_tencent_history(df, stock_code, stock_name):
    """将腾讯历史行情转换为现有数据字段格式。"""
    if df is None or len(df) == 0:
        return None
 
    converted = df.copy().sort_values('date').reset_index(drop=True)
    for col in ['open', 'high', 'low', 'close', 'amount']:
        converted[col] = pd.to_numeric(converted[col], errors='coerce')
 
    converted['stock_code_api'] = to_tencent_code(stock_code)
    converted['stock_code'] = str(stock_code).zfill(6)
    converted['stock_name'] = stock_name
    converted['date'] = pd.to_datetime(converted['date'])
 
    # 腾讯的 amount 字段实际单位为“手”,统一为成交量并估算成交额。
    converted['volume'] = converted['amount']
    converted['amount'] = converted['volume'] * converted['close'] * 100
    preclose = converted['close'].shift(1)
    converted['change_amount'] = converted['close'] - preclose
    converted['change_pct'] = np.where(
        preclose > 0,
        converted['change_amount'] / preclose * 100,
        np.nan,
    )
    converted['amplitude'] = np.where(
        preclose > 0,
        (converted['high'] - converted['low']) / preclose * 100,
        np.nan,
    )
    converted['turnover'] = np.nan
 
    columns = [
        'date', 'stock_code_api', 'open', 'close', 'high', 'low',
        'volume', 'amount', 'amplitude', 'change_pct', 'change_amount',
        'turnover', 'stock_code', 'stock_name'
    ]
    return converted[columns]
 
 
def fetch_real_stock_data_from_tencent_bse(
    n_stocks=500,
    days=365,
    stock_list=None,
    max_retries=2,
    retry_delay=1,
    request_delay=0.1,
    socket_timeout=30,
):
    """通过AKShare腾讯接口补齐BaoStock不支持的北交所历史行情。"""
    if stock_list is None or len(stock_list) == 0:
        return None
 
    selected = stock_list.copy()
    if n_stocks is not None:
        selected = selected.head(n_stocks)
    selected['代码'] = selected['代码'].astype(str).str.strip().str.zfill(6)
    selected = selected[selected['代码'].map(is_bse_stock_code)]
    if len(selected) == 0:
        return None
 
    try:
        import akshare as ak
        logger.info("="*60)
        logger.info("从腾讯行情获取北交所历史数据")
        logger.info("="*60)
        logger.info(f"✓ 待获取北交所股票: {len(selected)} 只")
    except ImportError:
        logger.error("❌ AKShare未安装,无法调用腾讯北交所行情接口")
        return None
 
    end_date = datetime.now().strftime('%Y%m%d')
    start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y%m%d')
    all_data = []
 
    for position, (_, row) in enumerate(selected.iterrows(), start=1):
        stock_code = row['代码']
        stock_name = row['名称']
        symbol = to_tencent_code(stock_code)
 
        for attempt in range(max_retries + 1):
            if attempt > 0:
                logger.info(f"    ↻ 重试 {attempt}/{max_retries}: {stock_name}({stock_code})")
            try:
                logger.info(
                    f"  [{position}/{len(selected)}] 获取 {stock_name}({stock_code})..."
                )
                raw = ak.stock_zh_a_hist_tx(
                    symbol=symbol,
                    start_date=start_date,
                    end_date=end_date,
                    adjust="qfq",
                    timeout=socket_timeout,
                )
                df = convert_tencent_history(raw, stock_code, stock_name)
                if df is not None and len(df) > 0:
                    df = calculate_technical_factors(df)
                    all_data.append(df)
                    logger.info(f"    ✓ 获取 {len(df)} 条记录")
                else:
                    logger.warning("    ⚠️ 无数据")
                break
            except Exception as e:
                logger.warning(f"    ⚠️ 腾讯行情获取失败: {e}")
                if attempt >= max_retries:
                    break
                if retry_delay:
                    time.sleep(retry_delay)
 
        if request_delay:
            time.sleep(request_delay)
 
    if not all_data:
        logger.error("❌ 腾讯接口未获取到任何北交所数据")
        return None
 
    combined = pd.concat(all_data, ignore_index=True)
    logger.info(
        f"\n✓ 腾讯北交所总计获取 {len(combined)} 条记录,"
        f"{combined['stock_code'].nunique()} 只股票"
    )
    return combined
 
 
def reconnect_baostock(bs):
    """BaoStock长时间运行后可能断开连接,重登后可继续请求。"""
    try:
        bs.logout()
    except Exception as e:
        logger.warning(f"⚠️ BaoStock重连前登出失败: {e}")
 
    login_result = bs.login()
    if getattr(login_result, 'error_code', '0') != '0':
        logger.error(f"❌ BaoStock重新登录失败: {login_result.error_msg}")
        return None
    logger.info("✓ BaoStock已重新登录")
    return login_result
 
 
def is_retryable_baostock_error(error_code, error_msg):
    """判断BaoStock错误是否像临时网络断连,适合重连重试。"""
    text = f"{error_code} {error_msg}".lower()
    retryable_keywords = [
        '10054',
        '网络',
        '接收',
        '连接',
        'closed',
        'reset',
        'timeout',
        'timed out',
    ]
    return any(keyword in text for keyword in retryable_keywords)
 
 
def fetch_real_stock_data_from_baostock(
    n_stocks=500,
    days=365,
    stock_list=None,
    max_retries=3,
    retry_delay=1,
    request_delay=0.1,
    socket_timeout=30,
):
    """从BaoStock获取真实股票历史数据,作为东方财富/AKShare不可用时的备用源。"""
    logger.info("="*60)
    logger.info("从BaoStock获取真实A股数据")
    logger.info("="*60)
 
    try:
        import baostock as bs
        logger.info("✓ BaoStock导入成功")
    except ImportError:
        logger.error("❌ BaoStock未安装,请运行: pip install baostock")
        return None
 
    end_date = datetime.now().strftime('%Y-%m-%d')
    start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y-%m-%d')
    all_data = []
 
    login_result = None
    previous_socket_timeout = socket.getdefaulttimeout()
    try:
        if socket_timeout:
            socket.setdefaulttimeout(socket_timeout)
            logger.info(f"✓ BaoStock网络超时设置为 {socket_timeout} 秒")
 
        login_result = bs.login()
        if getattr(login_result, 'error_code', '0') != '0':
            logger.error(f"❌ BaoStock登录失败: {login_result.error_msg}")
            return None
 
        use_external_stock_list = stock_list is not None
        if use_external_stock_list:
            if n_stocks is not None:
                stock_list = stock_list.head(n_stocks)
            external_stock_count = len(stock_list)
            stock_list = normalize_external_stock_list(stock_list)
            if stock_list is None or len(stock_list) == 0:
                logger.info("ℹ️ 股票列表中没有BaoStock支持的沪深股票")
                return None
 
            skipped_count = external_stock_count - len(stock_list)
            if skipped_count > 0:
                logger.info(
                    f"ℹ️ BaoStock不支持的 {skipped_count} 只股票已跳过,"
                    "北交所将由腾讯行情接口补齐"
                )
            logger.info(f"✓ 使用AKShare股票列表获取BaoStock历史行情: {len(stock_list)} 只股票")
        else:
            logger.info("📥 获取BaoStock股票列表...")
            stock_result = bs.query_stock_basic()
            if getattr(stock_result, 'error_code', '0') != '0':
                logger.error(f"❌ BaoStock股票列表获取失败: {stock_result.error_msg}")
                return None
 
            stock_list = baostock_result_to_dataframe(stock_result)
            if stock_list is None or len(stock_list) == 0:
                logger.error("❌ BaoStock未返回股票列表")
                return None
 
            stock_list = stock_list[
                (stock_list['type'].astype(str) == '1') &
                (stock_list['status'].astype(str) == '1')
            ].copy()
            if n_stocks is not None:
                stock_list = stock_list.head(n_stocks)
            logger.info(f"✓ BaoStock股票池数量: {len(stock_list)}")
 
        fields = "date,code,open,high,low,close,preclose,volume,amount,turn,pctChg"
 
        for position, (_, row) in enumerate(stock_list.iterrows(), start=1):
            if use_external_stock_list:
                bs_code = row['bs_code']
                stock_code = row['代码']
                stock_name = row['名称']
            else:
                bs_code = row['code']
                stock_code = normalize_baostock_code(bs_code)
                stock_name = row['code_name']
 
            for attempt in range(max_retries + 1):
                if attempt > 0:
                    logger.info(f"    ↻ 重试 {attempt}/{max_retries}: {stock_name}({stock_code})")
 
                try:
                    logger.info(f"  [{position}/{len(stock_list)}] 获取 {stock_name}({stock_code})...")
                    result = bs.query_history_k_data_plus(
                        bs_code,
                        fields,
                        start_date=start_date,
                        end_date=end_date,
                        frequency="d",
                        adjustflag="2"
                    )
 
                    if getattr(result, 'error_code', '0') != '0':
                        error_code = getattr(result, 'error_code', '')
                        error_msg = getattr(result, 'error_msg', '')
                        logger.warning(f"    ⚠️ 获取失败: {error_msg}")
                        if (
                            attempt < max_retries
                            and is_retryable_baostock_error(error_code, error_msg)
                        ):
                            if retry_delay:
                                time.sleep(retry_delay)
                            login_result = reconnect_baostock(bs)
                            if login_result is not None:
                                continue
                        break
 
                    df = convert_baostock_history(
                        baostock_result_to_dataframe(result),
                        stock_code,
                        stock_name
                    )
                    if df is not None and len(df) > 0:
                        df = calculate_technical_factors(df)
                        all_data.append(df)
                        logger.info(f"    ✓ 获取 {len(df)} 条记录")
                    else:
                        logger.warning("    ⚠️ 无数据")
                    break
 
                except Exception as e:
                    logger.warning(f"    ⚠️ 获取失败: {e}")
                    if attempt >= max_retries:
                        break
 
                    if retry_delay:
                        time.sleep(retry_delay)
 
                    login_result = reconnect_baostock(bs)
                    if login_result is None:
                        break
 
            if request_delay:
                time.sleep(request_delay)
 
        if all_data:
            combined = pd.concat(all_data, ignore_index=True)
            logger.info(f"\n✓ BaoStock总计获取 {len(combined)} 条记录,{combined['stock_code'].nunique()} 只股票")
            return combined
 
        logger.error("❌ BaoStock未获取到任何数据")
        return None
 
    except Exception as e:
        logger.error(f"❌ BaoStock获取数据失败: {e}", exc_info=True)
        return None
    finally:
        if login_result is not None:
            try:
                bs.logout()
            except Exception as e:
                logger.warning(f"⚠️ BaoStock登出失败: {e}")
        socket.setdefaulttimeout(previous_socket_timeout)
 
 
def calculate_technical_factors(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()
    
    df['price_to_ma20'] = df['close'] / df['ma20'] - 1
    df['price_to_ma60'] = df['close'] / df['ma60'] - 1
    
    df['date_dt'] = df['date']
    df['month'] = df['date_dt'].dt.strftime('%Y-%m')
    
    return df
 
 
def parse_n_stocks(value):
    """解析股票数量参数,all/全部 表示不限制。"""
    if value is None:
        return 500
 
    normalized = str(value).strip().lower()
    if normalized in ('all', 'full', '全部', '全量'):
        return None
 
    try:
        n_stocks = int(normalized)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("股票数量必须是正整数,或 all") from exc
 
    if n_stocks <= 0:
        raise argparse.ArgumentTypeError("股票数量必须是正整数,或 all")
    return n_stocks
 
 
def parse_args(argv=None):
    parser = argparse.ArgumentParser(description="更新A股真实行情数据")
    parser.add_argument(
        "--n-stocks",
        default="500",
        type=parse_n_stocks,
        help="更新股票数量,正整数或 all/全部;默认 500",
    )
    parser.add_argument(
        "--days",
        default=365,
        type=int,
        help="历史数据天数;默认 365",
    )
    return parser.parse_args(argv)
 
 
def main(argv=None):
    """主函数"""
    args = parse_args(argv)
    logger.info("="*60)
    logger.info("数据更新任务开始 - 使用真实数据源")
    logger.info("="*60)
    
    os.makedirs('logs', exist_ok=True)
    os.makedirs('data', exist_ok=True)
    
    stock_count_desc = "全部A股" if args.n_stocks is None else f"{args.n_stocks}只股票"
    logger.info(f"更新范围: {stock_count_desc}, 历史天数: {args.days}")
 
    df = fetch_real_stock_data_from_akshare(n_stocks=args.n_stocks, days=args.days)
    
    if df is not None and len(df) > 0:
        output_file = 'data/akshare_real_data_fixed.pkl'
        
        with open(output_file, 'wb') as f:
            pickle.dump(df, f)
        
        logger.info(f"\n✓ 数据已保存至: {output_file}")
        logger.info(f"✓ 数据时间范围: {df['date'].min()} 至 {df['date'].max()}")
        logger.info(f"✓ 股票数量: {df['stock_code'].nunique()}")
        logger.info(f"✓ 总记录数: {len(df)}")
        
        metadata = {
            'create_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'source': df.attrs.get('source', 'akshare_real'),
            'description': '从AKShare/BaoStock获取的真实A股数据',
            'requested_stock_count': 'all' if args.n_stocks is None else int(args.n_stocks),
            'requested_days': int(args.days),
            'stock_count': int(df['stock_code'].nunique()),
            'total_records': int(len(df)),
            'date_range': f"{df['date'].min()} to {df['date'].max()}"
        }
        
        with open(output_file.replace('.pkl', '_metadata.json'), 'w', encoding='utf-8') as f:
            json.dump(metadata, f, ensure_ascii=False, indent=2)
        
        logger.info("="*60)
        logger.info("✅ 数据更新任务完成")
        logger.info("="*60)
        return 0
    else:
        logger.error("❌ 数据更新失败")
        return 1
 
 
if __name__ == "__main__":
    sys.exit(main())