log
2026-07-09 1dd0c86d0fa658ed876b56846d3af57e20a4951a
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
#!/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
 
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,
    )
    if df is not None and len(df) > 0:
        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 code.startswith(('6', '9')):
        return f"sh.{code}"
    if code.startswith(('0', '2', '3')):
        return f"sz.{code}"
    if code.startswith(('4', '8')):
        return f"bj.{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 fetch_real_stock_data_from_baostock(n_stocks=500, days=365, stock_list=None):
    """从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
    try:
        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:
            stock_list = normalize_external_stock_list(stock_list)
            if stock_list is None or len(stock_list) == 0:
                logger.error("❌ AKShare股票列表无法转换为BaoStock代码")
                return None
 
            if n_stocks is not None:
                stock_list = stock_list.head(n_stocks)
            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']
 
            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':
                    logger.warning(f"    ⚠️ 获取失败: {result.error_msg}")
                    continue
 
                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("    ⚠️ 无数据")
 
            except Exception as e:
                logger.warning(f"    ⚠️ 获取失败: {e}")
                continue
 
        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}")
 
 
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())