log
2026-07-09 048ea1585b4e1b89ef1f547844869ef9a74accd8
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
#!/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
 
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。"""
    df = fetch_real_stock_data_from_akshare_only(n_stocks=n_stocks, days=days)
    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)
    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_real_stock_data_from_akshare_only(
    n_stocks=500,
    days=365,
    max_consecutive_failures=10,
):
    """从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:
        logger.info("📥 获取A股股票列表...")
        stock_list = fetch_akshare_stock_list(ak)
        
        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 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):
    """从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
 
        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()
        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):
            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 main():
    """主函数"""
    logger.info("="*60)
    logger.info("数据更新任务开始 - 使用真实数据源")
    logger.info("="*60)
    
    os.makedirs('logs', exist_ok=True)
    os.makedirs('data', exist_ok=True)
    
    df = fetch_real_stock_data_from_akshare(n_stocks=500, days=365)
    
    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股数据',
            '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())