← library app

4. Technical Indicators (for Backtesting)

Exact formulas, default periods, and the lookahead trap for each.

Algo-wide warnings.

  1. Lookahead/repainting. An indicator computed on bar t's close cannot drive a trade at bar t's close in live trading. Shift the signal one bar: act at open, or apply signal.shift(1) to returns. Indicators that use future bars (centered MAs, ZigZag, some pivots) repaint — never backtest with them.
  2. Warm-up / NaN. Every rolling indicator has an undefined warm-up window (first n bars, longer for recursive EMAs). Drop or mask it; don't trade on partially-formed values.
  3. OHLC source. State whether you use close, typical price , or HLC. Be consistent.
  4. Adjusted prices. Use split/dividend-adjusted series, or gaps will fire false signals.

Notation: C = close, H = high, L = low, V = volume, n = period.


Trend / Moving Averages

Simple Moving Average (SMA)

Def. Unweighted mean of the last n closes. Formula. . Defaults: 20/50/200. Signal. Price > SMA → uptrend bias. 50/200 cross = golden (bull) / death (bear) cross. Algo. C.rolling(n).mean(). NaN for first bars. Equal weighting lags hard on turns.

Exponential Moving Average (EMA)

Def. Weighted MA giving more weight to recent prices; reacts faster than SMA. Formula. , with . Seed with SMA of first n. Signal. Same as SMA but more responsive; common 12/26 for MACD. Algo. Recursive → technically depends on all history; warm-up ~3–5×n for stability. C.ewm(span=n, adjust=False).mean().

WMA / HMA / VWMA

Def. Linearly-weighted (WMA), Hull (HMA, low-lag), volume-weighted (VWMA) variants. Formula. , w linear. . Signal. HMA reduces lag while smoothing; VWMA emphasizes high-volume prices. Algo. HMA's nested WMAs compound warm-up length; verify against a reference implementation.

MACD (Moving Average Convergence Divergence)

Def. Momentum via the gap between two EMAs. Formula. , , . Signal. MACD crosses above Signal → bullish; histogram = momentum strength. Divergence vs price → reversal hint. Algo. Double-recursive (EMA of EMA) — long warm-up. Crossovers lag; histogram zero-cross is earlier but noisier.

ADX / DMI (Directional Movement)

Def. Trend strength (not direction); +DI/−DI give direction. Formula. From smoothed directional movement & ATR: +DI, −DI, then , . Default n=14. Signal. ADX >25 → trending (use trend systems); <20 → ranging (use mean-reversion). +DI>−DI → up. Algo. Uses Wilder's smoothing (not standard EMA): . Many libs get this subtly wrong — verify.

Parabolic SAR

Def. Trailing stop-and-reverse trend follower. Formula. , AF (accel factor) steps 0.02→0.20 at new extremes. Signal. Dots flip side → trend reversal / stop trigger. Algo. Whipsaws badly in ranges; the AF schedule is the key parameter.


Momentum / Oscillators

RSI (Relative Strength Index)

