log
2026-07-10 14be935990b432ce8b7d1346eae16d71f75cd030
fix: handle bse legacy code history
1 files added
3 files modified
574 ■■■■■ changed files
a_stock_manager.py 15 ●●●●● patch | view | raw | blame | history
config/bse_code_mapping.csv 249 ●●●●● patch | view | raw | blame | history
scripts/data_update_v2.py 181 ●●●●● patch | view | raw | blame | history
tests/test_data_update_v2.py 129 ●●●●● patch | view | raw | blame | history
a_stock_manager.py
@@ -343,7 +343,7 @@
    
    print(f"\n{Color.BOLD}【功能说明】{Color.ENDC}")
    print("  数据更新用于获取最新的股票市场数据")
    print("  • 支持多种数据源:AKShare、BaoStock")
    print("  • 支持多种数据源:AKShare、BaoStock、腾讯行情")
    print("  • 自动计算技术因子指标")
    print("  • 自动运行增强因子系统")
    print("  • 支持增量更新")
@@ -353,9 +353,10 @@
    print("2. 使用本地模拟数据(仅测试用)")
    print("3. 从AKShare在线获取(需要网络)")
    print("4. 仅重新计算因子(不更新数据)⭐新增")
    print("5. 仅补充北交所历史数据")
    print("0. 返回")
    
    choice = input("\n请选择 (0-4): ").strip()
    choice = input("\n请选择 (0-5): ").strip()
    
    if choice == '1':
        result = fetch_real_data()
@@ -384,6 +385,16 @@
        return result
    elif choice == '4':
        return run_enhanced_factor_system()
    elif choice == '5':
        result = run_script(
            'data_update_v2.py',
            "补充北交所历史数据并合并现有数据",
            args=['--bse-only', '--n-stocks', 'all'],
        )
        if result:
            print_info("北交所数据补充完成,正在运行增强因子系统...")
            run_enhanced_factor_system()
        return result
def fetch_real_data():
    """获取真实数据"""
config/bse_code_mapping.csv
New file
@@ -0,0 +1,249 @@
old_code,new_code
872931,920931
837023,920123
835438,920438
873706,920706
870656,920656
831396,920496
837403,920403
873806,920806
873690,920690
871263,920363
836961,920061
833284,920284
831175,920375
836547,920547
873703,920703
835579,920579
873570,920570
832522,920522
873132,920132
873679,920679
873833,920833
833030,920130
839493,920493
873693,920693
873726,920026
832786,920786
832978,920978
873665,920665
832469,920469
836419,920519
831627,920627
870976,920976
872953,920953
837174,920274
836504,920504
837748,920748
834058,920058
870726,920926
832982,920982
838701,920701
833751,920751
873576,920576
837592,920592
836717,920717
832175,920175
836208,920208
832651,920651
833455,920455
836221,920221
830779,920779
430017,920017
839719,920719
832471,920471
837006,920006
838837,920837
871478,920578
836699,920699
833394,920394
871694,920694
830896,920896
831304,920304
873593,920593
872895,920895
834261,920261
839792,920792
830809,920809
430556,920556
837663,920663
833575,920575
835857,920057
872541,920541
830974,920974
836422,920422
834770,920770
430478,920478
831906,920906
839273,920273
832149,920249
834407,920407
873167,920367
832802,920802
832023,920023
430425,920425
873152,920252
839371,920371
834950,920950
872392,920392
838262,920262
831195,920195
831855,920855
872351,920351
838227,920227
873001,920001
833781,920781
836247,920247
872190,920190
430718,920718
831526,920526
873305,920505
834033,920033
830879,920879
836807,920807
838810,920810
870508,920608
833429,920429
833171,920571
836957,920957
833075,920075
834014,920014
836414,920414
870866,920866
833230,920230
836942,920942
430300,920300
831087,920087
832110,920110
831641,920641
870199,920199
872374,920374
832662,920662
835237,920237
871634,920634
872808,920808
870357,920357
873339,920339
833914,920914
832876,920876
871753,920753
430139,920139
873527,920527
835892,920992
430476,920476
837046,920046
430685,920685
838402,920402
838971,920971
873122,920122
835207,920207
839790,920790
836270,920270
836395,920395
831152,920152
831834,920834
835985,920985
836871,920871
839725,920725
834062,920062
834639,920639
837821,920821
838670,920870
833943,920943
831278,920378
430564,920564
832491,920491
870299,920299
873223,920223
838171,920271
831167,920267
833533,920533
871970,920970
833580,920580
873169,920169
831689,920689
832419,920419
835179,920179
871857,920857
833346,920346
870204,920204
871245,920245
836720,920720
871981,920981
833873,920873
831832,920932
839680,920680
833454,920454
870436,920436
836260,920260
832171,920171
832145,920145
837092,920092
832089,920089
831305,920405
838924,920924
836892,920892
872925,920925
836077,920077
835305,920305
835174,920174
831039,920039
871642,920642
832566,920566
430090,920090
871553,920553
839946,920146
832885,920885
834765,920765
831768,920768
837212,920212
833523,920523
831726,920726
832225,920225
830832,920832
834599,920599
832735,920735
836239,920239
833427,920427
838275,920275
836826,920826
833509,920509
837344,920344
836675,920675
430510,920510
831856,920856
832000,920000
835670,920670
838030,920030
430047,920047
871396,920396
830839,920839
830964,920964
831961,920961
830946,920946
833819,920819
830799,920799
839729,920729
834682,920682
835640,920640
835508,920508
430489,920489
834475,920475
831445,920445
836433,920433
430418,920418
834415,920415
831370,920370
835368,920368
832278,920278
833266,920266
836263,920263
837242,920242
430198,920198
835185,920185
835184,920184
839167,920167
838163,920163
836149,920149
834021,920021
831010,920010
scripts/data_update_v2.py
@@ -34,6 +34,9 @@
)
logger = logging.getLogger(__name__)
BSE_CODE_SWITCH_DATE = '20251009'
BSE_LEGACY_END_DATE = '20251008'
def fetch_real_stock_data_from_akshare(n_stocks=500, days=365):
    """优先使用AKShare,失败时由BaoStock和腾讯行情共同兜底。"""
