Spaces:
Sleeping
Sleeping
File size: 24,245 Bytes
c68f3b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 | """
股票过滤模块 — 将自然语言过滤规则解析为结构化条件并执行。
架构:
用户自然语言 → LLM 解析为 FilterConditions
├── DuckDB 条件(K线数据: amount/volume/price)→ SQL 查询
└── 外部数据条件(akshare: 市值/ST/PE/PB)→ API 获取 + 缓存
使用固定 SQL 模板执行 DuckDB 查询,不信任 LLM 生成的 SQL。
"""
import json
import logging
import time
from dataclasses import dataclass, field
from typing import Any
logger = logging.getLogger(__name__)
# ─── 数据结构 ───────────────────────────────────────────────
@dataclass
class DuckDBCondition:
filter_type: str # "avg_daily_amount" | "avg_daily_volume" | "price_range" | "price_above_ma"
params: dict
description: str
@dataclass
class ExternalCondition:
data_type: str # "market_cap" | "circulating_market_cap" | "st_status" | "pe_ratio" | "pb_ratio"
operator: str # ">", "<", ">=", "<=", "==", "!="
value: Any
description: str
@dataclass
class FilterConditions:
duckdb_conditions: list[DuckDBCondition] = field(default_factory=list)
external_conditions: list[ExternalCondition] = field(default_factory=list)
unsupported: list[str] = field(default_factory=list)
# ─── 校验注册表 ──────────────────────────────────────────────
VALID_OPERATORS = {">", "<", ">=", "<=", "==", "!="}
DUCKDB_FILTER_SCHEMAS: dict[str, dict] = {
"avg_daily_amount": {"required": ["lookback_days", "min_value"]},
"avg_daily_volume": {"required": ["lookback_days", "min_value"]},
"price_range": {"at_least_one": ["min_price", "max_price"]},
"price_above_ma": {"required": ["ma_days"]},
}
EXTERNAL_LABEL_MAP = {
"market_cap": "总市值",
"circulating_market_cap": "流通市值",
"st_status": "ST状态",
"pe_ratio": "市盈率(动态)",
"pb_ratio": "市净率",
}
EXTERNAL_DATA_TYPES = set(EXTERNAL_LABEL_MAP.keys())
def _format_number(val: float) -> str:
"""将大数字格式化为易读的中文单位 (亿/万)"""
val = float(val)
if abs(val) >= 1e8:
return f"{val / 1e8:.2f}亿"
if abs(val) >= 1e4:
return f"{val / 1e4:.2f}万"
return f"{val:,.2f}"
def _parsed_desc_duckdb(cond: DuckDBCondition) -> str:
"""为 DuckDB 条件生成可读的执行描述"""
ft = cond.filter_type
p = cond.params
if ft == "avg_daily_amount":
days = p.get("lookback_days", 20)
val = p.get("min_value", 0)
return f"近{days}日日均成交金额 ≥ {_format_number(val)}元"
if ft == "avg_daily_volume":
days = p.get("lookback_days", 20)
val = p.get("min_value", 0)
return f"近{days}日日均成交量 ≥ {_format_number(val)}"
if ft == "price_range":
parts = []
if "min_price" in p:
parts.append(f"≥ {p['min_price']}元")
if "max_price" in p:
parts.append(f"≤ {p['max_price']}元")
return f"最新收盘价 {' 且 '.join(parts)}"
if ft == "price_above_ma":
days = p.get("ma_days", 20)
return f"收盘价 > {days}日均线"
return cond.description
def _parsed_desc_external(cond: ExternalCondition) -> str:
"""为外部数据条件生成可读的执行描述"""
if cond.data_type == "st_status":
if cond.operator == "!=" and cond.value is True:
return "排除ST股"
if cond.operator == "==" and cond.value is True:
return "仅保留ST股"
return f"ST状态 {cond.operator} {cond.value}"
label = EXTERNAL_LABEL_MAP.get(cond.data_type, cond.data_type)
val_str = _format_number(cond.value) if isinstance(cond.value, (int, float)) else str(cond.value)
unit = "元" if cond.data_type in ("market_cap", "circulating_market_cap") else ""
return f"{label} {cond.operator} {val_str}{unit}"
# ─── LLM 解析 ──────────────────────────────────────────────
PARSE_SYSTEM_PROMPT = """你是一个股票过滤条件解析器。将用户的自然语言过滤规则解析为结构化 JSON。
## 支持的 DuckDB 过滤类型(基于5分钟K线OHLCV数据)
| filter_type | 说明 | 参数 |
|---|---|---|
| avg_daily_amount | 近N日平均每日成交金额 | lookback_days(int), min_value(float,单位:元) |
| avg_daily_volume | 近N日平均每日成交量 | lookback_days(int), min_value(float) |
| price_range | 最新收盘价范围 | min_price(float,可选), max_price(float,可选) |
| price_above_ma | 价格在N日均线之上 | ma_days(int) |
## 支持的外部数据过滤类型(通过akshare实时获取)
| data_type | 说明 |
|---|---|
| market_cap | 总市值过滤(单位:元) |
| circulating_market_cap | 流通市值过滤(单位:元) |
| st_status | ST状态过滤(value为true表示排除ST,false表示只保留ST) |
| pe_ratio | 市盈率(动态)过滤 |
| pb_ratio | 市净率过滤 |
## 输出格式
严格输出以下JSON,不要输出其他内容:
```json
{
"duckdb_conditions": [
{"filter_type": "xxx", "params": {...}, "description": "原始条件描述"}
],
"external_conditions": [
{"data_type": "xxx", "operator": ">", "value": 123, "description": "原始条件描述"}
],
"unsupported": ["无法实现的条件描述"]
}
```
## 重要规则
- 金额单位统一为"元"。如"2亿元" → 200000000,"50亿" → 5000000000
- 市值单位统一为"元"
- st_status 用 operator "!=" value true 表示"排除ST"(非ST)
- 如果条件无法归类到以上任何类型,放入 unsupported
- 每个自然语言条件对应一个结构化条件
- 只输出JSON,不要解释"""
def parse_filter_rule(filter_rule: str) -> FilterConditions:
"""调用 LLM 将自然语言过滤规则解析为结构化条件"""
import config
if not config.ANTHROPIC_API_KEY:
raise ValueError("ANTHROPIC_API_KEY 未配置,无法解析过滤规则")
from anthropic import Anthropic
client = Anthropic(
api_key=config.ANTHROPIC_API_KEY,
base_url=config.ANTHROPIC_BASE_URL or None,
)
response = client.messages.create(
model=config.ANTHROPIC_MODEL,
max_tokens=1024,
system=PARSE_SYSTEM_PROMPT,
messages=[{"role": "user", "content": filter_rule}],
)
text = response.content[0].text.strip()
# 提取 JSON(可能被 ```json 包裹)
if "```" in text:
lines = text.split("\n")
json_lines = []
in_block = False
for line in lines:
if line.strip().startswith("```"):
in_block = not in_block
continue
if in_block:
json_lines.append(line)
text = "\n".join(json_lines)
parsed = json.loads(text)
conditions = FilterConditions()
for item in parsed.get("duckdb_conditions", []):
conditions.duckdb_conditions.append(DuckDBCondition(
filter_type=item["filter_type"],
params=item.get("params", {}),
description=item.get("description", ""),
))
for item in parsed.get("external_conditions", []):
conditions.external_conditions.append(ExternalCondition(
data_type=item["data_type"],
operator=item.get("operator", ">"),
value=item.get("value"),
description=item.get("description", ""),
))
conditions.unsupported = parsed.get("unsupported", [])
logger.info(
f"过滤规则解析完成: {len(conditions.duckdb_conditions)} DuckDB条件, "
f"{len(conditions.external_conditions)} 外部数据条件, "
f"{len(conditions.unsupported)} 不支持"
)
return conditions
# ─── DuckDB 过滤执行 ────────────────────────────────────────
def filter_by_kline(store, cond: DuckDBCondition) -> set[str]:
"""通过 DuckDB 查询 K 线数据执行过滤,返回符合条件的 code 集合。
使用固定 SQL 模板,不信任 LLM 生成的 SQL。
"""
con = store._connect_readonly()
try:
if cond.filter_type == "avg_daily_amount":
lookback = int(cond.params.get("lookback_days", 20))
min_val = float(cond.params.get("min_value", 0))
# 先按日聚合每日总成交金额,再取最近N日平均
sql = """
WITH daily AS (
SELECT code, CAST(datetime AS DATE) AS d, SUM(amount) AS daily_amount
FROM stocks
GROUP BY code, CAST(datetime AS DATE)
),
recent AS (
SELECT code, d, daily_amount,
ROW_NUMBER() OVER (PARTITION BY code ORDER BY d DESC) AS rn
FROM daily
),
avg_amount AS (
SELECT code, AVG(daily_amount) AS avg_daily_amount
FROM recent
WHERE rn <= $1
GROUP BY code
)
SELECT code FROM avg_amount WHERE avg_daily_amount >= $2
"""
result = con.execute(sql, [lookback, min_val]).fetchdf()
elif cond.filter_type == "avg_daily_volume":
lookback = int(cond.params.get("lookback_days", 20))
min_val = float(cond.params.get("min_value", 0))
sql = """
WITH daily AS (
SELECT code, CAST(datetime AS DATE) AS d, SUM(volume) AS daily_volume
FROM stocks
GROUP BY code, CAST(datetime AS DATE)
),
recent AS (
SELECT code, d, daily_volume,
ROW_NUMBER() OVER (PARTITION BY code ORDER BY d DESC) AS rn
FROM daily
),
avg_vol AS (
SELECT code, AVG(daily_volume) AS avg_daily_volume
FROM recent
WHERE rn <= $1
GROUP BY code
)
SELECT code FROM avg_vol WHERE avg_daily_volume >= $2
"""
result = con.execute(sql, [lookback, min_val]).fetchdf()
elif cond.filter_type == "price_range":
min_p = cond.params.get("min_price")
max_p = cond.params.get("max_price")
# 取每只股票最新收盘价
sql = """
WITH latest AS (
SELECT code, close,
ROW_NUMBER() OVER (PARTITION BY code ORDER BY datetime DESC) AS rn
FROM stocks
)
SELECT code FROM latest WHERE rn = 1
"""
conditions = []
params = []
if min_p is not None:
conditions.append(f"close >= ${len(params)+1}")
params.append(float(min_p))
if max_p is not None:
conditions.append(f"close <= ${len(params)+1}")
params.append(float(max_p))
if conditions:
sql = f"""
WITH latest AS (
SELECT code, close,
ROW_NUMBER() OVER (PARTITION BY code ORDER BY datetime DESC) AS rn
FROM stocks
)
SELECT code FROM latest WHERE rn = 1 AND {' AND '.join(conditions)}
"""
result = con.execute(sql, params).fetchdf()
elif cond.filter_type == "price_above_ma":
ma_days = int(cond.params.get("ma_days", 20))
sql = """
WITH daily_close AS (
SELECT code, CAST(datetime AS DATE) AS d,
LAST(close ORDER BY datetime) AS day_close
FROM stocks
GROUP BY code, CAST(datetime AS DATE)
),
ranked AS (
SELECT code, d, day_close,
ROW_NUMBER() OVER (PARTITION BY code ORDER BY d DESC) AS rn
FROM daily_close
),
ma AS (
SELECT code,
MAX(CASE WHEN rn = 1 THEN day_close END) AS latest_close,
AVG(CASE WHEN rn <= $1 THEN day_close END) AS ma_close
FROM ranked
GROUP BY code
)
SELECT code FROM ma WHERE latest_close > ma_close AND ma_close IS NOT NULL
"""
result = con.execute(sql, [ma_days]).fetchdf()
else:
raise ValueError(f"不支持的 DuckDB 过滤类型: {cond.filter_type}")
codes = set(result["code"].tolist())
logger.info(f"DuckDB 过滤 [{cond.filter_type}]: {len(codes)} 只符合条件")
return codes
finally:
con.close()
# ─── akshare 外部数据过滤 ────────────────────────────────────
_external_cache: dict[str, tuple[float, Any]] = {}
_CACHE_TTL = 4 * 3600 # 4 小时缓存
def _fetch_with_proxy():
"""通过动态代理获取 akshare 数据(SOCKS5)"""
import akshare as ak
import socket
import requests
import config
if not config.PROXY_API_URL:
raise RuntimeError("未配置代理 (PROXY_API_URL)")
# 从代理 API 获取 IP
resp = requests.get(config.PROXY_API_URL, timeout=10)
resp.raise_for_status()
addr = resp.text.strip().split(",")[0]
host, port_str = addr.split(":")
port = int(port_str)
logger.info(f"获取到代理: {host}:{port}")
# 临时设置 SOCKS5 全局代理,完成后恢复
import socks
original_socket = socket.socket
try:
socks.set_default_proxy(
socks.SOCKS5, host, port,
username=config.PROXY_USERNAME or None,
password=config.PROXY_PASSWORD or None,
)
socket.socket = socks.socksocket
logger.info("通过代理获取 akshare 数据...")
df = ak.stock_zh_a_spot_em()
logger.info(f"代理获取完成: {len(df)} 只股票")
return df
finally:
socket.socket = original_socket
socks.set_default_proxy()
def _get_a_share_spot_data():
"""获取全量A股实时行情数据(带4小时缓存,直连失败后走代理)"""
import akshare as ak
cache_key = "stock_zh_a_spot_em"
now = time.time()
if cache_key in _external_cache:
cached_time, cached_data = _external_cache[cache_key]
if now - cached_time < _CACHE_TTL:
logger.info("使用缓存的 A 股实时数据")
return cached_data
# 先直连尝试
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
logger.info(f"正在从 akshare 获取 A 股实时行情数据 (第{attempt}次)...")
df = ak.stock_zh_a_spot_em()
_external_cache[cache_key] = (time.time(), df)
logger.info(f"获取完成: {len(df)} 只股票")
return df
except Exception as e:
logger.warning(f"akshare 直连失败 (第{attempt}次): {e}")
if attempt < max_retries:
time.sleep(attempt * 2)
# 直连全部失败,尝试代理
import config
if config.PROXY_API_URL:
logger.info("直连失败,尝试通过代理获取...")
try:
df = _fetch_with_proxy()
_external_cache[cache_key] = (time.time(), df)
return df
except Exception as e:
logger.warning(f"代理获取也失败: {e}")
raise RuntimeError("akshare 数据获取失败(直连和代理均失败)。请检查网络连接或稍后再试。")
def _code_to_bare(code: str) -> str:
"""DuckDB 格式 'sh.600000' → akshare 格式 '600000'"""
if "." in code:
return code.split(".", 1)[1]
return code
def _compare(actual, operator: str, target) -> bool:
"""安全比较"""
try:
actual = float(actual)
target = float(target)
except (ValueError, TypeError):
return False
if operator == ">":
return actual > target
if operator == ">=":
return actual >= target
if operator == "<":
return actual < target
if operator == "<=":
return actual <= target
if operator == "==":
return actual == target
if operator == "!=":
return actual != target
return False
def filter_by_external(codes: list[str], conditions: list[ExternalCondition]) -> set[str]:
"""通过 akshare 外部数据过滤股票"""
df = _get_a_share_spot_data()
# 列名映射(akshare stock_zh_a_spot_em 返回的中文列名)
col_map = {
"market_cap": "总市值",
"circulating_market_cap": "流通市值",
"pe_ratio": "市盈率-动态",
"pb_ratio": "市净率",
}
# 建立 bare_code → row 索引
bare_to_row = {}
for _, row in df.iterrows():
bare_code = str(row.get("代码", ""))
bare_to_row[bare_code] = row
result_codes = set()
for code in codes:
bare = _code_to_bare(code)
row = bare_to_row.get(bare)
if row is None:
continue # akshare 中无此股票
match = True
for cond in conditions:
if cond.data_type == "st_status":
name = str(row.get("名称", ""))
is_st = "ST" in name.upper()
# value=true + operator="!=" 表示排除ST
if cond.operator == "!=" and cond.value is True:
if is_st:
match = False
break
elif cond.operator == "==" and cond.value is True:
if not is_st:
match = False
break
continue
col_name = col_map.get(cond.data_type)
if not col_name or col_name not in row.index:
continue
val = row[col_name]
if not _compare(val, cond.operator, cond.value):
match = False
break
if match:
result_codes.add(code)
logger.info(f"外部数据过滤: {len(codes)} → {len(result_codes)} 只符合条件")
return result_codes
# ─── 顶层 API ───────────────────────────────────────────────
def apply_stock_filter(filter_rule: str, store) -> list[str]:
"""自然语言过滤规则 → 过滤后的 code 列表"""
conditions = parse_filter_rule(filter_rule)
if conditions.unsupported:
logger.warning(f"过滤规则包含不支持的条件: {conditions.unsupported}")
codes = set(store.get_codes())
original_count = len(codes)
# 先 DuckDB 过滤(本地查询,便宜)
for cond in conditions.duckdb_conditions:
matched = filter_by_kline(store, cond)
codes &= matched
# 再 akshare 过滤(有网络开销,失败时降级为只用 DuckDB 结果)
if conditions.external_conditions and codes:
try:
codes = filter_by_external(list(codes), conditions.external_conditions)
except Exception as e:
logger.warning(f"外部数据过滤失败,跳过外部条件: {e}")
logger.info(f"过滤完成: {original_count} → {len(codes)} 只标的")
return sorted(codes)
def validate_filter_rule(filter_rule: str) -> dict:
"""保存前验证过滤规则:解析并结构校验所有条件是否可执行。
返回 {valid, conditions_summary, unsupported, invalid}
"""
conditions = parse_filter_rule(filter_rule)
summary = []
invalid = []
# 校验 DuckDB 条件
for c in conditions.duckdb_conditions:
schema = DUCKDB_FILTER_SCHEMAS.get(c.filter_type)
if schema is None:
invalid.append({
"description": c.description or c.filter_type,
"error": f"未知的过滤类型: {c.filter_type}",
})
continue
# 检查必需参数
missing = []
for param_name in schema.get("required", []):
val = c.params.get(param_name)
if val is None:
missing.append(param_name)
else:
try:
float(val)
except (ValueError, TypeError):
invalid.append({
"description": c.description or c.filter_type,
"error": f"参数 {param_name} 值无效: {val}",
})
break
else:
# 没有 break(参数类型都合法),继续检查 missing
if missing:
invalid.append({
"description": c.description or c.filter_type,
"error": f"缺少必需参数: {', '.join(missing)}",
})
continue
# at_least_one 检查(如 price_range)
at_least_one = schema.get("at_least_one", [])
if at_least_one and not any(c.params.get(p) is not None for p in at_least_one):
invalid.append({
"description": c.description or c.filter_type,
"error": f"至少需要一个参数: {', '.join(at_least_one)}",
})
continue
summary.append({
"description": c.description,
"parsed_description": _parsed_desc_duckdb(c),
"method": "K线数据过滤",
"source": "DuckDB",
"filter_type": c.filter_type,
})
continue
# 如果 for-else 的 else 没执行(即 break 了),说明已经 append 到 invalid
# 校验外部数据条件
for c in conditions.external_conditions:
if c.data_type not in EXTERNAL_DATA_TYPES:
invalid.append({
"description": c.description or c.data_type,
"error": f"未知的外部数据类型: {c.data_type}",
})
continue
if c.data_type == "st_status":
if c.operator not in ("==", "!="):
invalid.append({
"description": c.description or c.data_type,
"error": f"st_status 仅支持 == 或 != 运算符,当前为: {c.operator}",
})
continue
if not isinstance(c.value, bool):
invalid.append({
"description": c.description or c.data_type,
"error": f"st_status 的值必须为布尔值 (true/false),当前为: {c.value}",
})
continue
else:
if c.operator not in VALID_OPERATORS:
invalid.append({
"description": c.description or c.data_type,
"error": f"无效的运算符: {c.operator}",
})
continue
try:
float(c.value)
except (ValueError, TypeError):
invalid.append({
"description": c.description or c.data_type,
"error": f"值必须为数字: {c.value}",
})
continue
summary.append({
"description": c.description,
"parsed_description": _parsed_desc_external(c),
"method": "实时数据过滤",
"source": "akshare",
"data_type": c.data_type,
})
return {
"valid": len(invalid) == 0 and len(conditions.unsupported) == 0 and len(summary) > 0,
"conditions_summary": summary,
"unsupported": conditions.unsupported,
"invalid": invalid,
}
|