| | |
| | | import argparse |
| | | import time |
| | | import socket |
| | | import requests |
| | | |
| | | os.makedirs('logs', exist_ok=True) |
| | | |
| | |
| | | ] |
| | | ) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | BSE_CODE_SWITCH_DATE = '20251009' |
| | | BSE_LEGACY_END_DATE = '20251008' |
| | | |
| | | |
| | | def fetch_real_stock_data_from_akshare(n_stocks=500, days=365): |
| | |
| | | return None |
| | | |
| | | |
| | | def load_bse_code_mapping(mapping_path=None): |
| | | """加载北交所存量股票的新代码到旧代码映射。""" |
| | | path = Path(mapping_path) if mapping_path else project_root / 'config' / 'bse_code_mapping.csv' |
| | | try: |
| | | mapping_df = pd.read_csv(path, dtype=str) |
| | | return dict(zip(mapping_df['new_code'], mapping_df['old_code'])) |
| | | except Exception as e: |
| | | logger.warning(f"⚠️ 北交所新旧代码映射加载失败: {e}") |
| | | return {} |
| | | |
| | | |
| | | def tencent_bse_symbol_candidates(stock_code, code_mapping=None): |
| | | """返回腾讯接口可尝试的北交所新旧代码。""" |
| | | code = str(stock_code).strip().zfill(6) |
| | | symbols = [f"bj{code}"] |
| | | old_code = (code_mapping or {}).get(code) |
| | | if old_code and old_code != code: |
| | | symbols.append(f"bj{old_code}") |
| | | return symbols |
| | | |
| | | |
| | | def normalize_external_stock_list(stock_list): |
| | | """把AKShare股票列表标准化为BaoStock历史行情可用的字段。""" |
| | | if stock_list is None or len(stock_list) == 0: |
| | |
| | | return converted[columns] |
| | | |
| | | |
| | | def convert_tencent_history(df, stock_code, stock_name): |
| | | def fetch_tencent_history_raw( |
| | | symbol, |
| | | start_date, |
| | | end_date, |
| | | adjust='qfq', |
| | | timeout=30, |
| | | request_get=None, |
| | | ): |
| | | """直接读取腾讯日线接口,同时兼容 day/qfqday/hfqday。""" |
| | | request_get = request_get or requests.get |
| | | start_text = str(start_date).replace('-', '') |
| | | end_text = str(end_date).replace('-', '') |
| | | start_ts = pd.Timestamp(start_text) |
| | | end_ts = pd.Timestamp(end_text) |
| | | url = "https://proxy.finance.qq.com/ifzqgtimg/appstock/app/newfqkline/get" |
| | | frames = [] |
| | | |
| | | for year in range(start_ts.year, end_ts.year + 1): |
| | | range_start = max(start_ts, pd.Timestamp(year=year, month=1, day=1)) |
| | | range_end = min(end_ts, pd.Timestamp(year=year, month=12, day=31)) |
| | | params = { |
| | | "_var": f"kline_day{adjust}{year}", |
| | | "param": ( |
| | | f"{symbol},day,{range_start:%Y-%m-%d}," |
| | | f"{range_end:%Y-%m-%d},640,{adjust}" |
| | | ), |
| | | "r": "0.8205512681390605", |
| | | } |
| | | response = request_get(url, params=params, timeout=timeout) |
| | | if hasattr(response, 'raise_for_status'): |
| | | response.raise_for_status() |
| | | |
| | | data_text = response.text |
| | | json_start = data_text.find('{') |
| | | if json_start < 0: |
| | | continue |
| | | payload = json.loads(data_text[json_start:]) |
| | | symbol_data = payload.get('data', {}).get(symbol, {}) |
| | | |
| | | preferred_keys = [ |
| | | f"{adjust}day" if adjust else "day", |
| | | "day", |
| | | "qfqday", |
| | | "hfqday", |
| | | ] |
| | | rows = [] |
| | | for key in dict.fromkeys(preferred_keys): |
| | | if symbol_data.get(key): |
| | | rows = symbol_data[key] |
| | | break |
| | | if rows: |
| | | frames.append(pd.DataFrame(rows).iloc[:, :6]) |
| | | |
| | | columns = ['date', 'open', 'close', 'high', 'low', 'amount'] |
| | | if not frames: |
| | | return pd.DataFrame(columns=columns) |
| | | |
| | | result = pd.concat(frames, ignore_index=True) |
| | | result.columns = columns |
| | | result['date'] = pd.to_datetime(result['date'], errors='coerce') |
| | | for col in columns[1:]: |
| | | result[col] = pd.to_numeric(result[col], errors='coerce') |
| | | result = result[ |
| | | result['date'].between(start_ts, end_ts, inclusive='both') |
| | | ] |
| | | result = result.drop_duplicates('date').sort_values('date') |
| | | return result.reset_index(drop=True) |
| | | |
| | | |
| | | def convert_tencent_history(df, stock_code, stock_name, source_symbol=None): |
| | | """将腾讯历史行情转换为现有数据字段格式。""" |
| | | if df is None or len(df) == 0: |
| | | return None |
| | |
| | | for col in ['open', 'high', 'low', 'close', 'amount']: |
| | | converted[col] = pd.to_numeric(converted[col], errors='coerce') |
| | | |
| | | converted['stock_code_api'] = to_tencent_code(stock_code) |
| | | converted['stock_code_api'] = source_symbol or to_tencent_code(stock_code) |
| | | converted['stock_code'] = str(stock_code).zfill(6) |
| | | converted['stock_name'] = stock_name |
| | | converted['date'] = pd.to_datetime(converted['date']) |
| | |
| | | request_delay=0.1, |
| | | socket_timeout=30, |
| | | ): |
| | | """通过AKShare腾讯接口补齐BaoStock不支持的北交所历史行情。""" |
| | | """通过腾讯接口补齐BaoStock不支持的北交所历史行情。""" |
| | | if stock_list is None or len(stock_list) == 0: |
| | | return None |
| | | |
| | |
| | | if len(selected) == 0: |
| | | return None |
| | | |
| | | try: |
| | | import akshare as ak |
| | | logger.info("="*60) |
| | | logger.info("从腾讯行情获取北交所历史数据") |
| | | logger.info("="*60) |
| | | logger.info(f"✓ 待获取北交所股票: {len(selected)} 只") |
| | | except ImportError: |
| | | logger.error("❌ AKShare未安装,无法调用腾讯北交所行情接口") |
| | | return None |
| | | logger.info("="*60) |
| | | logger.info("从腾讯行情获取北交所历史数据") |
| | | logger.info("="*60) |
| | | logger.info(f"✓ 待获取北交所股票: {len(selected)} 只") |
| | | |
| | | end_date = datetime.now().strftime('%Y%m%d') |
| | | start_date = (datetime.now() - timedelta(days=days*2)).strftime('%Y%m%d') |
| | | code_mapping = load_bse_code_mapping() |
| | | all_data = [] |
| | | |
| | | for position, (_, row) in enumerate(selected.iterrows(), start=1): |
| | | stock_code = row['代码'] |
| | | stock_name = row['名称'] |
| | | symbol = to_tencent_code(stock_code) |
| | | symbols = tencent_bse_symbol_candidates(stock_code, code_mapping) |
| | | symbol_frames = [] |
| | | |
| | | for attempt in range(max_retries + 1): |
| | | if attempt > 0: |
| | | logger.info(f" ↻ 重试 {attempt}/{max_retries}: {stock_name}({stock_code})") |
| | | try: |
| | | logger.info( |
| | | f" [{position}/{len(selected)}] 获取 {stock_name}({stock_code})..." |
| | | ) |
| | | raw = ak.stock_zh_a_hist_tx( |
| | | symbol=symbol, |
| | | start_date=start_date, |
| | | end_date=end_date, |
| | | adjust="qfq", |
| | | timeout=socket_timeout, |
| | | ) |
| | | df = convert_tencent_history(raw, 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)} 条记录") |
| | | logger.info( |
| | | f" [{position}/{len(selected)}] 获取 {stock_name}({stock_code})..." |
| | | ) |
| | | for symbol_index, symbol in enumerate(symbols): |
| | | if symbol_index > 0: |
| | | logger.info(f" ↪ 尝试旧代码 {symbol[2:]}") |
| | | |
| | | symbol_start_date = start_date |
| | | symbol_end_date = end_date |
| | | if len(symbols) > 1: |
| | | if symbol_index == 0: |
| | | symbol_start_date = max(start_date, BSE_CODE_SWITCH_DATE) |
| | | else: |
| | | logger.warning(" ⚠️ 无数据") |
| | | break |
| | | except Exception as e: |
| | | logger.warning(f" ⚠️ 腾讯行情获取失败: {e}") |
| | | if attempt >= max_retries: |
| | | symbol_end_date = min(end_date, BSE_LEGACY_END_DATE) |
| | | if symbol_start_date > symbol_end_date: |
| | | continue |
| | | |
| | | for attempt in range(max_retries + 1): |
| | | if attempt > 0: |
| | | logger.info( |
| | | f" ↻ 重试 {attempt}/{max_retries}: " |
| | | f"{stock_name}({symbol})" |
| | | ) |
| | | try: |
| | | raw = fetch_tencent_history_raw( |
| | | symbol=symbol, |
| | | start_date=symbol_start_date, |
| | | end_date=symbol_end_date, |
| | | adjust="qfq", |
| | | timeout=socket_timeout, |
| | | ) |
| | | df = convert_tencent_history( |
| | | raw, |
| | | stock_code, |
| | | stock_name, |
| | | source_symbol=symbol, |
| | | ) |
| | | if df is not None and len(df) > 0: |
| | | symbol_frames.append(df) |
| | | else: |
| | | logger.info(f" ℹ️ {symbol} 无数据") |
| | | break |
| | | if retry_delay: |
| | | time.sleep(retry_delay) |
| | | except Exception as e: |
| | | logger.warning(f" ⚠️ 腾讯行情获取失败: {e}") |
| | | if attempt >= max_retries: |
| | | break |
| | | if retry_delay: |
| | | time.sleep(retry_delay) |
| | | |
| | | if symbol_frames: |
| | | df = pd.concat(symbol_frames, ignore_index=True) |
| | | df = df.drop_duplicates('date', keep='first').sort_values('date') |
| | | df = calculate_technical_factors(df) |
| | | all_data.append(df) |
| | | logger.info(f" ✓ 获取 {len(df)} 条记录") |
| | | else: |
| | | logger.warning(" ⚠️ 新旧代码均无数据") |
| | | |
| | | if request_delay: |
| | | time.sleep(request_delay) |
| | |
| | | type=int, |
| | | help="历史数据天数;默认 365", |
| | | ) |
| | | parser.add_argument( |
| | | "--bse-only", |
| | | action="store_true", |
| | | help="仅更新北交所数据,并合并到已有数据文件", |
| | | ) |
| | | return parser.parse_args(argv) |
| | | |
| | | |
| | | def merge_replacement_data(existing, replacement): |
| | | """用本次成功下载的股票数据替换已有数据中的对应股票。""" |
| | | if existing is None or len(existing) == 0: |
| | | return replacement.copy() |
| | | if replacement is None or len(replacement) == 0: |
| | | return existing.copy() |
| | | |
| | | replacement_codes = set(replacement['stock_code'].astype(str)) |
| | | kept = existing[ |
| | | ~existing['stock_code'].astype(str).isin(replacement_codes) |
| | | ] |
| | | return pd.concat([kept, replacement], ignore_index=True) |
| | | |
| | | |
| | | def main(argv=None): |
| | |
| | | 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}只股票" |
| | | stock_count_desc = "仅北交所" if args.bse_only else ( |
| | | "全部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) |
| | | output_file = 'data/akshare_real_data_fixed.pkl' |
| | | if args.bse_only: |
| | | stock_list = fetch_stock_list_from_akshare(n_stocks=None) |
| | | replacement = fetch_real_stock_data_from_tencent_bse( |
| | | n_stocks=None, |
| | | days=args.days, |
| | | stock_list=stock_list, |
| | | ) |
| | | if replacement is not None and len(replacement) > 0: |
| | | existing = None |
| | | if Path(output_file).exists(): |
| | | with open(output_file, 'rb') as f: |
| | | existing = pickle.load(f) |
| | | logger.info( |
| | | f"✓ 已加载现有数据: {len(existing)} 条记录," |
| | | f"{existing['stock_code'].nunique()} 只股票" |
| | | ) |
| | | else: |
| | | logger.warning("⚠️ 未找到现有数据文件,将只保存北交所数据") |
| | | |
| | | df = merge_replacement_data(existing, replacement) |
| | | df.attrs['source'] = 'bse_tencent_incremental' |
| | | else: |
| | | df = None |
| | | else: |
| | | 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) |
| | | |
| | |
| | | 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), |
| | | 'description': '从AKShare/BaoStock/腾讯行情获取的真实A股数据', |
| | | 'requested_stock_count': ( |
| | | 'bse_only' if args.bse_only |
| | | else ('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)), |