or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-commands.mdconstants-enums.mddata-access.mddata-models.mdframework-core.mdindex.mdportfolio-management.mdstrategy-execution.mdtrading-api.md
tile.json

tessl/pypi-rqalpha

Comprehensive algorithmic trading framework for Python with backtesting, simulation, and live trading capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/rqalpha@5.6.x

To install, run

npx @tessl/cli install tessl/pypi-rqalpha@5.6.0

index.mddocs/

RQAlpha

RQAlpha is a comprehensive algorithmic trading framework for Python that provides a complete solution for quantitative traders, covering data acquisition, algorithmic trading strategies, backtesting engine, simulated trading, live trading, and data analysis. The framework features a flexible configuration system, powerful extensibility through modules (Mods), and supports various trading scenarios from research and backtesting to production trading.

Package Information

  • Package Name: rqalpha
  • Language: Python
  • Installation: pip install rqalpha
  • License: Custom (Apache 2.0 for non-commercial use)
  • Documentation: http://rqalpha.readthedocs.io/zh_CN/latest/

Core Imports

import rqalpha

Common for strategy execution:

from rqalpha import run_file, run_code, run_func

Basic Usage

import rqalpha

# Execute a strategy from file
config = {
    "base": {
        "start_date": "2020-01-01",
        "end_date": "2020-12-31",
        "accounts": {"stock": 100000}
    }
}

result = rqalpha.run_file("my_strategy.py", config=config)

# Execute strategy from code string
strategy_code = """
def init(context):
    context.stocks = ["000001.XSHE"]

def handle_bar(context, bar_dict):
    order_target_percent("000001.XSHE", 0.5)
"""

result = rqalpha.run_code(strategy_code, config=config)

# Execute strategy using function callbacks
def init(context):
    context.stocks = ["000001.XSHE"]

def handle_bar(context, bar_dict):
    order_target_percent("000001.XSHE", 0.5)

result = rqalpha.run_func(config=config, init=init, handle_bar=handle_bar)

Architecture

RQAlpha follows a modular architecture enabling flexible trading system construction:

  • Strategy Layer: User-defined trading logic with lifecycle callbacks (init, handle_bar, handle_tick, etc.)
  • API Layer: Comprehensive trading APIs for order management, data access, and portfolio operations
  • Core Engine: Strategy execution, event processing, and phase management
  • Data Layer: Market data access, historical data, and real-time feeds
  • Portfolio System: Multi-account portfolio management with position tracking and P&L calculation
  • Broker Interface: Order execution simulation and live trading integration
  • Mod System: Extensible plugin architecture for custom functionality

This design enables RQAlpha to serve both individual traders and institutional users, providing APIs for strategy development, data handling, and integration with external trading systems.

Capabilities

Strategy Execution

Core entry points for running trading strategies, supporting file-based strategies, code strings, and function callbacks with comprehensive configuration options.

def run_file(strategy_file_path: str, config: dict = None) -> dict:
    """Execute strategy from file path with optional configuration."""

def run_code(code: str, config: dict = None) -> dict:
    """Execute strategy from code string with optional configuration."""

def run_func(**kwargs) -> dict:
    """Execute strategy using function callbacks (init, handle_bar, etc.)."""

Strategy Execution

Trading API

Order placement and management functions supporting stocks, futures, options, and bonds with various order types and position effects.

def order_shares(id_or_ins, amount, price_or_style=None):
    """Order by number of shares."""

def order_target_percent(id_or_ins, percent, price_or_style=None):
    """Target position by portfolio percentage."""

def get_open_orders():
    """Get all pending orders."""

def cancel_order(order):
    """Cancel pending order."""

Trading API

Data Access

Market data and historical data functions providing comprehensive access to pricing data, instrument information, calendar data, and financial metrics.

def history_bars(order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type='pre', adjust_orig=None):
    """Historical OHLCV bar data with adjustments."""

def current_snapshot(id_or_symbol):
    """Current market snapshot with bid/ask and volume."""

def all_instruments(type=None, date=None):
    """Get all available instruments by type and date."""

def get_trading_dates(start_date, end_date):
    """Get trading calendar dates between start and end."""

Data Access

Portfolio Management

Portfolio, account, and position management with real-time P&L tracking, multi-account support, and comprehensive position analytics.

def get_positions():
    """Get all current positions."""

def get_position(order_book_id, direction=POSITION_DIRECTION.LONG):
    """Get specific position with direction."""

def deposit(account_type, amount, receiving_days=0):
    """Deposit funds to account."""

def finance(amount, account_type=DEFAULT_ACCOUNT_TYPE.STOCK):
    """Finance/borrow funds."""

Portfolio Management

Constants and Enums

Trading system constants and enumerations defining order status, position effects, instrument types, exchanges, and execution phases.

ORDER_STATUS = CustomEnum([
    'PENDING_NEW', 'ACTIVE', 'FILLED', 'REJECTED', 'CANCELLED'
])

SIDE = CustomEnum([
    'BUY', 'SELL', 'FINANCING', 'MARGIN', 'CONVERT_STOCK'
])

INSTRUMENT_TYPE = CustomEnum([
    'CS', 'FUTURE', 'OPTION', 'ETF', 'LOF', 'INDX'
])

Constants and Enums

Data Models

Core data structures representing orders, trades, instruments, market data, and portfolio components with comprehensive metadata and properties.

class Order:
    """Order object with properties like order_id, instrument, quantity, status."""

class Trade:
    """Trade execution record."""

class Instrument:
    """Financial instrument with metadata."""

class BarObject:
    """OHLCV bar data with properties (open, high, low, close, volume)."""

Data Models

Framework Core

Strategy context, execution framework, and event system providing the foundation for strategy development and lifecycle management.

class StrategyContext:
    """Strategy context object (exposed as 'context' in strategies)."""
    portfolio: Portfolio
    stock_account: Account
    future_account: Account
    now: datetime
    universe: list

def subscribe_event(event_type, handler):
    """Subscribe to system events."""

Framework Core

Command Line Interface

Command line tools for strategy execution, data management, configuration generation, and system administration.

# CLI Commands (via 'rqalpha' command):
# rqalpha run - Run a trading strategy
# rqalpha create-bundle - Create data bundle using RQDatac
# rqalpha update-bundle - Update existing data bundle
# rqalpha generate-config - Generate default configuration file
# rqalpha mod - Mod management (install/uninstall/list/enable/disable)

CLI Commands

Types

# Configuration Types
Config = dict  # Strategy configuration dictionary
StrategyConfig = dict  # Strategy-specific configuration

# Execution Result
ExecutionResult = dict  # Strategy execution results with performance metrics

# Market Data Types
BarData = dict  # OHLCV bar data dictionary
TickData = dict  # Tick/quote data dictionary
Snapshot = dict  # Market snapshot data

# Order Types
OrderId = str  # Unique order identifier
InstrumentId = str  # Instrument identifier (order_book_id)
Price = float  # Price value
Quantity = float  # Quantity/amount value

# Date/Time Types
DateLike = Union[str, datetime.date, datetime.datetime]  # Date specification
Frequency = str  # Data frequency ('1d', '1m', etc.)