| | |
| | | import pickle |
| | | import json |
| | | import argparse |
| | | import re |
| | | import time |
| | | import socket |
| | | import requests |
| | |
| | | |
| | | BSE_CODE_SWITCH_DATE = '20251009' |
| | | BSE_LEGACY_END_DATE = '20251008' |
| | | STOCK_FILTER_ATTR_KEYS = ( |
| | | 'eligible_stock_count', |
| | | 'excluded_stock_count', |
| | | 'excluded_st_count', |
| | | 'excluded_delisted_count', |
| | | 'excluded_security_codes', |
| | | ) |
| | | |
| | | |
| | | def classify_ineligible_stock_name(stock_name): |
| | | """Return the exclusion reason for ST or delisting-marked A-share names.""" |
| | | normalized = re.sub(r'\s+', '', str(stock_name or '')).upper() |
| | | if '退' in normalized: |
| | | return 'delisted' |
| | | if re.match(r'^(?:S\*ST|SST|\*ST|ST)', normalized): |
| | | return 'st' |
| | | return None |
| | | |
| | | |
| | | def filter_eligible_stock_list(stock_list, code_column='代码', name_column='名称'): |
| | | """Filter ST and delisting names before any per-stock history request.""" |
| | | if stock_list is None or len(stock_list) == 0: |
| | | return stock_list |
| | | if code_column not in stock_list.columns or name_column not in stock_list.columns: |
| | | raise ValueError( |
| | | f"股票列表缺少过滤字段: {code_column}/{name_column}" |
| | | ) |
| | | |
| | | working = stock_list.copy() |
| | | reasons = working[name_column].map(classify_ineligible_stock_name) |
| | | excluded = working.loc[reasons.notna()].copy() |
| | | excluded_reasons = reasons.loc[reasons.notna()] |
| | | eligible = working.loc[reasons.isna()].copy().reset_index(drop=True) |
| | | excluded_codes = sorted({ |
| | | str(code).strip().split('.')[-1].zfill(6) |
| | | for code in excluded[code_column].tolist() |
| | | }) |
| | | eligible.attrs.update({ |
| | | 'eligible_stock_count': int(len(eligible)), |
| | | 'excluded_stock_count': int(len(excluded)), |
| | | 'excluded_st_count': int((excluded_reasons == 'st').sum()), |
| | | 'excluded_delisted_count': int((excluded_reasons == 'delisted').sum()), |
| | | 'excluded_security_codes': excluded_codes, |
| | | }) |
| | | if len(excluded) > 0: |
| | | logger.info( |
| | | "ℹ️ 股票池过滤 ST %d 只、退市标记 %d 只,剩余 %d 只", |
| | | eligible.attrs['excluded_st_count'], |
| | | eligible.attrs['excluded_delisted_count'], |
| | | len(eligible), |
| | | ) |
| | | return eligible |
| | | |
| | | |
| | | def copy_stock_filter_evidence(target, stock_list): |
| | | """Bind stock-universe filtering evidence to the downloaded market frame.""" |
| | | if target is None or stock_list is None: |
| | | return target |
| | | for key in STOCK_FILTER_ATTR_KEYS: |
| | | if key in stock_list.attrs: |
| | | target.attrs[key] = stock_list.attrs[key] |
| | | return target |
| | | |
| | | |
| | | def filter_ineligible_market_data(market_data, excluded_security_codes=None): |
| | | """Remove marked names and explicitly excluded current-universe codes.""" |
| | | if market_data is None or len(market_data) == 0: |
| | | return market_data |
| | | |
| | | filtered = market_data.copy() |
| | | original_attrs = dict(getattr(market_data, 'attrs', {})) |
| | | excluded_codes = { |
| | | str(code).strip().split('.')[-1].zfill(6) |
| | | for code in (excluded_security_codes or []) |
| | | } |
| | | mask = pd.Series(False, index=filtered.index) |
| | | if 'stock_name' in filtered.columns: |
| | | mask |= filtered['stock_name'].map( |
| | | classify_ineligible_stock_name |
| | | ).notna() |
| | | if excluded_codes and 'stock_code' in filtered.columns: |
| | | normalized_codes = ( |
| | | filtered['stock_code'].astype(str).str.strip().str.zfill(6) |
| | | ) |
| | | mask |= normalized_codes.isin(excluded_codes) |
| | | |
| | | removed_codes = [] |
| | | if mask.any() and 'stock_code' in filtered.columns: |
| | | removed_codes = sorted( |
| | | filtered.loc[mask, 'stock_code'].astype(str).str.zfill(6).unique() |
| | | ) |
| | | filtered = filtered.loc[~mask].copy().reset_index(drop=True) |
| | | filtered.attrs.update(original_attrs) |
| | | filtered.attrs['removed_ineligible_record_count'] = int(mask.sum()) |
| | | filtered.attrs['removed_ineligible_stock_codes'] = removed_codes |
| | | return filtered |
| | | |
| | | |
| | | def fetch_real_stock_data_from_akshare(n_stocks=500, days=365): |
| | |
| | | stock_list=stock_list, |
| | | ) |
| | | if df is not None and len(df) > 0: |
| | | df = filter_ineligible_market_data( |
| | | df, |
| | | stock_list.attrs.get('excluded_security_codes', []) |
| | | if stock_list is not None else [], |
| | | ) |
| | | if len(df) > 0: |
| | | copy_stock_filter_evidence(df, stock_list) |
| | | df.attrs['source'] = 'akshare_real' |
| | | return df |
| | | logger.warning("⚠️ AKShare结果仅包含 ST/退市股票,尝试备用数据源") |
| | | |
| | | logger.warning("⚠️ AKShare未获取到有效数据,尝试切换到备用数据源") |
| | | baostock_df = fetch_real_stock_data_from_baostock( |
| | |
| | | return None |
| | | |
| | | df = pd.concat(frames, ignore_index=True) |
| | | df = filter_ineligible_market_data( |
| | | df, |
| | | stock_list.attrs.get('excluded_security_codes', []) |
| | | if stock_list is not None else [], |
| | | ) |
| | | copy_stock_filter_evidence(df, stock_list) |
| | | if baostock_df is not None and tencent_df is not None: |
| | | df.attrs['source'] = 'baostock_tencent_real' |
| | | elif tencent_df is not None: |
| | |
| | | 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)} 只股票") |
| | | stock_list = filter_eligible_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[['代码', '名称']] |
| | | stock_list = filter_eligible_stock_list(stock_list[['代码', '名称']]) |
| | | logger.info(f"✓ 从东方财富实时列表获取到 {len(stock_list)} 只可用股票") |
| | | return stock_list |
| | | except Exception as e: |
| | | logger.warning(f"⚠️ 无法获取完整股票列表,可能是东方财富接口限制: {e}") |
| | | logger.info("ℹ️ 启用备用精选股票池...") |
| | | return fallback_stock_pool() |
| | | return filter_eligible_stock_list(fallback_stock_pool()) |
| | | |
| | | |
| | | def fetch_stock_list_from_akshare(n_stocks=None): |
| | |
| | | if '代码' not in normalized.columns or '名称' not in normalized.columns: |
| | | return None |
| | | |
| | | normalized = filter_eligible_stock_list(normalized) |
| | | 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', '代码', '名称']] |
| | | result = normalized[['bs_code', '代码', '名称']].copy() |
| | | result.attrs.update(normalized.attrs) |
| | | return result |
| | | |
| | | |
| | | def baostock_result_to_dataframe(result): |
| | |
| | | if stock_list is None or len(stock_list) == 0: |
| | | return None |
| | | |
| | | selected = stock_list.copy() |
| | | selected = filter_eligible_stock_list(stock_list) |
| | | if n_stocks is not None: |
| | | selected = selected.head(n_stocks) |
| | | selected = selected.head(n_stocks).copy() |
| | | selected['代码'] = selected['代码'].astype(str).str.strip().str.zfill(6) |
| | | selected = selected[selected['代码'].map(is_bse_stock_code)] |
| | | if len(selected) == 0: |
| | |
| | | return None |
| | | |
| | | combined = pd.concat(all_data, ignore_index=True) |
| | | copy_stock_filter_evidence(combined, selected) |
| | | logger.info( |
| | | f"\n✓ 腾讯北交所总计获取 {len(combined)} 条记录," |
| | | f"{combined['stock_code'].nunique()} 只股票" |
| | |
| | | |
| | | use_external_stock_list = stock_list is not None |
| | | if use_external_stock_list: |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks) |
| | | external_stock_count = len(stock_list) |
| | | stock_list = normalize_external_stock_list(stock_list) |
| | | if stock_list is None or len(stock_list) == 0: |
| | | logger.info("ℹ️ 股票列表中没有BaoStock支持的沪深股票") |
| | | return None |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks).copy() |
| | | |
| | | skipped_count = external_stock_count - len(stock_list) |
| | | if skipped_count > 0: |
| | |
| | | (stock_list['type'].astype(str) == '1') & |
| | | (stock_list['status'].astype(str) == '1') |
| | | ].copy() |
| | | stock_list = filter_eligible_stock_list( |
| | | stock_list, |
| | | code_column='code', |
| | | name_column='code_name', |
| | | ) |
| | | if n_stocks is not None: |
| | | stock_list = stock_list.head(n_stocks) |
| | | stock_list = stock_list.head(n_stocks).copy() |
| | | logger.info(f"✓ BaoStock股票池数量: {len(stock_list)}") |
| | | |
| | | fields = "date,code,open,high,low,close,preclose,volume,amount,turn,pctChg" |
| | |
| | | |
| | | if all_data: |
| | | combined = pd.concat(all_data, ignore_index=True) |
| | | copy_stock_filter_evidence(combined, stock_list) |
| | | logger.info(f"\n✓ BaoStock总计获取 {len(combined)} 条记录,{combined['stock_code'].nunique()} 只股票") |
| | | return combined |
| | | |
| | |
| | | ) |
| | | |
| | | if df is not None and len(df) > 0: |
| | | df = filter_ineligible_market_data( |
| | | df, |
| | | df.attrs.get('excluded_security_codes', []), |
| | | ) |
| | | if len(df) == 0: |
| | | logger.error("❌ 过滤 ST/退市股票后无有效数据") |
| | | return 1 |
| | | with open(output_file, 'wb') as f: |
| | | pickle.dump(df, f) |
| | | |