AKShare Financial Data Library

repository·main·Indexed 12 days ago

https://github.com/akfamily/akshare

A high-performance Python library for fetching financial data for quantitative research. It provides a unified interface to access a wide range of data sources, including A-shares, US stocks, funds, bonds, futures, options, cryptocurrencies, and global macroeconomic indicators (GDP, CPI, unemployment rates). The library includes tools for data collection, cleaning, and downloading, returning data primarily as pandas DataFrames.

Tokens
175.7K
Snippets
821
Records
896
Agent score
94%

What's inside AKShare

  1. Overview of AKShare Option Data Types

    main

    AKShare provides data for three main categories of options in the Chinese market:

    1. Stock Index Options (股指期权): Includes indices like CSI 300, SSE 50, and CSI 1000.
    2. ETF Options (ETF 期权): Includes various ETF-based options traded on SSE and SZSE.
    3. Commodity Futures Options (商品期货期权): Includes options related to various commodities (e.g., Aluminum, Gold, Crude Oil) traded on exchanges like SHFE, DCE, CZCE, and INE.
  2. Explore the AKShare Data Dictionary

    main

    The AKShare Data Dictionary provides detailed documentation for all available data interfaces. The dictionary is organized by financial asset classes and data types, allowing you to find specific APIs for stocks, futures, bonds, options, and more.

    Available data categories include:

    • Equities & Derivatives: stock, futures, bond, option, index (including qhkc)
    • Forex & Commodities: fx, currency, spot, energy
    • Funds: fund_private, fund_public, qdii
    • Macro & Economy: macro, interest_rate, bank
    • Specialized Data: nlp, article, event, hf, dc
    • Utilities: tool, others
  3. Understand Continuous Futures Contracts (Main vs. Index)

    main

    Because futures contracts expire, AKShare provides synthetic continuous contracts to allow for long-term historical analysis. There are two primary types:

    1. Main Continuous Contracts (主力连续合约)

    These track the most active contract (the one with the highest position/volume).

    • Code Suffixes: Ends in 88 or 888.
    • 88 (Simple Join): A simple concatenation of price/volume data from different active contracts. It does not perform price smoothing.
    • 888 (Smoothed): Applies a price adjustment to prevent artificial gaps during contract switches. It calculates the price difference between the old and new contract at $T-1$ and applies that offset to all historical prices. Volume and Open Interest are not adjusted; Turnover is set to 0.
    • Switching Logic: A switch occurs if another contract's position exceeds 1.1x the current main contract's position at market close.

    2. Index Continuous Contracts (指数连续合约)

    These represent a weighted average of all tradable contracts in a series.

    • Code Suffix: Ends in 99 (e.g., IF99).
    • Method: Uses cumulative open interest as the weighting factor to create a continuous price series. This is a data processing tool for market trend analysis and is not a tradable instrument.
  4. Review quantitative strategy types

    main

    AKShare documentation covers various quantitative strategy implementations across different asset classes. Common strategies include:

    Stock Strategies (股票)

    • Alpha Hedging (alpha对冲)
    • Call Auction Stock Selection (集合竞价选股)
    • Multi-factor Stock Selection (多因子选股)
    • Index Enhancement (指数增强)
    • Intraday Reversal Trading (日内回转交易)
    • Sector Rotation (行业轮动)
    • Machine Learning (机器学习)

    Futures Strategies (期货)

    • Dual Moving Average (双均线策略)
    • Alpha Hedging (alpha对冲)
    • Grid Trading (网格交易)
    • Cross-product Arbitrage (跨品种套利)
    • Inter-period Arbitrage (跨期套利)
    • Market Making (做市商交易)
    • Turtle Trading Method (海龟交易法)
  5. Understanding price adjustment (Forward vs Backward)

    main

    When dealing with stock or fund splits, mergers, or dividends, prices can show large gaps. Price adjustment (复权) ensures data continuity.

    1. Forward Adjustment (qfq)

    • Mechanism: Keeps the current price unchanged and adjusts historical prices up or down.
    • Use Case: Best for technical analysis and chart viewing, as it aligns with most trading software.
    • Drawbacks:
      • Historical prices are time-varying (they change when new dividends are issued).
      • For companies with continuous dividends, forward-adjusted prices can become negative.

    2. Backward Adjustment (hfq)

    • Mechanism: Keeps historical prices unchanged and adjusts the current price.
    • Use Case: Best for quantitative investment research as it represents the actual long-term wealth growth curve of an investor.
    • Drawbacks: Not suitable for visual chart analysis as the current price may deviate significantly from the actual market price.
  6. Understand stock price adjustment (Forward vs Backward)

    main

    Stock price adjustment (复权) is necessary to handle price gaps caused by stock splits, mergers, or dividends. Without adjustment, technical indicators and return calculations will be inaccurate.

    Forward Adjustment (qfq)

    • Mechanism: Keeps the current price constant and adjusts historical prices.
    • Use Case: Best for technical analysis and chart viewing (standard in most trading software).
    • Drawbacks:
      • Historical prices are time-varying (they change whenever a new dividend/split occurs).
      • For companies with continuous dividends, forward-adjusted prices can become negative.

    Backward Adjustment (hfq)

    • Mechanism: Keeps historical prices constant and adjusts the current price.
    • Use Case: Best for quantitative investment research as it represents the long-term wealth growth curve and true cumulative returns.
    • Drawbacks: The price may differ significantly from the actual market price, making it unsuitable for real-time chart viewing.
  7. Understand futures trading sessions and schedules

    main

    When working with futures data, it is important to account for different trading sessions: Call Auction (集合竞价), Day Session (日盘时间), and Night Session (夜盘时间). Trading hours vary significantly by exchange and specific product.

    Common Session Patterns

    • Call Auction (集合竞价): Typically occurs shortly before the day session (e.g., 08:55-09:00 or 20:55-21:00).
    • Day Session (日盘时间): Standard daytime trading, often split into morning and afternoon blocks (e.g., 09:00-11:30 and 13:30-15:00).
    • Night Session (夜盘时间): Extended trading hours for certain commodities like metals or energy (e.g., 21:00-23:00 or 21:00-01:00). Some products, like certain agricultural futures or financial indices, do not have night sessions.
  8. Understanding stock price adjustment (Forward vs Backward)

    main

    When analyzing historical stock data, price adjustments (复权) are necessary to account for corporate actions like stock splits, mergers, or dividends that create price gaps.

    Forward Adjustment (前复权 - qfq)

    • Mechanism: Keeps the current price unchanged and adjusts all historical prices downward/upward to maintain continuity.
    • Use Case: Best for technical analysis and chart viewing, as it aligns with most trading software.
    • Drawbacks: Historical prices are time-varying (change when new dividends are issued), and prices can occasionally become negative for high-dividend stocks.

    Backward Adjustment (后复权 - hfq)

    • Mechanism: Keeps historical prices unchanged and adjusts the current price upward/downward.
    • Use Case: Preferred for quantitative investment research as it represents the long-term wealth growth curve and reflects true investor returns.
    • Drawbacks: The adjusted price may differ significantly from the actual market price, making it less intuitive for real-time chart reading.
  9. Calculate Rolling Yield in Futures

    main

    Rolling Yield (展期收益率) measures the return gained or lost when switching from a near-month contract to a far-month contract.

    Formula: $$\text{Rolling Yield} = \frac{\text{Near-month Price} - \text{Far-month Price}}{\text{Near-month Price}}$$

    Market Structures:

    • Contango (远期溢价): Far-month price > Near-month price $\rightarrow$ Negative Rolling Yield.
    • Backwardation (远期折价): Far-month price < Near-month price $\rightarrow$ Positive Rolling Yield.
    • Flat (平价): Near-month price $\approx$ Far-month price $\rightarrow$ Rolling Yield $\approx$ 0.
  10. Run AKDocker with JupyterLab and Volume Mapping

    main

    To use AKShare interactively via JupyterLab and ensure your data/notebooks are saved to your local machine, run the container with port mapping and volume mounting.

    Important for Windows users: You must rewrite Windows paths like C:\home to the Docker-compatible format /c/home.

    Use the following command to start the service:

    docker run -it -p 8888:8888 --name akdocker -v /c/home:/home registry.cn-shanghai.aliyuncs.com/akfamily/aktools:jupyter jupyter-lab --allow-root --no-browser --ip=0.0.0.0

    Workflow:

    1. Run the command in your terminal.
    2. Look for the URL containing the token in the terminal output.
    3. Open the URL in your local browser (e.g., http://127.0.0.1:8888/lab?token=...).
    4. Work within the /home directory in JupyterLab. This directory is synchronized with your local /c/home folder, allowing you to persist .ipynb files and downloaded data locally.