CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rqalpha

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

Pending
Overview
Eval results
Files

data-access.mddocs/

Data Access

Market data and historical data functions providing comprehensive access to pricing data, instrument information, calendar data, financial metrics, and fundamental data. All functions support flexible querying with proper data alignment and adjustments.

Capabilities

Historical Market Data

Functions for accessing historical OHLCV bar data and tick data with various frequencies and adjustments.

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.

    Parameters:
    - order_book_id (str): Instrument identifier
    - bar_count (int): Number of bars to retrieve
    - frequency (str): Data frequency ('1d', '1m', '5m', '15m', '30m', '60m')
    - fields (str|list, optional): Fields to retrieve ('open', 'high', 'low', 'close', 'volume')
    - skip_suspended (bool): Skip suspended trading periods
    - include_now (bool): Include current incomplete bar
    - adjust_type (str): Adjustment type ('pre', 'post', 'none')
    - adjust_orig (str, optional): Original adjustment reference point

    Returns:
    numpy.ndarray|pandas.DataFrame: Historical bar data
    """

def history_ticks(order_book_id, count):
    """
    Historical tick data.

    Parameters:
    - order_book_id (str): Instrument identifier
    - count (int): Number of ticks to retrieve

    Returns:
    list[TickObject]: List of tick data objects
    """

Real-time Market Data

Functions for accessing current market snapshots and real-time pricing information.

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

    Parameters:
    - id_or_symbol (str): Instrument ID or symbol

    Returns:
    dict: Market snapshot with bid_price, ask_price, last_price, volume, etc.
    """

Instrument Information

Functions for discovering and accessing instrument metadata and classifications.

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

    Parameters:
    - type (str, optional): Instrument type filter ('CS', 'FUTURE', 'OPTION', 'ETF')
    - date (str|datetime, optional): Date for instrument universe

    Returns:
    pandas.DataFrame: DataFrame with instrument information
    """

def instruments(id_or_symbols):
    """
    Get specific instruments by ID.

    Parameters:
    - id_or_symbols (str|list[str]): Instrument ID(s) to retrieve

    Returns:
    Instrument|list[Instrument]: Instrument object(s) with metadata
    """

def symbol(order_book_id, sep=", "):
    """
    Get human-readable instrument symbol.

    Parameters:
    - order_book_id (str): Instrument identifier
    - sep (str): Separator for multiple symbols

    Returns:
    str: Human-readable symbol name
    """

Trading Calendar

Functions for accessing trading calendar information and date calculations.

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

    Parameters:
    - start_date (str|datetime): Start date
    - end_date (str|datetime): End date

    Returns:
    list[datetime.date]: List of trading dates
    """

def get_previous_trading_date(date, n=1):
    """
    Get previous trading day.

    Parameters:
    - date (str|datetime): Reference date
    - n (int): Number of trading days back

    Returns:
    datetime.date: Previous trading date
    """

def get_next_trading_date(date, n=1):
    """
    Get next trading day.

    Parameters:
    - date (str|datetime): Reference date
    - n (int): Number of trading days forward

    Returns:
    datetime.date: Next trading date
    """

Fixed Income Data

Functions for accessing bond and fixed income market data.

def get_yield_curve(date=None, tenor=None):
    """
    Yield curve data.

    Parameters:
    - date (str|datetime, optional): Date for yield curve
    - tenor (str, optional): Specific tenor ('1Y', '2Y', '5Y', '10Y', '30Y')

    Returns:
    pandas.DataFrame: Yield curve data with tenors and rates
    """

Market Structure Data

Functions for accessing index compositions, industry classifications, and market structure information.

def index_components(order_book_id, date=None):
    """
    Index constituent stocks.

    Parameters:
    - order_book_id (str): Index identifier
    - date (str|datetime, optional): Date for composition

    Returns:
    list[str]: List of constituent instrument IDs
    """

