Bollinger Bands in Python: calculate, check and plot


Bollinger Bands are one of the first indicators people code themselves, and one of the easiest to get slightly wrong. The formula fits on one line, but most Python snippets use pandas’ default standard deviation, and that makes the bands too wide on every single candle.

This tutorial does it properly. You’ll calculate Bollinger Bands in pandas, check every value against the TAAPI.IO Bollinger Bands API, plot them with mplfinance, and then scan six coins for a squeeze with %B and band width. All code is copy-paste ready, and every output below is from a real run on 1 December 2026.

What are Bollinger Bands?

Bollinger Bands are three lines drawn around price:

  • Middle band: the simple moving average of the last 20 closes
  • Upper band: the middle band plus 2 standard deviations of those 20 closes
  • Lower band: the middle band minus 2 standard deviations

When prices swing a lot, the standard deviation grows and the bands move apart. When prices go quiet, the bands close in. That makes them two tools in one: they show whether price is high or low relative to its recent range, and whether volatility is expanding or contracting. The 20 and 2 are John Bollinger’s defaults and what almost every charting platform uses.

What you need

  • Python 3.9 or newer, and three packages: pip install requests pandas mplfinance
  • A TAAPI.IO API key, saved in an environment variable so it never ends up in your code:
export TAAPI_KEY_V2="your_api_key"

Everything here runs on the Basic plan: it uses 50 candles of history and at most six requests a minute (Basic allows 20). US stocks, at the end of Step 3, need the Pro plan. Both plans come with a 7-day free trial.

Step 1: Calculate Bollinger Bands in pandas

First, get 50 closed daily candles for BTCUSDT from the candles endpoint. The call() helper retries on 202 (data still being fetched) and 429 (rate limit), so the scripts below don’t fail on a busy minute:

import os
import time

import pandas as pd
import requests

API_URL = 'https://v2.taapi.io'
API_KEY = os.environ.get('TAAPI_KEY_V2')


def call(method, path, **kwargs):
    """Send a request, wait and retry on 202 (queued) and 429 (rate limit)."""
    for _ in range(5):
        r = requests.request(method, f'{API_URL}{path}', timeout=30,
                             headers={'Authorization': f'Bearer {API_KEY}'}, **kwargs)
        if r.status_code == 202:
            time.sleep(2)
        elif r.status_code == 429:
            time.sleep(r.json().get('retryAfter', 15))
        else:
            r.raise_for_status()
            return r.json()
    raise RuntimeError(f'{path}: no result after 5 attempts')


candles = call('GET', '/candles', params={
    'exchange': 'binance', 'symbol': 'BTCUSDT', 'timeframe': '1d',
    'results': 50, 'backtrack': 1,
})
df = pd.DataFrame(candles)
df.index = pd.to_datetime(df['timestamp'], unit='s')

backtrack=1 skips today’s candle, which is still forming, so you only work with closed candles. Now the bands. This is the whole calculation:

close = df['close']
df['middle'] = close.rolling(20).mean()
std = close.rolling(20).std(ddof=0)
df['upper'] = df['middle'] + 2 * std
df['lower'] = df['middle'] - 2 * std

print(df[['close', 'upper', 'middle', 'lower']].tail(3).round(2))

When we ran it:

               close     upper    middle     lower
timestamp                                         
2026-11-28  59373.34  74836.91  64460.64  54084.37
2026-11-29  60013.02  72937.85  63692.87  54447.89
2026-11-30  59612.76  71130.64  62983.71  54836.77

The mistake in most Bollinger Bands code: ddof

Look at std(ddof=0). Bollinger Bands use the population standard deviation: divide by 20, the number of closes. pandas’ .std() defaults to the sample standard deviation, ddof=1, which divides by 19. Leave it out and every band comes out 2.6% too far from the middle (the square root of 20/19). On the same data:

wrong = close.rolling(20).std()          # pandas default: ddof=1
print(f"ddof=1 upper band: {df['middle'].iloc[-1] + 2 * wrong.iloc[-1]:,.2f}")
ddof=1 upper band: 71,342.28

That’s 211.64 above the correct 71,130.64, and the lower band is too low by the same amount. Small enough to look right on a chart, big enough to fire a “close outside the band” signal that no charting platform would show you.

Step 2: Check your bands against the API

The Bollinger Bands endpoint returns the same three bands for every candle you ask for. One request with the same results and backtrack:

bb = call('GET', '/indicator/bbands', params={
    'exchange': 'binance', 'symbol': 'BTCUSDT', 'timeframe': '1d',
    'results': 50, 'backtrack': 1,
})
api = pd.DataFrame({'upper': bb['valueUpperBand'], 'middle': bb['valueMiddleBand'],
                    'lower': bb['valueLowerBand']},
                   index=pd.to_datetime(bb['timestamp'], unit='s'))

diff = (df[['upper', 'middle', 'lower']] - api).abs().max().max()
print(f'API returned {len(api)} sets of bands, pandas {df["upper"].notna().sum()}')
print(f'Largest difference where both have a value: {diff:.8f}')
API returned 50 sets of bands, pandas 31
Largest difference where both have a value: 0.00000003

With ddof=0 your bands match the API to seven decimal places, so the formula is right. The first line shows the one thing pandas can’t do with these 50 candles: a 20-period window needs 19 earlier closes, so the first 19 rows are NaN and you get bands for only 31 days. The API calculates on the full history, so all 50 candles have bands. That’s why the rest of this tutorial uses the API’s values, and why you’d only need your own pandas version for something the API doesn’t offer.

This is the response from that request, shortened to the last value of each array:

{
  "valueUpperBand": [71130.63675249177],
  "valueMiddleBand": [62983.70550000016],
  "valueLowerBand": [54836.77424750853],
  "timestamp": [1795996800]
}

The arrays are ordered oldest first, like the candles, and the timestamps line up with them one for one.

Step 3: Plot Bollinger Bands with mplfinance

mplfinance draws the candles, make_addplot adds the three bands, and fill_between shades the space between the outer two. A second panel shows the band width, the number that tells you when a squeeze is building:

import mplfinance as mpf

bands = api.reindex(df.index)
bands['width'] = (bands['upper'] - bands['lower']) / bands['middle'] * 100

lines = [
    mpf.make_addplot(bands['upper'], color='#7c3aed', width=1),
    mpf.make_addplot(bands['middle'], color='#f59e0b', width=1, linestyle='--'),
    mpf.make_addplot(bands['lower'], color='#7c3aed', width=1),
    mpf.make_addplot(bands['width'], panel=1, color='#7c3aed', ylabel='Width %'),
]
mpf.plot(df[['open', 'high', 'low', 'close', 'volume']], type='candle', style='yahoo',
         addplot=lines, panel_ratios=(3, 1),
         fill_between=dict(y1=bands['lower'].values, y2=bands['upper'].values,
                           alpha=0.08, color='#7c3aed'),
         savefig='btcusdt-1d-bbands.png')

This is the chart from our run, drawn from the same 50 candles and bands:

BTCUSDT daily candles from Binance with Bollinger Bands 20, 2 and band width, 12 October to 30 November 2026 On 27 October the bands narrowed to 5.14% of price, the narrowest in the 50 days shown. Two days later Bitcoin closed at 77,992, below the lower band. It closed below the lower band seven times in the following weeks and above the middle band only once, on 4 November. The band width peaked at 38.12% on 23 November and has narrowed to 25.87% since. 55k 60k 65k 70k 75k 80k 85k 90k 0% 20% 40% Band width, % of the middle band 15 Oct 1 Nov 15 Nov 27 Oct: 5.14%, the narrowest of the 50 days 23 Nov: 38.12% Squeeze, then a close below the lower band on 29 Oct. 7 closes below it since, 1 above the middle band (4 Nov) Outer bands Middle (SMA 20) Close below band Band width BTCUSDT · Binance 1d candles · Bollinger Bands 20, 2 · 12 Oct – 30 Nov 2026 (closed candles)
Top: daily candles with Bollinger Bands 20, 2 from the API. The shaded area is between the upper and lower bands, and the dashed line is the middle band. Red circles mark closes below the lower band. Bottom: the band width as a percentage of the middle band.

How to read it: For most of October Bitcoin traded between 80,000 and 85,000, and the bands kept closing in. On 27 October they were just 5.14% of price apart, the narrowest in the 50 days shown. That’s a squeeze: low volatility, which rarely lasts. Two days later, on 29 October, BTC closed at 77,992, below the lower band at 79,000, and the squeeze turned into a downtrend. In the weeks that followed it closed below the lower band seven times and above the middle band only once, on 4 November, while the bands widened to 38.12% on 23 November. This is what John Bollinger calls walking the band: in a strong trend, closes outside a band are a sign of strength in that direction, not a reversal signal. Since late November the bands have been narrowing again as price moves sideways around 60,000.

