Getting Financial Data with Python
Data is the raw material of quantitative trading; all analysis and strategies rest on reliable historical market data.
Several Python libraries can fetch financial market data; this chapter focuses on the most common one, yfinance, and also introduces AKShare for fetching A-share data.
Fetching Data with yfinance
yfinance is a library that fetches financial data from Yahoo Finance, supporting stocks, indices, funds, forex, cryptocurrencies and more; it is free and requires no registration.
Install as follows:
pip install yfinance
The download Function and Its Parameters
The core function for fetching bulk historical data in yfinance is yf.download(); basic syntax:
yf.download(tickers, start=None, end=None, period=None, interval="1d",
auto_adjust=True, multi_level_index=True, progress=True, threads=True)
| Parameters | Type | Default value | Description |
|---|---|---|---|
| tickers | String or list | Required | The stock or index tickers to download; a single ticker as a string, multiple tickers as a list or a space-separated string |
| start / end | String | None | Start and end dates of the data, format "YYYY-MM-DD", defaulting to the earliest/latest available dates |
| period | String | None | Specify the time span directly, e.g. "1mo" (one month), "1y" (one year), "max"; an alternative to start/end |
| interval | String | "1d" | Candlestick interval, e.g. "1m", "1h", "1d", "1wk", "1mo" |
| auto_adjust | Boolean | True | Whether to auto-adjust. When True, prices are already adjusted and the Adj Close column is not returned |
| multi_level_index | Boolean | True | Whether to return multi-level column names. Set to False when downloading a single stock for simpler single-level columns |
| progress | Boolean | True | Whether to show a download progress bar |
| actions | Boolean | False | Whether to include corporate action data such as dividends and splits |
| threads | Boolean | True | Whether to use multi-threaded downloads, which is faster when downloading many stocks at once |
Important: newer yfinance (0.2.51 and above) changed the default of auto_adjust to True, so downloaded prices are adjusted and the Adj Close column is no longer returned. Code in older tutorials that analyzes the Close column directly is in fact analyzing adjusted prices under the new version; keep this in mind when reading old code.
Stock Ticker Rules
Tickers are written differently across markets on Yahoo Finance; Chinese A-shares need an exchange suffix:
| Market | Postfix | Example |
|---|---|---|
| Shanghai Stock Exchange (A-shares) | .SS | 600519.SS (Kweichow Moutai) |
| Shenzhen Stock Exchange (A-shares) | .SZ | 000568.SZ (Luzhou Laojiao) |
| Hong Kong stocks | .HK | 0700.HK (Tencent Holdings) |
| US stocks | No suffix | AAPL (Apple), MSFT (Microsoft) |
Fetching Kweichow Moutai Historical Data
The following example fetches stock data for Kweichow Moutai (600519.SS):
Example
import
yfinance
as
yf
Shanghai Stock Exchange, the ticker of Kweichow Moutai
symbol
=
"600519.SS"
auto_adjust=False: returns both the unadjusted Close price and the adjusted Adj Close price columns
multi_level_index=False: returns single-level column names when downloading one stock, making it easier to work with
maotai_data
=
yf.
download
(
symbol
,
start
=
"2022-01-01"
,
end
=
"2023-11-01"
,
auto_adjust
=
False
,
progress
=
False
,
multi_level_index
=
False
)
Print the first few rows of the data
(
maotai_data.
head
(
)
)
The result is a Pandas DataFrame containing Date, Open, High, Low, Close, Adjusted Close (Adj Close), and Volume.
For how to use Pandas DataFrame, see:Pandas Data Structures - DataFrame
After executing the above code, the output is as follows:
Adj Close Close High Low Open Volume
Date
2022-01-04 1772.844604 2051.229980 2068.949951 2014.000000 2055.00000 3384262
2022-01-05 1749.310059 2024.000000 2065.000000 2018.000000 2045.00000 2839551
2022-01-06 1713.200317 1982.219971 2036.000000 1938.510010 2022.01001 5179475
2022-01-07 1678.438721 1942.000000 1988.880005 1939.319946 1975.00000 2962670
2022-01-10 1699.181641 1966.000000 1977.000000 1917.550049 1928.01001 2962670
Compare the Close and Adj Close columns: Moutai paid dividends during the period, so the adjusted price is lower than the unadjusted price.
Use adjusted prices when computing returns and backtesting; otherwise the price gap caused by a dividend would be mistaken for a crash.
The detailed concept of adjustment is covered further in the data-cleaning material.
The Ticker Class: Getting Details of a Single Stock
Besides bulk downloads, yfinance also provides the Ticker class for getting information and real-time data on a specific financial instrument.
After creating an object with yf.Ticker('ticker'), you can access a rich set of attributes and methods:
| Attribute / Method | Usage | Description |
|---|---|---|
| history() | ticker.history(period="1mo", interval="1d") | Get historical data; period sets the span, interval sets the frequency |
| info | ticker.info | Basic company info: name, industry, market cap, etc. |
| dividends | ticker.dividends | Dividend data |
| splits | ticker.splits | Stock split data |
| actions | ticker.actions | Summary of corporate actions (splits, dividends, etc.) |
| major_holders | ticker.major_holders | Ownership ratios of major holders |
| institutional_holders | ticker.institutional_holders | Institutional ownership information |
| income_stmt | ticker.income_stmt | Annual income statement |
| balance_sheet | ticker.balance_sheet | Balance sheet |
| cashflow | ticker.cashflow | Cash flow statement |
| calendar | ticker.calendar | Financial calendar, e.g. earnings release dates |
| news | ticker.news | Related news |
The following code uses Microsoft (MSFT) as an example to demonstrate common Ticker operations:
Example
import
yfinance
as
yf
Create a Ticker object representing Microsoft stock
msft
=
yf.
Ticker
(
"MSFT"
)
Get market data for the past 5 trading days
hist
=
msft.
history
(
period
=
"5d"
)
(
hist.
head
(
)
)
After executing the above code, the output is as follows:
Open High Low Close Volume Dividends Stock Splits
Date
2026-10-16 00:00:00-04:00 541.309998 543.820007 524.429993 529.049988 24845700 0.0 0.0
2026-10-19 00:00:00-04:00 528.700012 535.570007 528.059998 533.520020 17994900 0.0 0.0
2026-10-20 00:00:00-04:00 533.909973 534.210022 525.840027 531.869995 14576000 0.0 0.0
Unlike download, the table returned by history() comes with Dividends and Stock Splits columns.
Fetching Multiple Stocks at Once
Batch research often needs data for multiple stocks at once; there are two ways:
Example
import
yfinance
as
yf
Method 1: the Tickers object, suitable for accessing each stock's details separately
tickers
=
yf.
Tickers
(
"msft aapl goog"
)
tickers.
tickers
[
"MSFT"
]
.
info
Microsoft's basic information
tickers.
tickers
[
"AAPL"
]
.
history
(
period
=
"1mo"
)
Apple's data for the past month
tickers.
tickers
[
"GOOG"
]
.
actions
Google's corporate actions
Method 2: download fetches multiple tickers at once, suitable for bulk price data
The returned DataFrame has multi-level columns (price type, ticker)
data
=
yf.
download
(
[
"SPY"
,
"AAPL"
]
,
period
=
"1mo"
,
progress
=
False
,
multi_level_index
=
False
)
Fetching A-Share Data with AKShare
yfinance's A-share data comes from Yahoo Finance with an update delay; for A-share research, domestic data sources are recommended.
AKShare is a free, open-source financial data interface library covering stocks, futures, options, funds, bonds, macro data and more, with no token registration required.
Install as follows:
pip install akshare
Example
import
akshare
as
ak
Fetching Kweichow Moutai A-Share Daily Data
symbol: the A-share ticker (without exchange suffix)
adjust="qfq": forward-adjusted; "hfq" is backward-adjusted, "" is unadjusted
df
=
ak.
stock_zh_a_hist
(
symbol
=
"600519"
,
period
=
"daily"
,
start_date
=
"20240101"
,
end_date
=
"20240115"
,
adjust
=
"qfq"
)
(
df.
head
(
3
)
)
Running the code above produces the following output (column names are in Chinese and directly readable):
日期 股票代码 开盘 收盘 最高 最低 成交量 成交额 振幅 涨跌幅 涨跌额 换手率
0 2024-01-02 600519 1580.66 1550.67 1583.85 1543.76 32156 5.440083e+09 2.52 -2.58 -40.99 0.26
1 2024-01-03 600519 1546.77 1559.66 1560.88 1541.99 20229 3.411401e+09 1.22 0.58 8.99 0.16
2 2024-01-04 600519 1558.66 1534.66 1558.66 1528.59 21551 3.603970e+09 1.93 -1.60 -25.00 0.17
Compared with yfinance, AKShare directly provides derived metrics such as price change and turnover rate, and also supports A-share-specific data like sector fund flows and the Dragon-Tiger list.
Comparison of Common Financial Databases
Besides yfinance and AKShare, there are many other good financial databases; choose by market and research needs:
| library | Main Coverage | Feature | Install Command |
|---|---|---|---|
| yfinance | US stocks, A-shares, Hong Kong stocks, global indices, cryptocurrencies | Free with no registration, the first choice for international markets | pip install yfinance |
| AKShare | A-shares, futures, funds, bonds, macro | Free and open source, rich interfaces, no token needed | pip install akshare |
| Tushare | Mainly A-shares | Requires registration for a token, points-based, high data quality | pip install tushare |
| baostock | A-shares, Hong Kong stocks, options | Free, suitable for basic security info and daily data | pip install baostock |
| pandas-datareader | Aggregates multiple online data sources | A veteran tool; some data sources no longer work, choose with care | pip install pandas-datareader |
| alpha_vantage | US stocks, forex, cryptocurrencies | Requires a free API key after registration, with built-in technical indicator calculations | pip install alpha_vantage |
| Quandl | Financial and economic data | Merged into Nasdaq Data Link, registration required | pip install quandl |
| ccxt | Cryptocurrency exchanges | A unified interface connecting hundreds of exchanges, supporting market data and trading | pip install ccxt |
Selection advice: use yfinance for US and global markets; AKShare or Tushare for A-shares; ccxt for cryptocurrencies. Data sources are just tools, far less important than the strategy research that follows.
Once you have the data, the next step is to see it clearly with charts; move on to theData visualizationchapter.