Skip to main content

Fetching & Cleaning Market Data

Exchange APIs, OHLCV data retrieval, handling gaps and missing data, timezone normalization, and building a clean local dataset.

From Thrive on YouTube

Watch the matching Thrive video

Watch the series
Trading Psychology: Revenge Trading, Tilt and the Fear of Missing Out

Trading Psychology: Revenge Trading, Tilt and the Fear of Missing Out

Part of Trading Psychology for Futures Traders. Education only. Not financial advice.

Fetching OHLCV Data from Exchanges

The ccxt library provides a unified interface to over 100 cryptocurrency exchanges. You write one set of code and it works across Binance, Coinbase, Kraken, and dozens more. OHLCV (Open-High-Low-Close-Volume) candles are the fundamental unit of market data. Every technical indicator, backtest, and ML model starts here.

python-Fetch daily BTC candles
1import ccxt
2import pandas as pd
3from datetime import datetime
4
5# Initialize exchange (no API key needed for public data)
6exchange = ccxt.binance({'enableRateLimit': True})
7
8# Fetch daily OHLCV candles
9since = exchange.parse8601('2020-01-01T00:00:00Z')
10ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1d', since=since, limit=1000)
11
12# Convert to DataFrame
13df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
14df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
15df = df.set_index('date')
16df = df.drop(columns=['timestamp'])
17
18print(f"Fetched {len(df)} candles")
19print(df.tail())

Handling Rate Limits

Exchanges throttle requests to prevent abuse. The enableRateLimit: True flag tells ccxt to automatically wait between requests. For large historical fetches, you need to paginate: fetching 1,000 candles at a time and incrementing the since parameter.

python-Paginated historical fetch
1import time
2
3def fetch_all_ohlcv(exchange, symbol, timeframe, start_date):
4 """Fetch complete OHLCV history with pagination."""
5 all_candles = []
6 since = exchange.parse8601(start_date)
7
8 while True:
9 candles = exchange.fetch_ohlcv(symbol, timeframe, since=since, limit=1000)
10 if not candles:
11 break
12 all_candles.extend(candles)
13 since = candles[-1][0] + 1 # next millisecond after last candle
14 time.sleep(exchange.rateLimit / 1000)
15
16 if len(candles) < 1000:
17 break # no more data
18
19 df = pd.DataFrame(all_candles, columns=['timestamp','open','high','low','close','volume'])
20 df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
21 return df.set_index('date').drop(columns=['timestamp'])
22
23btc = fetch_all_ohlcv(exchange, 'BTC/USDT', '1d', '2018-01-01T00:00:00Z')
24print(f"Total candles: {len(btc)}")

Storing Data

CSV works for small datasets. For anything beyond a single asset, use SQLite. It is a file-based database that requires zero configuration and handles millions of rows efficiently.

python-Save and load with CSV and SQLite
1# CSV: simple but slow for large datasets
2btc.to_csv('btc_daily.csv')
3btc_loaded = pd.read_csv('btc_daily.csv', parse_dates=['date'], index_col='date')
4
5# SQLite: better for multi-asset storage
6import sqlite3
7
8conn = sqlite3.connect('market_data.db')
9btc.to_sql('btc_daily', conn, if_exists='replace')
10
11# Load back
12btc_from_db = pd.read_sql('SELECT * FROM btc_daily', conn, parse_dates=['date'], index_col='date')
13conn.close()

Data Cleaning

Raw exchange data is messy. Gaps from exchange downtime, NaN values from failed fetches, timezone inconsistencies, and duplicate candles are common. Clean data before any analysis: garbage in, garbage out applies doubly to quantitative trading.

python-Cleaning OHLCV data
1# Remove duplicates
2df = df[~df.index.duplicated(keep='first')]
3
4# Handle missing values
5print(f"NaN count: {df.isna().sum().sum()}")
6df = df.fillna(method='ffill') # forward-fill gaps
7
8# Ensure timezone consistency
9df.index = df.index.tz_localize('UTC') if df.index.tz is None else df.index.tz_convert('UTC')
10
11# Resample to a different timeframe
12weekly = df.resample('W').agg({
13 'open': 'first', 'high': 'max',
14 'low': 'min', 'close': 'last', 'volume': 'sum'
15})
16
17# Compute basic statistics on clean data
18print(f"Date range: {df.index[0]} to {df.index[-1]}")
19print(f"Trading days: {len(df)}")
20print(f"Mean daily volume: ${df['volume'].mean():,.0f}")

Build once, reuse forever

Wrap your fetch-and-clean pipeline into a reusable function. Every backtest, every analysis, every ML model will start with the same clean DataFrame. Investing an hour in a solid data pipeline saves hundreds of hours of debugging corrupt data downstream.

Put this lesson to work

Free on Thrive, no account needed.