@@ -255,6 +258,27 @@
    return None
def load_bse_code_mapping(mapping_path=None):
    """加载北交所存量股票的新代码到旧代码映射。"""
    path = Path(mapping_path) if mapping_path else project_root / 'config' / 'bse_code_mapping.csv'
    try:
        mapping_df = pd.read_csv(path, dtype=str)
        return dict(zip(mapping_df['new_code'], mapping_df['old_code']))
    except Exception as e:
        logger.warning(f"⚠️ 北交所新旧代码映射加载失败: {e}")
        return {}
def tencent_bse_symbol_candidates(stock_code, code_mapping=None):
    """返回腾讯接口可尝试的北交所新旧代码。"""
    code = str(stock_code).strip().zfill(6)
    symbols = [f"bj{code}"]
    old_code = (code_mapping or {}).get(code)
    if old_code and old_code != code:
        symbols.append(f"bj{old_code}")
    return symbols
def normalize_external_stock_list(stock_list):
    """把AKShare股票列表标准化为BaoStock历史行情可用的字段。"""
    if stock_list is None or len(stock_list) == 0:
@@ -316,7 +340,7 @@
    return converted[columns]
def convert_tencent_history(df, stock_code, stock_name):
def convert_tencent_history(df, stock_code, stock_name, source_symbol=None):
    """将腾讯历史行情转换为现有数据字段格式。"""
    if df is None or len(df) == 0:
        return None
@@ -325,7 +349,7 @@
    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_api'] = source_symbol or 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'])
@@ -388,41 +412,78 @@
    end_date = datetime.now().strftime('%Y%m%d')
    start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y%m%d')
    code_mapping = load_bse_code_mapping()
    all_data = []
    for position, (_, row) in enumerate(selected.iterrows(), start=1):
        stock_code = row['代码']
        stock_name = row['名称']
        symbol = to_tencent_code(stock_code)
        symbols = tencent_bse_symbol_candidates(stock_code, code_mapping)
        symbol_frames = []
        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)} 条记录")
        logger.info(
            f"  [{position}/{len(selected)}] 获取 {stock_name}({stock_code})..."
        )
        for symbol_index, symbol in enumerate(symbols):
            if symbol_index > 0:
                logger.info(f"    ↪ 尝试旧代码 {symbol[2:]}")
            symbol_start_date = start_date
            symbol_end_date = end_date
            if len(symbols) > 1:
                if symbol_index == 0:
                    symbol_start_date = max(start_date, BSE_CODE_SWITCH_DATE)
                else:
                    logger.warning("    ⚠️ 无数据")
                break
            except Exception as e:
                logger.warning(f"    ⚠️ 腾讯行情获取失败: {e}")
                if attempt >= max_retries:
                    symbol_end_date = min(end_date, BSE_LEGACY_END_DATE)
            if symbol_start_date > symbol_end_date:
                continue
            for attempt in range(max_retries + 1):
                if attempt > 0:
                    logger.info(
                        f"    ↻ 重试 {attempt}/{max_retries}: "
                        f"{stock_name}({symbol})"
                    )
                try:
                    raw = ak.stock_zh_a_hist_tx(
                        symbol=symbol,
                        start_date=symbol_start_date,
                        end_date=symbol_end_date,
                        adjust="qfq",
                        timeout=socket_timeout,
                    )
                    df = convert_tencent_history(
                        raw,
                        stock_code,
                        stock_name,
                        source_symbol=symbol,
                    )
                    if df is not None and len(df) > 0:
                        symbol_frames.append(df)
                    else:
                        logger.info(f"    ℹ️ {symbol} 无数据")
                    break
                if retry_delay:
                    time.sleep(retry_delay)
                except KeyError as e:
                    if e.args == ('day',):
                        logger.info(f"    ℹ️ {symbol} 未返回日线数据")
                        break
                    logger.warning(f"    ⚠️ 腾讯行情解析失败: {e}")
                    break
                except Exception as e:
                    logger.warning(f"    ⚠️ 腾讯行情获取失败: {e}")
                    if attempt >= max_retries:
                        break
                    if retry_delay:
                        time.sleep(retry_delay)
        if symbol_frames:
            df = pd.concat(symbol_frames, ignore_index=True)
            df = df.drop_duplicates('date', keep='first').sort_values('date')
            df = calculate_technical_factors(df)
            all_data.append(df)
            logger.info(f"    ✓ 获取 {len(df)} 条记录")
        else:
            logger.warning("    ⚠️ 新旧代码均无数据")
        if request_delay:
            time.sleep(request_delay)
