### Quick Start Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Instructions for cloning the project, installing dependencies, configuring notifications, and running the system. ```bash # 1. 克隆项目 git clone https://github.com/Dzy-HW-XD/a-share-quant-selector.git cd a-share-quant-selector # 2. 安装依赖 pip3 install -r requirements.txt # 3. 配置钉钉通知(可选) # 编辑 config/config.yaml 填写 webhook 和 secret # 4. 首次全量抓取数据 python3 main.py init # 5. 执行选股(自动更新数据、选股、发送钉钉) python3 main.py run # 6. 快速测试(只处理前500只股票) python3 main.py run --max-stocks 500 # 7. 启动Web界面 python3 main.py web ``` -------------------------------- ### Example: Get Strategy Parameters Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example using curl to fetch the current strategy parameters configuration. ```bash curl http://localhost:5000/api/strategy-params ``` -------------------------------- ### Example: Get Stock List with Parameters Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example using curl to fetch stock list with specified page and per_page parameters. ```bash # 获取第1页,每页500只 curl http://localhost:5000/api/stocks?page=1&per_page=500 # 获取第2页,每页100只 curl http://localhost:5000/api/stocks?page=2&per_page=100 ``` -------------------------------- ### Example: Get K-line Chart Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example using curl to retrieve a stock's K-line chart as a PNG image. ```bash # 在浏览器中访问 http://localhost:5000/api/chart/600000 # 或通过curl保存 curl http://localhost:5000/api/chart/600000 -o 600000.png ``` -------------------------------- ### Code Example for Module Import Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/README.md Example code demonstrating module import and usage. ```python # 注意:示例代码中使用的模块已导入 # 实际使用时需要添加相应的import语句 result = csv_manager.read_stock('600000') ``` -------------------------------- ### Example: Execute Stock Selection (All Strategies) Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example using curl to execute all stock selection strategies with an empty JSON body. ```bash # 执行所有策略 curl -X POST http://localhost:5000/api/select \ -H "Content-Type: application/json" \ -d '{}' ``` -------------------------------- ### Example: Execute Stock Selection (Specific Strategy) Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example using curl to execute a specific stock selection strategy with a maximum number of stocks. ```bash # 执行特定策略,限制500只股票 curl -X POST http://localhost:5000/api/select \ -H "Content-Type: application/json" \ -d '{ "strategy": "BowlReboundStrategy", "max_stocks": 500 }' ``` -------------------------------- ### Workflow Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/strategy_registry.md An example demonstrating a typical workflow: initializing the registry and data manager, registering strategies, preparing stock data, running strategies, and processing results. ```python from strategy.strategy_registry import get_registry from utils.csv_manager import CSVManager # 1. Initialize registry and data manager registry = get_registry("config/strategy_params.yaml") csv_manager = CSVManager('data') # 2. Automatically register all strategies registry.auto_register_from_directory("strategy") # 3. Prepare stock data all_stocks = csv_manager.list_all_stocks() stock_data = {} for code in all_stocks[:1000]: # Process first 1000 stocks df = csv_manager.read_stock(code) if not df.empty: stock_data[code] = ('Stock Name', df) # 4. Execute strategies results = registry.run_all(stock_data) # 5. Process results for strategy_name, signals in results.items(): print(f"\n{strategy_name}: Selected {len(signals)} stocks") for item in signals[:5]: # Display top 5 print(f" {item['code']} {item['name']}") ``` -------------------------------- ### Command-line Startup Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Commands to start the web server from the command line. ```bash # Launch Web Server (default port 5000) python web_server.py # Specify port python web_server.py --port 8080 # Start from main.py python main.py web ``` -------------------------------- ### Correct Configuration Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md An example of a correctly configured B1PatternMatch section where weights sum to 1.0. ```yaml # ✅ 正确 B1PatternMatch: weights: trend_structure: 0.25 kdj_state: 0.25 volume_pattern: 0.25 price_shape: 0.25 # 总和1.0 ``` -------------------------------- ### Scenario 3: Quick Testing Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Commands for initializing stocks for testing, running stock selection, and starting a web interface to view results. ```bash # 初始化100只股票用于测试 python main.py init --max-stocks 100 # 执行选股 python main.py run --max-stocks 100 # 启动Web查看结果 python main.py web ``` -------------------------------- ### Example: Update Strategy Parameters Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example using curl to update strategy parameters with new values. ```bash curl -X PUT http://localhost:5000/api/strategy-params \ -H "Content-Type: application/json" \ -d '{ "strategy": "BowlReboundStrategy", "params": {"N": 3.0, "J_VAL": 25} }' ``` -------------------------------- ### Combined Usage Examples Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/B1_PATTERN_MATCH.md Examples of combining B1 matching with other categories or similarity thresholds. ```bash # Stocks in a falling bowl + B1 match python3 main.py run --b1-match --category bowl_center # Stocks near the bull/bear line + high similarity python3 main.py run --b1-match --category near_duokong --min-similarity 70 ``` -------------------------------- ### Signal Structure Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/README.md Example of the information structure returned by stock selection. ```python { 'date': '2025-11-20', 'close': 10.85, 'J': -5.20, 'category': 'bowl_center', 'reasons': ['回落碗中'] } ``` -------------------------------- ### PatternMatcher Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/pattern_matcher.md Example of initializing and using the PatternMatcher, including using default and custom configurations. ```python from strategy.pattern_matcher import PatternMatcher from strategy.pattern_config import SIMILARITY_WEIGHTS, MATCH_TOLERANCES # 使用默认配置(从strategy_params.yaml读取) matcher = PatternMatcher() # 使用自定义权重 custom_weights = { "trend_structure": 0.25, "kdj_state": 0.25, "volume_pattern": 0.25, "price_shape": 0.25 } matcher = PatternMatcher(weights=custom_weights) ``` -------------------------------- ### Scenario 2: Daily Automation Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Example of scheduling a daily stock selection and DingTalk notification at 15:05. ```bash # 每天15:05执行,自动选股并发钉钉通知 5 15 * * 1-5 python main.py run >> /var/log/quant.log 2>&1 ``` -------------------------------- ### Strategy Configuration Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Example YAML configuration for Bowl Rebound Strategy and B1 Pattern Match. ```yaml # 碗口反弹策略 BowlReboundStrategy: N: 2.4 # 成交量倍数(放量阳线判断) M: 20 # 回溯天数(查找关键K线) CAP: 4000000000 # 流通市值门槛(40亿) J_VAL: 0 # J值上限(KDJ超卖阈值) M1: 14 # MA周期1(多空线计算) M2: 28 # MA周期2(多空线计算) M3: 57 # MA周期3(多空线计算) M4: 114 # MA周期4(多空线计算) duokong_pct: 3 # 距离多空线百分比(分类用) short_pct: 2 # 距离短期趋势线百分比(分类用) # B1完美图形匹配 B1PatternMatch: min_similarity: 60 # 最小相似度阈值(只显示>=此值的股票) lookback_days: 25 # 回看天数(匹配时使用的数据天数) top_n_results: 15 # 展示Top N个匹配结果(钉钉通知中显示的数量) weights: # 四维相似度权重 trend_structure: 0.30 # 双线结构 kdj_state: 0.20 # KDJ状态 volume_pattern: 0.25 # 量能特征 price_shape: 0.25 # 价格形态 tolerances: # 匹配容差参数 trend_ratio: 0.10 # 趋势比值容差(±10%) price_bias: 10 # 价格偏离容差(±10%) trend_spread: 10 # 趋势发散容差(±10%) j_value: 30 # J值差异容差(±30) drawdown: 15 # 回撤幅度容差(±15%) ``` -------------------------------- ### Strategy Parameters - B1PatternMatch - Threshold and Results Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md Example of tuning B1PatternMatch parameters for similarity threshold, lookback days, and top results. ```yaml B1PatternMatch: min_similarity: 70 # 只显示>=70%相似的候选 lookback_days: 30 # 用最近30天的数据匹配 top_n_results: 10 # 只在钉钉显示Top 10 ``` -------------------------------- ### RateLimiter Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/dingtalk_notifier.md Example of how to instantiate and use the RateLimiter to acquire sending permission. ```python from utils.dingtalk_notifier import RateLimiter limiter = RateLimiter(max_per_minute=15, min_interval=3.0) limiter.acquire() # 获取发送许可,必要时阻塞等待 ``` -------------------------------- ### Configuration Error Example: Small M Value Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md An example of an incorrect configuration where the M value in BowlReboundStrategy is too small. ```yaml # ❌ 错误:M值过小 BowlReboundStrategy: M: 3 # M应该>=5 ``` -------------------------------- ### Configuration Example: Pattern Matching Priority Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md Configuration prioritizing pattern matching. ```yaml B1PatternMatch: min_similarity: 65 lookback_days: 35 top_n_results: 20 weights: trend_structure: 0.10 kdj_state: 0.10 volume_pattern: 0.20 price_shape: 0.60 # 形态权重最高 ``` -------------------------------- ### Configuration Example: Aggressive Stock Selection (Quantity First) Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md Configuration for aggressive stock selection prioritizing quantity. ```yaml BowlReboundStrategy: N: 1.5 M: 40 CAP: 2000000000 J_VAL: 50 duokong_pct: 3.0 short_pct: 2.0 B1PatternMatch: min_similarity: 50 weights: trend_structure: 0.10 kdj_state: 0.10 volume_pattern: 0.30 price_shape: 0.50 tolerances: trend_ratio: 0.20 j_value: 50 ``` -------------------------------- ### PatternFeatures Structure Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/README.md Example of the feature vector structure used for B1 matching. ```python { 'trend_structure': {...}, 'kdj_state': {...}, 'volume_pattern': {...}, 'price_shape': [...] } ``` -------------------------------- ### Redirecting Logs Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Examples of how to redirect program output to files, including saving all output, only errors, or using tee to display and save simultaneously. ```bash # 保存所有输出到文件 python main.py run >> run.log 2>&1 # 只保存错误 python main.py run 2>> error.log # 使用tee同时显示和保存 python main.py run 2>&1 | tee run.log ``` -------------------------------- ### Configuration Error Example: Weights Not Summing to 1.0 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md An example of an incorrect configuration where the weights in B1PatternMatch do not sum to 1.0. ```yaml # ❌ 错误:权重不等于1.0 B1PatternMatch: weights: trend_structure: 0.25 kdj_state: 0.25 volume_pattern: 0.25 price_shape: 0.20 # 总和0.95,不是1.0 ``` -------------------------------- ### Error Response Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example JSON structure for an error response. ```json { "success": false, "error": "Stock code does not exist: 999999" } ``` -------------------------------- ### Match Method Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/pattern_matcher.md Example of using the match method to calculate similarity between two stocks' features. ```python from strategy.pattern_matcher import PatternMatcher from strategy.pattern_feature_extractor import PatternFeatureExtractor from utils.csv_manager import CSVManager csv_manager = CSVManager('data') extractor = PatternFeatureExtractor(lookback_days=25) matcher = PatternMatcher() # 提取候选股特征 candidate_df = csv_manager.read_stock('600000') candidate_features = extractor.extract(candidate_df) # 提取案例特征 case_df = csv_manager.read_stock('688799') # 华纳药厂 case_features = extractor.extract(case_df, lookback_days=25) # 计算相似度 result = matcher.match(candidate_features, case_features) print(f"总相似度: {result['total_score']:.2f}%") for dim, score in result['breakdown'].items(): print(f" {dim}: {score:.2f}%") ``` -------------------------------- ### 修改选股参数示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/README.md Example of how to modify stock selection parameters in the configuration file. ```yaml BowlReboundStrategy: N: 2.5 # 修改成交量倍数 J_VAL: 25 # 修改J值阈值 # ... 其他参数 ``` -------------------------------- ### Workflow Example: Single Stock Feature Extraction Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/pattern_feature_extractor.md A complete workflow example for extracting features from a single stock. ```python from strategy.pattern_feature_extractor import PatternFeatureExtractor from utils.csv_manager import CSVManager csv_manager = CSVManager('data') extractor = PatternFeatureExtractor(lookback_days=25) # Read stock data df = csv_manager.read_stock('600000') # Extract features features = extractor.extract(df) ``` -------------------------------- ### 实现自定义策略 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/README.md Example of implementing custom strategy methods based on BaseStrategy. ```python def calculate_indicators(self, df) -> pd.DataFrame: # 计算指标 pass def select_stocks(self, df, stock_name='') -> list: # 选股逻辑 return signals ``` -------------------------------- ### Starting the Web Server Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Python code to run the Flask web server. ```python if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=False) ``` -------------------------------- ### acquire Method Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/dingtalk_notifier.md Example demonstrating how to use the acquire method before sending a DingTalk message and how to handle rate limit errors. ```python limiter = RateLimiter() # 发送消息前获取许可 limiter.acquire() # 发送钉钉消息 result = requests.post(webhook, json=payload) # 如果遇到限速错误,调用 on_rate_limit_error() if result.json().get('errcode') == 660026: limiter.on_rate_limit_error(retry_count=0) ``` -------------------------------- ### Constructor Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/pattern_feature_extractor.md Demonstrates how to instantiate the PatternFeatureExtractor with default and custom lookback days. ```python from strategy.pattern_feature_extractor import PatternFeatureExtractor # Default 25-day lookback extractor = PatternFeatureExtractor() # Custom lookback period extractor = PatternFeatureExtractor(lookback_days=30) ``` -------------------------------- ### Configuration Example: Conservative Stock Selection (Quality First) Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md Configuration for conservative stock selection prioritizing quality. ```yaml BowlReboundStrategy: N: 3.5 M: 20 CAP: 5000000000 J_VAL: 10 duokong_pct: 0.5 short_pct: 0.5 B1PatternMatch: min_similarity: 75 weights: trend_structure: 0.40 kdj_state: 0.20 volume_pattern: 0.20 price_shape: 0.20 tolerances: trend_ratio: 0.05 j_value: 15 ``` -------------------------------- ### Extending a New Strategy Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Python code example for creating a new stock selection strategy. ```python from strategy.base_strategy import BaseStrategy class MyStrategy(BaseStrategy): def __init__(self, params=None): super().__init__("我的策略", params) def calculate_indicators(self, df): # 计算指标 return df def select_stocks(self, df, stock_name=''): # 选股逻辑 return signals ``` -------------------------------- ### Configuration Priority - Command Line Override Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md Example demonstrating how command-line arguments override YAML configuration. ```bash # 命令行参数覆盖YAML配置 python main.py run --b1-match --min-similarity 75 --lookback-days 40 ``` -------------------------------- ### Crontab for Scheduled Tasks Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Example crontab entry for daily automatic stock selection. ```bash # 编辑 crontab crontab -e # 添加以下行(每天15:05执行,仅工作日) 5 15 * * 1-5 cd /root/quant-csv && /usr/bin/python3 main.py run >> /var/log/quant-csv/run.log 2>&1 ``` -------------------------------- ### Scenario 4: B1 Perfect Graphic Matching Test Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Examples of using the B1 matching feature for stock selection, including custom parameters. ```bash # 使用B1匹配执行选股 python main.py run --b1-match --max-stocks 500 # 自定义参数 python main.py run \ --b1-match \ --lookback-days 30 \ --min-similarity 75 \ --max-stocks 200 ``` -------------------------------- ### System Information Response Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Example JSON response for the system information API. ```json { "success": true, "total_stocks": 5000, "stocks_with_data": 4950, "latest_update": "2025-11-20", "data_dir": "/root/quant-csv/data", "strategies": [ "BowlReboundStrategy" ] } ``` -------------------------------- ### init 命令 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 命令行接口命令,用于首次全量初始化数据。 ```bash python main.py init [--max-stocks N] ``` -------------------------------- ### init 命令 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用init命令进行全量初始化、快速测试或初始化样本数据。 ```bash # 全量初始化 python main.py init # 快速测试(仅500只) python main.py init --max-stocks 500 # 样本数据(100只) python main.py init --max-stocks 100 ``` -------------------------------- ### API Route: Get Strategy Parameters Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md API endpoint to retrieve the current configuration of strategy parameters. ```python @app.route('/api/strategy-params') def get_strategy_params() ``` -------------------------------- ### Feature Vector Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/B1_PATTERN_MATCH.md Example of a feature vector for Guoxuan High-tech (002074) before a breakout. ```json { "trend_structure": { "short_vs_bullbear": 1.0, "short_slope": -0.95, "price_vs_short_pct": 0.0, "price_bias_pct": 0.0, "trend_spread_pct": 0.0, "is_in_bowl": false }, "kdj_state": { "j_value": -11.0, "j_position": "低位", "k_cross_d": false, "j_rebound": true }, "volume_pattern": { "avg_volume_ratio": 0.88, "volume_trend": "量能平稳", "shrink_then_expand": false, "max_volume_ratio": 2.1 }, "price_shape": { "normalized_curve": [0.0, 0.1, 0.05, 0.15, ..., 0.95], "max_drawdown": 11.0, "breakout_strength": -1.5, "overall_trend": "下降" } } ``` -------------------------------- ### send_selection_results Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/dingtalk_notifier.md Example of how to use the send_selection_results method with prepared data. ```python notifier = DingTalkNotifier(webhook_url, secret) # 准备数据 category_signals = { 'bowl_center': [...], 'near_duokong': [...], 'near_short_trend': [...] } # 发送结果 success = notifier.send_selection_results( strategy_name="碗口反弹策略", category_signals=category_signals, stock_names=stock_names, stock_data_dict=stock_data_dict ) ``` -------------------------------- ### run 命令 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 命令行接口命令,执行完整流程:更新数据 → 执行选股 → 发送钉钉通知。 ```bash python main.py run [options] ``` -------------------------------- ### DingTalkNotifier Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/dingtalk_notifier.md Example of how to instantiate the DingTalkNotifier with webhook URL and secret. ```python from utils.dingtalk_notifier import DingTalkNotifier notifier = DingTalkNotifier( webhook_url="https://oapi.dingtalk.com/robot/send?access_token=xxx", secret="SECxxx" ) ``` -------------------------------- ### send_b1_match_results Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/dingtalk_notifier.md Example of how to use the send_b1_match_results method with a list of matched results. ```python matched = [ { 'code': '600000', 'name': '平安银行', 'similarity': 85.5, 'matched_case': {'name': '华纳药厂', 'date': '2025-05-12'}, 'breakdown': {...}, 'signal': {...} }, ... ] success = notifier.send_b1_match_results( matched_results=matched, stock_names=stock_names, stock_data_dict=stock_data_dict, top_n=15 ) ``` -------------------------------- ### run 命令 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用run命令执行完整流程,包括指定股票数量、分类和B1匹配参数。 ```bash # 完整流程 python main.py run # 快速测试(仅500只股票) python main.py run --max-stocks 500 # 仅显示回落碗中的股票 python main.py run --category bowl_center # 启用B1完美图形匹配 python main.py run --b1-match # 自定义B1参数 python main.py run --b1-match --lookback-days 30 --min-similarity 70 ``` -------------------------------- ### FAQ: How to run continuously in the background? Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Answer to running continuously in the background using the 'schedule' command with 'nohup'. ```bash nohup python main.py schedule & ``` -------------------------------- ### init_data 方法 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md QuantSystem类的方法,用于首次全量初始化所有股票的历史数据。 ```python def init_data(self, max_stocks: int | None = None) -> None ``` -------------------------------- ### --version 选项 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 命令行接口选项,用于显示程序版本。 ```bash python main.py --version ``` -------------------------------- ### init_data 方法 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用init_data方法进行全量初始化或快速测试。 ```python system = QuantSystem() # 全量初始化(耗时) system.init_data() # 快速测试 system.init_data(max_stocks=100) ``` -------------------------------- ### QuantSystem 构造函数 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md QuantSystem类的构造函数,用于初始化系统并加载配置。 ```python def __init__(self, config_file: str = "config/config.yaml") ``` -------------------------------- ### FAQ: How to enable B1 perfect graphic matching? Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Answer to enabling B1 perfect graphic matching using the --b1-match flag. ```bash python main.py run --b1-match ``` -------------------------------- ### _smart_update 方法 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md QuantSystem类的方法,用于智能更新数据,仅在市场收盘后执行。 ```python def _smart_update(self, max_stocks: int | None = None, check_latest: bool = True) -> None ``` -------------------------------- ### 场景1:第一次使用 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 典型使用场景示例,展示首次使用时的初始化和启动Web界面的命令。 ```bash # 1. 初始化数据(全量) python main.py init # 2. 启动Web查看 python main.py web ``` -------------------------------- ### FAQ: How to select stocks of a specific category? Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Answer to selecting stocks of a specific category using the --category parameter. ```bash python main.py run --category bowl_center ``` -------------------------------- ### Getting a Registered Strategy Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/strategy_registry.md Retrieves a registered strategy by its name. ```python strategy = registry.get_strategy("BowlReboundStrategy") if strategy: print(f"Found strategy: {strategy.name}") else: print("Strategy not found") ``` -------------------------------- ### update 命令 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 命令行接口命令,用于增量更新数据。 ```bash python main.py update [--max-stocks N] ``` -------------------------------- ### schedule 命令 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 命令行接口命令,用于按配置定时执行选股。 ```bash python main.py schedule ``` -------------------------------- ### Exception Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/pattern_feature_extractor.md Provides an example of how to handle exceptions during feature extraction. ```python from strategy.pattern_feature_extractor import PatternFeatureExtractor extractor = PatternFeatureExtractor() try: features = extractor.extract(df) if not features.get('trend_structure'): print("数据不足,特征提取失败") else: # 特征成功提取 pass except Exception as e: print(f"特征提取异常: {e}") ``` -------------------------------- ### Similarity Threshold Adjustment Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/B1_PATTERN_MATCH.md Examples of adjusting the minimum similarity threshold for stricter or looser matching. ```bash # Strict matching (only highly similar) python3 main.py run --b1-match --min-similarity 75 # Loose matching (show more candidates) python3 main.py run --b1-match --min-similarity 50 ``` -------------------------------- ### schedule 命令 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用schedule命令启动定时调度,包括后台运行和crontab配置。 ```bash # 启动定时调度 python main.py schedule # 后台运行 nohup python main.py schedule > /var/log/quant-scheduler.log 2>&1 & # 定时任务(crontab) # 编辑crontab crontab -e # 添加行:每天15:05执行(仅工作日) 5 15 * * 1-5 cd /root/quant-csv && /usr/bin/python3 main.py run >> /var/log/quant-csv/run.log 2>&1 ``` -------------------------------- ### QuantSystem 构造函数 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用QuantSystem类的构造函数,包括使用默认配置和自定义配置。 ```python from main import QuantSystem # 使用默认配置文件 system = QuantSystem() # 使用自定义配置文件 system = QuantSystem(config_file="config/custom.yaml") ``` -------------------------------- ### YAML Parsing Error Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/errors.md Example of handling yaml.YAMLError when parsing YAML configuration files. ```python try: with open('config/strategy_params.yaml', 'r') as f: config = yaml.safe_load(f) except yaml.YAMLError as e: print(f"配置文件格式错误: {e}") config = {} # 使用默认配置 ``` -------------------------------- ### Data Type Conversion Error Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/errors.md Example of handling ValueError during string to float conversion. ```python try: price = float(price_str) except ValueError: print(f"无效的价格值: {price_str}") price = None ``` -------------------------------- ### Backup and Version Management Script Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/configuration.md Bash script for creating configuration templates and managing actual configurations. ```bash # 创建模板 cp config/config.yaml config/config.yaml.template # 编辑实际配置 cp config/config.yaml.template config/config.yaml # 填入敏感信息 # .gitignore中排除实际配置 echo "config/config.yaml" >> .gitignore ``` -------------------------------- ### Connection Timeout Error Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/errors.md Example of handling ConnectionTimeout or TimeoutError with a fallback to local cache. ```python try: df = fetcher.get_stock_history('600000') except (ConnectionError, TimeoutError) as e: print(f"网络错误: {e}") # 重试或使用本地缓存 df = csv_manager.read_stock('600000') ``` -------------------------------- ### web 命令 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 命令行接口命令,用于启动Flask Web服务器。 ```bash python main.py web [--port N] [--host ADDR] ``` -------------------------------- ### Extract Method Usage Example Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/pattern_feature_extractor.md Shows how to read stock data and extract features using the PatternFeatureExtractor. ```python from strategy.pattern_feature_extractor import PatternFeatureExtractor from utils.csv_manager import CSVManager csv_manager = CSVManager('data') df = csv_manager.read_stock('600000') extractor = PatternFeatureExtractor(lookback_days=25) features = extractor.extract(df) print(f"Trend features: {features['trend_structure']}") print(f"KDJ features: {features['kdj_state']}") print(f"Volume features: {features['volume_pattern']}") print(f"Price shape: length {len(features['price_shape'])}") ``` -------------------------------- ### Environment Variables Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Demonstrates how to set environment variables for PYTHONPATH and QUANT_DATA_DIR before running the script. ```bash # 设置Python路径 export PYTHONPATH=/path/to/project:$PYTHONPATH # 设置数据目录 export QUANT_DATA_DIR=/var/data/stocks # 运行 python main.py run ``` -------------------------------- ### Lookback Days Selection Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/B1_PATTERN_MATCH.md Examples of adjusting the lookback days for different trading styles (short-term, medium-term, long-term). ```bash # Short-term consolidation (1-2 weeks) python3 main.py run --b1-match --lookback-days 15 # Medium-term consolidation (3-4 weeks) - Default python3 main.py run --b1-match --lookback-days 25 # Long-term consolidation (1-2 months) python3 main.py run --b1-match --lookback-days 40 ``` -------------------------------- ### web 命令 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用web命令启动Web服务,包括指定端口和IP地址。 ```bash # 启动(默认5000端口) python main.py web # 指定端口 python main.py web --port 8080 # 指定IP和端口 python main.py web --host 192.168.1.100 --port 9000 ``` -------------------------------- ### update 命令 - 使用示例 Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md 演示如何使用update命令更新所有股票或指定数量的股票。 ```bash # 更新所有股票 python main.py update # 快速测试 python main.py update --max-stocks 500 ``` -------------------------------- ### REF Function Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/technical_indicators.md References n periods ago (REF). Gets the value from n days ago. ```python from utils.technical import REF prev_close = REF(df['close'], 1) # 前一日收盘价 volume_ratio = df['volume'] / REF(df['volume'], 1) # 成交量比率 ``` -------------------------------- ### Basic Commands Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Common commands for initializing, updating, running, and testing the quant selector. ```bash python3 main.py init python3 main.py update python3 main.py run python3 main.py run --max-stocks 500 python3 main.py run --category bowl_center python3 main.py web python3 main.py --version ``` -------------------------------- ### Production Environment Deployment Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/web_server.md Commands for deploying the web server in a production environment using Gunicorn or uWSGI. ```bash # Use gunicorn instead of Flask's built-in server pip install gunicorn gunicorn -w 4 -b 0.0.0.0:5000 web_server:app # Or use uwsgi pip install uwsgi uwsgi --http :5000 --wsgi-file web_server.py --callable app --processes 4 ``` -------------------------------- ### FAQ: How to change the number of stocks executed? Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/main_entry_point.md Answer to changing the number of stocks using the --max-stocks parameter. ```bash python main.py run --max-stocks 100 ``` -------------------------------- ### Project Structure Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Overview of the project's directory and file structure. ```bash ├── main.py # 主程序入口 ├── web_server.py # Web服务器 ├── B1_PATTERN_MATCH.md # B1完美图形匹配详细文档 ├── strategy/ # 策略模块 │ ├── __init__.py │ ├── base_strategy.py # 策略基类 │ ├── bowl_rebound.py # 碗口反弹策略 │ ├── strategy_registry.py # 策略注册器 │ ├── pattern_config.py # B1完美图形案例配置 │ ├── pattern_library.py # B1完美图形库管理 │ ├── pattern_matcher.py # 相似度计算引擎 │ └── pattern_feature_extractor.py # 特征提取模块 ├── utils/ # 工具模块 │ ├── akshare_fetcher.py # 数据获取 │ ├── csv_manager.py # CSV数据管理 │ ├── technical.py # 技术指标(KDJ/EMA/MA等) │ ├── kline_chart.py # K线图生成(标准版) │ ├── kline_chart_fast.py # K线图生成(快速版) │ └── dingtalk_notifier.py # 钉钉通知 ├── config/ # 配置文件 │ ├── config.yaml │ ├── strategy_params.yaml │ └── github.yaml ├── web/ # Web前端 │ ├── templates/ │ └── static/ └── data/ # 股票数据(CSV格式,自动创建) ``` -------------------------------- ### DTW Calculation Timeout Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/errors.md Example of checking for the fastdtw library and falling back to a simplified DTW if not found. ```python try: from fastdtw import fastdtw HAS_FASTDTW = True except ImportError: HAS_FASTDTW = False print("⚠️ fastdtw 未安装,将使用简化版DTW") ``` -------------------------------- ### Feature Extraction Failure Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/errors.md Example of handling a ValueError when feature extraction fails due to insufficient data. ```python extractor = PatternFeatureExtractor() features = extractor.extract(df) if not features.get('trend_structure'): print("特征提取失败,数据不足") features = extractor._empty_features() ``` -------------------------------- ### StrategyRegistry Constructor Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/strategy_registry.md Instantiates the StrategyRegistry, optionally loading parameters from a specified file. ```python from strategy.strategy_registry import StrategyRegistry # Use default configuration file registry = StrategyRegistry() # Use custom configuration file registry = StrategyRegistry("config/custom_params.yaml") ``` -------------------------------- ### DingTalk Notification Format - Normal Stock Selection Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/README.md Example format for stock selection results sent to DingTalk. ```text 🎯 BowlReboundStrategy: N: 2.4 (成交量倍数) M: 20 (回溯天数) CAP: 4000000000 (40亿市值门槛) J_VAL: 0 (J值上限) duokong_pct: 3 short_pct: 2 M1: 14 (MA周期) M2: 28 (MA周期) M3: 57 (MA周期) M4: 114 (MA周期) ⏰ 2026-03-02 15:30 🥣 回落碗中: 2 只 📊 靠近多空线: 1 只 📈 靠近短期趋势线: 0 只 📈 共选出: 3 只 --- ### 📊 000001 平安银行 **分类**: 🥣 回落碗中 **价格**: 10.85 | **J值**: -7.65 **关键K线日期**: 02-28 **入选理由**: 回落碗中 [K线图图片] ``` -------------------------------- ### CSV File Read/Write Error Handling Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/errors.md Example of handling FileNotFoundError and PermissionError when reading CSV files, with a fallback to network fetch. ```python try: df = csv_manager.read_stock('600000') except FileNotFoundError: print("本地缓存不存在,从网络获取") df = fetcher.get_stock_history('600000') except PermissionError: print("无权限访问数据目录") # 请求权限或更改目录 ``` -------------------------------- ### Get Registry Instance Source: https://github.com/dzy-hw-xd/a-share-quant-selector/blob/main/_autodocs/api-reference/strategy_registry.md Retrieves the global strategy registry instance using a singleton pattern. It can optionally load parameters from a specified file. ```python from strategy.strategy_registry import get_registry # Get the global registry registry = get_registry() # Automatically register all strategies registry.auto_register_from_directory("strategy") # Getting it again later returns the same instance registry2 = get_registry() assert registry is registry2 # True ```