If you have ever looked at a crypto price chart on TradingView or Binance, you have probably seen colorful lines weaving above, below, and through the candlesticks. Those lines are technical indicators—simple math formulas applied to historical price data to help traders spot trends, momentum, and volatility.
Most beginners install a giant third-party indicator library and treat those lines like a black box. When the bot buys or sells, they have no idea why. In this lesson, we are going to peel back the curtain and code the four most popular trading indicators from scratch in pure Python and pandas:
- Simple Moving Average (SMA): Smooths out daily price noise to reveal the overall trend.
- Exponential Moving Average (EMA): Like an SMA, but reacts faster to recent price changes.
- Relative Strength Index (RSI): Measures whether an asset has been bought or sold too aggressively on a 0–100 scale.
- Bollinger Bands: Creates an upper and lower channel around price to measure volatility.
Educational Note: All code, indicator formulas, and backtests in this course are strictly for educational simulations. Any live execution should always target Binance Testnet using paper funds—never treat indicator signals as financial advice.
Why Code Indicators Yourself?
You might wonder: "Why write these formulas by hand when libraries already exist?"
There are three practical reasons:
- Zero Mystery: When your bot makes a weird trade, you can inspect the exact math in 10 lines of code instead of guessing what a hidden C library did.
- No Installation Headaches: Some popular indicator packages require compiling C code (
TA-Lib), which breaks constantly on macOS, Windows, and cloud servers. Purepandasworks everywhere. - Easy Customization: Once you know how an indicator works, you can tweak it—like changing an RSI window from 14 candles to 7, or combining two indicators into a custom signal.
Prerequisites
Make sure you have Python 3.10+ installed, then install pandas, numpy, and requests (we will fetch free public candle data directly from Binance's public market API—no API keys needed for reading historical candles):
pip install pandas numpy requests
Building Your Lightweight Indicator Toolkit
Create a file named indicators.py. This script downloads 200 recent 1-hour Bitcoin (BTCUSDT) candles from Binance's public endpoint, calculates SMA, EMA, RSI, and Bollinger Bands using clean pandas functions, and prints the latest readings along with a human-readable summary.
"""
Lesson 11: Coding Popular Trading Indicators from Scratch
Deliverable: Your own lightweight Python indicator toolkit (indicators.py)
"""
import requests
import numpy as np
import pandas as pd
def fetch_binance_candles(symbol: str = "BTCUSDT", interval: str = "1h", limit: int = 200) -> pd.DataFrame:
"""Fetch public OHLCV candlestick data from Binance (no API key required)."""
url = "https://api.binance.com/api/v3/klines"
params = {"symbol": symbol, "interval": interval, "limit": limit}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
raw = response.json()
columns = [
"open_time", "open", "high", "low", "close", "volume",
"close_time", "quote_volume", "trades", "taker_buy_base",
"taker_buy_quote", "ignore"
]
df = pd.DataFrame(raw, columns=columns)
df["timestamp"] = pd.to_datetime(df["open_time"], unit="ms")
for col in ["open", "high", "low", "close", "volume"]:
df[col] = df[col].astype(float)
return df[["timestamp", "open", "high", "low", "close", "volume"]]
# ---------------------------------------------------------
# 1. Simple Moving Average (SMA)
# ---------------------------------------------------------
def add_sma(series: pd.Series, window: int = 20) -> pd.Series:
"""Average closing price over the last `window` candles."""
return series.rolling(window=window).mean()
# ---------------------------------------------------------
# 2. Exponential Moving Average (EMA)
# ---------------------------------------------------------
def add_ema(series: pd.Series, window: int = 20) -> pd.Series:
"""Weighted moving average that reacts faster to recent prices."""
return series.ewm(span=window, adjust=False).mean()
# ---------------------------------------------------------
# 3. Relative Strength Index (RSI)
# ---------------------------------------------------------
def add_rsi(series: pd.Series, window: int = 14) -> pd.Series:
"""
Momentum oscillator from 0 to 100 using Wilder's smoothing.
> 70 often signals 'overbought'; < 30 often signals 'oversold'.
"""
delta = series.diff()
gains = delta.clip(lower=0)
losses = -delta.clip(upper=0)
# Wilder's smoothing uses alpha = 1 / window
avg_gain = gains.ewm(alpha=1 / window, min_periods=window, adjust=False).mean()
avg_loss = losses.ewm(alpha=1 / window, min_periods=window, adjust=False).mean()
rs = avg_gain / avg_loss.replace(0, np.nan)
rsi = 100 - (100 / (1 + rs))
return rsi.fillna(50.0)
# ---------------------------------------------------------
# 4. Bollinger Bands
# ---------------------------------------------------------
def add_bollinger_bands(series: pd.Series, window: int = 20, num_std: float = 2.0) -> pd.DataFrame:
"""
Volatility channel: Middle = SMA, Upper/Lower = SMA +/- (num_std * std_dev).
"""
middle = series.rolling(window=window).mean()
std = series.rolling(window=window).std()
upper = middle + (num_std * std)
lower = middle - (num_std * std)
return pd.DataFrame({
"bb_upper": upper,
"bb_middle": middle,
"bb_lower": lower,
})
def enrich_dataframe(df: pd.DataFrame) -> pd.DataFrame:
"""Apply all indicators in our toolkit to a candlestick DataFrame."""
df = df.copy()
df["sma_20"] = add_sma(df["close"], window=20)
df["sma_50"] = add_sma(df["close"], window=50)
df["ema_20"] = add_ema(df["close"], window=20)
df["rsi_14"] = add_rsi(df["close"], window=14)
bb = add_bollinger_bands(df["close"], window=20, num_std=2.0)
df = pd.concat([df, bb], axis=1)
return df
if __name__ == "__main__":
print("Fetching latest 200 hourly candles for BTCUSDT...")
candles = fetch_binance_candles(symbol="BTCUSDT", interval="1h", limit=200)
enriched = enrich_dataframe(candles)
# Show the last 5 completed candles
display_cols = ["timestamp", "close", "sma_20", "ema_20", "rsi_14", "bb_lower", "bb_upper"]
print("\nLatest 5 Hourly Candles with Indicators:")
print(enriched[display_cols].tail(5).to_string(index=False, float_format="%.2f"))
# Quick plain-English interpretation of the latest candle
latest = enriched.iloc[-1]
trend = "BULLISH (EMA 20 > SMA 50)" if latest["ema_20"] > latest["sma_50"] else "BEARISH (EMA 20 <= SMA 50)"
if latest["rsi_14"] > 70:
rsi_state = "Overbought (> 70)"
elif latest["rsi_14"] < 30:
rsi_state = "Oversold (< 30)"
else:
rsi_state = "Neutral (30-70)"
print("\n--- Quick Market Snapshot (Educational Only) ---")
print(f"Latest Close : ${latest['close']:,.2f}")
print(f"Trend Read : {trend}")
print(f"RSI (14) : {latest['rsi_14']:.2f} -> {rsi_state}")
print(f"BB Channel : ${latest['bb_lower']:,.2f} to ${latest['bb_upper']:,.2f}")
Run the script in your terminal:
python indicators.py
Expected Terminal Output
Your exact prices will reflect the current live BTCUSDT market, and the table will look similar to this:
Fetching latest 200 hourly candles for BTCUSDT...
Latest 5 Hourly Candles with Indicators:
timestamp close sma_20 ema_20 rsi_14 bb_lower bb_upper
2026-12-03 07:00:00 94210.50 93840.12 93955.84 58.42 92910.40 94769.84
2026-12-03 08:00:00 94480.00 93895.30 94005.76 61.18 92935.15 94855.45
2026-12-03 09:00:00 94350.25 93942.80 94038.57 59.04 92980.60 94905.00
2026-12-03 10:00:00 94615.80 94010.45 94093.54 62.35 93025.10 94995.80
2026-12-03 11:00:00 94790.10 94088.90 94159.88 64.12 93090.75 95087.05
--- Quick Market Snapshot (Educational Only) ---
Latest Close : $94,790.10
Trend Read : BULLISH (EMA 20 > SMA 50)
RSI (14) : 64.12 -> Neutral (30-70)
BB Channel : $93,090.75 to $95,087.05
Common Beginner Mistake: Treating indicator values on the very first few rows of a DataFrame as valid signals. A 50-period SMA needs 50 candles before it can produce a real number—the first 49 rows are
NaN(blank). Always drop or skip the warm-up rows (df.dropna()) before generating buy/sell rules, or your bot might misread missing data as zero!
Study & Practice Recap
- Indicators are just simple math on price history: SMA and EMA smooth out noise to show trend, RSI tracks momentum (0–100), and Bollinger Bands measure volatility using standard deviation.
- Pure
pandasbeats black-box libraries for learning: Writing your ownindicators.pymodule gives you full transparency, zero C-compiler issues, and reusable functions you will import in the next four lessons. - Always respect the warm-up period: If your longest indicator is a 50-period moving average, fetch at least 100–200 candles so every calculation stabilizes properly.
Tiny Hands-On Exercise: Add a new function add_macd(series) to indicators.py that computes the MACD Line (EMA(12) - EMA(26)) and the Signal Line (EMA(9) of the MACD Line), then print both columns for the latest 5 candles.