@@ -694,7 +755,26 @@
        type=int,
        help="历史数据天数;默认 365",
    )
    parser.add_argument(
        "--bse-only",
        action="store_true",
        help="仅更新北交所数据,并合并到已有数据文件",
    )
    return parser.parse_args(argv)
def merge_replacement_data(existing, replacement):
    """用本次成功下载的股票数据替换已有数据中的对应股票。"""
    if existing is None or len(existing) == 0:
        return replacement.copy()
    if replacement is None or len(replacement) == 0:
        return existing.copy()
    replacement_codes = set(replacement['stock_code'].astype(str))
    kept = existing[
        ~existing['stock_code'].astype(str).isin(replacement_codes)
    ]
    return pd.concat([kept, replacement], ignore_index=True)
def main(argv=None):
@@ -707,14 +787,42 @@
    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}只股票"
    stock_count_desc = "仅北交所" if args.bse_only else (
        "全部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)
    output_file = 'data/akshare_real_data_fixed.pkl'
    if args.bse_only:
        stock_list = fetch_stock_list_from_akshare(n_stocks=None)
        replacement = fetch_real_stock_data_from_tencent_bse(
            n_stocks=None,
            days=args.days,
            stock_list=stock_list,
        )
        if replacement is not None and len(replacement) > 0:
            existing = None
            if Path(output_file).exists():
                with open(output_file, 'rb') as f:
                    existing = pickle.load(f)
                logger.info(
                    f"✓ 已加载现有数据: {len(existing)} 条记录,"
                    f"{existing['stock_code'].nunique()} 只股票"
                )
            else:
                logger.warning("⚠️ 未找到现有数据文件,将只保存北交所数据")
            df = merge_replacement_data(existing, replacement)
            df.attrs['source'] = 'bse_tencent_incremental'
        else:
            df = None
    else:
        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)
        
