Files
stocks/stock_picker_v5.py
2026-09-27 15:39:18 +08:00

765 lines
31 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
A 股形态选股与量化评估系统(优化版 v5:Superpowers 架构升级 + 逻辑修复)
========================================================================
相对 v4 的修复(v5):
[C1] 旧突破/涨幅透支改为硬过滤:突破后天数 > 60 或累计涨幅 > 80% 直接淘汰,
不再只做象征性软扣分(v4 会选出突破后 147/167 天、已涨 180% 的高位股)。
[C2] 量能分母修正:突破放量倍数、持续量、防天量全部改用「不含当日的20日均量」
(vma20 改为 shift(1)),修复 v4 中"防天量出货"检查因分母含当天而自我放行。
[I1] b2「平台突破有效性」由写死 6 分改为按"收盘站上箱顶幅度 + 突破放量质量"实算。
[I2] 突破信号新增"实体阳线"约束(收盘 > 开盘),不再让跳空十字星/长上影充当起爆。
[I4] 近10日支撑低点改为逐日对齐各自 MA20 比较(修正用今日 MA20 除历史低点导致的放宽)。
[I3] 新增 test_picker_v5.py,真正覆盖箱体/突破/打分/硬过滤的单元测试。
优化亮点:
1. 【量化模型分层】:
- 阶段解耦:清晰区分「刚突破确认期 (1~5日)」与「突破后主升/回踩期 (6~MAX 60日)」,避免只能接盘高位个股。
- 上市天数硬过滤:彻底避免次新股失真(必须上市 >= 180 交易日)。
2. 【并发网络弹性与防封禁】:
- 引入自适应令牌桶限流与指数退避(Exponential Backoff with Jitter),防止触发券商/接口 IP 封控。
- 统一网络 Session 与请求隔离。
3. 【SQLite/DuckDB 高效缓存】:
- 淘汰高危且易耗尽 inode 的海量 .pkl 文件,采用 SQLite 高性能结构化本地缓存(支持 WAL 模式与自动按日更新)。
4. 【高度模块化与测试验证支持】:
- 算法核心纯函数化(Pure Vectorized Functions),支持全自动 Mock 单元测试。
"""
from __future__ import annotations
import argparse
import datetime as dt
import logging
import math
import os
import pickle
import random
import re
import sqlite3
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, List, Optional, Tuple
# 注意:不要清除系统代理环境变量。本机腾讯/新浪行情接口依赖本地代理
# (127.0.0.1:7897) 才能访问,清空代理反而会导致全部超时。
import akshare as ak
import numpy as np
import pandas as pd
import requests
from requests.adapters import HTTPAdapter
# 配置日志
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 天以上(解耦旧版本强制 10 天的要求)
POST_MAX_BARS = 60 # [C1] 突破后最长跟踪窗口,超过视为旧突破,硬淘汰
MAX_GAIN_SINCE = 0.80 # [C1] 突破后累计涨幅上限,超过视为透支,硬淘汰(防接盘)
# 运行参数
FETCH_WORKERS = 6 # 推荐 4~8 线程,保护 IP
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.0) -> bool:
"""快速探测国内财经接口是否可达(3 秒硬超时)。"""
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("✗ 网络探测: 行情接口不可达,将使用本地缓存离线运行")
return False
# =========================================================
# SQLite 集中式高性能缓存引擎 (取代数万个小 pkl 文件)
# =========================================================
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) < 180:
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 migrate_legacy_pkl_cache(storage: SQLiteStorage, legacy_dir: str = "/root/股票2/hist_cache") -> int:
"""将旧版 `股票2/hist_cache` 中的海量 .pkl 日线缓存一次性导入 SQLite。
仅当 SQLite 中尚无该股票数据时才导入,避免重复劳动;导入后即可
在无网络环境下直接完成形态扫描。返回导入的股票数量。
"""
if not os.path.isdir(legacy_dir):
return 0
conn = storage._get_conn()
existing = {r[0] for r in conn.execute("SELECT DISTINCT symbol FROM kline_cache")}
# 同一代码可能有多份(不同日期)pkl,按文件名日期降序取最新一份
latest: Dict[str, str] = {}
for fn in os.listdir(legacy_dir):
if not fn.endswith(".pkl") or "_" not in fn:
continue
code = fn.split("_")[0]
if len(code) != 6 or not code.startswith(POOL_PREFIX):
continue
if code in existing:
continue
if code not in latest or fn > latest[code]:
latest[code] = fn
if not latest:
return 0
print(f"→ 检测到旧版缓存,正在导入 {len(latest)} 只股票日线至 SQLite...")
imported = 0
for code, fn in latest.items():
try:
with open(os.path.join(legacy_dir, fn), "rb") as f:
df = pickle.load(f)
if not isinstance(df, pd.DataFrame) or df.empty:
continue
df = _norm_df(df)
if df.empty:
continue
storage.save_kline(code, df)
imported += 1
except Exception:
continue
print(f"✓ 旧缓存导入完成: {imported} 只")
return imported
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()
# [C2] 关键修复:量能基准改为「不含当日」的 20 日均量。
# v4 用含当天的 vma20 作分母,导致天量当天把分母抬高,反而通过"≤3.5倍"的防出货检查。
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"
# [I4] 逐日低点对齐各自当日的 MA20,避免用今日 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) & # [I2] 实体阳线:收盘必须高于开盘,排除跳空十字星/长上影
(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
# [C1] 硬过滤:旧突破与涨幅透支不再软扣分,直接淘汰
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] # 分母为突破日前20日均量(不含突破当日)
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)
# [I1] b2 由写死 6 分改为实算:站上箱顶幅度 + 突破放量质量
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:
# 【主升浪/回踩期】:考察 MA20 承接力
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)
# vol_surge 已在 b2 处基于「不含当日的20日均量」计算,此处直接复用
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:
vol_ratio = np.nan
c3 = 4
else:
vol_ratio = np.nan
c3 = 5
# [C2] 逐日检验最近5日:任一天放量 > 3.5 倍其「前20日均量」即判风险
# (vma20[i] 已 shift(1),不含第 i 天本身,避免放量日抬高自己的分母)
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 缓存代码表(0 毫秒)
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. 如果本地为空,拉取全市场列表(使用轻量东财列表接口,带 3 秒严控超时)
print("首次初始化全市场股票池(快速接口获取)...")
exclude_pat = "|".join([re.escape(k) for k in EXCLUDE_KEYWORDS])
pool = pd.DataFrame()
try:
# 直接使用 requests 直连东财快查接口,设置 3 秒硬超时
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=3.5)
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"✓ 成功获取并持久化全市场股票池: 共 {len(pool)} 只")
except Exception as e:
logger.warning(f"轻量实时列表获取失败 ({e})")
# 3. 如果网络仍不可达,尝试从旧版股票2的 hist_cache 目录秒级提取已有股票代码
if pool.empty:
old_cache_dir = "/root/股票2/hist_cache"
if os.path.exists(old_cache_dir):
print("→ 秒级从已有历史行情中提取股票代码...")
old_files = os.listdir(old_cache_dir)
extracted = set()
for fn in old_files:
if "_" in fn:
code = fn.split("_")[0]
if len(code) == 6 and code.startswith(POOL_PREFIX):
extracted.add(code)
if extracted:
pool = pd.DataFrame({"代码": sorted(list(extracted)), "名称": sorted(list(extracted))})
storage.save_cached_pool(pool)
print(f"✓ 成功秒级提取历史股票池: 共 {len(pool)} 只")
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)
# 首次运行时,将旧版 股票2/hist_cache 的海量 pkl 一次性导入 SQLite,
# 之后即使无网络也能秒级完成扫描。
migrate_legacy_pkl_cache(storage)
# 网络可用性快速探测(3 秒),断网时直接走离线缓存,避免逐只重试卡死。
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()