log
2026-07-09 18469a98f3a661b8d33419be5992f2233203f19f
scripts/data_update_v2.py
@@ -19,11 +19,13 @@
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'),
        logging.FileHandler('logs/data_update_v3.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
@@ -31,6 +33,53 @@
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):
    """从AKShare获取真实股票历史数据"""
    logger.info("="*60)
    logger.info("从AKShare获取真实A股数据")
@@ -49,8 +98,7 @@
    
    try:
        logger.info("📥 获取A股股票列表...")
        stock_list = ak.stock_zh_a_spot_em()
        logger.info(f"✓ 获取到 {len(stock_list)} 只股票")
        stock_list = fetch_akshare_stock_list(ak)
        
        stock_list = stock_list.head(n_stocks)
        
@@ -100,6 +148,153 @@
    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):
@@ -153,8 +348,8 @@
        
        metadata = {
            'create_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'source': 'akshare_real',
            'description': '从AKShare获取的真实A股数据',
            '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()}"