log
2026-07-23 c9a0711438d32f33b65ffa29d8efd7aa37d61bdc
tests/test_data_update_v2.py
@@ -1,4 +1,5 @@
import importlib
import json
import sys
import unittest
from pathlib import Path
@@ -90,12 +91,63 @@
class DataUpdateV2BaoStockTests(unittest.TestCase):
    def test_stock_list_filter_excludes_st_and_delisting_names(self):
        stock_list = pd.DataFrame(
            [
                {"代码": "000001", "名称": "平安银行"},
                {"代码": "000002", "名称": "ST测试"},
                {"代码": "000003", "名称": "*ST示例"},
                {"代码": "000004", "名称": "S*ST样本"},
                {"代码": "000005", "名称": "测试退"},
                {"代码": "000006", "名称": "退市整理"},
            ]
        )
        result = data_update_v2.filter_eligible_stock_list(stock_list)
        self.assertEqual(
            result.to_dict("records"),
            [{"代码": "000001", "名称": "平安银行"}],
        )
        self.assertEqual(result.attrs["excluded_st_count"], 3)
        self.assertEqual(result.attrs["excluded_delisted_count"], 2)
        self.assertEqual(
            result.attrs["excluded_security_codes"],
            ["000002", "000003", "000004", "000005", "000006"],
        )
    def test_market_data_filter_uses_names_and_current_excluded_codes(self):
        market = pd.DataFrame(
            [
                {"stock_code": "000001", "stock_name": "平安银行"},
                {"stock_code": "000002", "stock_name": "ST测试"},
                {"stock_code": "000003", "stock_name": "历史正常名称"},
                {"stock_code": "000004", "stock_name": "退市整理"},
            ]
        )
        market.attrs["source"] = "fixture"
        result = data_update_v2.filter_ineligible_market_data(
            market,
            excluded_security_codes=["000003"],
        )
        self.assertEqual(result["stock_code"].tolist(), ["000001"])
        self.assertEqual(result.attrs["source"], "fixture")
        self.assertEqual(result.attrs["removed_ineligible_record_count"], 3)
        self.assertEqual(
            result.attrs["removed_ineligible_stock_codes"],
            ["000002", "000003", "000004"],
        )
    def test_fetch_akshare_stock_list_prefers_exchange_code_name_api(self):
        class FakeAkShare:
            def stock_info_a_code_name(self):
                return pd.DataFrame(
                    [
                        {"code": "000001", "name": "平安银行"},
                        {"code": "000002", "name": "ST测试"},
                        {"code": "000003", "name": "测试退"},
                        {"code": "600519", "name": "贵州茅台"},
                    ]
                )
