上传文件至「/」
This commit is contained in:
@@ -0,0 +1,750 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
A 股形态选股与量化评估系统(v6 Lite 腾讯极速版)
|
||||
========================================================================
|
||||
融合亮点:
|
||||
1. 【数据底座】:沿用腾讯财经极速公开接口(直连、轻量、无需配置 Token)
|
||||
2. 【算法核心升级至 v6】:
|
||||
- [E1] 真实满分 95 分归一化至 100 分制,门槛设为 74 分(对应 v5 的 70 分)
|
||||
- [E7] 修复持续放量 c2 漏洞:排除突破当日天量自我放行
|
||||
- [E8] 剔除 b6 不可达死分支
|
||||
- [E12] 平台整理天数动态回溯(60~250 根),彻底解决平台 K 线数恒为 120 的问题
|
||||
- [D4] 排序键优化:评分↓ -> 刚突破天数↑ -> 乖离率↑(优先刚起爆与低吸)
|
||||
- [E17/D5] 增加成交性与持仓提示:起爆日涨停标识、次日入场参考价、MA20 止损价
|
||||
"""
|
||||
|
||||
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_v6_Lite")
|
||||
|
||||
# =========================================================
|
||||
# 可调参数区 (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)
|
||||
PLATFORM_MAX_WIN = 250 # [E12] 平台长度可动态回溯至 250 根
|
||||
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 # 突破后累计涨幅上限,超过视为透支硬淘汰
|
||||
|
||||
# [E1] 评分量程归一化
|
||||
SCORE_RAW_MAX = 95 # 均线30 + 形态42 + 量价23 = 95
|
||||
MIN_SCORE = 74 # 归一化后的 74/100 对应原 70/95
|
||||
|
||||
# 运行参数
|
||||
FETCH_WORKERS = 6 # 并发拉取线程数
|
||||
MAX_RATE_PER_SEC = 10.0 # 全局最高 QPS 限流
|
||||
CACHE_DB_NAME = "stock_cache.sqlite3"
|
||||
OUTPUT_SUBDIR = "选股结果"
|
||||
|
||||
|
||||
# =========================================================
|
||||
# 限流器与安全网络 (Rate Limiter)
|
||||
# =========================================================
|
||||
|
||||
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://qt.gtimg.cn/q=sh600519",
|
||||
"http://qt.gtimg.cn/q=sz000001",
|
||||
]
|
||||
for u in urls:
|
||||
try:
|
||||
r = requests.get(u, timeout=timeout, proxies={"http": None, "https": None})
|
||||
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()
|
||||
return pd.read_sql_query("SELECT symbol as 代码, name as 名称 FROM stock_pool_meta", conn)
|
||||
|
||||
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")
|
||||
|
||||
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
|
||||
|
||||
errors = []
|
||||
if NETWORK_AVAILABLE:
|
||||
sources = [
|
||||
("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")),
|
||||
("em", lambda: ak.stock_zh_a_hist(symbol=symbol, period="daily", 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)
|
||||
|
||||
if cached_df is not None and not cached_df.empty:
|
||||
return cached_df
|
||||
|
||||
raise RuntimeError(" | ".join(errors) if errors else "无有效日线数据返回")
|
||||
|
||||
|
||||
# =========================================================
|
||||
# 形态计算纯函数模块 (v6 算法增强)
|
||||
# =========================================================
|
||||
|
||||
def normalize_score(raw: float) -> int:
|
||||
"""[E1] 95 分制换算为 100 分制"""
|
||||
return min(100, int(round(float(raw) / SCORE_RAW_MAX * 100)))
|
||||
|
||||
|
||||
def _c2_persist_volume(v: np.ndarray, vma20: np.ndarray, e: int, n: int) -> int:
|
||||
"""[E7] 排除突破当日天量,只考察突破次日及以后的均量"""
|
||||
seg = v[e + 1:min(e + 3, n)]
|
||||
if seg.size == 0 or not np.isfinite(vma20[e]) or vma20[e] <= 0:
|
||||
return 2
|
||||
return 4 if float(seg.mean()) / float(vma20[e]) >= 1.3 else 2
|
||||
|
||||
|
||||
def _b1_score(bars: int, width: float) -> int:
|
||||
"""[E12] 根据真实回溯平台长度进行打分"""
|
||||
first = (5 if bars >= 180 else 4 if bars >= 120 else 3 if bars >= 90 else 2)
|
||||
second = 5 if width <= 0.35 else 4 if width <= 0.45 else 3
|
||||
return first + second
|
||||
|
||||
|
||||
def platform_bars(h: np.ndarray, l: np.ndarray, e: int,
|
||||
min_bars: int = BASE_MIN_BARS, max_win: int = PLATFORM_MAX_WIN,
|
||||
max_width: float = BASE_MAX_WIDTH) -> int:
|
||||
"""[E12] 动态计算真实平台长度(60~250根),消除恒为 120 的问题"""
|
||||
best = 0
|
||||
lo_bound = max(0, e - max_win)
|
||||
for w in range(e - lo_bound, min_bars - 1, -1):
|
||||
b0 = e - w
|
||||
seg_h = h[b0:e]
|
||||
seg_l = l[b0:e]
|
||||
if seg_h.size == 0 or seg_l.size == 0:
|
||||
continue
|
||||
lo = float(seg_l.min())
|
||||
if lo <= 0:
|
||||
continue
|
||||
if float(seg_h.max()) / lo - 1.0 <= max_width:
|
||||
best = w
|
||||
break
|
||||
return best
|
||||
|
||||
|
||||
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. 突破信号与吸筹平台检测
|
||||
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}%已透支(防接盘)"
|
||||
|
||||
# [E12] 动态计算真实平台长度
|
||||
bars = platform_bars(h, l, e)
|
||||
if bars <= 0:
|
||||
return None, "无有效平台(箱体宽度超限)"
|
||||
|
||||
b0 = max(0, e - bars)
|
||||
width = h[b0:e].max() / l[b0:e].min() - 1.0
|
||||
box_hi = h[b0:e].max()
|
||||
vol_surge = v[e] / vma20[e]
|
||||
|
||||
b1 = _b1_score(bars, width)
|
||||
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_threshold = 0.195 if symbol.startswith(("300", "301", "688")) else 0.095
|
||||
is_limit_up_day = (r[e] >= limit_threshold - 0.005)
|
||||
b3 = 5 if is_limit_up_day 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 = "回踩蓄势/主升"
|
||||
|
||||
# [E8] gain_since 必 <= 0.80,故 5 if < 0.50 else 4
|
||||
b6 = 5 if gain_since < 0.50 else 4
|
||||
score_B = b1 + b2 + b3 + b4 + b5 + b6
|
||||
|
||||
# 4. 量价配合分析 (总分 23)
|
||||
c1 = 8 if vol_surge >= 2.2 else (6 if vol_surge >= 1.6 else 4)
|
||||
c2 = _c2_persist_volume(v, vma20, e, n) # [E7] 修复天量自我放行
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
raw_score = score_A + score_B + score_C
|
||||
total_score = normalize_score(raw_score) # [E1] 归一化至 100 分制
|
||||
latest_date = df["日期"].iloc[-1].strftime("%Y-%m-%d")
|
||||
|
||||
# 入场参考价与成交性列 (D5/E17)
|
||||
next_open = round(float(o[e + 1]), 2) if (e + 1 < n) else None
|
||||
|
||||
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),
|
||||
# v6 新增成交性与持仓提示列
|
||||
"起爆日是否涨停": is_limit_up_day,
|
||||
"入场参考价(次日开盘)": next_open,
|
||||
"止损价(MA20)": round(float(ma20[-1]), 2),
|
||||
}, 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)
|
||||
limit_flag = " [涨停板]" if detail["起爆日是否涨停"] else ""
|
||||
print(f" ★ [{detail['阶段']}] {code} {name:<6} "
|
||||
f"评分: {detail['综合评分']} (均线{detail['均线分']}/形态{detail['形态分']}/量价{detail['量价分']}) "
|
||||
f"突破后天数: {detail['突破后交易日']}{limit_flag}", 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"=== 启动形态扫描 (v6 Lite): 共 {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()
|
||||
|
||||
# [D4] v6 防追高核心排序逻辑:综合评分↓ -> 刚突破天数↑ -> 乖离率↑
|
||||
df_res = pd.DataFrame(self.matched_rows).sort_values(
|
||||
by=["综合评分", "突破后交易日", "乖离MA20%"],
|
||||
ascending=[False, True, True]
|
||||
).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
|
||||
|
||||
print("首次初始化全市场股票池(使用腾讯财经行情源)...")
|
||||
exclude_pat = "|".join([re.escape(k) for k in EXCLUDE_KEYWORDS])
|
||||
pool = pd.DataFrame()
|
||||
|
||||
session = requests.Session()
|
||||
session.trust_env = False # 绕过系统损坏代理
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/122.0.0.0 Safari/537.36",
|
||||
"Referer": "https://gu.qq.com/",
|
||||
}
|
||||
|
||||
all_rows = []
|
||||
try:
|
||||
page = 0
|
||||
while True:
|
||||
url = f"http://stock.gtimg.cn/data/index.php?appn=rank&t=ranka/chr&p={page}&o=0&l=80&v=list_data"
|
||||
r = session.get(url, headers=headers, timeout=6.0)
|
||||
if r.status_code == 200 and 'list_data="' in r.text:
|
||||
content = r.text.split('list_data="')[1].split('";')[0].strip()
|
||||
if not content:
|
||||
break
|
||||
items = content.split(",")
|
||||
for it in items:
|
||||
parts = it.split("~")
|
||||
if len(parts) >= 4:
|
||||
cd = parts[1].strip()
|
||||
nm = parts[2].strip()
|
||||
try:
|
||||
px = float(parts[3])
|
||||
except (ValueError, TypeError):
|
||||
px = 0.0
|
||||
all_rows.append({"代码": cd, "名称": nm, "最新价": px})
|
||||
if len(items) < 80:
|
||||
break
|
||||
page += 1
|
||||
else:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
|
||||
if all_rows:
|
||||
df_all = pd.DataFrame(all_rows)
|
||||
mask = (
|
||||
df_all["代码"].str.startswith(POOL_PREFIX) &
|
||||
~df_all["名称"].str.contains(exclude_pat, na=False) &
|
||||
(df_all["最新价"] >= MIN_PRICE)
|
||||
)
|
||||
pool = df_all[mask][["代码", "名称"]].drop_duplicates(subset=["代码"]).reset_index(drop=True)
|
||||
except Exception as e:
|
||||
logger.warning(f"腾讯行情列表获取异常: {e}")
|
||||
|
||||
# 备用保底
|
||||
if pool.empty:
|
||||
try:
|
||||
print(" -> 尝试备用通道: AkShare 交易所基础代码表...")
|
||||
df_info = ak.stock_info_a_code_name()
|
||||
df_info = df_info.rename(columns={"code": "代码", "name": "名称"})
|
||||
mask = (
|
||||
df_info["代码"].astype(str).str.startswith(POOL_PREFIX) &
|
||||
~df_info["名称"].astype(str).str.contains(exclude_pat, na=False)
|
||||
)
|
||||
pool = df_info[mask][["代码", "名称"]].astype(str).drop_duplicates().reset_index(drop=True)
|
||||
except Exception as e:
|
||||
logger.warning(f"备用通道亦失败: {e}")
|
||||
|
||||
if not pool.empty:
|
||||
storage.save_cached_pool(pool)
|
||||
print(f"✓ 成功获取并持久化全市场股票池至 SQLite: 共 {len(pool)} 只")
|
||||
else:
|
||||
print("✗ 无法获取全市场股票池,请检查网络连接。")
|
||||
|
||||
if limit and limit > 0:
|
||||
pool = pool.head(limit)
|
||||
return pool
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="A股慢牛与起爆形态智能筛选系统 (v6 Lite 腾讯极速版)")
|
||||
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="综合评分下限 (默认 74 分)")
|
||||
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"选股结果_v6_lite_{stamp}.csv")
|
||||
res_df.to_csv(csv_file, index=False, encoding="utf-8-sig")
|
||||
print(f"\n结果已成功导出至: {csv_file}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user