Why Raw Crypto Data Breaks Good Strategies
In tutorials, price charts always look spotless. In the real world, raw CSV files downloaded from crypto exchanges are surprisingly messy:
- Cryptic timestamps: Exchanges often export time as huge numbers like
1733184000000(milliseconds since January 1, 1970) instead of readable dates. - Duplicate or out-of-order rows: When you stitch two downloads together, the same candle can appear twice or out of sequence.
- Missing minutes (gaps): During exchange maintenance or low-volume moments, entire 1-minute candles simply vanish from the file.
- Corrupted values: Occasional
NaN(blank) prices or impossible zero/negative ticks can completely distort a moving average or fake a giant profit in a backtest.
If you feed dirty data into a trading bot or backtester, you get garbage in, garbage out. Cleaning your data first—and knowing how to convert 1-minute candles cleanly into 5-minute, 15-minute, or 1-hour charts (resampling)—is one of the highest-leverage skills in algorithmic trading.
Prerequisites
Activate your .venv and ensure pandas and numpy are installed:
pip install pandas numpy
No exchange account or API keys are needed. Our script creates a realistic "messy" raw exchange CSV locally so you can watch every cleaning step in action, and you can immediately point the same function at real historical CSVs later.
Common Beginner Mistake: Resampling OHLCV (Open, High, Low, Close, Volume) candles by taking the
.mean()of every column. That destroys real price action! When combining five 1-minute candles into one 5-minute candle, the rules are strict: Open =first, High =max, Low =min, Close =last, and Volume =sum.
Checkpoint Script: clean_chart_data.py
Save this script as clean_chart_data.py. It generates a messy 1-minute sample file (data/raw_btc_1m.csv) with duplicates, out-of-order rows, missing candles, and a corrupted NaN value—then cleans it and builds clean 5min and 15min charts.
"""
Lesson 3 Checkpoint: Reusable Crypto Chart Data Cleaner
Turns messy raw exchange CSV files into clean, gap-free UTC candles
and resamples them accurately into higher timeframes (5m, 15m, 1h).
"""
from pathlib import Path
import numpy as np
import pandas as pd
DATA_DIR = Path("data")
RAW_FILE = DATA_DIR / "raw_btc_1m.csv"
# The golden rules for resampling OHLCV candlestick data
OHLCV_RULES = {
"open": "first",
"high": "max",
"low": "min",
"close": "last",
"volume": "sum",
}
def create_messy_sample_csv(path: Path) -> None:
"""Create a realistic messy 1-minute exchange CSV for practice."""
path.parent.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(seed=7)
# 60 minutes of 1-minute timestamps in Unix milliseconds
timestamps = pd.date_range("2026-12-01 00:00:00", periods=60, freq="1min", tz="UTC")
closes = 65_000 + np.cumsum(rng.normal(0, 15, size=60))
df = pd.DataFrame({
"timestamp_ms": (timestamps.astype("int64") // 1_000_000),
"open": np.roll(closes, 1),
"high": closes + rng.uniform(5, 25, size=60),
"low": closes - rng.uniform(5, 25, size=60),
"close": closes,
"volume": rng.uniform(1.5, 18.0, size=60).round(3),
})
df.loc[0, "open"] = 65_000.0
# Inject real-world problems:
df.loc[10, "close"] = np.nan # 1) Missing/corrupted price
df = df.drop(index=[20, 21]) # 2) Exchange gap (2 missing minutes)
df = pd.concat([df, df.iloc[[5, 6]]]) # 3) Duplicate rows
df = df.sample(frac=1, random_state=1) # 4) Shuffled / out-of-order rows
df.to_csv(path, index=False)
def clean_ohlcv(raw_df: pd.DataFrame, freq: str = "1min") -> pd.DataFrame:
"""Clean raw exchange candles into a continuous UTC-indexed DataFrame."""
df = raw_df.copy()
# 1. Convert Unix millisecond timestamps into UTC datetimes
df["timestamp"] = pd.to_datetime(df["timestamp_ms"], unit="ms", utc=True)
df = df.drop(columns=["timestamp_ms"])
# 2. Sort chronologically and remove duplicate timestamps
df = df.sort_values("timestamp").drop_duplicates(subset=["timestamp"], keep="last")
df = df.set_index("timestamp")
# 3. Ensure all OHLCV columns are numeric and drop impossible <= 0 prices
for col in ["open", "high", "low", "close", "volume"]:
df[col] = pd.to_numeric(df[col], errors="coerce")
df.loc[df["close"] <= 0, "close"] = np.nan
# 4. Reindex onto an unbroken timeline so gaps become visible
full_index = pd.date_range(start=df.index.min(), end=df.index.max(), freq=freq, tz="UTC")
df = df.reindex(full_index)
df.index.name = "timestamp"
# 5. Fill gaps safely: carry forward last known close, set gap volume to 0
df["close"] = df["close"].ffill()
for col in ["open", "high", "low"]:
df[col] = df[col].fillna(df["close"])
df["volume"] = df["volume"].fillna(0.0)
# 6. Guarantee high >= max(open, close) and low <= min(open, close)
df["high"] = df[["high", "open", "close"]].max(axis=1)
df["low"] = df[["low", "open", "close"]].min(axis=1)
return df
def resample_candles(clean_df: pd.DataFrame, timeframe: str) -> pd.DataFrame:
"""Resample clean 1-minute candles into a higher timeframe (e.g. '5min', '15min', '1h')."""
return clean_df.resample(timeframe).agg(OHLCV_RULES).dropna()
def main() -> None:
create_messy_sample_csv(RAW_FILE)
raw = pd.read_csv(RAW_FILE)
print(f"Raw file loaded: {len(raw)} rows (contains duplicates, gaps, NaNs, unsorted)")
clean_1m = clean_ohlcv(raw, freq="1min")
clean_5m = resample_candles(clean_1m, "5min")
clean_15m = resample_candles(clean_1m, "15min")
clean_1m.to_csv(DATA_DIR / "clean_btc_1m.csv")
clean_5m.to_csv(DATA_DIR / "clean_btc_5m.csv")
clean_15m.to_csv(DATA_DIR / "clean_btc_15m.csv")
print(f"Clean 1m chart: {len(clean_1m)} rows | Missing values: {int(clean_1m.isna().sum().sum())}")
print(f"Resampled 5m chart: {len(clean_5m)} rows")
print(f"Resampled 15m chart: {len(clean_15m)} rows")
print("\nSample of clean 15-minute candles:")
print(clean_15m.round(2))
if __name__ == "__main__":
main()
Run it from your terminal:
python clean_chart_data.py
Expected Terminal Output
Raw file loaded: 60 rows (contains duplicates, gaps, NaNs, unsorted)
Clean 1m chart: 60 rows | Missing values: 0
Resampled 5m chart: 12 rows
Resampled 15m chart: 4 rows
Sample of clean 15-minute candles:
open high low close volume
timestamp
2026-12-01 00:00:00+00:00 65000.00 65066.22 64955.90 65018.89 137.45
2026-12-01 00:15:00+00:00 65018.89 65083.39 64964.42 65013.66 125.04
2026-12-01 00:30:00+00:00 65013.66 65031.26 64937.13 64953.55 141.61
2026-12-01 00:45:00+00:00 64953.55 65004.74 64917.27 64965.06 150.79
Your data/ folder now holds clean, UTC-aligned 1m, 5m, and 15m CSV files ready for indicators and backtesting.
Study & Practice Recap
- Always standardize to UTC: Converting Unix timestamps to UTC immediately avoids daylight-saving bugs and timezone mismatches across exchanges.
- Make gaps visible before filling them: Reindexing onto an unbroken
date_rangereveals missing minutes so you can safely forward-fill prices and set missing volume to0. - Respect OHLCV resampling rules: Use
first,max,min,last, andsumwhen rolling up candles so higher timeframes reflect true market highs and lows.
Tiny Hands-On Exercise: Add a line in main() to resample clean_1m into a 30min chart (clean_30m), print it, and verify that the sum of volume across all 30min candles equals the sum of volume across clean_1m.