@@ -117,6 +169,269 @@
        self.assertIsNone(data_update_v2.parse_n_stocks("all"))
        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"))
        self.assertEqual(data_update_v2.to_tencent_code("920099"), "bj920099")
        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(
            [
                {
                    "date": "2026-07-07",
                    "open": 20.0,
                    "close": 20.5,
                    "high": 20.8,
                    "low": 19.8,
                    "amount": 1000.0,
                },
                {
                    "date": "2026-07-08",
                    "open": 20.6,
                    "close": 21.0,
                    "high": 21.2,
                    "low": 20.4,
                    "amount": 1200.0,
                },
            ]
        )
        result = data_update_v2.convert_tencent_history(
            raw, stock_code="920099", stock_name="测试北交所"
        )
        self.assertEqual(result.loc[0, "stock_code_api"], "bj920099")
        self.assertEqual(result.loc[0, "volume"], 1000.0)
        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_fetch_tencent_history_raw_accepts_day_and_qfqday(self):
        row = ["2026-07-09", "20.0", "20.5", "20.8", "19.8", "1000"]
        class FakeResponse:
            def __init__(self, payload):
                self.text = "kline=" + json.dumps(payload)
            def raise_for_status(self):
                return None
        for data_key in ("day", "qfqday"):
            def fake_get(url, params, timeout, key=data_key):
                payload = {"data": {"bj920187": {key: [row]}}}
                return FakeResponse(payload)
            with self.subTest(data_key=data_key):
                result = data_update_v2.fetch_tencent_history_raw(
                    symbol="bj920187",
                    start_date="20260701",
                    end_date="20260710",
                    request_get=fake_get,
                )
                self.assertEqual(len(result), 1)
                self.assertEqual(result.loc[0, "date"], pd.Timestamp("2026-07-09"))
                self.assertEqual(result.loc[0, "close"], 20.5)
    def test_fetch_tencent_history_raw_returns_empty_for_unknown_code(self):
        class FakeResponse:
            text = 'kline={"data":{"bj999999":{"day":[]}}}'
            def raise_for_status(self):
                return None
        result = data_update_v2.fetch_tencent_history_raw(
            symbol="bj999999",
            start_date="20260701",
            end_date="20260710",
            request_get=lambda *args, **kwargs: FakeResponse(),
        )
        self.assertTrue(result.empty)
    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 FakeFetcher:
            def __init__(self):
                self.symbols = []
            def __call__(self, **kwargs):
                self.symbols.append(kwargs["symbol"])
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
        fake_fetch = FakeFetcher()
        stock_list = pd.DataFrame(
            [
                {"代码": "600519", "名称": "贵州茅台"},
                {"代码": "920099", "名称": "瑞华技术"},
            ]
        )
        with patch.object(
            data_update_v2,
            "fetch_tencent_history_raw",
            side_effect=fake_fetch,
        ):
            result = data_update_v2.fetch_real_stock_data_from_tencent_bse(
                stock_list=stock_list,
                days=10,
                request_delay=0,
            )
        self.assertIsNotNone(result)
        self.assertEqual(fake_fetch.symbols, ["bj920099"])
        self.assertEqual(result["stock_code"].unique().tolist(), ["920099"])
    def test_tencent_bse_fetch_falls_back_to_legacy_code_on_empty_new_code(self):
        class FakeFetcher:
            def __init__(self):
                self.symbols = []
            def __call__(self, **kwargs):
                symbol = kwargs["symbol"]
                self.symbols.append(symbol)
                if symbol == "bj920185":
                    return pd.DataFrame()
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
        fake_fetch = FakeFetcher()
        stock_list = pd.DataFrame([{"代码": "920185", "名称": "贝特瑞"}])
        with patch.object(
            data_update_v2,
            "fetch_tencent_history_raw",
            side_effect=fake_fetch,
        ):
            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_fetch.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 FakeFetcher:
            def __init__(self):
                self.calls = []
            def __call__(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_fetch = FakeFetcher()
        stock_list = pd.DataFrame([{"代码": "920185", "名称": "贝特瑞"}])
        with patch.object(
            data_update_v2,
            "fetch_tencent_history_raw",
            side_effect=fake_fetch,
        ):
            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_fetch.calls[0]["symbol"], "bj920185")
        self.assertEqual(fake_fetch.calls[0]["start_date"], "20251009")
        self.assertEqual(fake_fetch.calls[1]["symbol"], "bj835185")
        self.assertEqual(fake_fetch.calls[1]["end_date"], "20251008")
    def test_fetch_stock_list_from_akshare_all_keeps_full_list(self):
        stock_list = pd.DataFrame(
@@ -222,6 +537,62 @@
        self.assertIn("ma5", result.columns)
        self.assertTrue(fake_bs.logged_out)
    def test_fallback_merges_baostock_and_tencent_bse_rows(self):
        class FakeTencentFetcher:
            def __init__(self):
                self.symbols = []
            def __call__(self, **kwargs):
                self.symbols.append(kwargs["symbol"])
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
        fake_bs = FakeBaoStock()
        fake_tencent = FakeTencentFetcher()
        stock_list = pd.DataFrame(
            [
                {"代码": "600519", "名称": "贵州茅台"},
                {"代码": "920099", "名称": "瑞华技术"},
            ]
        )
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with patch.object(
                data_update_v2,
                "fetch_stock_list_from_akshare",
                return_value=stock_list,
            ):
                with patch.object(
                    data_update_v2,
                    "fetch_real_stock_data_from_akshare_only",
                    return_value=None,
                ):
                    with patch.object(
                        data_update_v2,
                        "fetch_tencent_history_raw",
                        side_effect=fake_tencent,
                    ):
                        result = data_update_v2.fetch_real_stock_data_from_akshare(
                            n_stocks=None, days=10
                        )
        self.assertEqual(fake_bs.history_codes, ["sh.600519"])
        self.assertEqual(fake_tencent.symbols, ["bj920099"])
        self.assertEqual(
            set(result["stock_code"].unique()), {"600519", "920099"}
        )
        self.assertEqual(result.attrs["source"], "baostock_tencent_real")
    def test_fetch_baostock_can_use_akshare_stock_list(self):
        fake_bs = FakeBaoStock()
        stock_list = pd.DataFrame(
@@ -253,9 +624,9 @@
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with patch.object(
                data_update_v2,
                "fetch_real_stock_data_from_akshare_only",
                return_value=None,
                data_update_v2, "fetch_stock_list_from_akshare", return_value=None
            ), patch.object(
                data_update_v2, "fetch_real_stock_data_from_akshare_only", return_value=None
            ):
                result = data_update_v2.fetch_real_stock_data_from_akshare(
                    n_stocks=1, days=10