Module 2 — Python for Quants

NumPy and Pandas — Vectorised Finance

Pandas, NumPy, and the data-wrangling muscle memory you'll use every day.

Learning objectives

  • Compute returns with no for-loops.
  • Align two ticker series on a common index.
  • Resample minute bars to daily.

CODE

Vectorised returns

import numpy as np
import pandas as pd

prices = pd.Series([100, 101, 100.5, 102, 103])
simple_ret = prices.pct_change()
log_ret = np.log(prices / prices.shift(1))

ann_vol = log_ret.std() * np.sqrt(252)

CODE

Alignment is everything

# Two assets often trade on slightly different calendars.
# pandas auto-aligns on the index — never on positional order.
aligned = pd.concat([aapl_close, msft_close], axis=1, join='inner')
aligned.columns = ['AAPL', 'MSFT']
returns = np.log(aligned).diff().dropna()
print(returns.corr())

CODE

Resampling

# Minute bars to daily OHLC
agg = minute_bars.resample('1D').agg({
    'open':   'first',
    'high':   'max',
    'low':    'min',
    'close':  'last',
    'volume': 'sum',
}).dropna()