Skill: tangweigang-jpg/stock-pattern-screener (version 0.3.3)

--- name: stock-pattern-screener description: |- 使用7种技术形态检测器（杯柄、三周紧绑、高紧旗、VCP、NR7等）按确定性顺序扫描股票池，支持跨检测器评分校准与置信度聚合排序。 license: Proprietary. See LICENSE.txt in project root. compatibility: Designed for Doramagic-host ecosystem (Claude Code / openclaw / Cursor). Requires Python 3.12+ with uv package manager. metadata: version: "v6.1" blueprint_id: "finance-bp-082" compiled_at: "2026-04-22T13:00:32.580572+00:00" capability_markets: "unspecified" capability_activities: "finance-analytics" sop_version: "crystal-compilation-v6.1" --- # 股票形态筛选 (stock-pattern-screener) > 使用7种技术形态检测器（杯柄、三周紧绑、高紧旗、VCP、NR7等）按确定性顺序扫描股票池，支持跨检测器评分校准与置信度聚合排序。 ## Pipeline `data_collection -> data_storage -> factor_computation -> target_selection -> trading_execution -> visualization` ## Top Use Cases (30 total) ### FastAPI Application Bootstrap (`UC-001`) Provides the main FastAPI application entry point with CORS middleware, dependency injection wiring, and runtime service initialization for the Hermes **Triggers**: api, server, start ### Server Authentication Service (`UC-005`) Provides single-user server authentication helpers including token encoding, decoding, expiration checking, and HMAC signature validation for securing **Triggers**: auth, authentication, token ### Setup Engine Pattern Detection (`UC-014`) Detects chart patterns (VCP, Cup-with-Handle, NR7, etc.) using normalized scoring and cross-detector calibration for trade setup quality assessment **Triggers**: setup, pattern, vcp For all **30** use cases, see [references/USE_CASES.md](references/USE_CASES.md). **Execute trigger**: `When user intent matches intent_router.uc_entries[].positive_terms AND user uses action verb (run/execute/跑/执行/backtest/fetch/collect)` ## What I'll Ask You - Target market: A-share (default), HK, or crypto? (US stocks in ZVT are half-baked — stockus_nasdaq_AAPL exists but coverage is thin) - Data source / provider: eastmoney (free, no account), joinquant (account+paid), baostock (free, good history), akshare, or qmt (broker)? - Strategy type: MACD golden-cross, MA crossover, volume breakout, fundamental screen, or custom factor? - Time range: start_timestamp and end_timestamp for backtest period - Target entity IDs: specific stocks (stock_sh_600000) or index components (SZ1000)? ## Semantic Locks (Fatal) | ID | Rule | On Violation | |---|---|---| | `SL-01` | Execute sell orders before buy orders in every trading cycle | halt | | `SL-02` | Trading signals MUST use next-bar execution (no look-ahead) | halt | | `SL-03` | Entity IDs MUST follow format entity_type_exchange_code | halt | | `SL-04` | DataFrame index MUST be MultiIndex (entity_id, timestamp) | halt | | `SL-05` | TradingSignal MUST have EXACTLY ONE of: position_pct, order_money, order_amount | halt | | `SL-06` | filter_result column semantics: True=BUY, False=SELL, None/NaN=NO ACTION | halt | | `SL-07` | Transformer MUST run BEFORE Accumulator in factor pipeline | halt | | `SL-08` | MACD parameters locked: fast=12, slow=26, signal=9 | halt | Full lock definitions: [references/LOCKS.md](references/LOCKS.md) ## Evidence Quality Notice > [QUALITY NOTICE] This crystal was compiled from blueprint finance-bp-082. Evidence verify ratio = 20.6% and audit fail total = 13. Generated results may have uncaptured requirement gaps. Verify critical decisions against source files (LATEST.yaml / LATEST.jsonl). ## Reference Files | File | Contents | When to Load | |---|---|---| | [references/seed.yaml](references/seed.yaml) | V6+ 全量权威 (source-of-truth) | 有行为/决策争议时必读 | | [references/ANTI_PATTERNS.md](references/ANTI_PATTERNS.md) | 0 条跨项目反模式 | 开始实现前 | | [references/WISDOM.md](references/WISDOM.md) | 跨项目精华借鉴 | 架构决策时 | | [references/CONSTRAINTS.md](references/CONSTRAINTS.md) | domain + fatal 约束 | 规则冲突时 | | [references/USE_CASES.md](references/USE_CASES.md) | 全量 KUC-* 业务场景 | 需要完整示例时 | | [references/LOCKS.md](references/LOCKS.md) | SL-* + preconditions + hints | 生成回测/交易代码前 | | [references/COMPONENTS.md](references/COMPONENTS.md) | AST 组件地图（按 module 拆分）| 查 API 时 | --- *Compiled by Doramagic crystal-compilation-v6.1 from `finance-bp-082` blueprint at 2026-04-22T13:00:32.580572+00:00.* *See [human_summary.md](human_summary.md) for non-technical overview.*

