Featured image of post LynxCrypto in Action: Master pandas in 6 Steps with Real Crypto Data

LynxCrypto in Action: Master pandas in 6 Steps with Real Crypto Data

Skip the syntax drill—fetch real BTC quotes with ccxt, process them with pandas, backtest with vectorbt. Six steps cover all the core pandas workflows in crypto quant trading: reading data, resampling, hand-calculating RSI and MACD, aligning multiple assets, and feeding everything into a backtesting engine.

You can’t do crypto quant without pandas. Your market data is a table, your indicators are columns, and your backtest engine chews on time-indexed DataFrames — vectorbt, Freqtrade, the strategy classes in your strategy/ directory, they all consume this exact data structure.

But most people learn pandas the wrong way: grinding through syntax manuals, memorizing APIs, finishing the book, and still not knowing how to handle a single candlestick.

This is the pandas crash course I put together for myself. The guiding principle is one: don’t learn syntax — learn by driving real crypto data. In quant, pandas does exactly four things — read data in, reshape it into a time-series table, calculate technical indicators, and run statistical analysis. I break it into 6 steps, each pairing a set of concepts with runnable code you can drop straight into a JupyterLab notebook. By the end, you’ll be able to independently pull data from ccxt → process it with pandas → run a vectorbt backtest — the full pipeline.

Environment assumption: you have a Python environment with ccxt + pandas + vectorbt installed (mine is the .venv in the LynxCrypto project) and JupyterLab is already running. If not, pip install ccxt pandas vectorbt jupyterlab gets you set up.

If you’re starting from zero with pandas, spend 30–60 minutes running through one of these HTML tutorials — all of them let you copy-paste and run the code directly:

  • Kaggle’s free Pandas course — https://www.kaggle.com/learn/pandas Runs code and exercises right in the browser, for free. The smoothest path to understanding Series / DataFrame / index / grouping concepts.
  • Pandas Official 10 Minutes to pandas — https://pandas.pydata.org/docs/user_guide/10min.html The official quick overview, all code is copy-pasteable. Builds a “what pandas can do” mental map.
  • Chapters 5–9 of Python for Data Analysis (by pandas author Wes McKinney) — freely available online, practical in tone, great to keep as a reference.

Work through any one of the above, then return to the 6 steps below. You’ll move much faster than if you just memorized syntax.

Step 1 — Turn Market Data into a DataFrame (Reading + Structure)

Concepts covered: Series, DataFrame, index, columns, dtypes, head / tail, to_datetime

Task: Pull BTC/USDT candlestick (OHLCV) data from an exchange via ccxt, and convert it into a time-indexed table.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import ccxt
import pandas as pd

# Pull BTC/USDT 1-minute candles from Binance — public data needs no API key
# Can't connect? Make sure your proxy is running, or swap 'binance' for 'okx'/'gate'
ex = ccxt.binance()
ohlcv = ex.fetch_ohlcv('BTC/USDT', '1m', limit=500)  # 500 candles

# ccxt returns a list of lists: [timestamp, open, high, low, close, vol]
df = pd.DataFrame(ohlcv, columns=['ts', 'open', 'high', 'low', 'close', 'vol'])
df['ts'] = pd.to_datetime(df['ts'], unit='ms')   # millisecond ts → datetime
df = df.set_index('ts')                            # make time the index
df.head()                                          # peek at the first 5 rows
df.dtypes                                          # inspect each column's dtype

Key takeaway: Each column in the table is a Series; the whole table is a DataFrame; the leftmost time column is the index. The index is the foundation of every pandas time-series operation — everything downstream (resampling, slicing, etc.) rests on it.

Step 2 — Time-Series Reshaping and Slicing (Indexing, Slicing, Resampling)

Concepts covered: DatetimeIndex, loc / iloc slicing, resample, time zones

Task: Resample 1-minute data into 4-hour candles, then take a recent slice.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# Slice by time (loc + a string timestamp)
recent = df.loc['2026-09-05':]

# Resample: 1m → 4h OHLC (financial-standard aggregation)
df_4h = df.resample('4h').agg({
    'open': 'first',   # interval open = first candle
    'high': 'max',      # interval high = max of all highs
    'low': 'min',
    'close': 'last',   # interval close = last candle
    'vol': 'sum'       # interval volume = sum
})
df_4h.head()

# Slice by position (iloc = Nth row)
df.iloc[:10]      # first 10 rows
df.iloc[-5:]      # last 5 rows

Key takeaway: loc slices by label (time strings / index values), iloc slices by position (Nth row). resample is the core tool for compressing high-frequency data into low-frequency — quant work heavily depends on it for 1m→4h, 1h→1d conversions.

Step 3 — Calculate Technical Indicators by Hand (Column Ops, rolling, shift, ewm)

Concepts covered: Column operations, rolling (rolling window), shift (lag), ewm (exponentially weighted), apply / lambda

Task: Without using any pre-built indicator library, calculate MA, RSI, and MACD from scratch to understand what’s going on under the hood.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# Simple Moving Average MA(20): rolling mean of the last 20 candles
df['ma20'] = df['close'].rolling(20).mean()

# RSI(14): compute price changes first, then smooth with ewm
delta = df['close'].diff()                     # diff = current minus previous
gain = delta.clip(lower=0)                      # keep only the positive side (gains)
loss = -delta.clip(upper=0)                     # keep only the negative side (losses), abs value
avg_gain = gain.ewm(alpha=1/14, adjust=False).mean()
avg_loss = loss.ewm(alpha=1/14, adjust=False).mean()
rs = avg_gain / avg_loss
df['rsi'] = 100 - 100 / (1 + rs)

