Bollinger Bands and Moving Averages in Python with pandas

Compute and plot Bollinger Bands, simple and exponential moving averages, %B and band width from a price series with pandas rolling() and ewm().

To plot Bollinger Bands in Python, compute a 20-day rolling mean with price.rolling(20).mean(), a rolling standard deviation with price.rolling(20).std(ddof=0), and draw the mean plus and minus two standard deviations with Matplotlib's ax.fill_between(). pandas does the whole calculation in four lines. For moving averages alone, see Rolling Average Plot in Pandas. For candles under the bands, add the bands with make_addplot as shown in Candlestick Charts in Python with mplfinance.

Quick Example

The prices are simulated (300 trading days) with a calm stretch followed by a volatile one, so you can see the bands widen and narrow. Swap price for your own closing-price Series with a DatetimeIndex.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(21)
dates = pd.bdate_range("2025-07-01", periods=300, name="Date")
daily_vol = np.where((np.arange(300) // 75) % 2 == 0, 0.009, 0.020)  # calm, then volatile
price = pd.Series(120 * np.exp(np.cumsum(rng.normal(0.0004, daily_vol))), index=dates, name="Close")

window = 20
middle = price.rolling(window).mean()
std = price.rolling(window).std(ddof=0)
upper = middle + 2 * std
lower = middle - 2 * std

fig, ax = plt.subplots(figsize=(10, 5.5))
ax.fill_between(price.index, lower, upper, color="#9bb7d4", alpha=0.35, label="Bollinger Bands (20, 2)")
ax.plot(middle, color="#1d4e89", lw=1.2, label="20-day SMA")
ax.plot(price, color="#222222", lw=1.1, label="Close")
ax.set_ylabel("Price (USD)")
ax.legend(loc="upper left")
plt.show()

Line chart of a simulated stock price with a shaded Bollinger Band around its 20 day moving average, narrow at first and wider in volatile stretches

The shaded band is the middle line plus and minus two standard deviations of the last 20 closes. It is narrow when prices have been steady and wide when they swing. The first 19 rows are NaN because a 20-day window is not full yet, so the bands start on the 20th day.

Why std(ddof=0)?

pandas' rolling().std() divides by n - 1 (ddof=1, the sample standard deviation). Bollinger's own definition uses the population standard deviation (ddof=0), which is what charting platforms use. With a 20-day window the sample version is wider by a factor of sqrt(20/19), about 2.6%:

sample = price.rolling(window).std()          # ddof=1, the pandas default
print(f"ratio: {(sample / std).iloc[-1]:.4f}")
print(f"upper band today: {upper.iloc[-1]:.2f} (ddof=0) vs {(middle + 2 * sample).iloc[-1]:.2f} (ddof=1)")
ratio: 1.0260
upper band today: 89.56 (ddof=0) vs 89.70 (ddof=1)

Use ddof=0 if you want your bands to match a trading platform or a textbook.

SMA vs EMA: which moving average should I plot?

A simple moving average (SMA) weights every day in the window equally. An exponential moving average (EMA) weights recent days more, so it turns sooner. In pandas the EMA is ewm(span=N, adjust=False).mean():

sma = price.rolling(20).mean()
ema = price.ewm(span=20, adjust=False).mean()
sma_50 = price.rolling(50).mean()

fig, ax = plt.subplots(figsize=(10, 5.5))
ax.plot(price, color="#bbbbbb", lw=1, label="Close")
ax.plot(sma, color="#1d4e89", lw=1.6, label="20-day SMA")
ax.plot(ema, color="#e07a1f", lw=1.6, label="20-day EMA")
ax.plot(sma_50, color="#2a7f62", lw=1.6, ls="--", label="50-day SMA")
ax.set_ylabel("Price (USD)")
ax.legend(loc="upper left")
plt.show()

Line chart of the price with 20 day SMA, 20 day EMA and 50 day SMA lines; the EMA sits closer to the price than the SMA

On average the EMA is 2.56 away from the close, the 20-day SMA 3.04 and the 50-day SMA 5.40, so the EMA stays closest and the 50-day line lags the most. Longer windows smooth more but react later, and no window avoids the trade-off. span=20 gives the EMA the same "center of mass" as roughly a 20-day window. With adjust=False the EMA starts at the first price, so there is no NaN warm-up; pass min_periods=20 to ewm() if you want the same blank start as the SMA.

How do I add %B and band width?

Two numbers summarize where the price sits in the bands. %B is (price - lower) / (upper - lower): 0 at the lower band, 1 at the upper band, above 1 when the close is outside it. Band width is (upper - lower) / middle, which measures how wide the bands are relative to price. Both fit in panels under the price chart:

pct_b = (price - lower) / (upper - lower)
width = (upper - lower) / middle

fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharex=True,
                                    gridspec_kw={"height_ratios": [3, 1, 1]})
ax1.fill_between(price.index, lower, upper, color="#9bb7d4", alpha=0.35)
ax1.plot(middle, color="#1d4e89", lw=1.2)
ax1.plot(price, color="#222222", lw=1.1)
ax1.set_ylabel("Price (USD)")

ax2.plot(pct_b, color="#1d4e89", lw=1)
ax2.axhline(1, color="#c0392b", lw=0.8, ls="--")
ax2.axhline(0, color="#c0392b", lw=0.8, ls="--")
ax2.set_ylabel("%B")

ax3.plot(width, color="#2a7f62", lw=1)
ax3.set_ylabel("Band width")
plt.show()

Three stacked panels: price with Bollinger Bands, the percent B indicator oscillating between 0 and 1, and band width rising during volatile stretches

The bottom panel makes the volatility regimes visible. Band width averages 0.051 in the first calm 75 days, 0.136 in the next volatile 75, 0.058 in the following calm stretch and 0.115 in the last volatile one. The narrowest it gets is 0.017 on February 27, 2026, and the widest is 0.272 on January 16, 2026. %B stays between 0 and 1 on 87% of the days that have bands, and peaks at 1.37, so the price closed well above the upper band at least once.

A narrow band means the market has been quiet, not that a move is coming. It is a description of the last 20 days.

How do I mark the days the price leaves the bands?

Use a boolean mask and ax.scatter():

above = price[price > upper]
below = price[price < lower]

fig, ax = plt.subplots(figsize=(10, 5.5))
ax.fill_between(price.index, lower, upper, color="#9bb7d4", alpha=0.35)
ax.plot(price, color="#222222", lw=1.1)
ax.scatter(above.index, above, color="#c0392b", s=28, zorder=3, label=f"Close above upper ({len(above)})")
ax.scatter(below.index, below, color="#2a7f62", s=28, zorder=3, label=f"Close below lower ({len(below)})")
ax.set_ylabel("Price (USD)")
ax.legend(loc="upper left")
plt.show()

Price chart with Bollinger Bands, red dots where the close is above the upper band and green dots where it is below the lower band

Across the 281 days that have bands, 14 closes were above the upper band and 23 below the lower band. They cluster. Six of the 14 upper-band closes come on six straight days, October 24 to 31, 2025, while the price kept climbing to its high of about 141. This is why a close outside the band is not a sell signal on its own: in a strong move the price stays outside, and the band catches up.

Which settings should I use?

Setting Common value Effect of raising it
Window 20 days Smoother middle line, bands react later
Number of standard deviations 2 Wider bands, fewer touches
Average type SMA An EMA middle line follows price more closely
ddof 0 1 makes the bands about 2.6% wider at a 20-day window

Bollinger's own suggestions are to use more standard deviations with longer windows (for example 2.1 at 50 days), and fewer with shorter ones.

Practical Tips

  • A touch of the band is not a signal by itself. In a trend, prices can ride the upper band for weeks. Combine the bands with a trend or momentum filter before acting on them.
  • Compute bands on adjusted close for real stocks, otherwise splits and dividends create fake jumps in the rolling statistics.
  • Use min_periods in rolling() if you want bands to start earlier on a short history. Early values come from fewer observations, so they are noisier.
  • Keep the bands and the price on the same axis. Plotting the bands on a secondary axis makes the touches meaningless.
  • For interactive hover, build the same three lines as traces in Plotly, see Interactive Candlestick Charts in Plotly.

Similar Topics