path: human_summary.md
content: # Human Summary

> I help you build quant strategies on A-share with ZVT — from data fetch to backtest, one flow. Just tell me what you want; I'll write the code, you don't have to dig docs. (Heads up: ZVT natively supports A-share, HK, and crypto. US stocks — stockus_nasdaq_AAPL — are half-baked; don't bother for serious work.)

## What I Can Do

- **tagline**: I help you build quant strategies on A-share with ZVT — from data fetch to backtest, one flow. Just tell me what you want; I'll write the code, you don't have to dig docs. (Heads up: ZVT natively supports A-share, HK, and crypto. US stocks — stockus_nasdaq_AAPL — are half-baked; don't bother for serious work.)
- **use_cases**: ['Legacy Runtime Database Migration', 'XUI-Reader CLI Workflows', 'FastAPI Application Bootstrap', 'A-share MACD daily golden-cross backtest with hfq price adjustment from eastmoney', 'End-to-end ZVT pipeline: FinanceRecorder + GoodCompanyFactor + StockTrader', 'Multi-factor strategy with TargetSelector (AND mode) combining MACD + volume breakout', 'Index composition data collection (SZ1000, SZ2000) with EM recorder']

## What I Ask You

- Target market: A-share (default), HK, or crypto? (US stocks in ZVT are half-baked — stockus_nasdaq_AAPL exists but coverage is thin)
- Data source / provider: eastmoney (free, no account), joinquant (account+paid), baostock (free, good history), akshare, or qmt (broker)?
- Strategy type: MACD golden-cross, MA crossover, volume breakout, fundamental screen, or custom factor?
- Time range: start_timestamp and end_timestamp for backtest period
- Target entity IDs: specific stocks (stock_sh_600000) or index components (SZ1000)?


path: references/ANTI_PATTERNS.md
content: # Anti-Patterns (Cross-Project)

Total: **0**


path: references/COMPONENTS.md
content: # Component Capability Map

**Project**: finance-bp-082--stock-screener
**Scan date**: 2026-04-22
**Stats**: {'total_files': 7, 'total_classes': 37, 'total_functions': 0, 'total_stages': 7}

## Modules (7)

- [data_collection_layer](components/data_collection_layer.md): 5 classes
- [screening_execution_layer](components/screening_execution_layer.md): 5 classes
- [pattern_detection_layer_(setup_engine)](components/pattern_detection_layer_-setup_engine.md): 6 classes
- [scoring_and_rating_layer](components/scoring_and_rating_layer.md): 5 classes
- [persistence_layer](components/persistence_layer.md): 5 classes
- [api_layer](components/api_layer.md): 6 classes
- [cache_infrastructure](components/cache_infrastructure.md): 5 classes


path: references/CONSTRAINTS.md
content: # Constraints

## preservation_manifest

```yaml
required_objects:
  business_decisions_count: 182
  fatal_constraints_count: 44
  non_fatal_constraints_count: 274
  use_cases_count: 30
  semantic_locks_count: 12
  preconditions_count: 4
  evidence_quality_rules_count: 2
  traceback_scenarios_count: 5

```


path: references/LOCKS.md
content: # Semantic Locks + Preconditions

## Semantic Locks (12)

### `SL-01` <sub>(on_violation: fatal)</sub>
Execute sell orders before buy orders in every trading cycle

### `SL-02` <sub>(on_violation: fatal)</sub>
Trading signals MUST use next-bar execution (no look-ahead)

### `SL-03` <sub>(on_violation: fatal)</sub>
Entity IDs MUST follow format entity_type_exchange_code

### `SL-04` <sub>(on_violation: fatal)</sub>
DataFrame index MUST be MultiIndex (entity_id, timestamp)

### `SL-05` <sub>(on_violation: fatal)</sub>
TradingSignal MUST have EXACTLY ONE of: position_pct, order_money, order_amount

### `SL-06` <sub>(on_violation: fatal)</sub>
filter_result column semantics: True=BUY, False=SELL, None/NaN=NO ACTION

### `SL-07` <sub>(on_violation: fatal)</sub>
Transformer MUST run BEFORE Accumulator in factor pipeline

### `SL-08` <sub>(on_violation: fatal)</sub>
MACD parameters locked: fast=12, slow=26, signal=9

### `SL-09` <sub>(on_violation: warning)</sub>
Default transaction costs: buy_cost=0.001, sell_cost=0.001, slippage=0.001

### `SL-10` <sub>(on_violation: fatal)</sub>
A-share equity trading is T+1 (no same-day close of buy positions)

### `SL-11` <sub>(on_violation: fatal)</sub>
Recorder subclass MUST define provider AND data_schema class attributes

### `SL-12` <sub>(on_violation: fatal)</sub>
Factor result_df MUST contain either 'filter_result' OR 'score_result' column

## Preconditions (4)

- **`PC-01`**: `python3 -c 'import zvt; print(zvt.__version__)'` → on_fail: Run: python3 -m pip install zvt then re-run: python3 -m zvt.init_dirs to initialize data directories
- **`PC-02`**: `python3 -c "from zvt.api.kdata import get_kdata; df = get_kdata(entity_ids=['stock_sh_600000'], limit=1); assert df is not None and len(df) > 0, 'No kdata found'"` → on_fail: Run recorder first: python3 -m zvt.recorders.em.em_stock_kdata_recorder --entity_ids stock_sh_600000 (replace with your target entity IDs)
- **`PC-03`**: `python3 -c "import os; from pathlib import Path; zvt_home = Path(os.environ.get('ZVT_HOME', Path.home() / '.zvt')); assert zvt_home.exists(), f'ZVT home not found: {zvt_home}'"` → on_fail: Run: python3 -m zvt.init_dirs
- **`PC-04`**: `python3 -c "import os, tempfile; from pathlib import Path; zvt_home = Path(os.environ.get('ZVT_HOME', Path.home() / '.zvt')); test_f = zvt_home / '.write_test'; test_f.touch(); test_f.unlink()"` → on_fail: Check directory permissions: chmod u+w ~/.zvt or set ZVT_HOME environment variable to a writable location


path: references/USE_CASES.md
content: # Known Use Cases (KUC)

Total: **30**

## `KUC-001`
**Source**: `backend/app/main.py`

Provides the main FastAPI application entry point with CORS middleware, dependency injection wiring, and runtime service initialization for the Hermes Market Copilot backend.

## `KUC-002`
**Source**: `xui-reader/src/xui_reader/cli.py`

Provides a Typer-based CLI for authenticating with X (Twitter), managing browser sessions, and collecting social media data for theme discovery and sentiment analysis.

## `KUC-003`
**Source**: `backend/scripts/run_legacy_runtime_migrations.py`

Runs pre-Alembic schema reconciliation steps exactly once to migrate legacy runtime data structures to the current schema.

## `KUC-004`
**Source**: `backend/app/use_cases/scanning/run_bulk_scan.py`

Orchestrates the full bulk scan execution lifecycle including checkpoint-based resume support, chunk processing, progress reporting, and cancellation handling.

## `KUC-005`
**Source**: `backend/app/services/server_auth.py`

Provides single-user server authentication helpers including token encoding, decoding, expiration checking, and HMAC signature validation for securing API endpoints.

## `KUC-006`
**Source**: `backend/app/interfaces/mcp/server.py`

Provides a minimal stdio MCP (Model Context Protocol) server for integrating the Hermes Market Copilot with external AI agents via JSON-RPC messaging.

## `KUC-007`
**Source**: `backend/tests/unit/test_universe_resolver_asia_indices.py`

Resolves index-based universes (HSI, NIKKEI225, TAIEX) to constituent symbols for targeted Asian market scanning.

## `KUC-008`
**Source**: `backend/tests/unit/test_watchlist_import_service.py`

Parses and deduplicates symbols from text, CSV, or tab-delimited watchlist imports for stock screening.

## `KUC-009`
**Source**: `backend/tests/unit/test_market_hours.py`

Provides utilities for detecting trading days, checking market open/close times, and managing NYSE calendar integration across US and Asian markets.

## `KUC-010`
**Source**: `backend/tests/unit/test_minervini_scanner.py`

Implements the Minervini trend template screening strategy for identifying growth stocks in strong uptrends with market cap, price, and volume criteria.

## `KUC-011`
**Source**: `backend/tests/unit/test_canslim_scanner.py`

Implements the CANSLIM screening strategy combining current earnings, annual earnings, new products/management, supply/demand, market direction, and leader/laggard analysis.

## `KUC-012`
**Source**: `backend/tests/unit/test_ipo_scanner.py`

Screens for stocks with recent IPO dates that meet Minervini/CANSLIM criteria, identifying early-stage companies with growth potential.

## `KUC-013`
**Source**: `backend/tests/unit/test_custom_scanner.py`

Provides a configurable stock screener with custom filters for price, volume, RS rating, market cap, debt, sector, EPS/sales growth, and technical criteria.

## `KUC-014`
**Source**: `backend/tests/unit/test_setup_engine_screener.py`

Detects chart patterns (VCP, Cup-with-Handle, NR7, etc.) using normalized scoring and cross-detector calibration for trade setup quality assessment.

## `KUC-015`
**Source**: `backend/tests/unit/test_breadth_calculator.py`

Calculates market breadth metrics including the percentage of stocks above their moving averages to assess overall market health and participation.

## `KUC-016`
**Source**: `backend/tests/unit/test_scan_result_query_builder.py`

Builds and executes filtered, sorted, paginated queries on scan results with support for JSON field extraction and complex filter conditions.

## `KUC-017`
**Source**: `backend/tests/unit/test_quality_policy_scoring.py`

Applies quality-aware fallback policy to stock ratings based on data completeness, excluding low-quality signals and downgrading partial data.

## `KUC-018`
**Source**: `backend/tests/unit/test_validation_service.py`

Validates scan predictions against actual price outcomes, tracking win rates and accuracy across different time horizons (20, 50, 100 days).

## `KUC-019`
**Source**: `backend/tests/unit/test_stock_universe_service_index_membership.py`

Manages stock universe membership including active/inactive status, index constituents (SP500, HSI, NIKKEI225, TAIEX), and market/exchange categorization.

## `KUC-020`
**Source**: `backend/tests/unit/test_assistant_gateway_service.py`

Bridges Hermes AI assistant requests to backend services, handling conversation management, tool routing, and MCP watchlist writes.

## `KUC-021`
**Source**: `backend/tests/unit/test_theme_discovery_ingestion_tasks.py`

Ingests content from various sources (Twitter, Substack, news) for theme discovery, tracking content items and error states during extraction.

## `KUC-022`
**Source**: `backend/tests/unit/test_setup_engine_feature_flag.py`

Controls setup engine inclusion in scan orchestrator via feature flag, allowing silent filtering when disabled without breaking existing workflows.

## `KUC-023`
**Source**: `backend/tests/unit/test_hybrid_fundamentals_service.py`

Fetches fundamentals from multiple providers (yfinance, finviz) with market-aware routing policy, caching, and FX normalization for international stocks.

## `KUC-024`
**Source**: `backend/tests/unit/test_breadth_tasks.py`

Orchestrates daily breadth calculation tasks with warmup checks, refusing to publish when price cache warmup is incomplete.

## `KUC-025`
**Source**: `backend/tests/unit/test_pattern_calibration.py`

Normalizes scores across multiple pattern detectors using cross-detector calibration to ensure consistent quality and readiness scoring.

## `KUC-026`
**Source**: `backend/tests/unit/test_multilingual_qa_harness.py`

Validates multilingual text extraction pipeline (CJK alias resolution, language detection, ticker normalization) against golden corpora with precision/recall gates.

## `KUC-027`
**Source**: `backend/tests/unit/test_mcp_market_copilot.py`

Provides MCP tools for stock snapshots, scan results, breadth data, and watchlist management accessible to external AI agents via JSON-RPC.

## `KUC-028`
**Source**: `backend/tests/unit/test_custom_scanner_mixed_market.py`

Applies market-aware filtering policies for multi-market scans, using USD-normalized criteria when scanning across US, HK, JP, and TW markets.

## `KUC-029`
**Source**: `backend/tests/unit/test_universe_compat_adapter.py`

Adapts legacy universe request formats to typed UniverseDefinition with deprecation headers for gradual migration from old API style.

## `KUC-030`
**Source**: `backend/tests/unit/test_theme_content_recovery_logic.py`

Detects and recovers from theme content corruption by resetting storage and recreating data immediately after schema rewind.


path: references/WISDOM.md
content: # Cross-Project Wisdom

Total: **0**


path: references/components/api_layer.md
content: # api_layer (6 classes)

## `create_scan`
`api_layer/create-scan.py:0`

## `get_scan_results`
`api_layer/get-scan-results.py:0`

## `CreateScanUseCase.execute`
`api_layer/createscanusecase-execute.py:0`

## `RunBulkScanUseCase.execute`
`api_layer/runbulkscanusecase-execute.py:0`

## `Task backend`
`api_layer/task-backend.py:0`

## `API framework`
`api_layer/api-framework.py:0`


path: references/components/cache_infrastructure.md
content: # cache_infrastructure (5 classes)

## `PriceCacheService.get`
`cache_infrastructure/pricecacheservice-get.py:0`

## `FundamentalsCacheService.get`
`cache_infrastructure/fundamentalscacheservice-get.py:0`

## `BenchmarkCacheService.get_benchmark`
`cache_infrastructure/benchmarkcacheservice-get-benchmark.py:0`

## `Cache backend`
`cache_infrastructure/cache-backend.py:0`

## `Lock implementation`
`cache_infrastructure/lock-implementation.py:0`


path: references/components/data_collection_layer.md
content: # data_collection_layer (5 classes)

## `DataPreparationLayer.fetch_stock_data`
`data_collection_layer/datapreparationlayer-fetch-stock-data.py:0`

## `StockDataProvider.get_stock_data`
`data_collection_layer/stockdataprovider-get-stock-data.py:0`

## `DataRequirements.merge`
`data_collection_layer/datarequirements-merge.py:0`

## `StockDataProvider port`
`data_collection_layer/stockdataprovider-port.py:0`

## `Cache backend`
`data_collection_layer/cache-backend.py:0`


path: references/components/pattern_detection_layer_-setup_engine.md
content: # pattern_detection_layer_(setup_engine) (6 classes)

## `PatternDetector.detect`
`pattern_detection_layer_(setup_engine)/patterndetector-detect.py:0`

## `PatternDetector.detect_safe`
`pattern_detection_layer_(setup_engine)/patterndetector-detect-safe.py:0`

## `SetupEngineAggregator.aggregate`
`pattern_detection_layer_(setup_engine)/setupengineaggregator-aggregate.py:0`

## `BreakoutReadinessFeatures.compute`
`pattern_detection_layer_(setup_engine)/breakoutreadinessfeatures-compute.py:0`

## `Detector implementation`
`pattern_detection_layer_(setup_engine)/detector-implementation.py:0`

## `Parameter profile`
`pattern_detection_layer_(setup_engine)/parameter-profile.py:0`


path: references/components/persistence_layer.md
content: # persistence_layer (5 classes)

## `SqlScanResultRepository.query`
`persistence_layer/sqlscanresultrepository-query.py:0`

## `SqlFeatureStoreRepository.publish_atomically`
`persistence_layer/sqlfeaturestorerepository-publish-atomic.py:0`

## `FeatureRun.state_transition`
`persistence_layer/featurerun-state-transition.py:0`

## `Repository implementation`
`persistence_layer/repository-implementation.py:0`

## `Query dialect`
`persistence_layer/query-dialect.py:0`


path: references/components/scoring_and_rating_layer.md
content: # scoring_and_rating_layer (5 classes)

## `calculate_composite_score`
`scoring_and_rating_layer/calculate-composite-score.py:0`

## `calculate_overall_rating`
`scoring_and_rating_layer/calculate-overall-rating.py:0`

## `apply_quality_policy`
`scoring_and_rating_layer/apply-quality-policy.py:0`

## `Scoring weights`
`scoring_and_rating_layer/scoring-weights.py:0`

## `Quality threshold`
`scoring_and_rating_layer/quality-threshold.py:0`


path: references/components/screening_execution_layer.md
content: # screening_execution_layer (5 classes)

## `ScanOrchestrator.scan_stock_multi`
`screening_execution_layer/scanorchestrator-scan-stock-multi.py:0`

## `BaseStockScreener.scan_stock`
`screening_execution_layer/basestockscreener-scan-stock.py:0`

## `ScreenerRegistry.get`
`screening_execution_layer/screenerregistry-get.py:0`

## `Screener implementation`
`screening_execution_layer/screener-implementation.py:0`

## `Composite scoring method`
`screening_execution_layer/composite-scoring-method.py:0`


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)