# MACD: difference between two EMAs
ema12 = df['close'].ewm(span=12, adjust=False).mean()
ema26 = df['close'].ewm(span=26, adjust=False).mean()
df['macd'] = ema12 - ema26
df['signal'] = df['macd'].ewm(span=9, adjust=False).mean()
df['hist'] = df['macd'] - df['signal']

df[['close', 'ma20', 'rsi']].tail()             # inspect the last few rows

Key takeaway: rolling(20).mean() opens a sliding window of 20 elements and computes the mean — almost every trend indicator derives from this. shift(1) slides data back by one position, commonly used to “compare today’s value against yesterday’s”. ewm computes a weighted mean with exponential decay, used by both RSI and MACD. Calculating these by hand makes it crystal clear what’s happening inside the pre-built functions from ft-pandas-ta.

Step 4 — Multi-Asset Alignment (concat, merge, correlation)

Concepts covered: concat, merge / join, multi-asset time alignment, fillna, corr (correlation)

Task: Align BTC and ETH closing prices onto one table, then compute their correlation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Pull ETH closing prices the same way
eth = ex.fetch_ohlcv('ETH/USDT', '1m', limit=500)
eth_df = pd.DataFrame(eth, columns=['ts','o','h','l','c','v'])
eth_df['ts'] = pd.to_datetime(eth_df['ts'], unit='ms')
eth_close = eth_df.set_index('ts')['c']

# Horizontal join: put BTC close and ETH close side by side (axis=1 = along columns)
both = pd.concat({'BTC': df['close'], 'ETH': eth_close}, axis=1)
both = both.dropna()            # drop rows that didn't align

both.corr()                     # correlation matrix
both['spread'] = both['BTC'] - both['ETH']   # new column = difference of the two
both.plot()                     # inline plotting (pandas built-in)

Key takeaway: The core of any multi-asset strategy (pair trading, cross-coin arbitrage) is “time alignment” — if the two coins’ timestamps don’t line up, use fillna or dropna; concat(axis=1) is the workhorse for horizontal merging. The high correlation between BTC and ETH is a fundamental fact of the crypto market, and both pair trading and statistical arbitrage are built on top of it.

Step 5 — Statistics and Visualization (describe, groupby, plotting)

Concepts covered: describe, pct_change (returns), groupby (grouping), agg (aggregation), plot

Task: Compute return distributions, group by day/hour to find patterns, and plot.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
df['ret'] = df['close'].pct_change()          # returns = (today - yesterday) / yesterday
df['ret'].describe()                          # quick summary: mean, std, quantiles

# Group by hour: find which hour has the highest volatility
df['hour'] = df.index.hour
df.groupby('hour')['ret'].agg(['mean', 'std', 'count'])

# Aggregate to daily returns
df['day'] = df.index.date
daily_ret = df.groupby('day')['ret'].sum()

# Plot (inline in the notebook)
df[['close','ma20']].plot(title='BTC close + MA20')
df['ret'].hist(bins=50)                        # histogram of return distribution

Key takeaway: describe() is the fastest data health check; groupby is “group by some column, then compute separately for each group” — quant work relies on it for finding patterns by hour / day of week / month. The shape of the return distribution (whether it’s normal, whether it has fat tails) determines your strategy’s risk assumptions. Crypto returns exhibit pronounced fat tails — that’s why the martingale strategy always loses in the long run (see the liquidation math in my previous post).

Step 6 — Bridge to vectorbt (Feeding DataFrames into the Backtest Engine)

Concepts covered: No new pandas concepts here — this step is about understanding “how the research output enters the backtest”: the pandas DataFrame is vectorbt’s standard input.

Task: Use the MA20 from Step 3 to generate a crossover signal, then feed it into vectorbt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import vectorbt as vbt

# Signal: buy when close crosses above MA20, sell when it crosses below (boolean Series)
entries = df['close'] > df['ma20']
exits   = df['close'] <= df['ma20']

# vectorbt takes close (Series) + entry/exit boolean signals
pf = vbt.Portfolio.from_signals(df['close'], entries, exits, init_cash=10000)
pf.stats()                  # backtest stats: total return, win rate, max drawdown, etc.
pf.plot()                   # backtest equity curve

Key takeaway: By this point, pandas data is “production-ready” — vectorbt, your strategy classes in strategy/, all consume this exact time-indexed DataFrame. During research, you prototype ideas in the notebook (these 6 steps); once solidified, you extract the logic into a .py module under strategy/. That’s the division of labor: the notebook is your scratchpad, the .py is your deliverable.

What you can do after this

  • You’ve walked through the 6 core pandas actions in quant (read / slice / calculate indicators / align / summarize / feed to backtest) using real crypto data
  • You can independently pull data from ccxt → process with pandas → run a vectorbt backtest through the full pipeline
  • Next step: compare your hand-calculated indicators and signals against the strategies already in your strategy/ folder (mine uses MacdCross as the reference), and understand the mapping between the “notebook exploration version” and the “engineering module version”

Four Anti-patterns (I fell into them, don’t)

  • Don’t cram ten ideas into one notebook — one notebook per research question, or you won’t even understand your own work three months from now.
  • Write assumptions and conclusions at the top of each notebook — when you look back, read those two lines first before diving into the code.
  • Extract finalized logic back into .py — notebooks should only hold research process, not become a catch-all stew.
  • Don’t just read — run — type out every snippet yourself, tweak parameters, observe the output change. You won’t learn by just watching.

This is the hands-on intro to the LynxCrypto series. Other articles in the series: Research Blueprint · From Grid Martingale to Alpha (Part 1) · Falsification · WFO Verdict · Tools Roadmap