MM Flow
FlowScripts

Perfected FlowScript

Put to Call Ratio

Put to Call Ratio V2 is indexed as 118_put_to_call_ratio.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

offchart

Axis

true

Size

13.7 KB

Lines

302

Native Signal Candidates

4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

4/4 guarded

Fear Regime

line 243:5

Trigger

(showShapes && crossFear)

Value

pcrZ

Deps

crossFear:var, showShapes:input

Greed Regime

line 253:5

Trigger

(showShapes && crossGreed)

Value

pcrZ

Deps

crossGreed:var, showShapes:input

Extreme Fear

line 265:5

Trigger

(showShapes && crossExtremeFear)

Value

pcrZ

Deps

crossExtremeFear:var, showShapes:input

Extreme Greed

line 275:5

Trigger

(showShapes && crossExtremeGreed)

Value

pcrZ

Deps

crossExtremeGreed:var, showShapes:input

118_put_to_call_ratio.flowscript

source path: kscripts/perfected/118_put_to_call_ratio.flowscript · sha256:d29127f618b97702a493ec59fa539a4cfc77305612e12194bd87de35b6439d1e

hash verified
//@version=2

// ============================================================================
// Put to Call Ratio V2 — Options Sentiment Gauge with Z-Score Normalization
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, FLOW, #options, #put, #call, #ratio, #sentiment
//
// Plots BTC options put-to-call ratio from configurable venues, with rolling
// z-score normalization, regime detection (fear / greed / neutral), and
// color-coded fills with shape markers for extreme readings. Extreme PCR
// levels flag contrarian opportunities per Zhu (2025) and Chan, Cheng &
// Lung (2004).
//
// Academic foundation (exact papers & formulas):
//  1. Zhu (2025), "The Put-Call Ratio as a Sentiment Indicator in Commodity
//     Markets". Uses Three-Stage Least Squares to confirm PCR as a robust
//     sentiment indicator during policy uncertainty. Extreme readings (>70%
//     put or call dominance) signal contrarian opportunities.
//
//  2. Chan, Cheng & Lung (2004), "Net Buying Pressure, Volatility Smile, and
//     Abnormal Profit of Hang Seng Index Options", Journal of Futures Markets,
//     24(12), 1165–1194. Net buying pressure on puts >> calls; PCR negatively
//     correlated with short-sale constraints. PCR outperforms VIX in explaining
//     S&P 500 variations unexplained by fundamentals.
//     DOI: https://doi.org/10.1002/fut.10140
//
//  3. Houlihan & Creamer (2019), "Does the Put-Call Ratio Predict Future
//     Returns?". PCR-based portfolios generate abnormal excess returns even
//     after Carhart four-factor adjustment. PCR has genuine predictive power.
//
//  4. Black & Scholes (1973), "The Pricing of Options and Corporate
//     Liabilities", Journal of Political Economy, 81(3), 637–654.
//     [Formula] ∂C/∂t + ½σ²S²∂²C/∂S² + rS∂C/∂S − rC = 0.
//     Puts and calls are symmetric derivatives around the forward price;
//     deviations from parity signal sentiment asymmetry.
//     DOI: https://doi.org/10.1086/260062
//
//  5. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//     Stock Returns", Journal of Finance, 61(4), 1645–1680. Composite sentiment
//     indices (of which PCR is a primary component) predict returns of
//     sentiment-sensitive stocks; extreme sentiment → contrarian profits.
//     DOI: https://doi.org/10.1111/j.1540-6261.2006.01885.x
//
//  6. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
//     in a High-Frequency World", Journal of Portfolio Management, 38(3), 1–14.
//     VPIN = Σ|V_buy − V_sell| / ΣV_total; informed trading probability.
//     Informed options flow often shows up as extreme PCR before spot moves.
// ============================================================================