def index_weights(order_book_id, date=None):
    """
    Index constituent weights.

    Parameters:
    - order_book_id (str): Index identifier
    - date (str|datetime, optional): Date for weights

    Returns:
    pandas.DataFrame: DataFrame with instruments and weights
    """

def concept(*concept_names):
    """
    Get stocks by concept categories.

    Parameters:
    - concept_names (str): Concept category names

    Returns:
    list[str]: List of instrument IDs in concept
    """

def get_industry(industry, source='citics'):
    """
    Get stocks by industry.

    Parameters:
    - industry (str): Industry name or code
    - source (str): Classification source ('citics', 'sw', 'zjw')

    Returns:
    list[str]: List of instrument IDs in industry
    """

def get_instrument_industry(order_book_ids, source='citics', level=1):
    """
    Get instrument industry classification.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - source (str): Classification source ('citics', 'sw', 'zjw')
    - level (int): Classification level (1, 2, 3)

    Returns:
    pandas.DataFrame: DataFrame with instruments and industry classifications
    """

Margin and Trading Data

Functions for accessing margin trading information and special trading programs.

def get_margin_stocks(exchange=None, margin_type="all"):
    """
    Margin trading eligible stocks.

    Parameters:
    - exchange (str, optional): Exchange filter ('XSHE', 'XSHG')
    - margin_type (str): Margin type ('margin', 'short_selling', 'all')

    Returns:
    list[str]: List of margin-eligible instrument IDs
    """

def get_stock_connect(order_book_ids, count=1, fields=None, expect_df=False):
    """
    Stock connect data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - count (int): Number of periods to retrieve
    - fields (list, optional): Specific fields to retrieve
    - expect_df (bool): Return DataFrame instead of dict

    Returns:
    dict|pandas.DataFrame: Stock connect trading data
    """

Financial Factor Data

Functions for accessing quantitative factors and financial metrics.

def get_factor(order_book_ids, factor_names, start_date, end_date, universe=None, expect_df=False):
    """
    Multi-factor data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - factor_names (str|list[str]): Factor name(s)
    - start_date (str|datetime): Start date
    - end_date (str|datetime): End date
    - universe (str, optional): Universe filter
    - expect_df (bool): Return DataFrame instead of dict

    Returns:
    dict|pandas.DataFrame: Factor data
    """

def get_securities_margin(order_book_ids, count=1, fields=None, expect_df=False):
    """
    Securities margin data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - count (int): Number of periods to retrieve
    - fields (list, optional): Specific fields
    - expect_df (bool): Return DataFrame instead of dict

    Returns:
    dict|pandas.DataFrame: Margin trading data
    """

def get_shares(order_book_ids, count=1, fields=None, expect_df=False):
    """
    Share count data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - count (int): Number of periods to retrieve
    - fields (list, optional): Fields ('total_shares', 'float_shares', etc.)
    - expect_df (bool): Return DataFrame instead of dict

    Returns:
    dict|pandas.DataFrame: Share count data
    """

def get_turnover_rate(order_book_ids, count=1, fields=None, expect_df=False):
    """
    Turnover rate data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - count (int): Number of periods to retrieve
    - fields (list, optional): Specific fields
    - expect_df (bool): Return DataFrame instead of dict

    Returns:
    dict|pandas.DataFrame: Turnover rate data
    """

def get_price_change_rate(order_book_ids, count=1, expect_df=False):
    """
    Price change rate data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - count (int): Number of periods to retrieve
    - expect_df (bool): Return DataFrame instead of dict

    Returns:
    dict|pandas.DataFrame: Price change rate data
    """

Corporate Actions

Functions for accessing corporate action data including splits and dividends.

def get_split(order_book_ids, start_date=None):
    """
    Stock split adjustment data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - start_date (str|datetime, optional): Start date for splits

    Returns:
    pandas.DataFrame: Split data with dates and ratios
    """

Futures Market Data

Functions for accessing futures-specific market data and contract information.