@@ -726,8 +834,11 @@
        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),
            'description': '从AKShare/BaoStock/腾讯行情获取的真实A股数据',
            'requested_stock_count': (
                'bse_only' if args.bse_only
                else ('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)),
tests/test_data_update_v2.py
@@ -118,6 +118,12 @@
        self.assertIsNone(data_update_v2.parse_n_stocks("全部"))
        self.assertEqual(data_update_v2.parse_n_stocks("6000"), 6000)
    def test_parse_args_supports_bse_only(self):
        args = data_update_v2.parse_args(["--bse-only", "--days", "30"])
        self.assertTrue(args.bse_only)
        self.assertEqual(args.days, 30)
    def test_bse_codes_use_tencent_instead_of_baostock(self):
        self.assertIsNone(data_update_v2.to_baostock_code("920099"))
        self.assertIsNone(data_update_v2.to_baostock_code("830001"))
@@ -125,6 +131,19 @@
        self.assertEqual(data_update_v2.to_tencent_code("830001"), "bj830001")
        self.assertEqual(data_update_v2.to_baostock_code("600519"), "sh.600519")
        self.assertEqual(data_update_v2.to_baostock_code("000001"), "sz.000001")
    def test_load_bse_code_mapping_contains_bettery_old_code(self):
        mapping = data_update_v2.load_bse_code_mapping()
        self.assertEqual(mapping["920185"], "835185")
        self.assertEqual(len(mapping), 248)
    def test_tencent_bse_symbol_candidates_include_legacy_code(self):
        symbols = data_update_v2.tencent_bse_symbol_candidates(
            "920185", {"920185": "835185"}
        )
        self.assertEqual(symbols, ["bj920185", "bj835185"])
    def test_convert_tencent_history_matches_existing_schema(self):
        raw = pd.DataFrame(
@@ -157,6 +176,29 @@
        self.assertEqual(result.loc[0, "amount"], 2050000.0)
        self.assertAlmostEqual(result.loc[1, "change_pct"], (21.0 / 20.5 - 1) * 100)
        self.assertTrue(pd.isna(result.loc[0, "turnover"]))
    def test_merge_replacement_data_replaces_only_downloaded_stocks(self):
        existing = pd.DataFrame(
            [
                {"stock_code": "600519", "date": pd.Timestamp("2026-07-08"), "close": 1.0},
                {"stock_code": "920185", "date": pd.Timestamp("2026-07-08"), "close": 2.0},
                {"stock_code": "920187", "date": pd.Timestamp("2026-07-08"), "close": 3.0},
            ]
        )
        replacement = pd.DataFrame(
            [
                {"stock_code": "920185", "date": pd.Timestamp("2026-07-09"), "close": 4.0},
            ]
        )
        result = data_update_v2.merge_replacement_data(existing, replacement)
        self.assertEqual(
            set(result["stock_code"]), {"600519", "920185", "920187"}
        )
        self.assertEqual(
            result[result["stock_code"] == "920185"]["close"].tolist(), [4.0]
        )
    def test_tencent_bse_fetch_uses_bj_market_prefix(self):
        class FakeAkShare:
@@ -197,6 +239,93 @@
        self.assertEqual(fake_ak.symbols, ["bj920099"])
        self.assertEqual(result["stock_code"].unique().tolist(), ["920099"])
    def test_tencent_bse_fetch_falls_back_to_legacy_code_on_missing_day(self):
        class FakeAkShare:
            def __init__(self):
                self.symbols = []
            def stock_zh_a_hist_tx(self, **kwargs):
                symbol = kwargs["symbol"]
                self.symbols.append(symbol)
                if symbol == "bj920185":
                    raise KeyError("day")
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
        fake_ak = FakeAkShare()
        stock_list = pd.DataFrame([{"代码": "920185", "名称": "贝特瑞"}])
        with patch.dict(sys.modules, {"akshare": fake_ak}):
            with patch.object(
                data_update_v2,
                "load_bse_code_mapping",
                return_value={"920185": "835185"},
            ):
                result = data_update_v2.fetch_real_stock_data_from_tencent_bse(
                    stock_list=stock_list,
                    days=365,
                    max_retries=2,
                    retry_delay=0,
                    request_delay=0,
                )
        self.assertIsNotNone(result)
        self.assertEqual(fake_ak.symbols, ["bj920185", "bj835185"])
        self.assertEqual(result.loc[0, "stock_code"], "920185")
        self.assertEqual(result.loc[0, "stock_code_api"], "bj835185")
    def test_tencent_bse_fetch_splits_date_range_at_code_switch(self):
        class FakeAkShare:
            def __init__(self):
                self.calls = []
            def stock_zh_a_hist_tx(self, **kwargs):
                self.calls.append(kwargs)
                date = "2026-07-08" if kwargs["symbol"] == "bj920185" else "2025-10-08"
                return pd.DataFrame(
                    [
                        {
                            "date": date,
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
        fake_ak = FakeAkShare()
        stock_list = pd.DataFrame([{"代码": "920185", "名称": "贝特瑞"}])
        with patch.dict(sys.modules, {"akshare": fake_ak}):
            with patch.object(
                data_update_v2,
                "load_bse_code_mapping",
                return_value={"920185": "835185"},
            ):
                result = data_update_v2.fetch_real_stock_data_from_tencent_bse(
                    stock_list=stock_list,
                    days=365,
                    request_delay=0,
                )
        self.assertEqual(len(result), 2)
        self.assertEqual(fake_ak.calls[0]["symbol"], "bj920185")
        self.assertEqual(fake_ak.calls[0]["start_date"], "20251009")
        self.assertEqual(fake_ak.calls[1]["symbol"], "bj835185")
        self.assertEqual(fake_ak.calls[1]["end_date"], "20251008")
    def test_fetch_stock_list_from_akshare_all_keeps_full_list(self):
        stock_list = pd.DataFrame(
            [{"代码": f"{index:06d}", "名称": f"测试{index}"} for index in range(10)]