1. Domestic Financial Market Data Tools#
1. Tushare#
Tushare provides comprehensive data on China's financial markets. It covers various financial products including A-shares, Hong Kong stocks, futures, funds, bonds, and foreign exchange, even including industry big data and cryptocurrency market data. Tushare's API is designed to be simple, returning data directly in Pandas DataFrame format, which is convenient for subsequent analysis. Although some advanced features require points or VIP access, the basic data can meet most research needs.
import tushare as ts
# Initialize Pro API
pro = ts.pro_api('your_token_here')
# Get daily data for the Shanghai Composite Index
df = pro.index_daily(ts_code='000001.SH', start_date='20200101', end_date='20230101')
print(df.head())
Applicable Scenarios: A-share quantitative analysis, financial academic research, macroeconomic analysis.
2. AkShare#
AkShare is a completely open-source and free financial data interface library, known for its timely data updates and wide coverage. It aggregates data sources from multiple financial information platforms such as Eastmoney and Sina Finance, supporting various financial products including stocks, futures, options, funds, foreign exchange, bonds, indices, and cryptocurrencies.
import akshare as ak
# Get historical market data for the Shanghai Composite Index
stock_zh_index_daily_df = ak.stock_zh_index_daily(symbol="sh000001")
print(stock_zh_index_daily_df.head())
Applicable Scenarios: High-frequency data needs, multi-market comprehensive analysis, data science projects.
3. baostock#
baostock focuses on providing data for the domestic A-share market, including historical market data, financial data, and dividend data. Its advantage lies in being completely free and having high data quality, making it particularly suitable for quantitative traders and researchers focused on A-share analysis.
import baostock as bs
import pandas as pd
# Log in to the system
lg = bs.login()
# Get historical data for Kweichow Moutai
rs = bs.query_history_k_data_plus("sh.600519",
"date,open,high,low,close,volume",
start_date='2020-01-01',
end_date='2023-01-01')
# Convert to DataFrame
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list, columns=rs.fields)
# Log out of the system
bs.logout()
Applicable Scenarios: A-share historical data analysis, financial factor research, quantitative strategy backtesting.
2. International Financial Market Data Portals#
4. yfinance#
yfinance is the preferred tool for obtaining global stock market data, especially US stock data. It provides historical stock prices (open, high, low, close, volume), real-time prices, dividend information, and supports data retrieval at different time granularities.
import yfinance as yf
# Get stock data for Apple Inc.
apple = yf.Ticker("AAPL")
# Get historical data for the past year
hist = apple.history(period="1y")
# Get data for multiple stocks
data = yf.download(['AAPL', 'MSFT', 'GOOG'],
start="2020-01-01",
end="2023-01-01")
Applicable Scenarios: US stock analysis, portfolio management, multinational corporate research.
5. pandas-datareader#
As an important part of the pandas ecosystem, pandas-datareader provides a unified API to access multiple financial data sources, including Yahoo Finance, FRED, World Bank, etc. It integrates seamlessly with pandas, making it an ideal choice for building automated data analysis workflows.
import pandas_datareader as pdr
from datetime import datetime
# Get stock data for Apple Inc.
start = datetime(2020, 1, 1)
end = datetime(2023, 1, 1)
aapl = pdr.get_data_yahoo('AAPL', start, end)
# Get US unemployment rate data
unrate = pdr.get_data_fred('UNRATE', start, end)
Applicable Scenarios: Economic data analysis, cross-data source research, automated report generation.
6. Alpha Vantage#
Alpha Vantage provides professional-grade global financial market data, covering over 200,000 financial instruments including stocks, ETFs, foreign exchange, and cryptocurrencies. Its unique advantage lies in its built-in technical analysis indicators, allowing direct access to processed technical indicator data.
from alpha_vantage.timeseries import TimeSeries
# Initialize API
ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas')
# Get daily data for Apple Inc.
data, meta_data = ts.get_daily(symbol='AAPL', outputsize='full')
# Get technical indicators (e.g., RSI)
from alpha_vantage.techindicators import TechIndicators
ti = TechIndicators(key='YOUR_API_KEY')
rsi_data, rsi_meta_data = ti.get_rsi(symbol='AAPL', interval='daily', time_period=14)
Applicable Scenarios: Quantitative strategy development, technical analysis, global market monitoring.
7. quandl#
quandl provides high-quality financial and economic data from hundreds of sources, including official data published by global exchanges, central banks, and government agencies. While some datasets require payment, there are also many free high-value datasets available for use.
import quandl
# Get US GDP data
gdp = quandl.get('FRED/GDP')
# Get gold price data
gold = quandl.get('LBMA/GOLD')
Applicable Scenarios: Macroeconomic research, fundamental analysis, long-term trend research.
8. iexfinance#
iexfinance provides access to the IEX Cloud platform, obtaining real-time stock data and company fundamentals. It is particularly suitable for scenarios requiring real-time trading data, providing high-quality stock market data.
from iexfinance.stocks import Stock
# Get stock data for Microsoft Corp.
msft = Stock("MSFT", token="YOUR_API_KEY")
# Get real-time quotes
quote = msft.get_quote()
# Get fundamental data
fundamentals = msft.get_fundamentals()
Applicable Scenarios: Real-time trading systems, fundamental analysis, portfolio monitoring.
3. Specialized Data Tools#
9. ccxt#
ccxt is the most comprehensive interface library in the cryptocurrency field, supporting APIs from over 140 cryptocurrency exchanges. It can not only obtain market data but also supports trade execution, making it an essential tool for cryptocurrency quantitative trading.
import ccxt
# Initialize Binance exchange
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET'
})
# Get BTC/USDT market data
ticker = exchange.fetch_ticker('BTC/USDT')
# Get OHLCV data
ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1d')
Applicable Scenarios: Cryptocurrency trading, blockchain analysis, digital asset portfolio management.
10. fixer#
fixer provides professional foreign exchange rate data, supporting real-time and historical exchange rate queries for over 170 currencies. It is supported by the European Central Bank, making its data authoritative and reliable, essential for foreign exchange trading and international business.
import requests
# Get the latest exchange rates
response = requests.get('http://data.fixer.io/api/latest?access_key=YOUR_API_KEY&symbols=USD,CNY,EUR')
data = response.json()
# Get historical exchange rates
hist_response = requests.get('http://data.fixer.io/api/2018-01-01?access_key=YOUR_API_KEY&symbols=USD,CNY')
Applicable Scenarios: Foreign exchange trading systems, multinational corporate finance, international travel applications.
11. yahooquery#
yahooquery is an enhanced alternative to yfinance, providing more comprehensive access to Yahoo Finance data, including financial statements, options data, market news, and other richer data types.
from yahooquery import Ticker
# Get data for Tesla Inc.
tsla = Ticker('TSLA')
# Get balance sheet
balance_sheet = tsla.balance_sheet()
# Get options data
options = tsla.option_chain
Applicable Scenarios: In-depth fundamental analysis, options strategy research, corporate financial analysis.
12. eodh#
eodhd provides global stock, ETF, index, and foreign exchange data, covering major exchanges worldwide. Its feature is providing rich historical data and economic indicators, suitable for global market analysis.
from eodhd import APIClient
# Initialize client
api = APIClient(api_key="YOUR_API_KEY")
# Get historical data for Apple Inc.
aapl_hist = api.get_historical_data("AAPL.US", "d", start="2020-01-01")
# Get dividend data
dividends = api.get_dividends("AAPL.US")
Applicable Scenarios: Global asset allocation, multinational investment research, dividend strategy analysis.
4. Featured Data Tools#
13. investpy#
investpy focuses on providing financial data for emerging markets, especially those difficult to obtain from mainstream data sources. It scrapes data from Investing.com, covering global stocks, indices, funds, etc.
import investpy
# Get stock data for Brazil
br_stocks = investpy.get_stocks(country='brazil')
# Get historical data for the Indian index
nifty_50 = investpy.get_index_historical_data(index='Nifty 50', country='india', from_date='01/01/2020', to_date='01/01/2023')
Applicable Scenarios: Emerging market research, global asset allocation, investment analysis in developing countries.
14. finnhub#
finnhub provides high-quality real-time financial market data, including real-time quotes for stocks, foreign exchange, and cryptocurrencies. It also provides news and social media sentiment data, suitable for high-frequency trading and sentiment analysis.
import finnhub
# Initialize client
finnhub_client = finnhub.Client(api_key="YOUR_API_KEY")
# Get real-time quotes
quote = finnhub_client.quote('AAPL')
# Get company news
news = finnhub_client.company_news('AAPL', _from="2023-01-01", to="2023-01-10")
Applicable Scenarios: High-frequency trading, market sentiment analysis, event-driven strategies.
15. wrds#
wrds (Wharton Research Data Services) is the gold standard in academic research, providing access to professional databases such as CRSP and Compustat. Although primarily aimed at academia, it is also a powerful tool for professional financial research.
import wrds
# Connect to the database
db = wrds.Connection()
# Query CRSP stock data
crsp_data = db.get_table(library='crsp', table='dsf')
# Query Compustat financial data
compustat = db.get_table(library='comp', table='funda')
Applicable Scenarios: Academic research, professional financial analysis, long-term historical data research.
Financial data is like oil in the modern investment world, and Python interface libraries are the tools for extraction and refinement. Choosing the right combination of tools can maximize data value.
- Domestic Financial Market Analysis: The combination of Tushare + AkShare + baostock can cover most needs;
- Global Market Analysis: The combination of yfinance + pandas-datareader + Alpha Vantage is more suitable;
- Cryptocurrency Trading Analysis: The ccxt tool can meet the needs;
“There’s nothing else, just practice makes perfect!” Use what you need.