qteasy Quantitative Investment Toolkit

repository·master·Indexed 40 days ago

https://github.com/shepherdpp/qteasy

A fast, localized quantitative investment toolkit for transitioning from research to live trading. Version 2.6.4 features a high-performance backtesting engine powered by NumPy and Numba, a unique data injection mechanism to prevent look-ahead bias, and consistent interfaces for backtesting, parameter optimization, and live/simulated trading. It includes tools for historical data retrieval, K-line visualization, and custom strategy development via GeneralStg.

Tokens
87.6K
Snippets
229
Records
337
Agent score
99%

What's inside qteasy

  1. Overview of QTEASY capabilities

    master

    QTEASY is a quantitative trading strategy development toolkit designed for full-lifecycle management. Its core capabilities include:

    • Financial Data Management: Fetching data from multiple channels, cleaning it, and storing it locally in a unified format. It uses DataType objects to provide structured access to complex information like adjusted prices and index constituents.
    • Strategy Development: Defining strategies using the BaseStrategy class. It supports a 'building block' approach where complex strategies are composed from simple ones, and includes over 70 built-in strategies (technical indicators, moving averages, breakouts, reversals, etc.).
    • Backtesting and Evaluation: Using the Operator class to run strategies against historical data following real market rhythms. It provides multi-dimensional evaluation, trading reports, and result charts.
    • Optimization: Utilizing algorithms such as Simulated Annealing, Genetic Algorithms, and Bayesian Optimization to find optimal parameters in large search spaces.
    • Simulated Live Trading: Running strategies against real-time market data to track logs, holdings, and account changes, ensuring the same logic used in backtesting is used in live environments to prevent 'look-ahead bias' (future functions).
  2. Core capabilities of qteasy

    master

    qteasy is a quantitative investment toolkit designed for three primary workflows:

    1. Financial Data Management:

      • Multi-channel data acquisition and cleaning with unified local storage.
      • Structured data management using DataType objects, allowing easy access to complex information like adjusted prices and index constituents.
      • Built-in visualization and statistical analysis for financial data.
    2. Strategy Creation:

      • Define strategies using the BaseStrategy class for clear, intuitive logic.
      • Access over 70 built-in strategies or compose complex strategies using a 'building block' mechanism (strategy mixing and grouping).
      • Built-in protection against 'look-ahead bias' (future functions) and data leakage through encapsulated data input methods.
      • Unified logic for both backtesting and live trading.
    3. Backtesting, Optimization, and Trading:

      • Manage strategy execution via the Operator class, which simulates real market rhythms and generates comprehensive performance reports.
      • Optimize strategy parameters using algorithms like Simulated Annealing, Genetic Algorithms, and Bayesian Optimization.
      • Support for simulated automated trading by tracking real-time market data, logs, holdings, and account changes.
      • Future support for real-world automated trading via QMT interfaces.
  3. Navigate simulated live trading functional areas

    master

    The simulated live trading functionality is organized into the following functional areas:

    • Configuration and Startup: Handles live configuration validation and running snapshots.
    • Ordering and Risk Management: Manages pre-submission evaluations and the visibility of rejected orders.
    • Fills and Status: Manages partial fills and state convergence.
    • Adaptation and Extension: Provides the adapter API and defines compatibility boundaries for new brokers.
    • Logging and Troubleshooting: Provides a specific sequence for troubleshooting using sys_log, trade_log, and risk_log.
  4. What is Live Trading in qteasy?

    master

    In qteasy, Live Trading (configured via mode=0) is a simulation mode where your strategy runs in real-time. Unlike backtesting, which 'fast-forwards' through historical data, Live Trading follows a real-time schedule to calculate signals, place orders, and record logs.

    Transactions are typically handled by a local simulated broker, meaning no real capital is involved. This mode is designed to bridge the gap between backtesting and real-world trading, allowing you to use the same strategy logic in a real-time environment to minimize the discrepancy between backtest results and live performance.

  5. What is process data (proc.*) and when to use it

    master

    In qteasy, process data (prefixed with proc.*) refers to data that changes based on the execution path of a backtest or live trading. Unlike static historical data, process data cannot be pre-generated and must be maintained by the Backtester or Trader during runtime.

    Use process data when your strategy depends on:

    • Account state: Current/historical cash (proc.own_cash), available cash (proc.available_cash), or total assets (proc.total_value).
    • Positions: Current holdings (proc.own_amounts), sellable quantities (proc.available_amounts), or position market value (proc.position_value).
    • Trade results: Actual executed quantities (proc.trade_records), transaction costs (proc.trade_cost), or execution prices (proc.trade_price).

    Key Concept: No Look-ahead Bias qteasy guarantees that when generating a signal at step $k$, the strategy cannot see the execution results of step $k$. It can only see completed historical data. For example, trade records are only visible up to step $k-1$.

  6. How the Broker adapter layer works

    master

    The Broker is the component responsible for receiving orders, acknowledging receipt, and asynchronously pushing execution reports (fills).

    To support different brokers (e.g., a simulator or a real QMT terminal) without changing the core Trader logic, qteasy uses a BrokerFacade (an adapter layer). This facade acts as a unified translation layer. The Trader interacts only with the Facade using a standard set of APIs, remaining agnostic of whether the underlying broker is a simulator or a real trading terminal.

    Typical Live Call Chain: Operator.run_live_trade() $\rightarrow$ Trader (Schedule, Risk, Ledger) $\rightarrow$ BrokerFacade (Unified API) $\rightarrow$ SimulatorBroker or your custom Broker.

    Operator.run_live_trade()
      → Trader(日程、风控、账本)
           → BrokerFacade(券商适配外壳:统一 API)
                → SimulatorBroker / 您注册的 Broker
  7. How RiskManager works and how to configure it

    master

    The RiskManager acts as a pre-submission checkpoint. It evaluates an OrderIntent against an AccountSnapshot using a chain of rules. If any rule fails, it produces a RiskDecision (Reject) containing an English reason and a rule_id.

    Configuration

    To enable risk management, you must instantiate a RiskManager with a list of rules in Python and pass it to your Trader during setup:

    # Example conceptual setup
    risk_manager = RiskManager([rule1, rule2, ...])
    trader = Trader(..., risk_manager=risk_manager)

    If no RiskManager is provided, the local rule chain is skipped, and orders are sent directly to the broker.

    Common Rule Scenarios

    ScenarioRule SemanticLive Behavior
    WhitelistOnly allow specific symbols (e.g., 000001.SZ)Rejects orders for symbols not in the list
    Single Order QtyMaximum quantity per order (e.g., 500 shares)Rejects if order quantity > limit
    Trading HoursOnly allow orders during specific windowsRejects orders placed during lunch breaks or after hours
    Daily TurnoverLimit cumulative daily turnoverRejects if (current order + daily total) > limit

    Troubleshooting Rule Rejections

    If the CLI displays: Order rejected by risk rule [MAX_ORDER_QTY]: order quantity exceeds limit

    1. Identify the rule_id (e.g., MAX_ORDER_QTY).
    2. Search risk_log for <RISK REJECTED> to see the specific details.
    3. Adjust your rule thresholds or the order parameters in your strategy.
  8. Perform factor research with HistoryPanel

    master

    The HistoryPanel (found in qteasy.history) is the primary container for research and data analysis. It allows you to transition from research to strategy development.

    Research Workflow:

    • Data Loading: Convert DataFrames to a HistoryPanel using dataframe_to_hp() or combine multiple sources using stack_dataframes().
    • Factor Analysis: Use the qteasy.research subpackage for advanced analysis. Note: Functions are not flattened into the top-level namespace; you must import them explicitly, e.g., from qteasy.research import factor_ic.
    • Capabilities: Supports correlation (corr), covariance (cov), and factor IC analysis.
    from qteasy.history import dataframe_to_hp
    from qteasy.research import factor_ic
    
    # Load data into research container
    hp = dataframe_to_hp(my_df)
    
    # Perform factor research
    results = factor_ic(hp, ...)
  9. Visualize data using HistoryPanel

    master

    Visualization in qteasy is decoupled from the execution engine using the HistoryPanel abstraction.

    • HistoryPanel: A three-dimensional data container (shares × hdates × htypes) that serves as the standard return type for get_history_data and the input for plotting.
    • Unified Plotting: Use HistoryPanel.plot(...) as the primary entry point. It automatically selects appropriate chart types (K-line, Volume, MACD, Line, etc.) based on the data htypes and shares.
    • Backends: The system generates a backend-agnostic chart specification. This allows the same logic to render via matplotlib (for static images/reports) or Plotly (for interactive web views) while maintaining consistent styling and semantics.
    • High-level APIs: Functions like qt.candle(...) are convenience wrappers that handle the workflow of: Fetch Data $\rightarrow$ Build HistoryPanel $\rightarrow$ Call hp.plot().
  10. Understanding `submit_with_ack` and order status

    master

    The submit_with_ack method provides a synchronous response regarding whether the broker has accepted the order. This is distinct from a risk management rejection (which happens before the order enters the order table).

    Order Mapping based on Acceptance:

    Acceptance ResultLocal Order Statusbroker_order_id
    accepted=TrueContinues lifecycleWritten back with broker ID and name
    accepted=FalseUsually rejectedRemains empty

    If an order is rejected and the broker_order_id is empty, it indicates the broker rejected the order at the acceptance stage. If a broker_order_id exists but no execution occurs, you should check the order status via poll_fills.

  11. Understand breaking changes in QTEASY 2.0 configuration

    master

    In QTEASY 2.0, the behavior of qt.configure regarding removed keys depends on the only_built_in_keys flag:

    • only_built_in_keys=True: Passing any of the removed keys (maximize_cash_usage, benchmark_asset_type, or benchmark_dtype) will trigger a KeyError.
    • only_built_in_keys=False: These keys can still be written to the configuration object, but they will not participate in any running logic.
  12. Rules for `manage_data` Database Field Names

    master

    When interacting with or documenting data tables in the manage_data module (e.g., manage_data/04–09. data_tables_*.md):

    • Do not translate field names (e.g., ocf_to_shortdebt, total_mv).
    • Only translate the surrounding Chinese descriptions, table headers, and section introductory text.
    • Ensure consistency for field names that appear across multiple tables.