Skip to content
OpenVibes.

∑Free guide · Quant· 70 formulas

The entire math behind quant trading bots

From log returns to Avellaneda–Stoikov. 70 formulas in the order you need them, each with what it means, when a bot actually uses it and a tested Python snippet you can copy. Plus 35 free courses, classic papers and docs.

Checked 26 Nov 202617 sectionsCopy-paste Python
Share on X
formulas
70formulas
sections
17sections
Python snippets
70Python snippets

Not financial advice. Education only. Formulas are the textbook versions; real markets break their assumptions (fat tails, regime changes, costs). Test everything on paper before risking money.

Contents · 17 sections⌄
  1. 01Returns4
  2. 02Volatility and variance4
  3. 03Mean, z-score and significance4
  4. 04Covariance and correlation4
  5. 05Regression, beta and alpha4
  6. 06Stationarity, cointegration and pairs4
  7. 07Mean reversion: Ornstein–Uhlenbeck3
  8. 08Momentum and trend3
  9. 09Kalman filter2
  10. 10Performance metrics5
  11. 11Kelly criterion and position sizing4
  12. 12Risk: VaR and expected shortfall4
  13. 13Order book microstructure and execution7
  14. 14Market making: Avellaneda–Stoikov2
  15. 15Options: Black–Scholes and the Greeks6
  16. 16Backtesting without fooling yourself6
  17. 17Fees, slippage and latency4
  18. →Free references (35)
  19. →Notes & FAQ

01 · the unit of everything

Returns

Every signal, risk number and performance stat starts from returns, not prices. Get these right first.

1.1Simple return

What it means
The percentage change from one bar to the next.
When a bot uses it
P&L and portfolio returns: simple returns add across assets, so a portfolio return is the weighted sum .
python
import numpy as np

def simple_returns(prices):
    p = np.asarray(prices, float)
    return p[1:] / p[:-1] - 1

1.2Log return

What it means
The continuously compounded return. Log returns add over time: the return over many bars is the sum of the bar returns.
When a bot uses it
Most models (volatility, z-scores, regressions) run on log returns because they are additive in time and closer to symmetric.
Example
Price 100 → 110 → 99: simple returns +10% and −10%, but you are down 1%. Log returns +9.53% and −10.54% sum to −1.01% = ln(0.99).
python
import numpy as np

def log_returns(prices):
    return np.diff(np.log(np.asarray(prices, float)))

1.3Compounding and annualized return (CAGR)

What it means
The constant yearly growth rate that turns your start equity into your end equity. N is bars per year (252 trading days, 365 for crypto daily, 8760 for crypto hourly).
When a bot uses it
The headline return number in every backtest report, and the numerator of the Calmar ratio.
python
import numpy as np

def cagr(returns, periods_per_year=252):
    r = np.asarray(returns, float)
    growth = np.prod(1 + r)
    return growth ** (periods_per_year / len(r)) - 1

1.4Volatility drag

What it means
Compound growth is lower than the average return. The bigger the swings, the bigger the gap.
When a bot uses it
Why leverage has a ceiling: doubling leverage doubles μ but quadruples σ²/2. It is the reason the Kelly criterion exists.
Example
+50% then −50% averages 0% but leaves you at 0.75× start (−25%).
python
def geometric_growth(mu, sigma):
    # mu, sigma per period (e.g. annual)
    return mu - 0.5 * sigma ** 2

02 · how much it moves

Volatility and variance

Volatility sizes positions, sets stops, scales signals and prices options. Bots estimate it constantly.

2.1Sample variance and standard deviation

What it means
The average squared distance from the mean (n−1 corrects the bias of using the sample mean).
When a bot uses it
The default risk estimate for each asset and the denominator of the Sharpe ratio and z-scores.
python
import numpy as np

def volatility(returns):
    return np.std(returns, ddof=1)

2.2Annualizing volatility (square-root-of-time)

What it means
If returns are independent, variance grows linearly with time, so volatility grows with the square root of time.
When a bot uses it
Converting a 1-minute or daily vol into the yearly number used in risk limits and option pricing.
Example
1% daily vol × √252 ≈ 15.9% a year.
python
import numpy as np

def annualize_vol(sigma, periods_per_year=252):
    return sigma * np.sqrt(periods_per_year)

2.3EWMA volatility (RiskMetrics)

What it means
An exponentially weighted variance: recent returns count more. RiskMetrics used λ = 0.94 for daily data.
When a bot uses it
A cheap, always-updating vol estimate for live position sizing and vol targeting.
python
import numpy as np

def ewma_vol(returns, lam=0.94):
    r = np.asarray(returns, float)
    var = np.empty_like(r)
    var[0] = r[0] ** 2
    for t in range(1, len(r)):
        var[t] = lam * var[t - 1] + (1 - lam) * r[t - 1] ** 2
    return np.sqrt(var)

2.4GARCH(1,1)

What it means
Volatility clusters: calm follows calm, storms follow storms. GARCH adds a long-run level that vol reverts to (needs α + β < 1).
When a bot uses it
Forecasting tomorrow's vol for sizing and risk, and spotting when the market is in a high-vol regime.
python
from arch import arch_model  # pip install arch