Step 4: %B and band width, the two numbers to code against

John Bollinger defined two measures that turn the bands into numbers you can compare across coins and timeframes:

Measure Calculation Reading
%B (close − lower) ÷ (upper − lower) 1 = on the upper band, 0 = on the lower band, below 0 = closed under it
Band width (upper − lower) ÷ middle × 100 Low compared with its own history = squeeze

On 29 October, BTC’s %B was −0.19: the close was 19% of the band’s height below the lower band. The full script prints both for the last candle. To scan a list of coins, you need one request per symbol: a /bulk call that returns 50 sets of bands and the last close together. Basic allows one symbol per bulk request, so this loop makes six requests, well inside the Basic rate limit. Pro allows 3 symbols per request and Expert 10, so there the scan needs fewer requests.

SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'XRPUSDT', 'BNBUSDT', 'DOGEUSDT']

print(f'{"Symbol":<10}{"Close":>12}{"%B":>7}{"Width":>9}{"Rank":>7}')
for symbol in SYMBOLS:
    body = {'constructs': [{
        'id': 'scan', 'exchange': 'binance', 'symbol': symbol, 'timeframe': '1d',
        'indicators': [
            {'id': 'bb', 'indicator': 'bbands', 'results': 50, 'backtrack': 1},
            {'id': 'price', 'indicator': 'price', 'backtrack': 1},
        ],
    }]}
    data = call('POST', '/bulk', json=body)['scan']
    bb, close = data['bb'], data['price']['value'][-1]

    widths = [(u - l) / m * 100 for u, m, l in
              zip(bb['valueUpperBand'], bb['valueMiddleBand'], bb['valueLowerBand'])]
    upper, lower = bb['valueUpperBand'][-1], bb['valueLowerBand'][-1]
    pct_b = (close - lower) / (upper - lower)
    rank = sum(w < widths[-1] for w in widths[:-1]) + 1    # 1 = narrowest of the 50

    flag = '  <- squeeze' if rank <= 5 else ''
    print(f'{symbol:<10}{close:>12,.6g}{pct_b:>7.2f}{widths[-1]:>8.2f}%{rank:>4}/50{flag}')

It uses the call() helper from Step 1. When we ran it on 1 December 2026:

Symbol           Close     %B    Width   Rank
BTCUSDT       59,612.8   0.29   25.87%  36/50
ETHUSDT       1,665.49   0.30   27.05%  34/50
SOLUSDT          72.57   0.47   20.72%  17/50
XRPUSDT          0.943   0.40   15.71%  14/50
BNBUSDT         554.72   0.34   25.66%  36/50
DOGEUSDT       0.05933   0.55   24.34%  26/50

Rank compares the latest band width with the 50 days before it: 1 means the narrowest, 50 the widest. Nothing is in a squeeze today. Volatility is still high after the November sell-off, and every coin closed in the lower half of its bands (%B below 0.5), except DOGE, just above the middle. XRP and SOL have the calmest bands of the six, so they’re the ones to watch if the market goes quiet. Run the scan each day, after the daily close at 00:00 UTC, and a coin whose rank drops to 5 or lower gets flagged.

A squeeze tells you a move is likely, not which way it will go. The Bollinger Bands API page shows how to detect the breakout itself: the first close outside a band right after a squeeze.

The full script

Steps 2 to 4 in one file, for one symbol: it fetches candles and bands, saves the chart and prints the latest values. Save it as bollinger_bands.py, set TAAPI_KEY_V2, and run it:

import os
import sys
import time

import mplfinance as mpf
import pandas as pd
import requests

API_URL = 'https://v2.taapi.io'
API_KEY = os.environ.get('TAAPI_KEY_V2')

EXCHANGE = sys.argv[1] if len(sys.argv) > 1 else 'binance'
SYMBOL = sys.argv[2] if len(sys.argv) > 2 else 'BTCUSDT'
TIMEFRAME = '1d'
RESULTS = 50                # candles to chart


def call(method, path, **kwargs):
    """Send a request, wait and retry on 202 (queued) and 429 (rate limit)."""
    for _ in range(5):
        r = requests.request(method, f'{API_URL}{path}', timeout=30,
                             headers={'Authorization': f'Bearer {API_KEY}'}, **kwargs)
        if r.status_code == 202:
            time.sleep(2)
        elif r.status_code == 429:
            time.sleep(r.json().get('retryAfter', 15))
        else:
            r.raise_for_status()
            return r.json()
    raise RuntimeError(f'{path}: no result after 5 attempts')