Def. Speed/magnitude of gains vs losses, bounded 0–100. Formula. (Wilder's smoothing); . Default n=14. Signal. >70 overbought, <30 oversold (in ranges); in trends RSI can stay extreme. Divergence = reversal hint. Algo. Must use Wilder smoothing , not SMA — results differ. First value needs n+1 bars.

Stochastic Oscillator

Def. Where close sits within the recent high–low range. Formula. , . Default n=14. Signal. >80 overbought, <20 oversold; %K crossing %D = signal. Algo. Division by zero when (flat range) — guard it. "Fast" vs "slow" stochastic = extra smoothing.

Rate of Change (ROC) / Momentum

Def. Percent change over n periods. Formula. . . Signal. Sign = direction; magnitude = strength. Cross-sectional ROC ranks drive momentum factors. Algo. Simple, robust, no smoothing artifacts. The basis of the academic 12-1 month momentum factor.

Williams %R

Def. Inverse stochastic; position in range scaled −100..0. Formula. . Default n=14. Signal. > −20 overbought, < −80 oversold. Algo. Same zero-range guard as stochastic.

CCI (Commodity Channel Index)

Def. Deviation of typical price from its mean, scaled. Formula. , . Default n=20. Signal. >+100 strong up / overbought; <−100 strong down / oversold. Algo. Uses mean absolute deviation (not std) — don't substitute std.


Volatility

ATR (Average True Range)

Def. Average range size including gaps; absolute volatility in price units. Formula. , . Default n=14. Signal. Rising ATR → expanding volatility. Used for position sizing & stops, not direction. Algo. In price units (not %), so not comparable across assets — normalize by price for cross-asset sizing. Standard for volatility-targeted stops (e.g. stop = entry − 2·ATR).

Bollinger Bands

Def. SMA envelope at ±k standard deviations. Formula. , . Defaults n=20, k=2. Signal. Price at upper/lower band = stretched; band squeeze (narrow width) precedes volatility breakouts. Algo. , . Uses population std — match your library's ddof.

Keltner Channels

Def. EMA envelope at ±k·ATR (volatility from range, not std). Formula. , . Common n=20, k=2. Signal. Bollinger inside Keltner = squeeze (low vol, breakout setup — the "TTM Squeeze"). Algo. Smoother than Bollinger (ATR < std spikes); good breakout filter.

Historical (Realized) Volatility

Def. Annualized std of returns over a window. Formula. . Daily → ×√252. Signal. Regime gauge; mean-reverting. Compare to implied vol for rich/cheap options. Algo. Use log returns; pick the annualization factor matching your bar frequency (see appendix). Parkinson/Garman-Klass estimators use OHLC for efficiency.

Average Daily Range / Choppiness Index

Def. ADR = typical daily range; Choppiness = trending vs ranging gauge. Formula. . Signal. Choppiness >61.8 → ranging; <38.2 → trending. Pairs well with ADX as a regime filter. Algo. Bounded 0–100; useful to switch strategy mode (trend vs mean-revert).


Volume

OBV (On-Balance Volume)

Def. Cumulative volume signed by price direction. Formula. . Signal. OBV trend confirms/diverges from price; divergence hints at reversal. Algo. A running cumulative sum → unbounded and path-dependent; only the shape/slope matters, not the level.

VWAP (Volume-Weighted Average Price)

Def. Average price weighted by volume, typically reset each session. Formula. , , cumulative within the day. Signal. Institutional benchmark; price > VWAP = buyers in control intraday. Mean-reversion anchor. Algo. Resets daily — don't carry across sessions. Anchored VWAP resets from a chosen event instead.

Accumulation/Distribution & CMF

Def. Volume flow weighted by where close sits in the bar. Formula. , , . Default n=20. Signal. CMF >0 → buying pressure; divergence from price = warning. Algo. Zero-range guard (H=L). CMF is bounded; A/D is cumulative (slope only).

Money Flow Index (MFI)

Def. Volume-weighted RSI. Formula. , split into positive/negative by TP direction; . Default n=14. Signal. >80 overbought, <20 oversold — like RSI but volume-aware. Algo. Needs both price and reliable volume; sparse-volume assets distort it.


Support/Resistance & Levels

Pivot Points

Def. Reference levels derived from prior period's OHLC. Formula. , , , (R2/S2 extend). Computed from prior day/week. Signal. Intraday support/resistance zones. Algo. Safe (non-repainting) because they use the completed prior period — but confirm you reference the closed bar, not the forming one.

Fibonacci Retracements

Def. Pullback levels between a swing high and low. Formula. Levels at 23.6%, 38.2%, 50%, 61.8%, 78.6% of the move. Signal. Potential reversal/continuation zones. Algo. Depends on chosen swing points → subjective and can repaint if swings are auto-detected with future data. Fix the anchor or treat as discretionary.

Donchian Channels

Def. Highest high / lowest low over n periods. Formula. , . Default n=20/55. Signal. Breakout above upper = entry (the classic Turtle system). Algo. Use H.rolling(n).max().shift(1) so the current bar's own high doesn't define its own breakout level (subtle lookahead).


Indicator selection by regime

Regime (from ADX/Choppiness) Use Avoid
Trending (ADX>25) MA cross, MACD, Donchian breakout, Parabolic SAR RSI/Stoch overbought-fades
Ranging (ADX<20) RSI, Stochastic, Bollinger fades, %R Breakout systems (whipsaw)
Any ATR (sizing/stops), volume confirmation