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
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.
1import ccxt2import pandas as pd3from datetime import datetime45# Initialize exchange (no API key needed for public data)6exchange = ccxt.binance({'enableRateLimit': True})78# Fetch daily OHLCV candles9since = exchange.parse8601('2020-01-01T00:00:00Z')10ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1d', since=since, limit=1000)1112# Convert to DataFrame13df = 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'])1718print(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.
1import time23def fetch_all_ohlcv(exchange, symbol, timeframe, start_date):4 """Fetch complete OHLCV history with pagination."""5 all_candles = []6 since = exchange.parse8601(start_date)78 while True:9 candles = exchange.fetch_ohlcv(symbol, timeframe, since=since, limit=1000)10 if not candles:11 break12 all_candles.extend(candles)13 since = candles[-1][0] + 1 # next millisecond after last candle14 time.sleep(exchange.rateLimit / 1000)1516 if len(candles) < 1000:17 break # no more data1819 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'])2223btc = 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.
1# CSV: simple but slow for large datasets2btc.to_csv('btc_daily.csv')3btc_loaded = pd.read_csv('btc_daily.csv', parse_dates=['date'], index_col='date')45# SQLite: better for multi-asset storage6import sqlite378conn = sqlite3.connect('market_data.db')9btc.to_sql('btc_daily', conn, if_exists='replace')1011# Load back12btc_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.
1# Remove duplicates2df = df[~df.index.duplicated(keep='first')]34# Handle missing values5print(f"NaN count: {df.isna().sum().sum()}")6df = df.fillna(method='ffill') # forward-fill gaps78# Ensure timezone consistency9df.index = df.index.tz_localize('UTC') if df.index.tz is None else df.index.tz_convert('UTC')1011# Resample to a different timeframe12weekly = df.resample('W').agg({13 'open': 'first', 'high': 'max',14 'low': 'min', 'close': 'last', 'volume': 'sum'15})1617# Compute basic statistics on clean data18print(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
Put this lesson to work
Free on Thrive, no account needed.