A-Share Quant Selector

repository·main·Indexed 42 days ago

https://github.com/dzy-hw-xd/a-share-quant-selector

A quantitative A-share stock selection system based on Python and akshare. It implements a 'Bowl Rebound' strategy and a B1 pattern-matching engine using a 3D similarity algorithm to identify breakout candidates. The system features automated DingTalk notifications, a Web management interface, and support for custom selection strategies inheriting from BaseStrategy.

Tokens
4.7K
Snippets
15
Records
19
Agent score
57%

What's inside A-Share Quant Selector

  1. How B1 Perfect Pattern Matching works

    main

    B1 Perfect Pattern Matching is a morphological similarity matching algorithm. It compares currently selected stocks against a library of 10 historical successful cases across multiple dimensions to find stocks with similar structural shapes rather than absolute price levels.

    Matching Dimensions and Weights

    The algorithm calculates a total similarity score based on four weighted dimensions:

    DimensionWeightDescription
    Dual-Line Structure30%Relative position, slope, and divergence of the 'ZhiXing' short-term trend line and the bull-bear line
    KDJ State20%J-value position, Golden Cross status, and trend direction
    Volume Characteristics25%Volume change patterns (e.g., shrinking then expanding)
    Price Morphology25%Similarity of the normalized price curve using the DTW (Dynamic Time Warping) algorithm

    Similarity Thresholds

    SimilarityMeaningRecommended Action
    ≥85%Highly similarHigh priority; morphology is very close to successful cases
    70-84%Moderately similarWorth watching; high morphological similarity
    60-69%Generally similarReference only; some similarity exists
    <60%Not similarLikely not a target pattern

    Note: The default threshold is 60%.

  2. Extend the system with a new selection strategy

    main

    You can add custom strategies by following these steps:

    1. Create a new file in the strategy/ directory.
    2. Inherit from the BaseStrategy class.
    3. Implement the calculate_indicators(self, df) and select_stocks(self, df, stock_name='') methods.
    4. Add any necessary parameters to config/strategy_params.yaml.

    The system will automatically detect and execute the new strategy.

    from strategy.base_strategy import BaseStrategy
    
    class MyStrategy(BaseStrategy):
        def __init__(self, params=None):
            super().__init__("我的策略", params)
        
        def calculate_indicators(self, df):
            # Calculate indicators
            return df
        
        def select_stocks(self, df, stock_name=''):
            # Selection logic
            return signals
  3. Access the Web Interface

    main

    The project includes a web-based dashboard accessible at http://localhost:5000. It provides the following views:

    • System Overview (📊 系统概览): View total stock counts and the latest data update date.
    • Stock List (📈 股票列表): Browse all stocks with basic information and search capabilities.
    • Selection Results (🎯 选股结果): View detailed signals from executed stock selection strategies.
    • Strategy Configuration (⚙️ 策略配置): Modify strategy parameters online.
    http://localhost:5000
  4. Run the Quant Selector and Web Interface

    main

    Use the following commands to execute the system's core workflows:

    • Full Workflow (Update data $\rightarrow$ Select stocks $\rightarrow$ Send DingTalk notifications):
      python3 main.py run
    • Quick Test (Process only the first 500 stocks):
      python3 main.py run --max-stocks 500
    • Category Filtering (Only select stocks in the 'bowl center' category):
      python3 main.py run --category bowl_center
    • Start Web Management Interface (Default port 5000):
      python3 main.py web
    • Incremental Update (Run daily after market close):
      python3 main.py update
    python3 main.py run
    python3 main.py run --max-stocks 500
    python3 main.py web
  5. Install and Setup A-Share Quant Selector

    main

    Follow these steps to set up the environment and run the quant selector for the first time:

    1. Clone the repository:
      git clone https://github.com/Dzy-HW-XD/a-share-quant-selector.git
      cd a-share-quant-selector
    2. Install dependencies:
      pip3 install -r requirements.txt
    3. Configure DingTalk notifications (Optional): Edit config/config.yaml to provide your webhook and secret.
    4. Initialize data (Fetch 6 years of historical data):
      python3 main.py init
    git clone https://github.com/Dzy-HW-XD/a-share-quant-selector.git
    cd a-share-quant-selector
    pip3 install -r requirements.txt
    python3 main.py init
  6. Use B1 Pattern Matching for Stock Selection

    main

    The B1 Pattern Match feature uses a 3D similarity engine to rank stocks based on 10 historical successful cases. It evaluates stocks across four dimensions: Trend Structure (30%), Volume Pattern (25%), Price Shape (25%), and KDJ State (20%).

    CLI Usage

    • Enable B1 matching:
      python3 main.py run --b1-match
    • Custom lookback and similarity:
      python3 main.py run --b1-match --lookback-days 30 --min-similarity 70

    Configuration

    You can adjust the matching engine in config/strategy_params.yaml under the B1PatternMatch section, including min_similarity, lookback_days, and the weights for each dimension.

    python3 main.py run --b1-match --lookback-days 30 --min-similarity 70
  7. Configure B1 Pattern Match via CLI

    main

    You can customize the B1 pattern matching process using command-line flags to adjust the lookback period, similarity sensitivity, and category filtering.

    Adjust Lookback Days

    Use --lookback-days to define the window of historical data used for matching (the algorithm uses data before the breakout date to capture the consolidation phase):

    • Short-term consolidation (1-2 weeks): --lookback-days 15
    • Medium-term consolidation (3-4 weeks - Default): --lookback-days 25
    • Long-term consolidation (1-2 months): --lookback-days 40

    Adjust Similarity Threshold

    Use --min-similarity to filter results:

    • Strict matching: --min-similarity 75
    • Loose matching: --min-similarity 50

    Combine with Categories

    You can filter by specific stock categories while performing B1 matching:

    • Bowl center stocks: --b1-match --category bowl_center
    • Near bull-bear line with high similarity: --b1-match --category near_duokong --min-similarity 70
    # Example: Medium-term consolidation with strict 75% similarity
    python3 main.py run --b1-match --lookback-days 25 --min-similarity 75
  8. Set up a Cron Job for Daily Automated Selection

    main

    To automate the stock selection process daily, add a task to your crontab. For example, to run the selection process every weekday at 15:05 and log the output to /var/log/quant-csv/run.log, use the following command:

    1. Open crontab editor: crontab -e
    2. Add the following line (adjust the path to your project directory):
    # 每天15:05执行,仅工作日
    5 15 * * 1-5 cd /root/quant-csv && /usr/bin/python3 main.py run >> /var/log/quant-csv/run.log 2>&1
  9. Extend B2/B3 Perfect Pattern Matching

    main

    The system is designed to allow expansion from B1 to B2 or B3 pattern matching. To implement a new pattern (e.g., B2), follow these steps:

    1. Configuration: Add the new pattern configuration (e.g., B2_PERFECT_CASES) in pattern_config.py.
    2. Library Class: Create a new library class (e.g., B2PatternLibrary) modeled after B1PatternLibrary.
    3. CLI Argument: Add a new command-line parameter (e.g., --b2-match) in main.py.
    4. Notification: Register a new notification method (e.g., send_b2_match_results()) in dingtalk_notifier.py.
  10. Configure B1 Top N Results in strategy_params.yaml

    main

    To adjust the number of matching results displayed in DingTalk notifications, edit the config/strategy_params.yaml file. Increasing this value results in longer messages.

    Recommended value: 10-20.

    B1PatternMatch:
      top_n_results: 15  # Default displays the top 15 matching results
  11. Configure DingTalk Notifications

    main

    To enable automated notifications, edit config/config.yaml and provide your DingTalk webhook and secret.

    Notifications include:

    • Standard Selection Results: Displays strategy parameters (e.g., N, M, CAP, J_VAL), timestamp, and categorized stock counts (e.g., 🥣 回落碗中, 📊 靠近多空线). Individual stock details include price, J-value, key K-line dates, and an included K-line image showing trends and volume.
    • B1 Perfect Pattern Matching: Triggered via the --b1-match flag. It provides a ranked list of stocks based on similarity percentage, matching historical cases, and a breakdown of scores across four dimensions: 趋势 (Trend), KDJ, 量能 (Volume), and 形态 (Pattern).
    # Edit config/config.yaml
    webhook: 'YOUR_WEBHOOK_URL'
    secret: 'YOUR_SECRET'
  12. How the Smart Update logic works

    main

    The system uses an internal _smart_update mechanism to optimize data fetching and avoid unnecessary network calls:

    1. Time Check: If the current time is before 15:00 (market close), the system skips network updates and uses existing local data to prevent fetching incomplete intraday data.
    2. Data Freshness Check: It performs a sampled check (up to 100 stocks) to see if the latest date in the local CSV matches today's date. If all sampled stocks already have today's data, the update is skipped entirely.
    3. Incremental Update: If updates are needed, it triggers fetcher.daily_update() to fetch only the missing data.