AStock

repository·master·Indexed 42 days ago

https://github.com/harrisonxi/astock

A Python-based terminal tool for real-time monitoring of Chinese A-share stocks. It features stock monitoring, health statistics via ahealth.py, and candlestick chart visualization via acandle.py. The tool supports stock code autocompletion, index shorthand codes, and the ability to monitor stocks from an input.list file.

Tokens
2.3K
Snippets
11
Records
11
Agent score
53%

What's inside AStock

  1. Run stock health statistics with ahealth.py

    master

    Use ahealth.py to generate statistical reports for stocks. Note that by default, this script does not include ChiNext (创业板) stocks. To include them, you must manually add the relevant stock codes to stock.list.

    python ahealth.py
  2. Monitor Chinese stocks in the terminal

    master

    Run astock.py followed by stock codes to monitor real-time data in your terminal.

    Code Autocompletion:

    • Codes starting with 6 will automatically be prefixed with sh.
    • Codes starting with 0 or 3 will automatically be prefixed with sz.

    Output Interpretation:

    • The value following the price change percentage represents the daily amplitude.
    • The subsequent integer represents the position of the current price within the daily amplitude: (current_price - low) / (high - low).
    • A trailing + or - sign indicates the order imbalance (委比). More + signs indicate a higher ratio of buy orders relative to sell orders (up to 5 signs).
    python astock.py sh600000 sz000001
    
    # Or use autocompletion for 6-series and 0-series codes
    python astock.py 600000 000001
  3. Monitor stocks from an input file

    master

    Instead of passing stock codes as command-line arguments, you can create a file named input.list in the same directory as the script. Separate each stock code with a newline character. AStock will read this file to determine which stocks to monitor.

    # input.list example
    sh600000
    sz000001
    600001
  4. Draw candlestick charts with acandle.py

    master

    The acandle.py script provides candlestick visualization. This feature requires pandas and numpy to be installed. The data format follows the TuShare open-source library standard (refer to test.csv in the repository for the expected schema).

    python acandle.py
  5. Install AStock dependencies

    master

    To use the core monitoring functionality of AStock, you must install the requests library via pip.

    If you wish to use the candlestick drawing feature (acandle.py), you must also install pandas and numpy.

    # Core dependency
    pip install requests
    
    # Additional dependency for candlestick drawing
    pip install pandas numpy
  6. Fetch K-line (Candlestick) data from Sina Finance API

    master

    You can retrieve K-line data using the Sina Finance JSONP API. The request URL requires a specific format for the path segment to handle caching or time validation, and query parameters to define the stock and timeframe.

    URL Structure

    The URL follows this pattern: https://quotes.sina.cn/cn/api/jsonp_v2.php/var%20_{stock_id}_{scale}_{timestamp}=/CN_MarketDataService.getKLineData?symbol={stock_id}&scale={scale}&ma={ma_param}&datalen={length}

    Path Segment Components (_{stock_id}_{scale}_{timestamp}):

    • stock_id: The stock identifier (e.g., sh600036).
    • scale: The time interval in minutes.
    • timestamp: A 13-digit Unix timestamp (milliseconds). This is used to avoid cache or potentially as a termination parameter.

    Query Parameters

    • symbol: The stock ID (e.g., sh600036).
    • scale: The time interval. Supported values include:
      • Minute levels: 5, 15, 30, 60.
      • Daily K-line: 240.
      • Weekly K-line: 1200.
    • ma: Set to no to exclude moving averages. If you remove the ma=no parameter, the API returns additional fields for 5, 10, and 30-period moving average prices (ma_price5, ma_price10, ma_price30) and volumes (ma_volume5, ma_volume10, ma_volume30).
    • datalen: The number of data points to return.

    Data Format

    Each data item in the response contains:

    • day: Timestamp/Date
    • open: Opening price
    • high: Highest price
    • low: Lowest price
    • close: Closing price
    • volume: Trading volume (shares)
    # Example: 60-minute K-line for sh600036
    https://quotes.sina.cn/cn/api/jsonp_v2.php/var%20_sh600036_60_1577432551767=/CN_MarketDataService.getKLineData?symbol=sh600036&scale=60&ma=no&datalen=1023
    
    # Example: Daily K-line (scale=240) with Moving Averages
    https://quotes.sina.cn/cn/api/jsonp_v2.php/var%20_sh600036_240_1577432551767=/CN_MarketDataService.getKLineData?symbol=sh600036&scale=240&datalen=1023
  7. Retrieve and use stock adjustment (dividend/split) data

    master

    Sina Finance provides APIs to retrieve adjustment factors for calculating adjusted prices. This is useful for identifying ex-dividend dates and calculating true returns.

    Adjustment APIs

    • Forward Adjustment (前复权): https://finance.sina.com.cn/realstock/company/{stock_id}/qfq.js
    • Backward Adjustment (后复权): https://finance.sina.com.cn/realstock/company/{stock_id}/hfq.js

    Data Format

    The response is a series of JSON objects containing:

    • d: The date of the adjustment.
    • f: The adjustment factor.

    Calculation Logic

    To calculate the adjusted return using these factors, use the following logic:

    Using Forward Adjustment (qfq): To compare a price at date $T_1$ with a price at date $T_2$ (where $T_2$ is the more recent date): $$\text{Return} = \frac{\text{Price}{T2} / f{T2}}{\text{Price}{T1} / f{T1}}$$

    Using Backward Adjustment (hfq): $$\text{Return} = \frac{\text{Price}{T2} \times f{T2}}{\text{Price}{T1} \times f{T1}}$$

    Note: The ratio of factors in hfq is the inverse of the ratio in qfq.

    // Example response from qfq.js
    [{"d":"2019-06-03", "f":"1.0000000000000000"}, {"d":"2007-01-18", "f":"1.3000000000000000"}]
  8. Fetch real-time stock quotes via Sina Finance API

    master

    You can retrieve real-time market data by querying the Sina Finance API endpoint. The endpoint supports single or multiple stock symbols separated by commas.

    Endpoint URL Pattern: https://hq.sinajs.cn/list={symbol}

    Example URLs:

    • Single stock: https://hq.sinajs.cn/list=sh000001
    • Multiple stocks: https://hq.sinajs.cn/list=sh000001,sh600036

    Data Format: The response is a JavaScript variable assignment (e.g., var hq_str_sh000001="..."). The values are comma-separated strings. Note that some responses end with a trailing comma, while others do not.

    Field Mapping (in order):

    1. Stock Name
    2. Opening Price
    3. Previous Close
    4. Current Price
    5. High Price
    6. Low Price
    7. Bid 1 Price
    8. Ask 1 Price
    9. Volume (Lots for indices, Shares for individual stocks)
    10. Turnover (Yuan)
    11. Bid 1 Volume (Shares)
    12. Bid 1 Price
    13. Bid 2 Volume (Shares)
    14. Bid 2 Price ... (continues through Bid 5)
    15. Ask 1 Volume (Shares)
    16. Ask 1 Price ... (continues through Ask 5)
    17. Date (YYYY-MM-DD)
    18. Time (HH:mm:ss)
    19. Status (00: Normal, -2: Not listed, -3/03: Delisted)
    https://hq.sinajs.cn/list=sh000001,sh600036
  9. Fetch intraday time-series data via Sina Finance API

    master

    To retrieve intraday (minute-by-minute) price and volume data, use the vML_DataList.php endpoint.

    Endpoint URL Pattern: https://vip.stock.finance.sina.com.cn/quotes_service/view/vML_DataList.php?asc=j&symbol={symbol}&num={count}

    Parameters:

    • asc: Sort order (e.g., j)
    • symbol: The stock symbol (e.g., sh600036)
    • num: The number of data points to retrieve

    Data Format: The response returns a list of lists. Each inner list represents a single time interval.

    Field Mapping (per item):

    1. Time (HH:mm:ss)
    2. Transaction Price
    3. Transaction Volume (Shares)
    https://vip.stock.finance.sina.com.cn/quotes_service/view/vML_DataList.php?asc=j&symbol=sh600036&num=11
  10. Fetch detailed transaction records via Sina Finance API

    master

    To access granular transaction-level details (tick data), use the CN_TransListV2.php endpoint.

    Endpoint URL Pattern: https://vip.stock.finance.sina.com.cn/quotes_service/view/CN_TransListV2.php?num={count}&symbol={symbol}

    Data Format: The response contains a JavaScript array trade_item_list. Additionally, it provides a variable trade_INVOL_OUTVOL containing daily totals.

    Field Mapping (per transaction item):

    1. Time (HH:mm:ss)
    2. Transaction Volume (Shares)
    3. Transaction Price
    4. Type (UP: Buy, DOWN: Sell, EQUAL: Neutral)

    Daily Totals (trade_INVOL_OUTVOL):

    1. Total Buy Volume (Shares)
    2. Total Sell Volume (Shares)
    https://vip.stock.finance.sina.com.cn/quotes_service/view/CN_TransListV2.php?num=11&symbol=sh600036
  11. Use special index codes in AStock

    master

    AStock supports shorthand codes for major Chinese market indices:

    • sh: Shanghai Composite Index (mapped to sh000001)
    • sz: Shenzhen Component Index (mapped to sz399001)
    • zx: SME Board Index
    • cy: ChiNext Index
    • 300: CSI 300 Index
    python astock.py sh sz