# -*- coding: utf-8 -*- """ 多数据源适配器 - 腾讯财经主 + 新浪备 + 东方财富财务 + 超时保护 ================================================================ 全部HTTP API,无状态无连接,不会阻塞Flask主线程 数据源: - K线数据: 腾讯财经 (web.ifzq.gtimg.cn) - 财务数据: 东方财富 (push2.eastmoney.com) - 备用K线: 新浪财经 (money.finance.sina.com.cn) """ import urllib.request import json import time import pandas as pd import numpy as np import threading from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeout class DataSourceAdapter: """多数据源适配器 - 纯HTTP API,纯HTTP API无外部依赖""" def __init__(self, timeout=15): self.timeout = timeout self._headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', } # ============================================================ # 腾讯财经 (主K线数据源) # ============================================================ def _fetch_tencent_kline(self, code, start_date='2019-01-01', end_date='2026-05-31'): """腾讯财经API - 日K线(前复权)""" # 确保带市场前缀: 600519 -> sh600519, 000001 -> sz000001, 300001 -> sz300001 if not code.startswith(('sh', 'sz', 'SH', 'SZ')): code = code.replace('.', '').replace('SH', '').replace('SZ', '').strip() if code.startswith(('6', '9')): tencent_code = 'sh' + code else: tencent_code = 'sz' + code else: tencent_code = code.replace('.', '') sd = start_date.replace('-', '') ed = end_date.replace('-', '') # 腾讯API不支持日期范围参数,获取全部后程序端过滤 url = f"http://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={tencent_code},day,,,1000,qfq" req = urllib.request.Request(url, headers=self._headers) resp = urllib.request.urlopen(req, timeout=self.timeout) result = json.loads(resp.read().decode('utf-8')) data = result.get('data', {}) stock_data = data.get(tencent_code, {}) day_data = stock_data.get('qfqday') or stock_data.get('day', []) if not day_data: return None # 腾讯qfqday格式: [date, open, close, high, low, volume(手)] rows = [] for item in day_data: if isinstance(item, list) and len(item) >= 6 and item[0] and float(item[2]) > 0: rows.append({ 'date': item[0], 'open': float(item[1]) if item[1] else 0, 'high': float(item[3]) if len(item) > 3 and item[3] else 0, 'low': float(item[4]) if len(item) > 4 and item[4] else 0, 'close': float(item[2]) if item[2] else 0, 'volume': float(item[5]) * 100 if item[5] else 0, # 手转股 'amount': 0, 'turn': '0', }) if not rows: return None if not rows: return None df = pd.DataFrame(rows) df['date'] = pd.to_datetime(df['date']) df = df.sort_values('date').reset_index(drop=True) df = df[df['close'] > 0].reset_index(drop=True) return df # ============================================================ # 新浪财经 (备用K线数据源) # ============================================================ def _fetch_sina_kline(self, code, days=1500): """新浪财经API - 日K线""" sc = code.replace('.', '') url = (f'http://money.finance.sina.com.cn/quotes_service/api/json_v2.php' f'/CN_MarketData.getKLineData?symbol={sc}&scale=240&ma=no&datalen={days}') req = urllib.request.Request(url, headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Referer': 'https://finance.sina.com.cn/' }) resp = urllib.request.urlopen(req, timeout=self.timeout) text = resp.read().decode('gbk', errors='replace') klines = json.loads(text) if not klines or not isinstance(klines, list): return None rows = [] for item in klines: rows.append({ 'date': item['day'], 'open': float(item['open']), 'high': float(item['high']), 'low': float(item['low']), 'close': float(item['close']), 'volume': float(item['volume']), 'amount': float(item.get('close', 0)) * float(item.get('volume', 0)), 'turn': '0', }) df = pd.DataFrame(rows) df['date'] = pd.to_datetime(df['date']) df = df.sort_values('date').reset_index(drop=True) return df # ============================================================ # 东方财富 (财务数据) # ============================================================ def _fetch_tencent_financial(self, code): """腾讯行情API - 实时行情与财务指标""" tencent_code = code.replace('.', '') url = f"http://qt.gtimg.cn/q={tencent_code}" try: req = urllib.request.Request(url, headers=self._headers) resp = urllib.request.urlopen(req, timeout=self.timeout) text = resp.read().decode('gbk', errors='replace') # 提取~分隔的内容 content_str = text.split('"')[1] parts = content_str.split('~') # 字段索引映射 return { 'current': float(parts[3]) if parts[3] else 0, 'yesterday_close': float(parts[4]) if parts[4] else 0, 'open': float(parts[5]) if parts[5] else 0, 'volume': float(parts[6]) if parts[6] else 0, 'high': float(parts[33]) if len(parts) > 33 and parts[33] else 0, 'low': float(parts[34]) if len(parts) > 34 and parts[34] else 0, 'pe_ttm': float(parts[37]) if len(parts) > 37 and parts[37] else 0, 'pb': float(parts[38]) if len(parts) > 38 and parts[38] else 0, 'total_mv': float(parts[39]) if len(parts) > 39 and parts[39] else 0, 'turnover_ratio': float(parts[43]) if len(parts) > 43 and parts[43] else 0, 'eps': float(parts[47]) if len(parts) > 47 and parts[47] else 0, 'bvps': float(parts[48]) if len(parts) > 48 and parts[48] else 0, 'reserve_per_share': float(parts[46]) if len(parts) > 46 and parts[46] else 0, 'liability_ratio': float(parts[51]) if len(parts) > 51 and parts[51] else 0, } except Exception as e: print(f"[WARN] 腾讯行情数据获取失败: {e}") return None # ============================================================ # 带超时的安全调用 # ============================================================ def _safe_call(self, func, *args, **kwargs): """带超时的函数调用,避免阻塞""" with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(func, *args, **kwargs) try: return future.result(timeout=self.timeout) except FuturesTimeout: print(f"[WARN] 数据源超时 ({self.timeout}s): {func.__name__}") return None except Exception as e: print(f"[WARN] 数据源异常: {func.__name__}: {e}") return None # ============================================================ # 公共接口 # ============================================================ def fetch_stock_data(self, code, start_date=None, end_date=None, min_rows=200): """ 获取股票K线数据 策略: 腾讯财经优先 -> 新浪财经备用 """ sd = start_date or '2019-01-01' ed = end_date or '2026-05-31' # 来源1: 腾讯财经 df = self._safe_call(self._fetch_tencent_kline, code, sd, ed) if df is not None and len(df) >= min_rows: if start_date: df = df[df['date'] >= pd.Timestamp(start_date)] if end_date: df = df[df['date'] <= pd.Timestamp(end_date)] if len(df) >= min_rows: print(f"[数据] 腾讯财经获取 {code}: {len(df)}行") return df # 来源2: 新浪财经 df = self._safe_call(self._fetch_sina_kline, code, days=1500) if df is not None and len(df) >= min_rows: if start_date: df = df[df['date'] >= pd.Timestamp(start_date)] if end_date: df = df[df['date'] <= pd.Timestamp(end_date)] if len(df) >= min_rows: print(f"[数据] 新浪财经获取 {code}: {len(df)}行") return df print(f"[ERROR] 所有K线数据源失败: {code}") return None def fetch_financial_data(self, code): """获取财务数据(腾讯行情API)""" return self._safe_call(self._fetch_tencent_financial, code) def fetch_multi_stocks(self, codes, min_rows=200): """批量获取多只股票数据""" results = {} for code in codes: df = self.fetch_stock_data(code, min_rows=min_rows) if df is not None: results[code] = df time.sleep(0.3) return results # 全局单例 _data_adapter = None def get_data_adapter(timeout=15): """获取数据适配器单例""" global _data_adapter if _data_adapter is None: _data_adapter = DataSourceAdapter(timeout=timeout) return _data_adapter