def fetch(path):
    return call('GET', path, params={
        'exchange': EXCHANGE, 'symbol': SYMBOL, 'timeframe': TIMEFRAME,
        'results': RESULTS, 'backtrack': 1,
    })


def main():
    if not API_KEY:
        sys.exit('Set the TAAPI_KEY_V2 environment variable to your TAAPI.IO API key.')

    try:
        candles = fetch('/candles')
        bb = fetch('/indicator/bbands')
    except (requests.RequestException, RuntimeError) as err:
        sys.exit(f'Request failed: {err}')

    df = pd.DataFrame(candles)
    df.index = pd.to_datetime(df['timestamp'], unit='s')
    df = df[['open', 'high', 'low', 'close', 'volume']]

    bands = pd.DataFrame({'upper': bb['valueUpperBand'], 'middle': bb['valueMiddleBand'],
                          'lower': bb['valueLowerBand']},
                         index=pd.to_datetime(bb['timestamp'], unit='s')).reindex(df.index)
    bands['width'] = (bands['upper'] - bands['lower']) / bands['middle'] * 100
    bands['pct_b'] = (df['close'] - bands['lower']) / (bands['upper'] - bands['lower'])

    lines = [
        mpf.make_addplot(bands['upper'], color='#7c3aed', width=1),
        mpf.make_addplot(bands['middle'], color='#f59e0b', width=1, linestyle='--'),
        mpf.make_addplot(bands['lower'], color='#7c3aed', width=1),
        mpf.make_addplot(bands['width'], panel=1, color='#7c3aed', ylabel='Width %'),
    ]
    filename = f'{SYMBOL.lower()}-{TIMEFRAME}-bbands.png'
    mpf.plot(df, type='candle', style='yahoo', addplot=lines,
             fill_between=dict(y1=bands['lower'].values, y2=bands['upper'].values,
                               alpha=0.08, color='#7c3aed'),
             title=f'{SYMBOL} {TIMEFRAME} ({EXCHANGE}) with Bollinger Bands 20, 2',
             ylabel='Price', panel_ratios=(3, 1), figsize=(11, 7),
             savefig=dict(fname=filename, dpi=150, bbox_inches='tight'))

    last, b = df.iloc[-1], bands.iloc[-1]
    narrowest = bands['width'].idxmin()
    print(f'{len(df)} candles, {df.index[0]:%Y-%m-%d} to {df.index[-1]:%Y-%m-%d}')
    print(f'Last close {last.close:,.2f}   upper {b.upper:,.2f}   '
          f'middle {b.middle:,.2f}   lower {b.lower:,.2f}')
    print(f'%B {b.pct_b:.2f}   width {b.width:.2f}%   '
          f'narrowest {bands["width"].min():.2f}% on {narrowest:%Y-%m-%d}')
    print(f'Chart saved to {filename}')


if __name__ == '__main__':
    main()

Run it with no arguments for BTCUSDT on Binance:

50 candles, 2026-10-12 to 2026-11-30
Last close 59,612.76   upper 71,130.64   middle 62,983.71   lower 54,836.77
%B 0.29   width 25.87%   narrowest 5.14% on 2026-10-27
Chart saved to btcusdt-1d-bbands.png

For a US stock, pass stocks and the ticker (Pro plan and above):

python bollinger_bands.py stocks AAPL
50 candles, 2026-09-21 to 2026-11-30
Last close 354.08   upper 365.21   middle 349.40   lower 333.60
%B 0.65   width 9.05%   narrowest 3.72% on 2026-10-09
Chart saved to aapl-1d-bbands.png

Stocks don’t trade at weekends, so 50 daily candles reach back to 21 September. Apple’s bands are much narrower than Bitcoin’s, 9.05% against 25.87%, which is why you compare band width with a symbol’s own history, as the scan does, and not across symbols.

A few ways to adapt it:

  • Another timeframe: set TIMEFRAME to 4h or 1h for intraday squeezes.
  • Other settings: the bands endpoint takes period (default 20) and stddev (default 2). A stddev of 2.5, for example, gives wider bands and fewer touches.
  • More history: raise RESULTS, up to the history your plan includes (50 candles on Basic, 300 on Pro).
  • Only the width: the Bollinger Bands Width endpoint returns band width directly.

Where to go from here

Ready to try it on your own symbols? Start for free with a 7-day trial on Basic or Pro. The examples are an illustration, not a backtest, and nothing here is financial advice.