DEV Community

ayushman4you-ctrl
ayushman4you-ctrl

Posted on Edited on

CPR Calculation Formula in Python: Building a Narrow CPR Breakout Scanner with Pandas

Most intraday breakout strategies fail because traders enter breakouts on wide-range, choppy days. Central Pivot Range (CPR) solves this by measuring the previous session's price compression before the market opens.

When the distance between Top Central (TC) and Bottom Central (BC) compresses below 0.25% of the Pivot price, it signals an impending volatility expansion (a Narrow CPR session).

The CPR Calculation Formula

Using the previous trading day's High, Low, and Close:

  • Pivot (P) = (High + Low + Close) / 3
  • Bottom Central (BC) = (High + Low) / 2
  • Top Central (TC) = (Pivot - BC) + Pivot
  • CPR Width % = (|TC - BC| / Pivot) * 100

Vectorized Python Implementation


python
import pandas as pd
import numpy as np

def calculate_cpr(df, narrow_threshold_pct=0.25):
    df = df.copy()
    prev_h = df['High'].shift(1)
    prev_l = df['Low'].shift(1)
    prev_c = df['Close'].shift(1)

    df['Pivot'] = (prev_h + prev_l + prev_c) / 3.0
    df['BC'] = (prev_h + prev_l) / 2.0
    df['TC'] = (df['Pivot'] - df['BC']) + df['Pivot']

    df['CPR_Width_Pct'] = (((df['TC'] - df['BC']).abs() / df['Pivot']) * 100.0).round(3)
    df['Narrow_CPR'] = np.where(df['CPR_Width_Pct'] < narrow_threshold_pct, 1, 0)
    return df
Why abs(TC - BC) Matters
On days when the previous session closed near its highs (Close > (High + Low)/2), TC sits above Pivot and BC sits below Pivot. On weak closes, TC and BC invert—so taking the absolute difference ensures CPR_Width_Pct is always positive.

Copy-Paste Script & Formula Guide: CPR Calculation Formula in Python — PyQuant Library

Complete 126+ Python Quant & Credit Risk Scripts Bundle: Download on Gumroad
Enter fullscreen mode Exit fullscreen mode

Top comments (0)