J-Quants API Client for Python

repository·main·Indexed 41 days ago

https://github.com/j-quants/jquants-api-client-python

A Python client library for the J-Quants API, providing access to Japanese market data such as stock prices, financial summaries, and market indicators. It features the ClientV2 class for interacting with the V2 API and returns data as pandas DataFrames. Supports retrieval of listed stock information via get_eq_master, daily price data via get_eq_bars_daily, and financial summaries via get_fin_summary. Requires Python 3.10+ and pandas 2.2+.

Tokens
3.2K
Snippets
12
Records
15
Agent score
52%

What's inside J-Quants

  1. Environment and Compatibility Requirements

    main

    The following environment is required for jquants-api-client:

    • Python: 3.10 or higher.
    • pandas: 2.2 or higher (supports pandas 3.x).

    Note on pandas 3.x compatibility: If using pandas 3.x, the dtype of returned DataFrames may change:

    • String columns: object $\rightarrow$ str
    • Date columns: datetime64[ns] $\rightarrow$ datetime64[us]

    If your processing logic depends on specific pandas dtypes, please account for these changes.

  2. Explore comprehensive data retrieval examples in AlpacaDB sample

    main
    For a more exhaustive list of data retrieval methods and usage patterns, refer to the AlpacaDB/jquants-api-sample repository. This collection of notebooks covers a wide range of methods available in jquants-api-client-python for fetching various types of financial data.
  3. Use J-Quants API V2 starter notebook in Google Colab

    main

    For a guided introduction to using the J-Quants API V2 and performing basic data retrieval with ClientV2, you can use the official Google Colab starter notebook. This notebook is executable and provides a step-by-step explanation of the client's usage.

    https://colab.research.google.com/github/J-Quants/jquants-api-client-python/blob/master/examples/20260119-007-jquants-api-v2-starter.ipynb
  4. Configure the J-Quants API Client

    main

    The client requires an API key obtained from the J-Quants API Dashboard. You can provide the key in several ways. The configuration is loaded in the following order (later sources overwrite earlier ones):

    1. /content/drive/MyDrive/drive_ws/secret/jquants-api.toml (Google Colab only)
    2. ${HOME}/.jquants-api/jquants-api.toml
    3. jquants-api.toml (local directory)
    4. Environment variable JQUANTS_API_CLIENT_CONFIG_FILE (points to a config file)
    5. Environment variable JQUANTS_API_KEY (direct key string)

    To use a TOML configuration file, use the following format:

    [jquants-api-client]
    api_key = "YOUR_API_KEY"
    [jquants-api-client]
    api_key = "*****"
  5. Configure J-Quants API V2 Authentication

    main

    J-Quants API V2 uses an API key (x-api-key) for authentication. You can configure the ClientV2 class using one of the following three methods:

    Method 1: Direct Argument

    Pass the api_key directly to the ClientV2 constructor.

    Method 2: Environment Variable

    Set the JQUANTS_API_KEY environment variable. The client will automatically detect it.

    Method 3: Configuration File

    Create a jquants-api.toml file in ~/.jquants-api/ or the current directory with the following structure.

    # Method 1: Direct Argument
    cli = jquantsapi.ClientV2(api_key="your-api-key")
    
    # Method 2: Environment Variable
    # export JQUANTS_API_KEY="your-api-key"
    cli = jquantsapi.ClientV2()
    
    # Method 3: Configuration File (jquants-api.toml)
    # [jquants-api-client]
    # api_key = "your-api-key"
  6. Handle Rate Limits and `_range` methods

    main

    Methods ending in _range (e.g., get_eq_bars_daily_range, get_fin_summary_range) perform parallel API requests for the specified date range. This increases the risk of hitting rate limits.

    If you exceed the rate limit, the API returns an HTTP 429 Too Many Requests error. To avoid this:

    • Avoid very wide date ranges in a single call.
    • Avoid executing multiple _range requests in a short period.
    • If a 429 occurs, wait for a period before retrying or split the request into smaller date segments.
  7. Initialize ClientV2 and fetch daily stock data

    main

    Use jquantsapi.ClientV2 to interact with the V2 API. You can pass the api_key directly to the constructor or rely on the JQUANTS_API_KEY environment variable. API responses are returned as pandas DataFrames.

    from datetime import datetime
    from dateutil import tz
    import jquantsapi
    
    # Using an explicit API key
    my_api_key: str = "*****"
    cli = jquantsapi.ClientV2(api_key=my_api_key)
    
    # Fetching daily price range data
    df = cli.get_eq_bars_daily_range(
        start_dt=datetime(2022, 7, 25, tzinfo=tz.gettz("Asia/Tokyo")),
        end_dt=datetime(2022, 7, 26, tzinfo=tz.gettz("Asia/Tokyo")),
    )
    print(df)
    
    # Alternatively, if JQUANTS_API_KEY is set in environment variables:
    # cli = jquantsapi.ClientV2()
  8. Reference: ClientV2 Wrapper Methods (V2 API)

    main

    The ClientV2 class provides wrappers for various J-Quants API endpoints. These are categorized into data wrappers and utility methods.

    ### Wrappers (Data Endpoints)
    - get_eq_master - 上場銘柄一覧
    - get_eq_bars_daily - 株価日足
    - get_eq_bars_daily_am - 株価午前終値
    - get_eq_earnings_cal - 決算発表予定日(3・9月期決算会社のみ・翌営業日分)
    - get_eq_investor_types - 投資部門別売買状況
    - get_eq_valuation - バリュエーション指標(PER/PBR/ROE・時価総額)
    - get_idx_bars_daily - 指数日足
    - get_idx_bars_daily_topix - TOPIX日足
    - get_mkt_calendar - 営業日カレンダー
    - get_mkt_short_ratio - 空売り比率
    - get_mkt_short_sale_report - 空売り報告
    - get_mkt_margin_interest - 週次信用取引残高
    - get_mkt_margin_alert - 信用規制情報
    - get_mkt_breakdown - 売買内訳
    - get_drv_bars_daily_fut - 先物日足
    - get_drv_bars_daily_opt - オプション日足
    - get_drv_bars_daily_opt_225 - 日経225オプション日足
    - get_fin_summary - 決算サマリー
    - get_fin_summary_cursor - 決算サマリー(cursor 差分取得)
    - get_fin_details - 財務詳細
    - get_fin_details_cursor - 財務詳細(cursor 差分取得)
    - get_fin_dividend - 配当情報
    - get_fin_earnings_date - 決算発表予定日
    - get_edinet_major_shareholders - 大株主状況(EDINET)
    - get_edinet_cross_shareholdings - 政策保有株式(EDINET)
    - get_edinet_large_volume_shareholders - 大量保有報告書(EDINET)
    - get_bulk_list - バルクデータ一覧
    - get_bulk - バルクデータ取得
    - get_eq_bars_minute - 分足
    - get_eq_bars_5minute - 5分足(分足から算出)
    - get_eq_bars_15minute - 15分足(分足から算出)
    - get_td_list - 適時開示インデックス一覧
    - get_td_files - 適時開示ファイルダウンロードURL取得
    - get_td_bulk - 適時開示インデックス一括ダウンロードURL取得
    
    ### Utilities
    - get_market_segments - 市場区分一覧
    - get_17_sectors - 17業種一覧
    - get_33_sectors - 33業種一覧
    
    ### Range Utilities (Batch retrieval by date range)
    - get_list - 銘柄一覧(セクター情報付き)
    - get_eq_bars_daily_range - 株価日足(範囲指定)
    - get_eq_valuation_range - バリュエーション指標(範囲指定)
    - get_mkt_short_ratio_range - 空売り比率(範囲指定)
    - get_mkt_short_sale_report_range - 空売り報告(範囲指定)
    - get_mkt_margin_interest_range - 信用取引残高(範囲指定)
    - get_mkt_margin_alert_range - 信用規制情報(範囲指定)
    - get_mkt_breakdown_range - 売買内訳(範囲指定)
    - get_drv_bars_daily_fut_range - 先物日足(範囲指定)
    - get_drv_bars_daily_opt_range - オプション日足(範囲指定)
    - get_drv_bars_daily_opt_225_range - 日経225オプション日足(範囲指定)
    - get_fin_summary_range - 決算サマリー(範囲指定)
    - get_fin_details_range - 財務詳細(範囲指定)
    - get_fin_earnings_date_range - 決算発表予定日(公表日の範囲指定)
  9. Get financial summary with get_fin_summary and caching

    main

    Retrieve quarterly and annual financial results for listed companies.

    Single Stock Summary

    Use get_fin_summary(code="...") to get data for a specific company.

    Range Summary with Caching

    Use get_fin_summary_range() to fetch data over a period. You can provide a cache_dir argument to save the results locally. Subsequent calls will use the cache, reducing API consumption.

    import os
    from datetime import datetime, timedelta
    
    # Single stock
    df_fins = cli.get_fin_summary(code="86970")
    
    # Range with caching
    cache_dir = os.path.expanduser("~/.jquants/cache")
    d_from = datetime.now() - timedelta(days=30)
    d_to = datetime.now() - timedelta(days=1)
    
    df_fins_range = cli.get_fin_summary_range(
        start_dt=d_from.strftime("%Y%m%d"),
        end_dt=d_to.strftime("%Y%m%d"),
        cache_dir=cache_dir
    )
  10. Get daily stock price data with get_eq_bars_daily

    main

    Retrieve daily stock price data for a specific stock code. The data includes adjusted prices (accounting for stock splits/mergers) and unadjusted prices.

    Note: The code parameter typically requires a 5-digit string (e.g., 86970 for JPX).

    # Get daily prices for a specific stock (e.g., JPX 8697)
    df_price = cli.get_eq_bars_daily(code="86970")