log
2026-07-09 ea0033a548df503ed07ffbed024a66b9758fafed
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
import importlib
import sys
import unittest
from pathlib import Path
from unittest.mock import patch
 
import pandas as pd
 
 
PROJECT_ROOT = Path(__file__).resolve().parents[1]
(PROJECT_ROOT / "logs").mkdir(exist_ok=True)
sys.path.insert(0, str(PROJECT_ROOT / "scripts"))
 
data_update_v2 = importlib.import_module("data_update_v2")
 
 
class FakeBaoStockResult:
    def __init__(self, data):
        self.error_code = "0"
        self.error_msg = "success"
        self.fields = list(data.columns)
        self._rows = data.values.tolist()
        self._index = -1
 
    def get_data(self):
        raise AssertionError("fallback should iterate BaoStock rows without get_data()")
 
    def next(self):
        self._index += 1
        return self._index < len(self._rows)
 
    def get_row_data(self):
        return self._rows[self._index]
 
 
class FakeBaoStock:
    def __init__(self):
        self.logged_out = False
 
    def login(self):
        return type("LoginResult", (), {"error_code": "0", "error_msg": "success"})()
 
    def logout(self):
        self.logged_out = True
 
    def query_stock_basic(self):
        return FakeBaoStockResult(
            pd.DataFrame(
                [
                    {
                        "code": "sh.600519",
                        "code_name": "贵州茅台",
                        "ipoDate": "2001-08-27",
                        "outDate": "",
                        "type": "1",
                        "status": "1",
                    }
                ]
            )
        )
 
    def query_history_k_data_plus(
        self, code, fields, start_date, end_date, frequency, adjustflag
    ):
        return FakeBaoStockResult(
            pd.DataFrame(
                [
                    {
                        "date": "2026-07-08",
                        "code": code,
                        "open": "1500.0",
                        "high": "1510.0",
                        "low": "1495.0",
                        "close": "1508.0",
                        "preclose": "1490.0",
                        "volume": "10000",
                        "amount": "15080000",
                        "turn": "0.12",
                        "pctChg": "1.20",
                    }
                ]
            )
        )
 
 
class DataUpdateV2BaoStockTests(unittest.TestCase):
    def test_convert_baostock_history_matches_existing_schema(self):
        raw = pd.DataFrame(
            [
                {
                    "date": "2026-07-08",
                    "code": "sh.600519",
                    "open": "1500.0",
                    "high": "1510.0",
                    "low": "1495.0",
                    "close": "1508.0",
                    "preclose": "1490.0",
                    "volume": "10000",
                    "amount": "15080000",
                    "turn": "0.12",
                    "pctChg": "1.20",
                }
            ]
        )
 
        result = data_update_v2.convert_baostock_history(
            raw, stock_code="600519", stock_name="贵州茅台"
        )
 
        self.assertEqual(result.loc[0, "stock_code"], "600519")
        self.assertEqual(result.loc[0, "stock_name"], "贵州茅台")
        self.assertEqual(result.loc[0, "stock_code_api"], "sh.600519")
        self.assertEqual(float(result.loc[0, "change_pct"]), 1.20)
        self.assertEqual(float(result.loc[0, "turnover"]), 0.12)
        self.assertTrue(pd.api.types.is_datetime64_any_dtype(result["date"]))
        for col in ["open", "close", "high", "low", "volume", "amount"]:
            self.assertTrue(pd.api.types.is_numeric_dtype(result[col]))
 
    def test_fetch_uses_baostock_when_akshare_returns_no_rows(self):
        fake_bs = FakeBaoStock()
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with 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
                )
 
        self.assertIsNotNone(result)
        self.assertEqual(result["stock_code"].unique().tolist(), ["600519"])
        self.assertIn("ma5", result.columns)
        self.assertTrue(fake_bs.logged_out)
 
    def test_baostock_result_to_dataframe_uses_iterator_api(self):
        raw = pd.DataFrame([{"code": "sh.600519", "code_name": "贵州茅台"}])
 
        result = data_update_v2.baostock_result_to_dataframe(FakeBaoStockResult(raw))
 
        self.assertEqual(result.to_dict("records"), raw.to_dict("records"))
 
 
if __name__ == "__main__":
    unittest.main()