def garch_forecast(returns_pct):
    res = arch_model(returns_pct, vol='GARCH', p=1, q=1).fit(disp='off')
    return res.forecast(horizon=1).variance.iloc[-1, 0] ** 0.5

03 · is it real or noise?

Mean, z-score and significance

Before a bot trades a pattern it should ask whether the pattern is bigger than the noise.

3.1Z-score

What it means
How many standard deviations a value is from its (rolling) mean.
When a bot uses it
The standard mean-reversion trigger: enter when |z| > 2, exit when z crosses back near 0. Also used to normalize features.
python
import pandas as pd

def rolling_z(series: pd.Series, window=60):
    mu = series.rolling(window).mean()
    sd = series.rolling(window).std()
    return (series - mu) / sd

3.2Standard error of the mean

What it means
How uncertain your estimate of the average return is. Halving it takes 4× the data.
When a bot uses it
Tells you whether the average trade is distinguishable from zero.
python
import numpy as np

def standard_error(x):
    x = np.asarray(x, float)
    return x.std(ddof=1) / np.sqrt(len(x))

3.3t-statistic of the mean

What it means
Signal-to-noise of the average return. Rule of thumb: |t| > 2 is weak evidence, and with many tested ideas you need far more (around 3).
When a bot uses it
A quick significance check on a strategy's per-trade or per-day P&L.
python
from scipy import stats

def t_test(returns):
    return stats.ttest_1samp(returns, 0.0)  # statistic, pvalue

3.4t-stat of a Sharpe ratio

What it means
A Sharpe ratio is a mean divided by a std, so its significance grows with the square root of the sample length.
When a bot uses it
Sanity check for a backtest: annual Sharpe 1 over 4 years gives t ≈ 2, borderline.
python
import numpy as np

def sharpe_t(sr_annual, years):
    return sr_annual * np.sqrt(years)

04 · how things move together

Covariance and correlation

Diversification, hedging and pairs trading all come down to how two return series co-move.

4.1Covariance

What it means
Positive when two series tend to be above their means at the same time.
When a bot uses it
The building block of portfolio risk and of hedge ratios.
python
import numpy as np

def covariance(x, y):
    return np.cov(x, y, ddof=1)[0, 1]

4.2Pearson correlation

What it means
Covariance rescaled to −1…1, so you can compare across assets.
When a bot uses it
Choosing pair candidates, checking that new signals are not just old ones, and watching for correlations jumping toward 1 in a crash.
python
import numpy as np

def correlation(x, y):
    return np.corrcoef(x, y)[0, 1]

4.3Portfolio variance

What it means
Total risk of a book given weights w and covariance matrix Σ. For two assets: .
When a bot uses it
Risk checks before every rebalance, and the objective in mean-variance optimizers.
Example
Two assets, 20% vol each, ρ = 0.5, 50/50: σ = √0.03 ≈ 17.3%, less than 20%.
python
import numpy as np

def portfolio_vol(w, cov):
    w = np.asarray(w, float)
    return float(np.sqrt(w @ cov @ w))

4.4Covariance shrinkage (Ledoit–Wolf)

What it means
Blend the noisy sample covariance S with a simple structured target F. Ledoit–Wolf picks δ from the data.
When a bot uses it
With many assets and little history, raw S makes optimizers bet on noise. Shrinkage gives stabler weights.
python
from sklearn.covariance import LedoitWolf

def shrunk_cov(returns_matrix):
    lw = LedoitWolf().fit(returns_matrix)
    return lw.covariance_, lw.shrinkage_

05 · separate skill from market

Regression, beta and alpha

Regression splits a return stream into the part explained by a factor (beta) and the part that is left (alpha).

5.1OLS regression

What it means
The coefficients that minimize squared errors. With one regressor: .
When a bot uses it
Hedge ratios, factor exposures and linear signal models.
python
import numpy as np

def ols(X, y):
    X = np.column_stack([np.ones(len(X)), X])  # add intercept
    coef, *_ = np.linalg.lstsq(X, y, rcond=None)
    return coef  # [alpha, beta1, ...]

5.2Beta

What it means
How much an asset moves per 1% move in the market (or any benchmark).
When a bot uses it
Market-neutral bots short β units of the index per unit of the asset to remove market risk.
python
import numpy as np

def beta(asset, market):
    c = np.cov(asset, market, ddof=1)
    return c[0, 1] / c[1, 1]

5.3CAPM and Jensen's alpha

What it means
Return beyond what the market exposure alone would have paid.
When a bot uses it
Checks whether a strategy has real edge or is just leveraged beta.
python
def jensen_alpha(r_asset, r_market, beta, r_free=0.0):
    return r_asset - (r_free + beta * (r_market - r_free))

5.4R²

What it means
Share of variance the model explains. In markets a tiny R² (1%) can still be a tradable edge.
When a bot uses it
Comparing signal models, and checking how much of a book is just factor exposure.
python
import numpy as np

def r_squared(y, y_hat):
    y, y_hat = np.asarray(y), np.asarray(y_hat)
    return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - y.mean()) ** 2)

