# -*- coding: utf-8 -*- """ A 股形态选股与量化评估系统(优化版 v5:Superpowers 架构升级 + 跨平台纯净版) ======================================================================== - 移除所有对旧环境 `/root/股票2/hist_cache` 绝对路径的硬编码与回退 - 统一使用基于脚本当前目录的 SQLite (stock_cache.sqlite3) 本地高速缓存 - 纯净开箱即用,支持 Windows / Linux / WSL 环境直接运行 """ from __future__ import annotations import argparse import datetime as dt import logging import os import random import re import sqlite3 import threading import time from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Dict, List, Optional, Tuple import akshare as ak import numpy as np import pandas as pd import requests # 配置日志 logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S", ) logger = logging.getLogger("StockPicker") # ========================================================= # 可调参数区 (Strategy Configuration) # ========================================================= DATA_DAYS = 730 # 拉取日历天数 (覆盖近2年) MIN_LISTING_BARS = 180 # 上市至少 180 个交易日(过滤次新) POOL_PREFIX = ("60", "00", "30", "68") # 排除北交所,保留主板/双创 EXCLUDE_KEYWORDS = ("ST", "退") MIN_PRICE = 2.0 # 均线系统 MA_FAST, MA_MID, MA_SLOW = 20, 50, 200 SLOPE_FAST_BARS = 5 SLOPE_SLOW_BARS = 20 BASE_FLOOR_RATIO = 0.93 # 近 10 日最低价 >= MA20 * 0.93 CLOSE_MIN_RATIO = 0.97 # 现价 >= MA20 * 0.97 MAX_BIAS_MA20 = 0.30 # 现价偏离 MA20 最大 30% # 平台与突破 BASE_WIN = 120 # 平台回看最长窗口 BASE_MIN_BARS = 60 # 平台最少 K 线数 (约3个月) BASE_MAX_WIDTH = 0.55 # 平台箱体振幅 (高/低 - 1) BASE_NET_LO, BASE_NET_HI = -0.30, 0.60 LOOKBACK_HIGH = 60 # 创 N 日新高 VOL_SURGE_MIN = 1.5 # 突破日放量 >= 1.5 倍 20日均量 BREAK_MIN_CHG = 0.04 # 突破日中阳起爆涨幅 >= 4% POST_MIN_BARS = 1 # 突破发生至少 1 天以上 POST_MAX_BARS = 60 # 突破后最长跟踪窗口,超过视为旧突破硬淘汰 MAX_GAIN_SINCE = 0.80 # 突破后累计涨幅上限,超过视为透支硬淘汰 # 运行参数 FETCH_WORKERS = 6 # 并发拉取线程数 MAX_RATE_PER_SEC = 10.0 # 全局最高 QPS 限流 MIN_SCORE = 70 CACHE_DB_NAME = "stock_cache.sqlite3" OUTPUT_SUBDIR = "选股结果" # ========================================================= # 限流器与安全网络 (Rate Limiter & Resilient Network) # ========================================================= class TokenBucketLimiter: """平滑令牌桶限流器,防止打爆行情接口触发封禁。""" def __init__(self, rate: float): self.rate = rate self.capacity = max(1.0, rate) self.tokens = self.capacity self.last_time = time.monotonic() self.lock = threading.Lock() def acquire(self): with self.lock: now = time.monotonic() elapsed = now - self.last_time self.last_time = now self.tokens = min(self.capacity, self.tokens + elapsed * self.rate) if self.tokens < 1.0: wait_time = (1.0 - self.tokens) / self.rate time.sleep(wait_time) self.tokens = 0.0 else: self.tokens -= 1.0 LIMITER = TokenBucketLimiter(MAX_RATE_PER_SEC) NETWORK_AVAILABLE = True def probe_network(timeout: float = 3.5) -> bool: """快速探测国内财经接口是否可达。""" global NETWORK_AVAILABLE urls = [ "http://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=1&fid=f12&fs=m:0+t:6&fields=f12", "http://qt.gtimg.cn/q=sh600519", ] for u in urls: try: r = requests.get(u, timeout=timeout) if r.status_code == 200 and len(r.text) > 0: NETWORK_AVAILABLE = True print("✓ 网络探测: 行情接口可达,将在线更新/拉取数据") return True except Exception: continue NETWORK_AVAILABLE = False print("✗ 网络探测: 行情接口不可达,将尝试使用本地 SQLite 缓存离线运行") return False # ========================================================= # SQLite 集中式高性能缓存引擎 # ========================================================= class SQLiteStorage: def __init__(self, db_path: str): self.db_path = db_path self._local = threading.local() self._init_db() def _get_conn(self) -> sqlite3.Connection: if not hasattr(self._local, "conn") or self._local.conn is None: conn = sqlite3.connect(self.db_path, timeout=30.0) conn.execute("PRAGMA journal_mode = WAL") conn.execute("PRAGMA synchronous = NORMAL") self._local.conn = conn return self._local.conn def _init_db(self): conn = sqlite3.connect(self.db_path) with conn: conn.execute(""" CREATE TABLE IF NOT EXISTS stock_pool_meta ( symbol TEXT PRIMARY KEY, name TEXT, updated_at TEXT ) """) conn.execute(""" CREATE TABLE IF NOT EXISTS kline_cache ( symbol TEXT, trade_date TEXT, open REAL, close REAL, high REAL, low REAL, volume REAL, updated_at TEXT, PRIMARY KEY(symbol, trade_date) ) """) conn.execute("CREATE INDEX IF NOT EXISTS idx_sym_date ON kline_cache(symbol, trade_date)") conn.close() def get_cached_pool(self) -> pd.DataFrame: conn = self._get_conn() df = pd.read_sql_query("SELECT symbol as 代码, name as 名称 FROM stock_pool_meta", conn) return df def save_cached_pool(self, df: pd.DataFrame): if df.empty: return conn = self._get_conn() now_str = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") records = [(str(row.代码).zfill(6), str(row.名称), now_str) for row in df.itertuples()] with conn: conn.executemany("INSERT OR REPLACE INTO stock_pool_meta (symbol, name, updated_at) VALUES (?, ?, ?)", records) def get_kline(self, symbol: str, start_date: str) -> Optional[pd.DataFrame]: conn = self._get_conn() query = """ SELECT trade_date as 日期, open as 开盘, close as 收盘, high as 最高, low as 最低, volume as 成交量 FROM kline_cache WHERE symbol = ? AND trade_date >= ? ORDER BY trade_date ASC """ df = pd.read_sql_query(query, conn, params=(symbol, start_date)) if df.empty or len(df) < MIN_LISTING_BARS: return None df["日期"] = pd.to_datetime(df["日期"]) return df def save_kline(self, symbol: str, df: pd.DataFrame): if df.empty: return conn = self._get_conn() now_str = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") records = [] for row in df.itertuples(index=False): d_str = pd.to_datetime(row.日期).strftime("%Y%m%d") records.append(( symbol, d_str, float(getattr(row, "开盘", row.收盘)), float(row.收盘), float(row.最高), float(row.最低), float(row.成交量), now_str )) with conn: conn.executemany(""" INSERT OR REPLACE INTO kline_cache (symbol, trade_date, open, close, high, low, volume, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, records) # ========================================================= # 数据层规范与清洗 # ========================================================= def _with_prefix(symbol: str) -> str: code = symbol.strip() return ("sh" if code.startswith(("6", "9")) else "sz") + code def _norm_df(df: pd.DataFrame) -> pd.DataFrame: if df is None or df.empty: return pd.DataFrame() lower = {str(c).lower(): c for c in df.columns} def g(*names): for nm in names: if nm in lower: return lower[nm] return None dcol = g("日期", "date") if dcol is None: return pd.DataFrame() out = {"日期": pd.to_datetime(df[dcol], errors="coerce")} for target, names in { "开盘": ("开盘", "open"), "收盘": ("收盘", "close"), "最高": ("最高", "high"), "最低": ("最低", "low"), "成交量": ("成交量", "volume"), }.items(): col = g(*names) out[target] = pd.to_numeric(df[col], errors="coerce") if col else np.nan res = pd.DataFrame(out).dropna(subset=["日期", "收盘", "最高", "最低"]) if "开盘" in res.columns and res["开盘"].isna().any(): res["开盘"] = res["开盘"].fillna(res["收盘"]) return res.sort_values("日期").drop_duplicates(subset="日期", keep="last").reset_index(drop=True) def fetch_stock_daily(symbol: str, storage: SQLiteStorage, use_cache: bool = True) -> pd.DataFrame: today_str = dt.date.today().strftime("%Y%m%d") start_str = (dt.date.today() - dt.timedelta(days=DATA_DAYS)).strftime("%Y%m%d") # 1. 本地缓存读取 cached_df = None if use_cache: cached_df = storage.get_kline(symbol, start_str) if cached_df is not None and not cached_df.empty: if (dt.date.today() - cached_df["日期"].iloc[-1].date()).days <= 3: return cached_df # 2. 在线拉取与重试 errors = [] if NETWORK_AVAILABLE: sources = [ ("em", lambda: ak.stock_zh_a_hist(symbol=symbol, period="daily", start_date=start_str, end_date=today_str, adjust="qfq")), ("tx", lambda: ak.stock_zh_a_hist_tx(symbol=_with_prefix(symbol), start_date=start_str, end_date=today_str, adjust="qfq")), ("sina", lambda: ak.stock_zh_a_daily(symbol=_with_prefix(symbol), start_date=start_str, end_date=today_str, adjust="qfq")), ] for src_name, fetch_fn in sources: for attempt in range(2): LIMITER.acquire() try: raw = fetch_fn() df = _norm_df(raw) if not df.empty and len(df) >= MIN_LISTING_BARS: if use_cache: storage.save_kline(symbol, df) return df except Exception as e: errors.append(f"{src_name}:{str(e)[:30]}") time.sleep(0.3 * (attempt + 1) + random.random() * 0.2) # 3. 离线降级 if cached_df is not None and not cached_df.empty: return cached_df raise RuntimeError(" | ".join(errors) if errors else "无有效日线数据返回") # ========================================================= # 形态计算纯函数模块 (向量化评估) # ========================================================= def evaluate_technical_pattern(symbol: str, name: str, df: pd.DataFrame) -> Tuple[Optional[Dict], Optional[str]]: n = len(df) if n < MIN_LISTING_BARS: return None, f"上市交易日不足{MIN_LISTING_BARS}天(排除次新)" c = df["收盘"].to_numpy(dtype=float) o = df["开盘"].to_numpy(dtype=float) h = df["最高"].to_numpy(dtype=float) l = df["最低"].to_numpy(dtype=float) v = df["成交量"].to_numpy(dtype=float) s_close = pd.Series(c) ma20 = s_close.rolling(MA_FAST).mean().to_numpy() ma50 = s_close.rolling(MA_MID).mean().to_numpy() ma200 = s_close.rolling(MA_SLOW).mean().to_numpy() vma20 = pd.Series(v).shift(1).rolling(MA_FAST).mean().to_numpy() roll_max60 = pd.Series(h).shift(1).rolling(LOOKBACK_HIGH).max().to_numpy() # 1. 均线与价格硬门槛过滤 if np.isnan(ma200[-1]) or np.isnan(ma200[-1 - SLOPE_SLOW_BARS]): return None, "MA200有效数据不足" if not (ma20[-1] > ma50[-1] > ma200[-1]): return None, "均线未形成多头排列" if ma20[-1] <= ma20[-1 - SLOPE_FAST_BARS]: return None, "MA20短期斜率未向上" bias20 = c[-1] / ma20[-1] - 1.0 if bias20 > MAX_BIAS_MA20: return None, f"乖离过大({bias20*100:.1f}%), 谨防追顶" if c[-1] < ma20[-1] * CLOSE_MIN_RATIO: return None, "现价已跌破MA20" floor10 = float(np.min(l[-10:] / ma20[-10:])) if floor10 < BASE_FLOOR_RATIO: return None, "近10日破MA20支撑" # 2. 均线打分 (总分 30) score_A = 8 ma200_up = ma200[-1] > ma200[-1 - SLOPE_SLOW_BARS] ma20_slope_val = (ma20[-1] - ma20[-1 - SLOPE_FAST_BARS]) / ma20[-1 - SLOPE_FAST_BARS] score_A += 6 if (ma200_up and ma20_slope_val > 0.005) else (4 if (ma200_up or ma20_slope_val > 0.005) else 2) score_A += 4 if (c[-1] >= ma20[-1] and c[-1] >= ma50[-1]) else 2 ride_ratio = float(np.mean(l[-20:] / ma20[-20:] >= 0.95)) score_A += 7 if ride_ratio >= 0.95 else (6 if ride_ratio >= 0.85 else (5 if ride_ratio >= 0.70 else 3)) d_bias = abs(bias20) score_A += 5 if d_bias <= 0.05 else (4 if d_bias <= 0.10 else (2 if d_bias <= 0.18 else 0)) # 3. 突破信号与吸筹平台检测 (总分 45) r = np.zeros(n) r[1:] = c[1:] / c[:-1] - 1.0 valid_break_mask = ( (~np.isnan(vma20)) & (vma20 > 0) & (~np.isnan(ma50)) & (~np.isnan(ma200)) & (c > roll_max60) & (v >= VOL_SURGE_MIN * vma20) & (c > ma50) & (c > ma200) & (r >= BREAK_MIN_CHG) & (c > o) & (np.isfinite(o)) & (o > 0) ) candidate_indices = np.where(valid_break_mask)[0] candidate_indices = [ i for i in candidate_indices if i >= BASE_MIN_BARS and (n - 1 - i) >= POST_MIN_BARS ] if not candidate_indices: return None, "未发现放量突破信号" chosen_e = None for e_candidate in reversed(candidate_indices): b0 = max(0, e_candidate - BASE_WIN) hi_box = h[b0:e_candidate].max() lo_box = l[b0:e_candidate].min() if lo_box <= 0 or (hi_box / lo_box - 1.0) > BASE_MAX_WIDTH: continue net_box = c[e_candidate - 1] / c[b0] - 1.0 if not (BASE_NET_LO <= net_box <= BASE_NET_HI): continue if c[e_candidate] < hi_box * 0.98: continue chosen_e = e_candidate break if chosen_e is None: return None, "突破事件存在但前期吸筹平台不规范" e = chosen_e post_bars = n - 1 - e gain_since = c[-1] / c[e] - 1.0 if post_bars > POST_MAX_BARS: return None, f"突破已过去{post_bars}日(>{POST_MAX_BARS}日上限, 视为旧突破)" if gain_since > MAX_GAIN_SINCE: return None, f"突破后涨幅{gain_since*100:.0f}%已透支(防接盘)" b0 = max(0, e - BASE_WIN) bars = e - b0 width = h[b0:e].max() / l[b0:e].min() - 1.0 box_hi = h[b0:e].max() vol_surge = v[e] / vma20[e] b1 = (5 if bars >= 120 else 4 if bars >= 90 else 3) + (5 if width <= 0.35 else 4 if width <= 0.45 else 3) margin = c[e] / box_hi - 1.0 b2 = 2 b2 += 2 if margin >= 0.02 else (1 if margin >= 0.005 else 0) b2 += 2 if vol_surge >= 2.0 else (1 if vol_surge >= 1.5 else 0) limit_up = 0.195 if symbol.startswith(("300", "301", "688")) else 0.095 b3 = 5 if r[e] >= limit_up - 0.005 else (4 if r[e] >= 0.05 else 3) if post_bars <= 5: b4 = 10 if c[-1] >= c[e] * 0.98 else 6 b5 = 4 stage_desc = "刚突破起爆" else: post = np.arange(e + 1, n) above_frac = float(np.mean(c[post] >= ma20[post])) if above_frac < 0.50: return None, "突破后跌破MA20过频" b4 = (6 if above_frac >= 0.80 else 4) + (6 if float(np.min(l[post] / ma20[post])) >= 0.94 else 3) b5 = 4 if gain_since >= 0.05 else 2 stage_desc = "回踩蓄势/主升" b6 = 5 if gain_since < 0.50 else (4 if gain_since < 1.00 else 2) score_B = b1 + b2 + b3 + b4 + b5 + b6 # 4. 量价配合分析 (总分 25) c1 = 8 if vol_surge >= 2.2 else (6 if vol_surge >= 1.6 else 4) c2 = 4 if v[e:e + min(3, n - e)].mean() / vma20[e] >= 1.3 else 2 if post_bars > 1: ret_post = np.diff(c[e:]) post_vol = v[e + 1:] up_vol = post_vol[ret_post >= 0] dn_vol = post_vol[ret_post < 0] if len(up_vol) > 0 and len(dn_vol) > 0 and up_vol.mean() > 0: vol_ratio = float(dn_vol.mean() / up_vol.mean()) c3 = 7 if vol_ratio <= 0.65 else (5 if vol_ratio <= 0.85 else 3) else: c3 = 4 else: c3 = 5 recent_idx = range(max(0, n - 5), n) c4_ok = all(np.isfinite(vma20[i]) and v[i] <= 3.5 * vma20[i] for i in recent_idx) c4 = 4 if c4_ok else 1 score_C = c1 + c2 + c3 + c4 total_score = min(100, score_A + score_B + score_C) latest_date = df["日期"].iloc[-1].strftime("%Y-%m-%d") return { "代码": symbol, "名称": name, "阶段": stage_desc, "数据日期": latest_date, "收盘": round(float(c[-1]), 2), "MA20": round(float(ma20[-1]), 2), "MA50": round(float(ma50[-1]), 2), "MA200": round(float(ma200[-1]), 2), "综合评分": int(total_score), "均线分": score_A, "形态分": score_B, "量价分": score_C, "乖离MA20%": round(bias20 * 100, 1), "突破日期": df["日期"].iloc[e].strftime("%Y-%m-%d"), "突破后交易日": int(post_bars), "突破日涨幅%": round(r[e] * 100, 1), "突破量比": round(float(vol_surge), 1), "突破后涨幅%": round(gain_since * 100, 1), "平台振幅%": round(width * 100, 1), "平台K线数": int(bars), }, None # ========================================================= # 调度工作流 # ========================================================= class StockScanner: def __init__(self, args, storage: SQLiteStorage): self.args = args self.storage = storage self.lock = threading.Lock() self.analyzed_count = 0 self.error_count = 0 self.matched_rows: List[Dict] = [] self.skip_reasons: Dict[str, int] = {} def _process_one(self, code: str, name: str): try: df = fetch_stock_daily(code, self.storage, use_cache=not self.args.no_cache) except Exception as err: with self.lock: self.error_count += 1 reason = f"网络/数据异常: {str(err)[:40]}" self.skip_reasons[reason] = self.skip_reasons.get(reason, 0) + 1 return detail, reason = evaluate_technical_pattern(code, name, df) with self.lock: self.analyzed_count += 1 cur_done = self.analyzed_count if detail is not None: if detail["综合评分"] >= self.args.min_score: self.matched_rows.append(detail) print(f" ★ [{detail['阶段']}] {code} {name:<6} " f"评分: {detail['综合评分']} (均线{detail['均线分']}/形态{detail['形态分']}/量价{detail['量价分']}) " f"突破后天数: {detail['突破后交易日']}", flush=True) elif reason: self.skip_reasons[reason] = self.skip_reasons.get(reason, 0) + 1 if cur_done % 100 == 0: print(f" >> 扫描进度: {cur_done} 只已完成...", flush=True) def run(self, pool: pd.DataFrame) -> pd.DataFrame: items = list(zip(pool["代码"].astype(str), pool["名称"].astype(str))) workers = min(self.args.workers, len(items) or 1) t0 = time.time() print(f"=== 启动形态扫描: 共 {len(items)} 只标的, 并发工作线程: {workers} ===") with ThreadPoolExecutor(max_workers=workers) as executor: futs = [executor.submit(self._process_one, c, n) for c, n in items] try: for _ in as_completed(futs): pass except KeyboardInterrupt: print("\n[中断] 用户手动停止,准备整理已有结果...") executor.shutdown(wait=False, cancel_futures=True) elapsed = time.time() - t0 print(f"\n扫描完成! 总耗时: {elapsed:.1f} 秒, 分析: {self.analyzed_count}, 异常: {self.error_count}") return self._summarize() def _summarize(self) -> pd.DataFrame: if self.skip_reasons: print("\n主要未通过/拦截原因分布 (TOP 8):") for k, v in sorted(self.skip_reasons.items(), key=lambda x: -x[1])[:8]: print(f" {v:>5} 只: {k}") if not self.matched_rows: print("\n未筛选出达标股票。") return pd.DataFrame() df_res = pd.DataFrame(self.matched_rows).sort_values( by=["综合评分", "突破后涨幅%"], ascending=[False, False] ).reset_index(drop=True) return df_res def get_stock_pool(codes: Optional[str], limit: Optional[int], storage: SQLiteStorage) -> pd.DataFrame: if codes: wanted = [x.strip() for x in codes.split(",") if x.strip()] return pd.DataFrame({"代码": wanted, "名称": wanted}) # 1. 优先读取本地 SQLite 缓存代码表 cached_pool = storage.get_cached_pool() if cached_pool is not None and len(cached_pool) >= 1000: print(f"✓ 已秒级命中本地股票池缓存: 共 {len(cached_pool)} 只") if limit and limit > 0: return cached_pool.head(limit) return cached_pool # 2. 从东财接口在线获取股票池 print("首次初始化全市场股票池(东财在线接口)...") exclude_pat = "|".join([re.escape(k) for k in EXCLUDE_KEYWORDS]) pool = pd.DataFrame() try: url = "http://push2.eastmoney.com/api/qt/clist/get" params = { "pn": "1", "pz": "6000", "po": "1", "np": "1", "fltt": "2", "invt": "2", "fid": "f12", "fs": "m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048", "fields": "f12,f14,f2" } resp = requests.get(url, params=params, timeout=5.0) if resp.status_code == 200: data = resp.json() diff = data.get("data", {}).get("diff", []) if diff: rows = [] for item in diff: cd = str(item.get("f12", "")).strip() nm = str(item.get("f14", "")).strip() px = item.get("f2") try: px = float(px) except (ValueError, TypeError): px = 0.0 rows.append({"代码": cd, "名称": nm, "最新价": px}) df_all = pd.DataFrame(rows) mask = ( df_all["代码"].str.startswith(POOL_PREFIX) & ~df_all["名称"].str.contains(exclude_pat, na=False) & (df_all["最新价"] >= MIN_PRICE) ) pool = df_all[mask][["代码", "名称"]].reset_index(drop=True) storage.save_cached_pool(pool) print(f"✓ 成功获取并持久化全市场股票池至 SQLite: 共 {len(pool)} 只") except Exception as e: logger.warning(f"获取全市场股票池失败: {e}") if pool.empty: print("✗ 无法获取全市场股票池,请检查网络连接或代理设置。") if limit and limit > 0: pool = pool.head(limit) return pool def main(): parser = argparse.ArgumentParser(description="A股慢牛与起爆形态智能筛选系统") parser.add_argument("--limit", type=int, default=None, help="快速试跑限制数量") parser.add_argument("--workers", type=int, default=FETCH_WORKERS, help="并发网络线程") parser.add_argument("--min-score", type=int, default=MIN_SCORE, help="综合评分下限") parser.add_argument("--codes", type=str, default=None, help="指定股票代码(逗号隔开)") parser.add_argument("--no-cache", action="store_true", help="禁用 SQLite 缓存") args = parser.parse_args() # 动态获取脚本所在目录,确保在所有操作系统上都是标准相对路径 base_dir = os.path.dirname(os.path.abspath(__file__)) out_dir = os.path.join(base_dir, OUTPUT_SUBDIR) os.makedirs(out_dir, exist_ok=True) db_path = os.path.join(base_dir, CACHE_DB_NAME) storage = SQLiteStorage(db_path) # 快速探测网络连通性 probe_network() # 获取标的池 pool = get_stock_pool(args.codes, args.limit, storage) if pool.empty: print("未获取到有效股票标的。程序退出。") return scanner = StockScanner(args, storage) res_df = scanner.run(pool) if not res_df.empty: stamp = dt.datetime.now().strftime("%Y%m%d_%H%M") csv_file = os.path.join(out_dir, f"选股结果_{stamp}.csv") res_df.to_csv(csv_file, index=False, encoding="utf-8-sig") print(f"\n结果已成功导出至: {csv_file}") if __name__ == "__main__": main()