RQAlpha Documentation

repository·master·Indexed 27 days ago

https://github.com/ricequant/rqalpha

RQAlpha is a quantitative trading research platform and algorithm trading system. It features an event-driven architecture, a mod system for extensibility, and a specific strategy lifecycle consisting of init, before_trading, handle_bar, and after_trading. The platform supports HDF5 data bundles, YAML configuration, and provides a comprehensive API for order execution, position management, and historical data retrieval.

Tokens
40.3K
Snippets
80
Records
185
Agent score
92%

What's inside RQAlpha

  1. Overview of RQAlpha

    master
    RQAlpha is a comprehensive solution for programmatic traders, covering data acquisition, algorithmic trading, backtesting engines, live simulation, live trading, and data analysis. It is designed to be highly configurable and extensible via a Mod Hook interface, allowing users to build customized trading systems.
  2. Understand RQAlpha's Event-Driven Architecture

    master
    RQAlpha uses an event-driven architecture where components register for specific events using add_listener. When an event occurs, the registered code executes immediately. This allows developers to seamlessly insert custom logic (like risk control or progress monitoring) into the backtesting process by subscribing to existing events.
  3. Read custom data directly in a strategy

    master

    You can read local files or access databases directly within your strategy.

    Important Considerations:

    • Execution Phase: Always perform data loading within init, before_trading, handle_bar, handle_tick, or after_trading functions. Do not execute data retrieval code outside these functions.
    • Path Resolution: The current working directory is the path where the rqalpha command is executed, not the strategy file's directory. To avoid errors with relative paths, use context.config.base.strategy_file to locate the strategy file and derive relative paths from there.
    from rqalpha.api import *
    import os
    import pandas as pd
    
    def read_csv_as_df(csv_path):
        data = pd.read_csv(csv_path)
        return data
    
    def init(context):
        # Get the absolute path of the strategy file
        strategy_file_path = context.config.base.strategy_file
        # Resolve relative path based on the strategy file location
        csv_path = os.path.join(os.path.dirname(strategy_file_path), "../IF1706_20161108.csv")
        
        # Load data and attach to context for use in other functions
        IF1706_df = read_csv_as_df(csv_path)
        context.IF1706_df = IF1706_df
    
    def before_trading(context):
        logger.info(context.IF1706_df)
    
    __config__ = {
        "base": {
            "start_date": "2015-01-09",
            "end_date": "2015-01-10",
            "frequency": "1d",
            "matching_type": "current_bar",
            "benchmark": None,
            "accounts": {
                "future": 1000000
            }
        },
        "extra": {
            "log_level": "verbose",
        },
    }
  4. Write a simple backtest strategy

    master

    To reproduce bugs or test logic, create a strategy file using the rqalpha.apis module. A standard strategy includes init, before_trading, handle_bar, and after_trading functions.

    Key lifecycle functions:

    • init(context): Initialize strategy parameters and universe.
    • before_trading(context): Execute logic before the market opens.
    • handle_bar(context, bar_dict): Main trading logic executed at every bar.
    • after_trading(context): Execute logic after the market closes.
    from rqalpha.apis import *
    
    def init(context):
        """初始化策略"""
        logger.info("策略初始化")
        context.stock = "000001.XSHE"  # 平安银行
        update_universe(context.stock)
    
    def before_trading(context):
        """每日开盘前执行"""
        logger.info(f"日期: {context.now.date()}")
    
    def handle_bar(context, bar_dict):
        """每个bar执行一次 - 主要交易逻辑"""
        # 获取历史数据
        prices = history_bars(context.stock, 20, '1d', 'close')
    
        if prices is not None:
            avg_price = prices.mean()
            current_price = bar_dict[context.stock].close
    
            # 简单的均值回归策略
            if current_price < avg_price * 0.98:
                order_value(context.stock, 30000)
                logger.info(f"买入 {context.stock}")
            elif current_price > avg_price * 1.02:
                position = get_position(context.stock)
                if position.quantity > 0:
                    order_target_percent(context.stock, 0)
                    logger.info(f"卖出 {context.stock}")
    
    def after_trading(context):
        """每日收盘后执行"""
        positions = context.portfolio.positions
        if len(positions) > 0:
            logger.info(f"持仓: {[p.order_book_id for p in positions.values()]}")
  5. Use RQData for financial data integration

    master

    RQData is a financial data service that integrates seamlessly with RQAlpha. To use it, simply import rqdatac within your strategy. It provides access to various data types including:

    • Contract Info: Basic info for A-shares, indices, funds, futures, and bonds.
    • A-share Info: Trading days, splits, dividends, suspensions, and ST status.
    • Market Data: A-share historical and real-time data, index snapshots, and valuations.
    • Fund Data: NAV, disclosures, and holdings.
    • Futures/Options/Spot: Full market options, futures historical/snapshot data, and main contract continuity.
    • Convertible Bonds: Basic contract and price data.
    • Financial Data: Comprehensive A-share financial statements (operating, profitability, valuation) with Point-in-Time API support.
    • Industry/Sector/Concept: Classification and turnover data.
    • Style Factors: Exposure, returns, covariance, and idiosyncratic risk.
    • Macro Data: Reserve requirements, money supply, etc.
    • Alternative Data: E-commerce (Tmall, Taobao, JD) and sentiment data (Xueqiu, Eastmoney).
  6. Manage branches for RQAlpha development

    master

    RQAlpha uses specific branches to manage stability and development:

    • master: The latest stable version. Only team members merge develop into master during official releases.
    • develop: The latest development version. All new code submissions must pass all tests before being merged here.

    Branch Naming Rules:

    • bug/xxx: Use this for bug fixes.
    • feature/xxx: Use this for adding new features (ensure documentation and tests are updated).
  7. Create a Custom Module (Mod) by Subscribing to Events

    master

    To extend RQAlpha, implement the AbstractMod interface. You can use the start_up method to access the env.event_bus and register listeners for specific events using add_listener(EVENT_TYPE, callback_function).

    Example: Creating a progress bar module that updates after each trading day.

    import click
    from rqalpha.interface import AbstractMod
    from rqalpha.events import EVENT
    
    
    class ProgressMod(AbstractMod):
        def __init__(self):
            self._env = None
            self.progress_bar = None
    
        def start_up(self, env, mod_config):
            self._env = env
            # Registering listeners for system init and post-trading events
            env.event_bus.add_listener(EVENT.POST_AFTER_TRADING, self._tick)
            env.event_bus.add_listener(EVENT.POST_SYSTEM_INIT, self._init)
    
        def _init(self, event):
            # Initialize progress bar based on trading calendar length
            trading_length = len(self._env.config.base.trading_calendar)
            self.progress_bar = click.progressbar(length=trading_length, show_eta=False)
    
        def _tick(self, event):
            # Update progress bar on every tick/trading day end
            self.progress_bar.update(1)
    
        def tear_down(self, success, exception=None):
            # Clean up/finish progress bar on exit
            if self.progress_bar:
                self.progress_bar.render_finish()
    
    
    def load_mod():
        return ProgressMod()
  8. Build and view RQAlpha documentation

    master

    Use the following make commands to manage the documentation build process:

    • make html: Compiles the documentation and generates HTML files in {project}/docs/build/.
    • make htmlview: Starts a local server to view the compiled documentation.
    • make clean: Removes all files in the build directory.
    • make watch: Automatically recompiles the documentation whenever source files are changed.
    make html
    make htmlview
    make clean
    make watch