chan.py Framework

repository·main·Indexed 24 days ago

https://github.com/vespa314/chan.py

A high-performance Chan Theory (缠论) framework for technical analysis, calculating strokes (bi), segments (seg), and central pivots (zs). It supports multi-level calculations, custom buy/sell point strategies, and machine learning integration with 500+ default features and support for XGB, LightGBM, and MLP models. The framework includes data interfaces for Futu, AkShare, and BaoStock, a backtesting framework, and visualization tools via CPlotDriver and CAnimateDriver. Requires Python 3.11+.

Tokens
12.3K
Snippets
16
Records
45
Agent score
82%

What's inside chan.py

  1. Overview of chan.py Functional Levels

    main

    The chan.py framework is designed to be used at four different levels of depth:

    1. Basic Chan Theory Element Calculation: Computing fractals, strokes (笔), segments (线段), central pivots (中枢), and buy/sell points. Supports multi-level calculations, indicator configuration (MACD, Moving Averages, Bollinger Bands, Demark, etc.), and multiple data sources (futu, akshare, baostock, or local files).
    2. Strategy Buy/Sell Point Development: Calculating morphological buy/sell points and supporting custom dynamic buy/sell point strategies, including divergence (背驰) algorithm configuration.
    3. Machine Learning Integration: Scoring buy/sell points using ML models. The framework provides 500+ default features and includes interfaces for data ingestion, model training, prediction, and model I/O. Supported models include XGB, LightGBM, and MLP. It also includes an AutoML hyperparameter search engine.
    4. Live Trading: Ensuring consistency between online and offline models/features. Supports integration with the Futu trading engine (simulated and real accounts) for opening/closing positions and real-time price tracking. Supports MySQL and SQLite backends.
  2. Core capabilities of the chan.py framework

    main

    The framework provides three primary capabilities for Chan-theory (缠论) analysis:

    1. Static Calculation: Calculates Chan-theory elements (strokes, segments, central pivots, buy/sell points) based on a given range of K-lines.
    2. Incremental Updates: Provides incremental updates to Chan-theory elements as new K-lines are added.
    3. Extensibility:
      • Supports custom data source integration.
      • Allows users to extract calculated elements to build custom trading strategies.
  3. Understand the project directory structure

    main

    The chan.py project is organized into several functional modules for Chan-theory (缠论) analysis, strategy development, and trading. Key directories include:

    • Bi (笔): Core elements like Bi.py (Bi class) and BiList.py.
    • Seg (线段): Segment calculation logic including Seg.py and various implementation styles (SegListChan.py, SegListDef.py, SegListDYH.py).
    • ZS (中枢): Central hub (Zhongshu) logic with ZS.py and ZSList.py.
    • KLine: K-line management including KLine.py and KLine_List.py.
    • BuySellPoint (bsp): Morphological buy/sell points.
    • CustomBuySellPoint (cbsp): Custom dynamic buy/sell point strategies using Strategy.py.
    • DataAPI: Data interfaces for AkShare, BaoStock, Futu, and OfflineData.
    • ModelStrategy: Backtesting framework (backtest.py) and machine learning model generation (MLPModelGenerator.py, LGBMModelGenerator.py, XGBTrainModelGenerator.py).
    • Trade: Trading engine components like TradeEngine.py and FutuTradeEngine.py.
    • OfflineData: Tools for downloading and updating historical data.
    • Plot: Visualization tools using matplotlib via PlotDriver.py.
  4. Understanding the "Current Frame" and signal volatility

    main

    The framework operates on a "frame" concept. At any given moment (e.g., after adding a new K-line), the CChan class provides the current state of all Chan-theory elements based on the K-lines seen so far.

    Important: Signal Volatility Because the framework calculates elements based on the current available data, buy/sell signals are considered "morphological" and may change or disappear as new K-lines are fed into the system:

    • A K-line might be identified as a buy point in the current frame, but if the price continues to drop in subsequent K-lines, that signal may be canceled or moved.
    • A signal at a local minimum will persist as long as the price does not break that minimum, until the morphology no longer supports the signal.
  5. Understand the typical trading workflow

    main

    A standard trading cycle implemented in Trade/Script follows these steps:

    1. Data Update: Update offline data for all watched stocks using DataAPI/OfflineDataAPI.py (preferred over network APIs for speed).
    2. Signal Calculation: Run signal generation logic.
    3. Breakout Detection: Check if a signal has broken out. If a model is configured, verify if the model score exceeds the specified threshold before opening a position.
    4. Post-hoc Validation: For higher-timeframe trades (e.g., daily), re-verify the breakout and score after the K-line completes.
      • If valid: Monitor price for stop-loss, take-profit, or new buy/sell signals.
      • If invalid: Sell immediately in the next cycle, regardless of profit/loss.
  6. Compare Segment-based vs. Intra-segment Central Zone algorithms

    main

    The zs_algo parameter in CChanConfig determines how central zones (zhongshu) are calculated:

    1. Intra-segment Central Zone (normal)

    • Central zones must be contained within a single segment.
    • The central zone must consist of an odd number of strokes (bi).
    • It cannot cross segment boundaries.

    2. Cross-segment Central Zone (over_seg)

    • Central zones can span across multiple segments.
    • When a new central zone is generated, the starting stroke considers the segment direction.
    • A stroke is included in a central zone if its high/low range overlaps with the existing central zone range.
    • The number of strokes in a cross-segment central zone can be even or odd.
    • Adjacent central zones belonging to different segments are not merged to prevent creating excessively large zones.

    3. Automatic (auto)

    • Uses the normal algorithm for confirmed segments and the over_seg algorithm for unconfirmed segments.
  7. Understand Segment (CSeg) types: Real vs. Virtual

    main

    The framework distinguishes between confirmed segments and inferred segments to handle the inherent lag in Chan theory calculations.

    • Real Segments (is_sure=True): These are confirmed segments. In visualization, these appear as solid lines. A segment is confirmed when specific conditions (like gap patterns in the characteristic sequence) are met.
    • Virtual Segments (is_sure=False): These are inferred segments that may change as new K-lines are added. In visualization, these appear as dashed lines. They typically appear at the beginning or end of a sequence when information is insufficient to confirm a top or bottom fractal.

    Warning: If all calculated segments are virtual (is_sure=False), do not perform backtesting or live trading. Wait until at least one real segment (is_sure=True) appears before analyzing strategies.

  8. Using the is_sure attribute to distinguish confirmed elements

    main

    Every element in the framework includes an is_sure attribute to indicate whether the element is finalized or still subject to change.

    • is_sure=True: The element is confirmed. It will not be modified or reverted to is_sure=False as new K-lines are added.
    • is_sure=False: The element is unconfirmed (e.g., a "virtual" stroke or segment). These elements only appear at the beginning or the end of the K-line sequence and may change as more data arrives.

    In visual representations, is_sure=False elements are typically rendered as dashed lines.

  9. Understand Chan Theory terminology and variables

    main

    The framework uses specific terminology for its core components:

    • klu (K Line Unit): A single K-line.
    • klc (K Line Combine): A combined K-line (note: these do not have open or close price attributes).
    • bsp (Buy Sell Point): Morphological buy/sell points calculated based on structure and definitions. These are considered 'correct' once calculated for past data.
    • cbsp (Custom Buy Sell Point): Trading points generated by user-defined strategies (via the cbsp_strategy parameter in CChanConfig). These are evaluated as each new K-line appears and may lag behind bsp.
    • segseg: A 'segment of a segment' (treating segments as if they were strokes/bi) used to calculate higher-level segment structures.
    • segbsp: Morphological buy/sell points corresponding to segseg.
    • segzs: The central zone (zhongshu) corresponding to segseg.
  10. Quickstart Guide for chan.py

    main
    For a fast start with the framework, please refer to the official Quickstart Guide. Note that the public version of the code contains basic static calculation capabilities but may lack strategy classes, features, models, AutoML frameworks, and trading engine integrations found in the full version.
  11. Sync trading data to Notion

    main
    If Notion credentials are configured in config.yaml, the routine script Script/Notion/DB_sync_Notion.py will automatically synchronize operation data for stocks that have already opened positions into a designated Notion table. This process also embeds the corresponding opening position images into the Notion pages.