06 · find spreads that come back

Stationarity, cointegration and pairs

Prices wander; some spreads between prices don't. Statistical arbitrage trades the spreads that are stationary.

6.1Augmented Dickey–Fuller test

What it means
If γ is significantly negative the series pulls back toward its mean (stationary). Prices usually fail; returns usually pass.
When a bot uses it
Screen candidate spreads before trading them as mean-reverting.
python
from statsmodels.tsa.stattools import adfuller

def is_stationary(series, alpha=0.05):
    stat, pvalue, *_ = adfuller(series)
    return pvalue < alpha, pvalue

6.2Engle–Granger cointegration

What it means
Two non-stationary prices are cointegrated if some linear combination of them (the spread u) is stationary.
When a bot uses it
Pairs trading: long y and short β·x when the spread is low, the reverse when it is high.
python
from statsmodels.tsa.stattools import coint
import numpy as np

def pair_test(y, x):
    t, pvalue, _ = coint(y, x)
    beta = np.polyfit(x, y, 1)[0]
    return pvalue, beta

6.3Spread z-score trading rule

What it means
Sell the spread when it is stretched high, buy it when stretched low, flatten when it returns to normal (otherwise keep yesterday's position).
When a bot uses it
The core loop of a stat-arb bot. Typical values: z_in = 2, z_out = 0.5.
python
import numpy as np

def pair_positions(z, z_in=2.0, z_out=0.5):
    pos, out = 0, []
    for v in z:
        if v > z_in: pos = -1
        elif v < -z_in: pos = 1
        elif abs(v) < z_out: pos = 0
        out.append(pos)
    return np.array(out)

6.4Half-life of mean reversion

What it means
How many bars it takes for a deviation to shrink by half. λ must be negative.
When a bot uses it
Sets lookback windows and max holding time. A 3-day half-life suits a daily bot; a 3-month one ties up capital.
Example
λ = −0.05 → half-life ≈ 13.5 bars.
python
import numpy as np

def half_life(spread):
    s = np.asarray(spread, float)
    lam = np.polyfit(s[:-1], np.diff(s), 1)[0]
    return -np.log(2) / np.log(1 + lam)

07 · the model of a rubber band

Mean reversion: Ornstein–Uhlenbeck

The OU process is the continuous-time model of a spread that keeps getting pulled back to a mean.

7.1Ornstein–Uhlenbeck process

What it means
X drifts toward μ at speed θ while being shaken by noise of size σ.
When a bot uses it
The standard model for a pairs spread, a basis, or a funding-rate deviation.
python
import numpy as np

def simulate_ou(x0, theta, mu, sigma, dt, n, seed=0):
    rng = np.random.default_rng(seed)
    x = np.empty(n); x[0] = x0
    a = np.exp(-theta * dt)
    sd = sigma * np.sqrt((1 - a ** 2) / (2 * theta))
    for t in range(1, n):
        x[t] = mu + (x[t - 1] - mu) * a + sd * rng.standard_normal()
    return x

7.2Exact discretization and fitting

What it means
Sampled at fixed steps, OU is an AR(1): regress , then and .
When a bot uses it
Fit θ, μ, σ from data with one linear regression.
python
import numpy as np

def fit_ou(x, dt=1.0):
    x = np.asarray(x, float)
    b, a = np.polyfit(x[:-1], x[1:], 1)
    theta = -np.log(b) / dt
    mu = a / (1 - b)
    resid = x[1:] - (a + b * x[:-1])
    sigma = resid.std(ddof=2) * np.sqrt(2 * theta / (1 - b ** 2))
    return theta, mu, sigma

7.3OU half-life and equilibrium width

What it means
How fast it comes back, and how wide it swings around μ in the long run.
When a bot uses it
Entry bands are usually set in units of σ∞ (e.g. enter at μ ± 2σ∞).
python
import numpy as np

def ou_stats(theta, sigma):
    return np.log(2) / theta, sigma / np.sqrt(2 * theta)

08 · what went up keeps going (for a while)

Momentum and trend

Trend-following bots bet that recent winners keep winning over weeks to months. The math is simple; the risk control is the hard part.

8.1Moving averages (SMA and EMA)

What it means
Smoothed price. The EMA reacts faster because it weights recent prices more.
When a bot uses it
Crossover signal: long when the fast average is above the slow one, .
python
import numpy as np
import pandas as pd

def ma_cross(close: pd.Series, fast=20, slow=100):
    f = close.ewm(span=fast, adjust=False).mean()
    s = close.ewm(span=slow, adjust=False).mean()
    return np.sign(f - s)

8.2Time-series momentum with vol scaling

What it means
Go long if the asset's own past return over L bars is positive, short if negative, and size so every position carries the same risk.
When a bot uses it
The classic managed-futures rule (Moskowitz, Ooi and Pedersen, 2012 use a 12-month lookback).
python
import numpy as np
import pandas as pd

def tsmom(returns: pd.Series, lookback=252, target_vol=0.10, ann=252):
    sig = np.sign(returns.rolling(lookback).sum())
    vol = returns.ewm(span=60).std() * np.sqrt(ann)
    return (sig * target_vol / vol).shift(1)  # trade next bar

8.3Cross-sectional momentum

What it means
Rank assets by past return; buy the winners, short the losers, dollar-neutral.
When a bot uses it
Equity and crypto rotation bots. Skipping the most recent bar avoids short-term reversal.
python
import pandas as pd

def xs_momentum(past_returns: pd.Series):
    centred = past_returns.rank() - (len(past_returns) + 1) / 2
    return centred / centred.abs().sum()  # gross exposure 1

09 · estimates that update every tick

Kalman filter

The Kalman filter tracks a hidden quantity (a hedge ratio, a fair value) that drifts over time, updating its estimate as each new observation arrives.

9.1Predict step

What it means
Roll the estimate forward and grow its uncertainty by the process noise Q.
When a bot uses it
Each bar, before seeing the new price.
python
def kf_predict(x, P, F=1.0, Q=1e-5):
    return F * x, F * P * F + Q

9.2Update step

What it means
Blend prediction and new observation, weighted by how much you trust each (the Kalman gain K).
When a bot uses it
Dynamic hedge ratio for pairs: state x = β, observation y_t = price of A, H = price of B. The residual is the live spread.
python
def kf_hedge_ratio(ya, yb, Q=1e-5, R=1e-3):
    beta, P, out = 0.0, 1.0, []
    for a, b in zip(ya, yb):
        P += Q                      # predict (random-walk beta)
        K = P * b / (b * P * b + R)  # gain
        beta += K * (a - b * beta)   # update
        P *= (1 - K * b)
        out.append(beta)
    return out

10 · was it worth the risk?

Performance metrics

Return alone means nothing. These ratios put return next to the risk taken to earn it.

10.1Sharpe ratio

What it means
Excess return per unit of volatility, annualized with N bars per year.
When a bot uses it
The default score for comparing strategies and allocating capital.
Example
0.1% mean daily return, 1% daily vol: SR = 0.1 × √252 ≈ 1.59.
python
import numpy as np

def sharpe(returns, rf_per_period=0.0, periods_per_year=252):
    ex = np.asarray(returns, float) - rf_per_period
    return ex.mean() / ex.std(ddof=1) * np.sqrt(periods_per_year)

10.2Sortino ratio

What it means
Like Sharpe, but only downside moves (below target τ) count as risk.
When a bot uses it
Fairer for strategies with big upside spikes, such as option buying or trend following.
python
import numpy as np

def sortino(returns, target=0.0, periods_per_year=252):
    r = np.asarray(returns, float)
    dd = np.sqrt(np.mean(np.minimum(0, r - target) ** 2))
    return (r.mean() - target) / dd * np.sqrt(periods_per_year)

10.3Maximum drawdown

What it means
The worst peak-to-trough loss of the equity curve W.
When a bot uses it
Kill switches and risk limits: stop trading if live drawdown exceeds, say, 1.5× the backtest MDD.
python
import numpy as np

def max_drawdown(returns):
    w = np.cumprod(1 + np.asarray(returns, float))
    peak = np.maximum.accumulate(w)
    return float(np.max(1 - w / peak))

10.4Calmar ratio

What it means
Yearly growth per unit of worst drawdown (classically measured over 36 months).
When a bot uses it
Ranks strategies by how painful they are to hold.
python
def calmar(cagr_value, mdd_value):
    return cagr_value / mdd_value

10.5Information ratio

What it means
Sharpe of the excess return over a benchmark b (σ(r − b) is the tracking error).
When a bot uses it
Scoring a bot that is meant to beat an index or a buy-and-hold baseline.
python
import numpy as np

def information_ratio(r, bench, periods_per_year=252):
    a = np.asarray(r, float) - np.asarray(bench, float)
    return a.mean() / a.std(ddof=1) * np.sqrt(periods_per_year)

11 · how much to bet

Kelly criterion and position sizing

Edge decides direction; sizing decides whether you survive. Kelly maximizes long-run growth, and nearly everyone bets a fraction of it.

11.1Kelly for a binary bet

What it means
Bet this fraction of capital when you win b per 1 staked with probability p (q = 1 − p).
When a bot uses it
Sizing bets with fixed payoffs: prediction markets, binary options, take-profit/stop-loss setups with a known hit rate.
Example
p = 0.55 at even odds (b = 1): f* = 10% of capital.
python
def kelly_binary(p, b):
    return p - (1 - p) / b

11.2Kelly for continuous returns

What it means
Optimal leverage is excess return over variance; for many assets, the inverse covariance times the excess returns.
When a bot uses it
Upper bound on leverage. Full Kelly is very volatile and μ is uncertain, so bots use half Kelly or less.
python
import numpy as np

def kelly_weights(mu, cov, rf=0.0, fraction=0.5):
    return fraction * np.linalg.solve(cov, np.asarray(mu) - rf)

11.3Volatility targeting

What it means
Scale exposure so the position's expected volatility stays constant.
When a bot uses it
Keeps risk steady as markets calm down or blow up; used by most systematic funds.
python
def vol_target_size(capital, target_vol, est_vol):
    return capital * target_vol / est_vol

11.4Fixed-fractional risk per trade

What it means
Size so that hitting your stop loses a fixed share of equity (e.g. 1%).
When a bot uses it
The default for discretionary-style bots with explicit stops.
Example
$10,000 equity, 1% risk, entry 100, stop 95 → 20 units.
python
def position_size(equity, risk_pct, entry, stop):
    return risk_pct * equity / abs(entry - stop)

12 · how much can I lose?

Risk: VaR and expected shortfall

Risk limits answer one question: on a bad day, how bad? VaR gives the threshold; expected shortfall gives the average beyond it.

12.1Parametric (normal) VaR

What it means
The loss you expect to exceed only (1 − α) of the time, assuming normal returns.
When a bot uses it
Fast pre-trade risk limits.
Example
32.9k.
python
from scipy.stats import norm

def var_normal(value, mu, sigma, alpha=0.95):
    return value * (norm.ppf(alpha) * sigma - mu)

12.2Historical VaR

What it means
Take the empirical (1 − α) quantile of past returns. No normality assumption.
When a bot uses it
Captures fat tails that the normal model misses.
python
import numpy as np

def var_historical(returns, value=1.0, alpha=0.95):
    return -np.quantile(returns, 1 - alpha) * value

12.3Expected shortfall (CVaR)

What it means
The average loss on the days that are worse than VaR. For a normal at 95%, ES ≈ 2.06σ versus VaR = 1.645σ.
When a bot uses it
Better tail measure for strategies that sell insurance (short options, market making).
python
import numpy as np

def expected_shortfall(returns, alpha=0.95):
    r = np.asarray(returns, float)
    q = np.quantile(r, 1 - alpha)
    return -r[r <= q].mean()

12.4Scaling VaR over a horizon

What it means
Under independent returns (and μ ≈ 0), h-day VaR grows with √h.
When a bot uses it
Converting a 1-day limit into a 10-day one. Breaks down when returns are autocorrelated.
python
import numpy as np

def scale_var(var_1d, days):
    return var_1d * np.sqrt(days)

13 · where the edge leaks out

Order book microstructure and execution

At short horizons the order book is the signal and execution cost is the enemy. These formulas run inside every HFT and execution bot.

13.1Mid price and spread

What it means
The reference price, and the cost of crossing the book. A market round trip pays the full spread.
When a bot uses it
Every quote, fill and P&L mark is measured against the mid.
python
def mid_spread_bps(bid, ask):
    mid = (bid + ask) / 2
    return mid, (ask - bid) / mid * 1e4

13.2Order-book imbalance

What it means
Share of resting size on the bid. Near 1: buyers stacked, the next move is more likely up.
When a bot uses it
One of the strongest very-short-horizon signals in liquid markets.
python
def imbalance(q_bid, q_ask):
    return q_bid / (q_bid + q_ask)

13.3Weighted mid (imbalance-adjusted price)

What it means
Mid price tilted toward the side that is likely to be hit next. Stoikov's micro-price refines this into a proper martingale estimate.
When a bot uses it
Fair-value input for market makers and for deciding whether to cross.
Example
Bid 99.98 × 10, ask 100.02 × 30: I = 0.25, P_w = 99.99 (the mid is 100.00).
python
def weighted_mid(bid, ask, q_bid, q_ask):
    i = q_bid / (q_bid + q_ask)
    return i * ask + (1 - i) * bid

13.4Order-flow imbalance (OFI)

What it means
Net pressure from changes at the best bid and ask. Summed over an interval, OFI moves the mid roughly linearly: (Cont, Kukanov and Stoikov, 2014).
When a bot uses it
Short-term price prediction from L1 book updates.
python
import numpy as np

def ofi(bid_px, bid_sz, ask_px, ask_sz):
    bp, bq, ap, aq = map(np.asarray, (bid_px, bid_sz, ask_px, ask_sz))
    e = ((bp[1:] >= bp[:-1]) * bq[1:] - (bp[1:] <= bp[:-1]) * bq[:-1]
         - (ap[1:] <= ap[:-1]) * aq[1:] + (ap[1:] >= ap[:-1]) * aq[:-1])
    return e.sum()

13.5VWAP and TWAP

What it means
VWAP is the volume-weighted average traded price; TWAP slices an order into equal pieces over time.
When a bot uses it
Execution benchmarks and the two most common ways to work a large order.
python
import numpy as np

def vwap(prices, volumes):
    p, v = np.asarray(prices, float), np.asarray(volumes, float)
    return (p * v).sum() / v.sum()

def twap_slices(total_qty, n_slices):
    return [total_qty / n_slices] * n_slices

13.6Slippage and implementation shortfall

What it means
How much worse you traded than the price when you decided to trade. Positive = cost.
When a bot uses it
Measured on every fill; the live-versus-backtest gap usually hides here.
python
def slippage_bps(fill_px, decision_px, side):
    s = 1 if side == 'buy' else -1
    return s * (fill_px - decision_px) / decision_px * 1e4

13.7Square-root market impact

What it means
Impact grows with the square root of order size relative to daily volume, with Y of order 1. Trading 4× more costs about 2× more per share.
When a bot uses it
Capacity estimates and deciding how many slices or days a big order needs.
Example
σ = 2%, order = 1% of daily volume, Y = 1: about 0.2% impact.
python
import numpy as np

def sqrt_impact(qty, daily_volume, daily_vol, Y=1.0):
    return Y * daily_vol * np.sqrt(qty / daily_volume)

14 · quote both sides, manage inventory

Market making: Avellaneda–Stoikov

A market maker earns the spread but carries inventory risk. Avellaneda and Stoikov (2008) derived where to quote so inventory does not blow up.

14.1Reservation price

What it means
Your personal fair price: the mid s shifted against your inventory q. Long inventory → you value the asset less → quote lower to sell it off.
When a bot uses it
Centers the quotes. γ is risk aversion, σ is volatility, T − t is time left in the session.
python
def reservation_price(mid, inventory, gamma, sigma, time_left):
    return mid - inventory * gamma * sigma ** 2 * time_left

14.2Optimal spread

What it means
Total quoted spread: an inventory-risk term plus a term from how fast fill probability decays with distance (order arrival intensity ).
When a bot uses it
Quote bid at r − spread/2 and ask at r + spread/2, then requote on every book update.
python
import numpy as np

def as_quotes(mid, inventory, gamma, sigma, k, time_left):
    r = mid - inventory * gamma * sigma ** 2 * time_left
    spread = gamma * sigma ** 2 * time_left + (2 / gamma) * np.log(1 + gamma / k)
    return r - spread / 2, r + spread / 2  # bid, ask

15 · pricing the future

Options: Black–Scholes and the Greeks

Options bots price, hedge and trade volatility. Everything rests on one model of how prices move.

15.1Geometric Brownian motion

What it means
The standard model of a price: log price is a random walk with drift. Prices stay positive.
When a bot uses it
Monte Carlo simulation of paths for pricing and stress tests.
python
import numpy as np

def gbm_paths(s0, mu, sigma, T, steps, n_paths, seed=0):
    rng = np.random.default_rng(seed)
    dt = T / steps
    z = rng.standard_normal((n_paths, steps))
    log_inc = (mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * z
    return s0 * np.exp(np.cumsum(log_inc, axis=1))

15.2Black–Scholes price

What it means
Fair value of a European call (C) and put (P) under GBM with constant volatility.
When a bot uses it
Pricing, implied-vol inversion and Greeks for every option a bot touches.
Example
S = K = 100, r = 5%, σ = 20%, T = 1: call ≈ 10.45, put ≈ 5.57.
python
import numpy as np
from scipy.stats import norm

def bs_price(S, K, T, r, sigma, call=True):
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    if call:
        return S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
    return K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)

15.3Put–call parity

What it means
A call minus a put with the same strike and expiry equals a forward. No model needed.
When a bot uses it
Arbitrage checks and synthetic positions; a violation (after costs) is free money or a data error.
python
import numpy as np

def parity_gap(C, P, S, K, r, T):
    return (C - P) - (S - K * np.exp(-r * T))

15.4The Greeks (call)

What it means
Sensitivities: price per 1 (Γ), per 1.00 of vol (vega), per year of time (Θ). φ is the normal density.
When a bot uses it
Delta hedging (hold −Δ shares per option), gamma and vega limits.
python
import numpy as np
from scipy.stats import norm

def call_greeks(S, K, T, r, sigma):
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    delta = norm.cdf(d1)
    gamma = norm.pdf(d1) / (S * sigma * np.sqrt(T))
    vega = S * norm.pdf(d1) * np.sqrt(T)
    theta = -S * norm.pdf(d1) * sigma / (2 * np.sqrt(T)) - r * K * np.exp(-r * T) * norm.cdf(d2)
    return delta, gamma, vega, theta

15.5Implied volatility (Newton's method)

What it means
The volatility that makes the model price equal the market price, found by iterating.
When a bot uses it
Comparing implied vs realized vol is the core of volatility trading.
python
import numpy as np
from scipy.stats import norm

def implied_vol(price, S, K, T, r, sigma=0.2, tol=1e-8):
    for _ in range(100):
        d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
        d2 = d1 - sigma * np.sqrt(T)
        model = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
        vega = S * norm.pdf(d1) * np.sqrt(T)
        step = (model - price) / vega
        sigma -= step
        if abs(step) < tol:
            break
    return sigma

15.6Delta-hedged P&L (gamma vs theta)

What it means
A delta-hedged long option makes money when the market moves more than implied vol priced in, and bleeds theta otherwise.
When a bot uses it
The P&L engine of gamma scalping and vol-arb bots.
python
def gamma_pnl(gamma, S, realized_vol, implied_vol, dt):
    return 0.5 * gamma * S ** 2 * (realized_vol ** 2 - implied_vol ** 2) * dt

16 · most edges die here

Backtesting without fooling yourself

A backtest is a hypothesis test you can run thousands of times, which is exactly the problem. These formulas measure how much of a result is luck.

16.1No look-ahead: trade on the next bar

What it means
A position can only use information available before the return it earns.
When a bot uses it
In pandas: compute the signal, then .shift(1) before multiplying by returns.
python
import pandas as pd

def backtest(signal: pd.Series, returns: pd.Series):
    return signal.shift(1) * returns  # yesterday's signal earns today's return

16.2Multiple testing

What it means
Test enough ideas and some will pass by luck.
When a bot uses it
Track how many variants you tried; 20 tests at 5% give a 64% chance of a fake winner.
python
def family_false_positive(alpha, n_tests):
    return 1 - (1 - alpha) ** n_tests

16.3Standard error of the Sharpe ratio

What it means
For i.i.d. normal returns (Lo, 2002), with SR and T in the same units (e.g. per-period SR, T periods).
When a bot uses it
Error bars on a backtest Sharpe.
python
import numpy as np

def sharpe_se(sr_per_period, n_periods):
    return np.sqrt((1 + 0.5 * sr_per_period ** 2) / n_periods)

16.4Probabilistic Sharpe ratio

What it means
Probability that the true Sharpe beats a benchmark SR*, adjusting for track length T, skew γ₃ and kurtosis γ₄ (non-excess; per-period SR).
When a bot uses it
Minimum bar before allocating capital: e.g. require PSR(0) > 0.95.
python
import numpy as np
from scipy.stats import norm, skew, kurtosis

def psr(returns, sr_star=0.0):
    r = np.asarray(returns, float)
    sr = r.mean() / r.std(ddof=1)
    g3, g4 = skew(r), kurtosis(r, fisher=False)
    z = (sr - sr_star) * np.sqrt(len(r) - 1) / np.sqrt(1 - g3 * sr + (g4 - 1) / 4 * sr ** 2)
    return norm.cdf(z)

16.5Deflated Sharpe ratio

What it means
The Sharpe the luckiest of N worthless strategies would show (γ ≈ 0.5772, the Euler–Mascheroni constant). DSR is the PSR against that bar (Bailey and López de Prado, 2014).
When a bot uses it
Report DSR, not raw Sharpe, after any parameter sweep.
python
import numpy as np
from scipy.stats import norm

def expected_max_sharpe(n_trials, var_sr):
    g = 0.5772156649
    return np.sqrt(var_sr) * ((1 - g) * norm.ppf(1 - 1 / n_trials)
                              + g * norm.ppf(1 - 1 / (n_trials * np.e)))
# DSR = psr(returns, sr_star=expected_max_sharpe(N, var_of_trial_sharpes))

16.6Walk-forward validation

What it means
Fit only on the past, test on the next unseen block, roll forward. The gap g (purge/embargo) stops overlapping labels leaking.
When a bot uses it
The honest out-of-sample estimate. Shuffled k-fold leaks future information in time series.
python
from sklearn.model_selection import TimeSeriesSplit

def walk_forward(n_samples, n_splits=5, gap=10):
    return list(TimeSeriesSplit(n_splits=n_splits, gap=gap).split(range(n_samples)))

17 · the tax on every trade

Fees, slippage and latency

Many backtests that look great on paper lose money live because of costs. Put them in from day one.

17.1Round-trip cost

What it means
Per round trip you pay the fee f twice, half the spread s twice (entering and exiting at market) and impact ι twice. Everything in bps.
When a bot uses it
The hurdle every trade's expected edge must clear.
Example
5 bps taker fee, 2 bps spread, no impact: 12 bps per round trip.
python
def round_trip_bps(fee_bps, spread_bps, impact_bps=0.0):
    return 2 * (fee_bps + spread_bps / 2 + impact_bps)

17.2Annual cost drag from turnover

What it means
Turnover × cost per unit traded comes straight off returns. c here is the one-way cost per unit of notional traded.
When a bot uses it
High-frequency signals need tiny costs: 50× annual turnover at 6 bps one-way is 3% a year.
python
def net_return(gross, annual_turnover, cost_one_way):
    return gross - annual_turnover * cost_one_way

17.3Break-even hit rate

What it means
With average win W, average loss L (both positive) and cost c per trade, you need to win more than this share of trades.
When a bot uses it
Quick check whether a scalping rule can survive fees.
Example
Win 10 bps, lose 10 bps, 4 bps cost: need 70% winners.
python
def breakeven_hit_rate(avg_win, avg_loss, cost):
    return (avg_loss + cost) / (avg_win + avg_loss)

17.4Latency cost

What it means
For a random walk with per-second volatility σ, the expected absolute move during a delay of Δt seconds grows with √Δt (√(2/π) ≈ 0.8 is the mean of |N(0,1)|).
When a bot uses it
Sizing the value of a faster connection, or how stale a quote gets before it reaches the exchange.
python
import numpy as np

def expected_move(sigma_per_sec, delay_sec):
    return sigma_per_sec * np.sqrt(2 / np.pi * delay_sec)

Go deeper

35 free references

Courses, the original papers and the docs for every library used above. Every link checked 26 Nov 2026.

tags

Showing 35 of 35

free course · MIT OCW

Full MIT course with video lectures: linear algebra, probability, stochastic calculus, time series, portfolio theory and Black–Scholes, taught partly by practitioners.

Courses & booksfoundationsoptions
Open verified 26 Nov 2026

video series

Visual intuition for vectors, matrices, eigenvalues and change of basis, everything under covariance matrices and PCA.

Courses & booksfoundations
Open verified 26 Nov 2026
04

StatQuest

youtube.com

YouTube

Short, clear videos on statistics and machine learning: p-values, regression, cross-validation.

Courses & booksstatistics
Open verified 26 Nov 2026

free book

The free ISL book (R and Python editions): regression, classification, resampling and model selection.

Courses & booksstatisticsbacktesting
Open verified 26 Nov 2026
07

QuantEcon lectures

python.quantecon.org

free lectures

Open-source Python lectures on probability, Markov chains, Kalman filtering, optimization and dynamic programming.

Courses & booksfoundationskalman
Open verified 26 Nov 2026
11

Engle: GARCH 101

stern.nyu.edu

paper · PDF

Nobel laureate Robert Engle's plain-language introduction to ARCH/GARCH volatility models.

Papersvolatility
Open verified 26 Nov 2026

technical doc · PDF

J.P. Morgan/Reuters document that made VaR and EWMA volatility (λ = 0.94) an industry standard.

Papersriskvolatility
Open verified 26 Nov 2026

arXiv

Short review of market impact: why it is concave in volume and what that means for execution.

Papersmicrostructureexecution
Open verified 26 Nov 2026
24

Kenneth French Data Library

mba.tuck.dartmouth.edu

free data

Free daily and monthly factor returns (market, size, value, momentum) to test betas and alphas against.

Data & docsdataregression
Open verified 26 Nov 2026
25

statsmodels: adfuller

statsmodels.org

docs

Augmented Dickey–Fuller test reference.

Data & docspairstime series
Open verified 26 Nov 2026
26

statsmodels: coint

statsmodels.org

docs

Engle–Granger cointegration test reference.

Data & docspairs
Open verified 26 Nov 2026
27

arch (Python)

arch.readthedocs.io

docs

GARCH-family volatility models, bootstraps and unit-root tests for Python.

Data & docsvolatility
Open verified 26 Nov 2026
28

SciPy stats

docs.scipy.org

docs

Distributions, normal CDF/PPF, skew, kurtosis and hypothesis tests.

Data & docsstatistics
Open verified 26 Nov 2026

docs

Solvers, inverses and eigen-decompositions for covariance and portfolio math.

Data & docsfoundations
Open verified 26 Nov 2026

docs

Walk-forward splits with an optional gap for time-series validation.

Data & docsbacktesting
Open verified 26 Nov 2026
32

docs

Rolling and exponentially weighted windows for z-scores, moving averages and EWMA vol.

Data & docsfoundations
Open verified 26 Nov 2026
33

py_vollib

github.com

GitHub

Fast Black–Scholes prices, Greeks and implied volatility in Python.

Data & docsoptions
Open verified 26 Nov 2026
34

QuantLib

quantlib.org

open-source library

The standard open-source library for pricing derivatives and fixed income.

Data & docsoptions
Open verified 26 Nov 2026

How to use this page

Read it top to bottom once. The order is deliberate: returns feed volatility, volatility feeds sizing and risk, and the last two sections (backtesting and costs) decide whether any of it makes money live.

Every snippet is plain NumPy, SciPy, pandas, statsmodels, scikit-learn or arch, and every one was run before publishing. They are deliberately small: building blocks for your own bot, not a trading system.

The 50-formula one-sheet by hft.md (adapted from the MIT Sloan "Quant Bible") inspired this page. Here the math is written out as text, so you can search it, link to each formula and copy the code.

FAQ

What math do you need for algorithmic trading?

Statistics (means, variance, regression, hypothesis tests), linear algebra (covariance matrices), basic time series (stationarity, autocorrelation) and probability. Stochastic calculus only matters for options pricing, and order-book math only for high-frequency strategies.

Which formula matters most for a trading bot?

Position sizing and costs. A small edge with good sizing (volatility targeting, fractional Kelly) and realistic costs survives; a big backtest edge with no cost model usually does not.

Is a Sharpe ratio of 1 good?

For a live strategy after costs, an annual Sharpe around 1 is respectable and above 2 is rare. In a backtest it means little on its own: check the probabilistic and deflated Sharpe ratio, especially after trying many variants.

Why use log returns instead of simple returns?

Log returns add up over time, so multi-period returns and statistics are simpler. Simple returns add up across assets, so use them for portfolio P&L.

Is this financial advice?

No. It is educational material. The formulas are standard textbook versions and real markets break their assumptions.

Education only, not financial advice. Formulas are the textbook versions; real markets break their assumptions (fat tails, regime changes, costs). Test everything on paper before risking money.

One new goldmine a day

Get the next list before it goes viral.

Free. One email when a new list drops. No spam, unsubscribe in one click.

Or follow @eng_khairallah1 on X.

More goldmines