KHQuant (看海量化)

repository·main·Indexed 23 days ago

https://github.com/khscience/oskhquant

An open-source quantitative trading system for medium-to-low frequency strategies, optimized for the A-share market. It provides a local, Python-friendly backtesting and simulation platform with a PyQt5-based GUI, integrating with MiniQMT for market data access. The system supports the integration of AI and signal processing algorithms using libraries like Pandas, NumPy, TensorFlow, and PyTorch. It is designed for strategy research and historical data validation, licensed under CC BY-NC 4.0.

Tokens
15.2K
Snippets
8
Records
68
Agent score
81%

What's inside KHQuant

  1. Overview of the KHQuant Main Interface

    main

    The KHQuant interface uses a three-column layout designed for backtesting (Note: Live Trading is currently not supported).

    Layout Structure

    • Top Toolbar: Global operations (loading/saving configs, starting/stopping strategies, data management, settings).
    • Left Panel (Core Configuration): Defines strategy behavior (strategy files, backtest parameters, stock pools, data settings).
    • Middle Panel (Execution Driver): Defines the strategy "heartbeat" (event triggers, pre/post-market tasks, account status).
    • Right Panel (Information Feedback): Monitoring window (system logs, strategy prints, trade/execution reports, error alerts).
    • Bottom Status Bar: Real-time feedback and backtest progress.
  2. Identify suitable use cases for KHQuant

    main

    KHQuant is designed for medium-to-low frequency quantitative trading strategies. Suitable scenarios include:

    • Factor-based strategies: Stock selection and rotation based on value, growth, quality, or momentum factors.
    • Trend following: Strategies using technical indicators like Moving Averages, Bollinger Bands, MACD, or RSI.
    • Statistical arbitrage: Pair trading, basis trading (using MiniQMT supported instruments), and ETF arbitrage.
    • Event-driven strategies: Trading based on external events like earnings reports, news, or policy changes.
    • AI/ML strategies: Using Scikit-learn, TensorFlow, or PyTorch for mid-to-low frequency signal generation.
    • Portfolio management: Dynamic rebalancing and asset allocation based on risk profiles.
    • Automation: Converting manual trading logic into automated code execution.
  3. Understand the CSkhQuant System Architecture

    main

    CSkhQuant (看海量化交易平台) is a quantitative trading system built with Python and PyQt5. The system is organized into several functional modules that handle everything from the user interface to core trading logic and data management.

    Core Modules Overview

    1. Main Interface: Provides the primary GUI for strategy execution, backtesting, account management, and real-time market monitoring (GUIkhQuant.py). It also includes a dedicated interface for batch downloading and cleaning stock data (GUI.py).
    2. Data Management: Includes tools for browsing local data (GUIDataViewer.py), scheduling automated data updates (GUIScheduler.py), and specialized parsers/viewers for miniQMT data formats (miniQMT_data_parser.py, miniQMT_data_viewer.py).
    3. Analysis & Visualization: Features interactive charting tools (GUIplotLoadData.py) and detailed backtesting result analysis windows (backtest_result_window.py).
    4. Core Framework: The engine of the system, comprising the strategy execution engine (khFrame.py), trading tools (khQTTools.py), order/cost management (khTrade.py), and risk control (khRisk.py).
    5. Technical Indicators: A high-performance library for technical analysis (MyTT.py).
  4. Understand KHQuant limitations and constraints

    main

    Before deploying, be aware of the following limitations of the KHQuant system:

    • Not for High-Frequency Trading (HFT):
      • Data: MiniQMT provides 3-second snapshots rather than tick-by-tick data, which is insufficient for microsecond-level precision.
      • Latency: The Python-based architecture and MiniQMT link cannot meet sub-millisecond execution requirements.
    • Historical Data Constraints: MiniQMT (broker version) has limits on historical data depth. Tick data is typically limited to ~1 month, 1/5-minute K-lines to ~1 year, and daily data is more complete. For longer historical minute/tick data, the professional 'Research version' of QMT is required.
    • Market Scope: Core optimization is focused on the A-share market (Stocks, ETFs, some Futures/Options) via MiniQMT. It is not natively optimized for complex cross-market arbitrage (e.g., Global markets, Forex, Crypto).
    • Operating System: The system is primarily developed and tested on Windows due to the MiniQMT client requirements. Running on Linux or macOS via compatibility layers like Wine is not officially supported and may be unstable.
  5. Structure of a KHQuant strategy file

    main

    A strategy file in KHQuant is a standard Python script that implements specific callback functions defined by the framework. To create a new strategy, you should implement the following core functions:

    • init(stock_list, context): Executed once at the start of the task for global initialization (defining variables, loading data).
    • khHandlebar(context): The core logic function. It is called repeatedly based on the frequency set in the 'Run Driver' area. It is responsible for market analysis and generating trading signals.
    • khPreMarket(context) (Optional): Called at a specified time before the market opens. Useful for daily stock selection or factor calculation.
    • khPostMarket(context) (Optional): Called at a specified time after the market closes. Useful for performance attribution or saving strategy state.
    from typing import Dict, List
    
    def init(stock_list, context):
        """
        策略初始化函数,在任务开始时仅执行一次。
        用于定义全局变量、加载外部数据等。
        """
        pass
    
    def khHandlebar(context: Dict) -> List[Dict]:
        """
        策略核心逻辑,会被框架根据设定的频率反复调用。
        负责行情判断和生成交易信号。
        """
        signals = []
        return signals
    
    def khPreMarket(context: Dict) -> List[Dict]:
        """
        盘前处理函数(可选)。
        在每日开盘前的指定时间点调用。
        """
        signals = []
        return signals
    
    def khPostMarket(context: Dict) -> List[Dict]:
        """
        盘后处理函数(可选)。
        在每日收盘后的指定时间点调用。
        """
        signals = []
        return signals
  6. Use the khFrame and khQTTools core framework

    main

    The core logic of the platform is driven by khFrame.py and supported by khQTTools.py.

    • khFrame.py: Acts as the central quantitative trading framework. It manages the strategy execution engine, handles both backtesting and live trading, manages data subscriptions, and processes events (triggered by time or signals).
    • khQTTools.py: A utility toolkit used for data processing, generating trading signals, calculating technical indicators, and determining trading windows. It supports multi-process data handling.
  7. Manage trading, costs, and risk with khTrade and khRisk

    main

    For executing and controlling trades, use the following modules:

    • khTrade.py: Handles order management, execution, and asset tracking. It automatically calculates trading costs including commissions (佣金), stamp duty (印花税), and slippage (滑点).
    • khRisk.py: Provides risk management capabilities, including position limit checks, stop-loss control, and monitoring of risk indicators.
  8. Important Disclaimers and Risk Warnings

    main

    Core Functionality

    • The current version of KHQuant is a strategy backtesting and research platform. Its core function is historical data validation. The official version does not include direct live trading execution functions.

    Data and Reliability

    • Data Accuracy: While the system performs basic integrity and format checks on data from MiniQMT, these are technical safeguards and do not guarantee data accuracy. Accuracy depends entirely on the broker's MiniQMT and its upstream sources.
    • No Investment Advice: KHQuant and its outputs (backtest reports, performance metrics, example code) are for educational and research purposes only. They do not constitute investment advice or trading recommendations. Past performance does not guarantee future results.

    Liability

    • Users assume all responsibility for any losses (financial, data, or hardware) resulting from the use of this software, including errors in data, network issues, or user-modified code used for live trading.
  9. Access time and account data from `context`

    main

    All real-time state information is accessible through the context dictionary.

    Time Data

    Access context['__current_time__'] to get:

    • timestamp: Unix timestamp (int).
    • datetime: YYYY-MM-DD HH:MM:SS (str).
    • date: YYYY-MM-DD (str).
    • time: HH:MM:SS (str).

    Account Data

    Access context['__account__'] to get:

    • cash: Available cash for trading (float).
    • market_value: Total market value of all positions (float).
    • total_asset: cash + market_value (float).
    • frozen_cash: Cash frozen due to pending orders (float).
  10. Choose a trigger mode for strategy execution

    main

    The trigger mode defines the frequency and timing of the khHandlebar function calls (the strategy's "heartbeat").

    Tick Trigger

    Executes whenever market transaction data arrives (in MiniQMT, this is a snapshot every 3 seconds).

    • Pros: Maximum flexibility for adding custom filtering logic.
    • Cons: High data volume and slower backtesting speeds due to the large amount of data required.

    K-Line Trigger

    Executes based on fixed time intervals. In the KHQuant backtesting system, supported periods are 1-minute and 5-minute K-lines.

    • Pros: Low resource consumption and fast backtesting. Ideal for trend-following and technical analysis strategies.
    • Note: In live trading, even if subscribing to 1m/5m K-lines, the data feed typically pushes updates every 3 seconds. In backtesting, execution occurs strictly at the end of the K-line period.

    Custom Time Trigger

    Allows you to specify exact timestamps for execution. Ideal for scheduled trading (e.g., opening auction or market close strategies) or non-standard intervals (e.g., every 10 minutes).

    • Important: Unlike Tick or K-line triggers, a Custom Time trigger does not automatically pass data to the khHandlebar function. You must manually call data acquisition interfaces (e.g., get_market_data) inside your function.
    • Smart Adaptation:
      • If all timestamps are on the exact minute (e.g., 09:30:00), the system uses 1-minute K-line data.
      • If timestamps include non-minute seconds (e.g., 09:30:15), the system switches to underlying Tick data for precision.
    • Precision Tip: For stability in MiniQMT, all custom timestamps should be set to a multiple of 3 seconds.
  11. Use Data Supplement to drive internal backtesting

    main

    The Data Supplement (数据补充) feature is designed to update and maintain the internal historical database used by MiniQMT and the KHQuant backtesting engine.

    How it works: Unlike Data Download, this mechanism calls the xtquant.download_history_data function to write data directly into the MiniQMT system's local data directory. During backtesting, strategies then use high-speed functions like get_market_data_ex to read this local data.

    Data Storage Details:

    • Location: Data is stored in the MiniQMT installation directory under userdata_mini\datadir.
    • Format: Data is stored in an optimized internal binary format (.dat files).
    • Directory Structure: Inside the datadir, you will find folders for different exchanges (e.g., SH for Shanghai, SZ for Shenzhen). Within these, subfolders represent the data frequency in seconds:
      • 0: Tick data
      • 60: 1-minute data
      • 300: 5-minute data
      • 86400: Daily (1d) data
  12. Configure pre-market and post-market triggers

    main

    KHQuant allows strategies to execute non-core logic at specific times each trading day using two trigger functions:

    • khPreMarket: Triggered at a user-defined time (e.g., 09:25:00). Use this for pre-opening preparations such as fetching the daily stock pool, canceling yesterday's unfilled orders, or resetting state variables.
    • khPostMarket: Triggered at a user-defined time (e.g., 15:05:00). Use this for post-closing tasks such as calculating daily trading statistics, recording position/asset snapshots, or preprocessing data for the next day.