Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python financial data libraries pull stock prices, crypto quotes, economic series, and company fundamentals into Python code. A client wraps a market data API or exchange feed and returns each series as a DataFrame or typed records. These libraries let trading bots, research notebooks, and AI agents work from current and historical market data.
Popularity
yfinance has the most monthly downloads in this comparison, at 17.0M.
def get_historical(symbol, start_date, end_date, interval='1d'):
"""Fetch historical data for a symbol with specified interval
Args:
symbol: Stock symbol (e.g., 'AAPL')
start_date: Start date (YYYY-MM-DD)
end_date: End date (YYYY-MM-DD)
interval: Data interval - valid values: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
Note: Intraday data (< 1d) is only available for last 60 days
"""
try:
import io, contextlib
ticker = yf.Ticker(symbol)
_buf = io.StringIO()
with contextlib.redirect_stdout(_buf):
hist = ticker.history(start=start_date, end=end_date, interval=interval,
timeout=_NET_TIMEOUT)
if hist.empty:
return []
historical_data = []
for index, row in hist.iterrows():
# Guard every conversion the way get_batch_quotes already does — a # single NaN bar must not take the whole series with it. close = _num(row['Close'])
if close is None:
continue # a bar with no close is not a price point
historical_data.append({
"symbol": symbol,
"timestamp": int(index.timestamp()),
"open": _num(row['Open']),
"high": _num(row['High']),
"low": _num(row['Low']),
"close": close,
"volume": _int(row['Volume'], 0),
"adj_close": close
})
return historical_data
except Exception as e:
return {"error": str(e), "symbol": symbol}
CCXT
Trades and reads market data on more than 100 cryptocurrency exchanges through one API.
@retrier
def fetch_bids_asks(self, symbols: list[str] | None = None, *, cached: bool = False) -> dict:
"""
:param symbols: List of symbols to fetch
:param cached: Allow cached result
:return: fetch_bids_asks result
"""
if not self.exchange_has("fetchBidsAsks"):
return {}
if cached:
with self._cache_lock:
tickers = self._fetch_tickers_cache.get("fetch_bids_asks")
if tickers:
return tickers
try:
tickers = self._api.fetch_bids_asks(symbols)
with self._cache_lock:
self._fetch_tickers_cache["fetch_bids_asks"] = tickers
return tickers
except ccxt.NotSupported as e:
raise OperationalException(
f"Exchange {self._api.name} does not support fetching bids/asks in batch. "
f"Message: {e}"
) from e
except ccxt.DDoSProtection as e:
raise DDosProtection(e) from e
except (ccxt.OperationFailed, ccxt.ExchangeError) as e:
raise TemporaryError(
f"Could not load bids/asks due to {e.__class__.__name__}. Message: {e}"
) from e
except ccxt.BaseError as e:
raise OperationalException(e) from e
Databento
Provides the official Python client for Databento.
def databento_data(
symbols: list[str],
start_time: str,
end_time: str,
schema: str,
file_prefix: str,
*folders: str,
dataset: str = "GLBX.MDP3",
to_catalog: bool = True,
base_path: Path | None = None,
use_exchange_as_venue: bool = True,
load_databento_files_if_exist: bool = False,
as_legacy_cython: bool = False,
**kwargs: Any,
) -> dict[str, Any]:
"""
Download and save Databento data and definition files, and optionally save the data
to a catalog.
Parameters
---------- symbols : list[str]
The symbols to retrieve data for.
start_time : str
The start time of the data in ISO 8601 format.
end_time : str
The end time of the data in ISO 8601 format.
schema : str
The data schema to retrieve, either "definition" or another valid schema.
file_prefix : str
The prefix to use for the downloaded data files.
*folders : str
Additional folders to create in the data path.
dataset : str, optional
The Databento dataset to use, defaults to "GLBX.MDP3".
to_catalog : bool, optional
Whether to save the data to a catalog, defaults to True.
base_path : Path, optional
The base path to use for the data folder, defaults to None.
use_exchange_as_venue : bool, optional
Whether to use actual exchanges for instrument ids or GLBX, defaults to True.
load_databento_files_if_exist : bool, optional
Whether to load Databento files if they already exist, defaults to False.
as_legacy_cython : bool, optional
Whether to use legacy Cython format, defaults to False.
**kwargs : Any
Additional keyword arguments to pass to the Databento API.
Returns
------- dict[str, Any]
A dictionary containing the downloaded data and metadata with keys:
- symbols: The list of symbols
- dataset: The dataset name
- schema: The schema name
- start: The start time
- end: The end time
- databento_definition_file: Path to definition file
- databento_data_file: Path to data file (if schema != "definition")
- databento_definition: Definition data object
- databento_data: Data object (if schema != "definition")
- catalog: Catalog object (if to_catalog=True)
- nautilus_definition: Processed definition data (if to_catalog=True)
- nautilus_data: Processed market data (if to_catalog=True)
Notes
----- If schema is equal to 'definition' then no data is downloaded or saved to the catalog.
"""
used_path = create_data_folder(*folders, "databento", base_path=base_path)
definition_start_date, definition_end_date = databento_definition_dates(start_time, end_time)
definition_file_name = f"{file_prefix}_definition.dbn.zst"
definition_file = used_path / definition_file_name
if not definition_file.exists():
if client is None:
raise ValueError(
"Databento client not initialized. Call init_databento_client() first.",
)
definition = client.timeseries.get_range(
schema="definition",
dataset=dataset,
symbols=symbols,
start=definition_start_date,
end=definition_end_date,
path=definition_file,
**kwargs,
)
else:
definition = load_databento_data(definition_file) if load_databento_files_if_exist else None
data = None
used_start_time = start_time.replace(":", "-").replace(".", "-")
used_end_time = end_time.replace(":", "-").replace(".", "-")
data_file_name = f"{file_prefix}_{schema}_{used_start_time}_{used_end_time}.dbn.zst"
data_file = used_path / data_file_name
if schema != "definition":
if not data_file.exists():
if client is None:
raise ValueError(
"Databento client not initialized. Call init_databento_client() first.",
)
data = client.timeseries.get_range(
schema=schema,
dataset=dataset,
symbols=symbols,
start=start_time,
end=end_time,
path=data_file,
**kwargs,
)
else:
data = load_databento_data(data_file) if load_databento_files_if_exist else None
result = {
"symbols": symbols,
"dataset": dataset,
"schema": schema,
"start": start_time,
"end": end_time,
"databento_definition_file": definition_file,
"databento_data_file": data_file if schema != "definition" else None,
"databento_definition": definition,
"databento_data": data,
}
if schema == "definition":
del result["databento_data_file"]
del result["databento_data"]
if to_catalog:
catalog_data = save_data_to_catalog(
*folders,
definition_file=definition_file,
data_file=data_file,
base_path=base_path,
use_exchange_as_venue=use_exchange_as_venue,
as_legacy_cython=as_legacy_cython,
)
result.update(catalog_data)
return result
from ib_async import *
# util.startLoop() # uncomment this line when in a notebookib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
# Request historical datacontract = Forex('EURUSD')
bars = ib.reqHistoricalData(
contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)
# Convert to pandas dataframe (pandas needs to be installed):df = util.df(bars)
print(df.head())
ib.disconnect()
FAQ
yfinance suits research on stock prices and fundamentals from Yahoo Finance. CCXT suits cryptocurrency exchanges through one unified API. Databento and Alpaca-py suit licensed historical and live market data.
yfinance retrieves market data, ticker information, and financial statements from Yahoo Finance. The code license of the library and the terms for using the data are separate.
Databento is the official Python client for the Databento market data service. Historical data and live streams use separate clients, and each needs an API key and dataset permissions.
AKShare is a financial data interface library that returns pandas DataFrames from many sources, including Chinese equity, ETF, and macroeconomic series.
CCXT is a cryptocurrency trading API that covers many exchanges through one interface. It fetches market data and candles where an exchange supports them, and its Pro version adds WebSocket streams.
For coding agents
Found your financial data library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.