define(
    title="Put to Call Ratio V2",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Data Sources --
var putSymbol = input(name="putSymbol", type="string", defaultValue="BTC-PERPETUAL", label="Put Symbol / Proxy", group="Data Sources")
var putExch = input(name="putExch", type="string", defaultValue="DERIBIT", label="Put Exchange", group="Data Sources")
var callSymbol = input(name="callSymbol", type="string", defaultValue="BTC", label="Call Symbol / Proxy", group="Data Sources")
var callExch = input(name="callExch", type="string", defaultValue="DERIBIT", label="Call Exchange", group="Data Sources")
var useVolume = input(name="useVolume", type="boolean", defaultValue=true, label="Prefer Volume over OI", group="Data Sources")

// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="PCR EMA Smooth Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Computation")
var normLookback = input(name="normLookback", type="number", defaultValue=168, label="Normalization Lookback", constraints={min: 20, max: 500, step: 10}, group="Computation")
var fearThresh = input(name="fearThresh", type="number", defaultValue=2.0, label="Fear Regime Z-Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var greedThresh = input(name="greedThresh", type="number", defaultValue=2.0, label="Greed Regime Z-Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeFear = input(name="extremeFear", type="number", defaultValue=3.0, label="Extreme Fear Z-Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")
var extremeGreed = input(name="extremeGreed", type="number", defaultValue=3.0, label="Extreme Greed Z-Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")

// -- Display --
var showPCR = input(name="showPCR", type="boolean", defaultValue=true, label="Show PCR Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Show Raw PCR (unsmoothed)", group="Display")

// -- Colors --
var pcrColor = input(name="pcrColor", type="color", defaultValue="#ab47bc", label="PCR Line Color", group="Colors")
var fearColor = input(name="fearColor", type="color", defaultValue="#ef5350", label="Fear Color", group="Colors")
var greedColor = input(name="greedColor", type="color", defaultValue="#26a69a", label="Greed Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var extremeFearColor = input(name="extremeFearColor", type="color", defaultValue="#ff1744", label="Extreme Fear Color", group="Colors")
var extremeGreedColor = input(name="extremeGreedColor", type="color", defaultValue="#00e676", label="Extreme Greed Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard and volume/OI fallback chain
// ---------------------------------------------------------------------------

// Attempt to fetch taker volume (preferred for PCR) per Lee-Ready (1991) flow logic.
// If unavailable, fall back to open_interest close as a positioning proxy.
// Note: true options PCR requires put/call volume data; configure symbols to
// match your exchange's options instrument names (e.g., BTC-24MAR23-24000-P).
timeseries putTaker = source("taker_volume", putSymbol, putExch)
timeseries callTaker = source("taker_volume", callSymbol, callExch)

timeseries putOI = open_interest(symbol=putSymbol, exchange=putExch)
timeseries callOI = open_interest(symbol=callSymbol, exchange=callExch)

// Volume proxy: taker.buy + taker.sell when available; otherwise OI.close
timeseries putVol = (isnum(putTaker.buy) && isnum(putTaker.sell))
    ? (putTaker.buy + putTaker.sell)
    : (useVolume ? putOI.close : putOI.close)

timeseries callVol = (isnum(callTaker.buy) && isnum(callTaker.sell))
    ? (callTaker.buy + callTaker.sell)
    : (useVolume ? callOI.close : callOI.close)

// Guard: halt until data feeds have loaded to avoid NaN propagation
if (isnan(putVol[0]) || isnan(callVol[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Put/Call Ratio (PCR) with zero-division guard --
// PCR = Put Volume / Call Volume; > 1 → put dominance (fear/hedging);
// < 1 → call dominance (greed/speculation). Per Zhu (2025), extreme PCR
// readings (> 70% put or call dominance) signal contrarian opportunities.
timeseries pcrRaw = putVol / max(callVol, 1e-9)

// -- 3.2 Smoothing (EMA per Baker & Wurgler 2006 noise-reduction) --
timeseries pcrSmooth = ema(pcrRaw, smoothLen)

// -- 3.3 Normalization around zero using rolling mean as anchor --
// Captures demand-pressure asymmetry per Chan, Cheng & Lung (2004).
timeseries normMean = sma(pcrSmooth, normLookback)
timeseries pcrNorm = pcrSmooth - normMean

// -- 3.4 Z-score standardisation (guarded against zero std) --
// Z_t = (PCR_t − μ_t) / σ_t per Zhao & Palomar (2018) mean-reversion framework.
timeseries pcrStd = stdev(pcrSmooth, normLookback)
timeseries pcrZ = (pcrStd > 0) ? (pcrSmooth - normMean) / pcrStd : 0

// -- 3.5 Regime detection (configurable thresholds, no magic numbers) --
// Fear = high PCR (puts dominant); Greed = low PCR (calls dominant).
// Maps to Baker & Wurgler (2006) sentiment regime segmentation.
var fearRegime = pcrZ > fearThresh
var greedRegime = pcrZ < -greedThresh
var extremeFearRegime = pcrZ > extremeFear
var extremeGreedRegime = pcrZ < -extremeGreed
var neutralRegime = !fearRegime && !greedRegime

// -- 3.6 Extreme crossing detection (shape triggers) --
var crossFear = pcrZ >= fearThresh && !isnan(pcrZ[1]) && pcrZ[1] < fearThresh
var crossGreed = pcrZ <= -greedThresh && !isnan(pcrZ[1]) && pcrZ[1] > -greedThresh
var crossExtremeFear = pcrZ >= extremeFear && !isnan(pcrZ[1]) && pcrZ[1] < extremeFear
var crossExtremeGreed = pcrZ <= -extremeGreed && !isnan(pcrZ[1]) && pcrZ[1] > -extremeGreed

// -- 3.7 Static state tracking (session-level persistence) --
// Tracks PCR extremes, regime durations, and extreme-event counts for
// context-aware alerting per Houlihan & Creamer (2019) portfolio framework.
static sessionPCRHi = -999999.0
static sessionPCRLo = 999999.0
static fearBarCount = 0
static greedBarCount = 0
static extremeFearCount = 0
static extremeGreedCount = 0
static lastBarIdx = 0

var currentBarIdx = bar_index[0]
if (!isnan(currentBarIdx) && currentBarIdx != lastBarIdx) {
    lastBarIdx = currentBarIdx

    if (pcrZ > sessionPCRHi) {
        sessionPCRHi = pcrZ
    }
    if (pcrZ < sessionPCRLo) {
        sessionPCRLo = pcrZ
    }

    if (fearRegime) {
        fearBarCount = fearBarCount + 1
    } else {
        fearBarCount = 0
    }
    if (greedRegime) {
        greedBarCount = greedBarCount + 1
    } else {
        greedBarCount = 0
    }

    if (extremeFearRegime) {
        extremeFearCount = extremeFearCount + 1
    }
    if (extremeGreedRegime) {
        extremeGreedCount = extremeGreedCount + 1
    }
}

// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Normalized PCR line (plotLine)
if (showPCR) {
    plotLine(
        value=pcrNorm,
        width=2,
        colors=[pcrColor],
        label=["PCR Normalized"],
        desc=["Put/Call Ratio centred at rolling mean; positive = put dominance (fear), negative = call dominance (greed)"]
    )
}

// 4.2 Z-Score line with regime-coded fill (plotLine + fill)
// colorIndex maps: 0 = fear, 1 = greed, 2 = neutral
timeseries regimeColorIdx = fearRegime ? 0 : (greedRegime ? 1 : 2)
if (showZScore) {
    plotLine(
        value=([pcrZ, zeroLine]),
        width=2,
        colors=[fearColor, greedColor, neutralColor],
        colorIndex=regimeColorIdx,
        label=["PCR Z-Score"],
        desc=["Z-score of PCR; filled histogram colour-coded by sentiment regime per Baker & Wurgler (2006)"],
        fill=true
    )
}

// 4.3 PCR histogram bars (plotBar)
if (showHistogram) {
    plotBar(
        value=pcrZ,
        colors=[fearColor, greedColor],
        label=["PCR Bars"],
        desc=["PCR z-score bars; positive = fear/put-heavy, negative = greed/call-heavy"]
    )
}

// 4.4 Regime crossing shapes (plotShape)
if (showShapes && crossFear) {
    plotShape(
        value=pcrZ,
        shape="triangledown",
        color=extremeFearColor,
        width=3,
        label=["Fear Regime"],
        desc=["PCR entered fear regime (put dominance); hedging pressure rising — contrarian long opportunity per Zhu (2025)"]
    )
}
if (showShapes && crossGreed) {
    plotShape(
        value=pcrZ,
        shape="triangleup",
        color=extremeGreedColor,
        width=3,
        label=["Greed Regime"],
        desc=["PCR entered greed regime (call dominance); speculative euphoria — contrarian short opportunity per Zhu (2025)"]
    )
}

// 4.5 Extreme regime shapes (plotShape)
if (showShapes && crossExtremeFear) {
    plotShape(
        value=pcrZ,
        shape="diamond",
        color=extremeFearColor,
        width=4,
        label=["Extreme Fear"],
        desc=["Extreme fear detected — put volume massively dominant; panic selling / hedging climax"]
    )
}
if (showShapes && crossExtremeGreed) {
    plotShape(
        value=pcrZ,
        shape="diamond",
        color=extremeGreedColor,
        width=4,
        label=["Extreme Greed"],
        desc=["Extreme greed detected — call volume massively dominant; speculative climax / FOMO peak"]
    )
}

// 4.6 Optional raw PCR (unsmoothed) for reference
if (showRaw) {
    plotLine(
        value=pcrRaw,
        width=1,
        colors=[opacity(pcrColor, 50)],
        label=["PCR Raw"],
        desc=["Unsmoothed put/call ratio; noisy but shows true market state"]
    )
}

// 4.7 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=fearThresh, color=opacity(fearColor, 30), width=1)
hline(value=-greedThresh, color=opacity(greedColor, 30), width=1)
hline(value=extremeFear, color=opacity(extremeFearColor, 20), width=1)
hline(value=-extremeGreed, color=opacity(extremeGreedColor, 20), width=1)