def get_dominant_future(underlying_symbol, rule=0):
    """
    Get dominant future contract.

    Parameters:
    - underlying_symbol (str): Underlying asset symbol
    - rule (int): Dominance rule (0=volume, 1=open_interest)

    Returns:
    str: Dominant contract instrument ID
    """

Financial Statements

Functions for accessing fundamental financial data from company reports.

def get_pit_financials(fields, quarter=None, interval=None, order_book_ids=None, if_adjusted='all'):
    """
    Point-in-time financial data.

    Parameters:
    - fields (str|list[str]): Financial statement fields
    - quarter (str, optional): Specific quarter ('2020Q1')
    - interval (str, optional): Data interval
    - order_book_ids (str|list[str], optional): Instrument filter
    - if_adjusted (str): Adjustment type ('all', 'none')

    Returns:
    pandas.DataFrame: Financial statement data
    """

def get_pit_financials_ex(order_book_ids, fields, count, statements='latest'):
    """
    Enhanced PIT financial data.

    Parameters:
    - order_book_ids (str|list[str]): Instrument ID(s)
    - fields (str|list[str]): Financial fields
    - count (int): Number of periods
    - statements (str): Statement type filter

    Returns:
    pandas.DataFrame: Enhanced financial data
    """

def get_current_performance(order_book_id, quarter, fields=None):
    """
    Current performance data.

    Parameters:
    - order_book_id (str): Instrument identifier
    - quarter (str): Quarter specification
    - fields (list, optional): Specific performance fields

    Returns:
    dict: Performance metrics
    """

Data Query Interface

SQL-like query interface for flexible data access.

def query(*entities):
    """
    SQL-like query interface for data.

    Parameters:
    - entities: Query entities and filters

    Returns:
    QueryResult: Query result object with data access methods

    Usage:
    from rqalpha.apis import query
    result = query(fundamentals.income_statement.revenue).filter(
        fundamentals.stockcode.in_(["000001.XSHE", "000002.XSHE"])
    )
    """

Data Usage Examples

Historical Data Analysis

def init(context):
    # Get 252 days of daily data
    hist_data = history_bars("000001.XSHE", 252, "1d", fields=["close", "volume"])
    
    # Calculate moving average
    ma_20 = hist_data["close"][-20:].mean()
    ma_60 = hist_data["close"][-60:].mean()
    
    context.ma_signal = ma_20 > ma_60

def handle_bar(context, bar_dict):
    # Get recent 5-minute data
    recent_data = history_bars("000001.XSHE", 12, "5m")
    
    # Current snapshot
    snapshot = current_snapshot("000001.XSHE")
    bid_price = snapshot["bid_price"]
    ask_price = snapshot["ask_price"]

Universe Construction

def init(context):
    # Get all stocks
    all_stocks = all_instruments(type="CS")
    
    # Filter by industry
    tech_stocks = get_industry("软件服务", source="sw")
    
    # Get index components
    hs300_stocks = index_components("000300.XSHG")
    
    # Combine filters
    context.universe = list(set(tech_stocks) & set(hs300_stocks))
    update_universe(context.universe)

def handle_bar(context, bar_dict):
    # Get factor data for universe
    factor_data = get_factor(
        context.universe, 
        ["pe_ratio", "pb_ratio", "roe"], 
        context.now, 
        context.now
    )

Calendar and Timing

def before_trading(context):
    # Check if today is month end
    next_trading_day = get_next_trading_date(context.now)
    if next_trading_day.month != context.now.month:
        context.is_month_end = True
    else:
        context.is_month_end = False
    
    # Get trading dates for the month
    month_start = context.now.replace(day=1)
    trading_days = get_trading_dates(month_start, context.now)
    context.trading_days_in_month = len(trading_days)

Install with Tessl CLI

npx tessl i tessl/pypi-rqalpha

docs

cli-commands.md

constants-enums.md

data-access.md

data-models.md

framework-core.md

index.md

portfolio-management.md

strategy-execution.md

trading-api.md

tile.json