Why Regular Python Loops Are Too Slow for Crypto Data
Crypto markets never sleep. There are 525,600 minutes in a single year, which means just one year of 1-minute Bitcoin candles is over half a million rows of price data. If you want to test a trading idea across 5 years or 10 coins, you are suddenly crunching millions of rows.
When most beginners calculate an indicator—like a percentage return or a moving average—they naturally reach for a Python for loop that visits row 1, then row 2, then row 3, all the way to row 500,000.
The problem is that a Python for loop checks data types and does housekeeping on every single row, one by one. Pandas (built on top of NumPy) works differently through a technique called vectorization. Instead of telling Python to add two numbers 500,000 separate times, Pandas hands the entire column of numbers to compiled C code in one shot—like moving 500,000 bricks with a freight train instead of carrying them one by one by hand.
In this lesson, you will run a head-to-head benchmark on 500,000 price rows and watch Pandas beat a standard for loop by a massive margin.
Prerequisites
Activate your .venv from Lesson 1 and make sure pandas and numpy are installed:
pip install pandas numpy
No exchange API keys are needed for this lesson—we will generate 500,000 realistic synthetic Bitcoin price candles locally so you can run the benchmark offline anytime.
Common Beginner Mistake: Using
df.iterrows()ordf.apply(..., axis=1)inside Pandas and assuming it is fast. Those methods are actually Python loops in disguise and can be even slower than a plainforloop on a list! Whenever you work with price columns, always use column-wide operations likedf["close"].pct_change()ordf["close"].rolling(20).mean().
Checkpoint Script: speed_benchmark.py
Save this file as speed_benchmark.py. It generates 500,000 1-minute price rows and calculates the exact same three trading metrics—bar-by-bar return, 20-candle moving average, and a simple trend signal—using a classic Python for loop first, and then using vectorized Pandas.
"""
Lesson 2 Checkpoint: For Loop vs. Pandas Speed Benchmark
Crunches 500,000 crypto price rows using both a standard Python loop
and vectorized Pandas operations, then compares speed and accuracy.
"""
import time
import numpy as np
import pandas as pd
NUM_ROWS = 500_000
SMA_WINDOW = 20
def generate_price_data(num_rows: int) -> pd.DataFrame:
"""Create reproducible synthetic 1-minute BTC price candles."""
rng = np.random.default_rng(seed=42)
# Simulate small random percentage moves around $60,000
pct_moves = rng.normal(loc=0.0, scale=0.0005, size=num_rows)
prices = 60_000.0 * np.cumprod(1.0 + pct_moves)
return pd.DataFrame({"close": prices})
def run_python_for_loop(prices: list[float]) -> tuple[list[float], list[int], float]:
"""Calculate returns, 20-bar SMA, and trend signal row-by-row."""
start = time.perf_counter()
returns = [0.0] * len(prices)
signals = [0] * len(prices)
for i in range(1, len(prices)):
returns[i] = (prices[i] - prices[i - 1]) / prices[i - 1]
if i >= SMA_WINDOW - 1:
# Slice and average the last 20 closes on every row
window = prices[i - SMA_WINDOW + 1 : i + 1]
sma = sum(window) / SMA_WINDOW
signals[i] = 1 if prices[i] > sma else 0
elapsed = time.perf_counter() - start
return returns, signals, elapsed
def run_pandas_vectorized(df: pd.DataFrame) -> tuple[pd.DataFrame, float]:
"""Calculate the exact same metrics using vectorized Pandas operations."""
start = time.perf_counter()
result = df.copy()
result["return"] = result["close"].pct_change().fillna(0.0)
result["sma_20"] = result["close"].rolling(window=SMA_WINDOW).mean()
result["signal"] = (result["close"] > result["sma_20"]).astype(int)
elapsed = time.perf_counter() - start
return result, elapsed
def main() -> None:
print(f"Generating {NUM_ROWS:,} synthetic 1-minute crypto price rows...")
df = generate_price_data(NUM_ROWS)
price_list = df["close"].tolist()
print("\n1) Running standard Python for loop...")
loop_returns, loop_signals, loop_time = run_python_for_loop(price_list)
print(f" For-loop time: {loop_time:.4f} seconds")
print("\n2) Running vectorized Pandas...")
pd_df, pd_time = run_pandas_vectorized(df)
print(f" Pandas time: {pd_time:.4f} seconds")
speedup = loop_time / pd_time
signals_match = (pd_df["signal"].tolist() == loop_signals)
returns_match = np.allclose(pd_df["return"].to_numpy(), np.array(loop_returns))
print("\n" + "=" * 50)
print(f" SPEEDUP: {speedup:.1f}x faster with Pandas!")
print(f" RETURNS MATCH: {returns_match}")
print(f" SIGNALS MATCH: {signals_match}")
print(f" BULLISH ROWS: {int(pd_df['signal'].sum()):,} / {NUM_ROWS:,}")
print("=" * 50)
if __name__ == "__main__":
main()
Run it from your terminal:
python speed_benchmark.py
Expected Terminal Output
(Exact timings vary slightly depending on your computer's CPU, but Pandas should consistently finish in a tiny fraction of a second while the loop takes much longer.)
Generating 500,000 synthetic 1-minute crypto price rows...
1) Running standard Python for loop...
For-loop time: 0.8914 seconds
2) Running vectorized Pandas...
Pandas time: 0.0112 seconds
==================================================
SPEEDUP: 79.6x faster with Pandas!
RETURNS MATCH: True
SIGNALS MATCH: True
BULLISH ROWS: 248,619 / 500,000
==================================================
Notice that both methods produce the exact same answers (RETURNS MATCH: True and SIGNALS MATCH: True), yet Pandas does it in 3 readable lines of code and finishes nearly two orders of magnitude faster. When you scale up to 50-bar or 200-bar windows across multiple indicators, that gap easily passes 100x.
Study & Practice Recap
- Think in columns, not rows: Vectorized operations let Pandas process an entire price series in compiled C code instead of stepping row-by-row in Python.
- Built-in rolling tools save time and bugs: Functions like
.pct_change()and.rolling(20).mean()are both faster and less error-prone than manual index math. - Always verify equivalence: When optimizing a trading calculation, check that your fast version matches the slow version (
np.allclose) before trusting it in a backtest.
Tiny Hands-On Exercise: Change SMA_WINDOW from 20 to 100 in speed_benchmark.py and re-run it. Watch what happens to the for loop time versus the Pandas time—notice how Pandas barely slows down at all!