Perfected FlowScript
SCF ACF Heatmap
SCF ACF Heatmap — Perfected Edition is indexed as 090_scf_acf_heatmap.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
18.7 KB
Lines
432
Native Signal Candidates
7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Sig lag 1
line 318:9
Trigger
(showSignificance) && (sig1)
Value
acf1
Deps
showSignificance:input, sig1:var
Sig lag 2
line 328:9
Trigger
(showSignificance) && (sig2)
Value
acf2
Deps
showSignificance:input, sig2:var
Sig lag 3
line 338:9
Trigger
(showSignificance) && (sig3)
Value
acf3
Deps
showSignificance:input, sig3:var
Sig lag 5
line 348:9
Trigger
(showSignificance) && (sig5)
Value
acf5
Deps
showSignificance:input, sig5:var
Sig lag 8
line 358:9
Trigger
(showSignificance) && (sig8)
Value
acf8
Deps
showSignificance:input, sig8:var
Sig lag 13
line 368:9
Trigger
(showSignificance) && (sig13)
Value
acf13
Deps
showSignificance:input, sig13:var
Unlabeled shape
line 381:5
Trigger
(showRegimeLabel && isLastBar)
Value
acfComposite
Deps
isLastBar:builtin, showRegimeLabel:input
090_scf_acf_heatmap.flowscript
source path: kscripts/perfected/090_scf_acf_heatmap.flowscript · sha256:0e46c49bfc8a86d0ca79419f678d344885c4474678868903a9204a4138ff7cb7
//@version=2
// ============================================================================
// SCF ACF Heatmap — Perfected Edition
// Author: SoulzBTC (@SoulzBTC) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #acf, #autocorrelation, #heatmap, #momentum, #meanreversion
//
// Production-grade multi-lag autocorrelation heatmap for regime detection.
// Computes Pearson ACF across configurable lag set (1, 2, 3, 5, 8, 13)
// using rolling-window covariance / variance, with strength-based color coding,
// significance markers, and momentum / mean-reversion / random-walk regime
// classification.
//
// Academic foundations:
// 1. Lo & MacKinlay (1988), "Stock Market Prices Do Not Follow Random Walks"
// (Rev. Financial Studies, 1(1), 41–66). Variance ratio test: VR>1
// = positive autocorrelation (momentum); VR<1 = negative autocorrelation
// (mean reversion). Key formula: VR(q) = Var(q-period return) / [q × Var(1-period return)].
// 2. Lo & MacKinlay (1989), "The Size and Power of the Variance Ratio Test
// in Finite Samples." Heteroscedastic-robust z* statistic for VR inference.
// 3. Box & Jenkins (1970), "Time Series Analysis: Forecasting and Control."
// Canonical ACF framework: ρ(k) = Cov(r_t, r_{t-k}) / Var(r_t).
// 4. Poterba & Summers (1988), "Mean Reversion in Stock Prices" (J. Financial
// Economics, 22(1), 27–59). Negative autocorrelation at medium horizons
// validates mean-reversion regime identification.
// 5. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers."
// Positive autocorrelation at short horizons (momentum) documented.
// Key formula: J_K = Σ w_{i,t-K} · R_{i,t} where winner/loser portfolios
// are formed on past 3–12 month returns.
// 6. Fama & French (1988), "Permanent and Temporary Components of Stock Prices."
// Decomposes returns into random-walk and stationary components; ACF
// directly measures the stationary (mean-reverting) portion.
// ============================================================================
define(
title="SCF ACF Heatmap — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- Computation ---
var returnLen = input(name="returnLen", type="number", defaultValue=1, label="Return period (1=default)", constraints={min: 1, max: 20, step: 1}, group="Computation")
var acfWindow = input(name="acfWindow", type="number", defaultValue=50, label="ACF rolling window", constraints={min: 10, max: 200, step: 1}, group="Computation")
var useLog = input(name="useLog", type="boolean", defaultValue=true, label="Use log returns", group="Computation")
// --- Thresholds ---
var sigThreshold = input(name="sigThreshold", type="number", defaultValue=0.15, label="Significance threshold", constraints={min: 0.01, max: 0.5, step: 0.01}, group="Thresholds")
var strongThreshold = input(name="strongThreshold", type="number", defaultValue=0.3, label="Strong correlation threshold", constraints={min: 0.05, max: 0.8, step: 0.05}, group="Thresholds")
// --- Lag Toggles ---
var showLag1 = input(name="showLag1", type="boolean", defaultValue=true, label="Show lag 1", group="Lags")
var showLag2 = input(name="showLag2", type="boolean", defaultValue=true, label="Show lag 2", group="Lags")
var showLag3 = input(name="showLag3", type="boolean", defaultValue=true, label="Show lag 3", group="Lags")
var showLag5 = input(name="showLag5", type="boolean", defaultValue=true, label="Show lag 5", group="Lags")
var showLag8 = input(name="showLag8", type="boolean", defaultValue=true, label="Show lag 8", group="Lags")
var showLag13 = input(name="showLag13", type="boolean", defaultValue=true, label="Show lag 13", group="Lags")
// --- Display ---
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show composite ACF line", group="Display")
var showSignificance = input(name="showSignificance", type="boolean", defaultValue=true, label="Show significance markers", group="Display")
var showRegimeLabel = input(name="showRegimeLabel", type="boolean", defaultValue=true, label="Show regime label", group="Display")
var showEnv = input(name="showEnv", type="boolean", defaultValue=true, label="Show ACF envelope", group="Display")
// --- Colors ---
var strongPosColor = input(name="strongPosColor", type="color", defaultValue="#00e676", label="Strong positive color", group="Colors")
var weakPosColor = input(name="weakPosColor", type="color", defaultValue="#26a69a", label="Weak positive color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral color", group="Colors")
var weakNegColor = input(name="weakNegColor", type="color", defaultValue="#ef5350", label="Weak negative color", group="Colors")
var strongNegColor = input(name="strongNegColor", type="color", defaultValue="#ff1744", label="Strong negative color", group="Colors")
var compositeColor = input(name="compositeColor", type="color", defaultValue="#ffd700", label="Composite line color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvData.close
// isnan guard — prevents NaN propagation on startup
if (isnan(close[0]) || isnan(close[1])) {
return
}
// ---------------------------------------------------------------------------
// 3. RETURNS
// ---------------------------------------------------------------------------
// Log returns: ln(P_t / P_{t-1}) — more stable for variance-based statistics
// Simple returns: (P_t - P_{t-1}) / P_{t-1} — standard percentage return
var rRaw = close[1] > 0 ? (useLog ? math.log(close / close[1]) : (close - close[1]) / close[1]) : 0
// ---------------------------------------------------------------------------
// 4. ROLLING STATISTICS (base series)
// ---------------------------------------------------------------------------
// Rolling mean and variance of the return series used as the denominator
// for all lag autocorrelations. Stationarity assumption: Var(r_t) ≈ Var(r_{t-k}).
var mu0 = sma(source=rRaw, period=acfWindow)
var sd0 = stdev(source=rRaw, period=acfWindow)
var var0 = sd0 * sd0
// ---------------------------------------------------------------------------
// 5. AUTOCORRELATION PER LAG
// ---------------------------------------------------------------------------
// ACF(k) = Cov(r_t, r_{t-k}) / Var(r_t)
// Computed as rolling covariance between the current return series and the
// k-lagged series, normalized by the rolling variance of the base series.
// Lag 1
var r1 = rRaw[1]
var mu1 = sma(source=r1, period=acfWindow)
var cov1 = sma(source=(rRaw - mu0) * (r1 - mu1), period=acfWindow)
var acf1 = var0 > 0 ? cov1 / var0 : 0
// Lag 2
var r2 = rRaw[2]
var mu2 = sma(source=r2, period=acfWindow)
var cov2 = sma(source=(rRaw - mu0) * (r2 - mu2), period=acfWindow)
var acf2 = var0 > 0 ? cov2 / var0 : 0
// Lag 3
var r3 = rRaw[3]
var mu3 = sma(source=r3, period=acfWindow)
var cov3 = sma(source=(rRaw - mu0) * (r3 - mu3), period=acfWindow)
var acf3 = var0 > 0 ? cov3 / var0 : 0
// Lag 5
var r5 = rRaw[5]
var mu5 = sma(source=r5, period=acfWindow)
var cov5 = sma(source=(rRaw - mu0) * (r5 - mu5), period=acfWindow)
var acf5 = var0 > 0 ? cov5 / var0 : 0
// Lag 8
var r8 = rRaw[8]
var mu8 = sma(source=r8, period=acfWindow)
var cov8 = sma(source=(rRaw - mu0) * (r8 - mu8), period=acfWindow)
var acf8 = var0 > 0 ? cov8 / var0 : 0
// Lag 13
var r13 = rRaw[13]
var mu13 = sma(source=r13, period=acfWindow)
var cov13 = sma(source=(rRaw - mu0) * (r13 - mu13), period=acfWindow)
var acf13 = var0 > 0 ? cov13 / var0 : 0
// ---------------------------------------------------------------------------
// 6. COMPOSITE ACF
// ---------------------------------------------------------------------------
// Arithmetic mean across all active (visible) lags. Provides a single
// summary measure of autocorrelation structure.
var activeCount = 0
var acfSum = 0.0
if (showLag1) { acfSum = acfSum + acf1; activeCount = activeCount + 1 }
if (showLag2) { acfSum = acfSum + acf2; activeCount = activeCount + 1 }
if (showLag3) { acfSum = acfSum + acf3; activeCount = activeCount + 1 }
if (showLag5) { acfSum = acfSum + acf5; activeCount = activeCount + 1 }
if (showLag8) { acfSum = acfSum + acf8; activeCount = activeCount + 1 }
if (showLag13) { acfSum = acfSum + acf13; activeCount = activeCount + 1 }
var acfComposite = activeCount > 0 ? acfSum / activeCount : 0
// ---------------------------------------------------------------------------
// 7. REGIME DETECTION
// ---------------------------------------------------------------------------
// Momentum: positive composite ACF > threshold (Lo & MacKinlay 1988 VR>1)
// Mean-reversion: negative composite ACF < -threshold (Poterba & Summers 1988)
// Random-walk: |composite ACF| within threshold (Fama & French 1988)
var regimeMomentum = acfComposite > sigThreshold
var regimeMeanRev = acfComposite < -sigThreshold
var regimeRandom = !regimeMomentum && !regimeMeanRev
var regimeColor = regimeMomentum ? strongPosColor : (regimeMeanRev ? strongNegColor : neutralColor)
var regimeLabel = regimeMomentum ? "MOMENTUM" : (regimeMeanRev ? "MEAN-REVERSION" : "RANDOM-WALK")
// ---------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
static barCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
}
static lastRegime = 0 // 0=random, 1=momentum, -1=meanrev
static regimeDuration = 0
static maxComposite = 0.0
static minComposite = 0.0
if (!isLiveUpdate) {
var currentRegime = regimeMomentum ? 1 : (regimeMeanRev ? -1 : 0)
if (currentRegime == lastRegime) {
regimeDuration = regimeDuration + 1
} else {
regimeDuration = 1
}
lastRegime = currentRegime
if (acfComposite > maxComposite) {
maxComposite = acfComposite
}
if (acfComposite < minComposite) {
minComposite = acfComposite
}
}
// ---------------------------------------------------------------------------
// 9. SIGNIFICANCE FLAGS
// ---------------------------------------------------------------------------
// A lag is flagged as significant when its absolute ACF exceeds the
// significance threshold. Per Lo & MacKinlay (1989), heteroscedastic-robust
// inference is recommended for finite-sample ACF estimates.
var sig1 = math.abs(acf1) > sigThreshold
var sig2 = math.abs(acf2) > sigThreshold
var sig3 = math.abs(acf3) > sigThreshold
var sig5 = math.abs(acf5) > sigThreshold
var sig8 = math.abs(acf8) > sigThreshold
var sig13 = math.abs(acf13) > sigThreshold
// ---------------------------------------------------------------------------
// 10. COLOR CODING BY CORRELATION STRENGTH
// ---------------------------------------------------------------------------
// Five-tier color scheme:
// Strong positive (|acf| ≥ strongThreshold) → bright green
// Weak positive (sig ≤ |acf| < strong) → muted green
// Neutral (|acf| < sig) → gray
// Weak negative (sig ≤ |acf| < strong) → muted red
// Strong negative (|acf| ≥ strongThreshold) → bright red
var abs1 = math.abs(acf1)
var acfColor1 = abs1 < sigThreshold ? neutralColor : (abs1 < strongThreshold ? (acf1 > 0 ? weakPosColor : weakNegColor) : (acf1 > 0 ? strongPosColor : strongNegColor))
var abs2 = math.abs(acf2)
var acfColor2 = abs2 < sigThreshold ? neutralColor : (abs2 < strongThreshold ? (acf2 > 0 ? weakPosColor : weakNegColor) : (acf2 > 0 ? strongPosColor : strongNegColor))
var abs3 = math.abs(acf3)
var acfColor3 = abs3 < sigThreshold ? neutralColor : (abs3 < strongThreshold ? (acf3 > 0 ? weakPosColor : weakNegColor) : (acf3 > 0 ? strongPosColor : strongNegColor))
var abs5 = math.abs(acf5)
var acfColor5 = abs5 < sigThreshold ? neutralColor : (abs5 < strongThreshold ? (acf5 > 0 ? weakPosColor : weakNegColor) : (acf5 > 0 ? strongPosColor : strongNegColor))
var abs8 = math.abs(acf8)
var acfColor8 = abs8 < sigThreshold ? neutralColor : (abs8 < strongThreshold ? (acf8 > 0 ? weakPosColor : weakNegColor) : (acf8 > 0 ? strongPosColor : strongNegColor))
var abs13 = math.abs(acf13)
var acfColor13 = abs13 < sigThreshold ? neutralColor : (abs13 < strongThreshold ? (acf13 > 0 ? weakPosColor : weakNegColor) : (acf13 > 0 ? strongPosColor : strongNegColor))
// ---------------------------------------------------------------------------
// 11. PLOTTING
// ---------------------------------------------------------------------------
// --- Reference lines ---
hline(value=0, color="#ffffff", width=1)
hline(value=sigThreshold, color=transparency(strongPosColor, 60), width=1)
hline(value=-sigThreshold, color=transparency(strongNegColor, 60), width=1)
hline(value=strongThreshold, color=transparency(strongPosColor, 40), width=1)
hline(value=-strongThreshold, color=transparency(strongNegColor, 40), width=1)
// --- Lag bars (color-coded histogram) ---
if (showLag1) {
plotBar(value=acf1, colors=[acfColor1], width=2, label=["ACF lag 1"], desc=["Autocorrelation at lag 1: ρ(1) = Cov(r_t, r_{t-1}) / Var(r_t)"])
}
if (showLag2) {
plotBar(value=acf2, colors=[acfColor2], width=2, label=["ACF lag 2"], desc=["Autocorrelation at lag 2: ρ(2) = Cov(r_t, r_{t-2}) / Var(r_t)"])
}
if (showLag3) {
plotBar(value=acf3, colors=[acfColor3], width=2, label=["ACF lag 3"], desc=["Autocorrelation at lag 3: ρ(3) = Cov(r_t, r_{t-3}) / Var(r_t)"])
}
if (showLag5) {
plotBar(value=acf5, colors=[acfColor5], width=2, label=["ACF lag 5"], desc=["Autocorrelation at lag 5: ρ(5) = Cov(r_t, r_{t-5}) / Var(r_t)"])
}
if (showLag8) {
plotBar(value=acf8, colors=[acfColor8], width=2, label=["ACF lag 8"], desc=["Autocorrelation at lag 8: ρ(8) = Cov(r_t, r_{t-8}) / Var(r_t)"])
}
if (showLag13) {
plotBar(value=acf13, colors=[acfColor13], width=2, label=["ACF lag 13"], desc=["Autocorrelation at lag 13: ρ(13) = Cov(r_t, r_{t-13}) / Var(r_t)"])
}
// --- Composite line with fill to zero ---
if (showComposite) {
var compBull = acfComposite >= 0
plotLine(
value=[acfComposite, 0],
width=1,
colors=[transparency(compositeColor, 30), transparency(neutralColor, 10)],
colorIndex=compBull ? 0 : 1,
fill=true,
label=["Composite ACF", "Zero"],
desc=["Composite autocorrelation across active lags", "Zero reference line"]
)
plotLine(
value=acfComposite,
width=2,
colors=[compositeColor],
label=["Composite ACF"],
desc=["Composite ACF: arithmetic mean of all active lags"]
)
}
// --- ACF envelope (rolling max/min) ---
if (showEnv) {
var envHigh = highest(source=acfComposite, period=acfWindow)
var envLow = lowest(source=acfComposite, period=acfWindow)
plotLine(
value=envHigh,
width=1,
colors=[transparency(strongPosColor, 70)],
label=["ACF High"],
desc=["Rolling maximum of composite ACF over window"]
)
plotLine(
value=envLow,
width=1,
colors=[transparency(strongNegColor, 70)],
label=["ACF Low"],
desc=["Rolling minimum of composite ACF over window"]
)
}
// --- Significance shape markers ---
if (showSignificance) {
if (sig1) {
plotShape(
value=acf1,
shape="triangleup",
colorIndex=acf1 > 0 ? strongPosColor : strongNegColor,
width=3,
label=["Sig lag 1"],
desc=["Significant autocorrelation at lag 1: |ρ(1)| > " + sigThreshold]
)
}
if (sig2) {
plotShape(
value=acf2,
shape="triangleup",
colorIndex=acf2 > 0 ? strongPosColor : strongNegColor,
width=3,
label=["Sig lag 2"],
desc=["Significant autocorrelation at lag 2: |ρ(2)| > " + sigThreshold]
)
}
if (sig3) {
plotShape(
value=acf3,
shape="triangleup",
colorIndex=acf3 > 0 ? strongPosColor : strongNegColor,
width=3,
label=["Sig lag 3"],
desc=["Significant autocorrelation at lag 3: |ρ(3)| > " + sigThreshold]
)
}
if (sig5) {
plotShape(
value=acf5,
shape="triangleup",
colorIndex=acf5 > 0 ? strongPosColor : strongNegColor,
width=3,
label=["Sig lag 5"],
desc=["Significant autocorrelation at lag 5: |ρ(5)| > " + sigThreshold]
)
}
if (sig8) {
plotShape(
value=acf8,
shape="triangleup",
colorIndex=acf8 > 0 ? strongPosColor : strongNegColor,
width=3,
label=["Sig lag 8"],
desc=["Significant autocorrelation at lag 8: |ρ(8)| > " + sigThreshold]
)
}
if (sig13) {
plotShape(
value=acf13,
shape="triangleup",
colorIndex=acf13 > 0 ? strongPosColor : strongNegColor,
width=3,
label=["Sig lag 13"],
desc=["Significant autocorrelation at lag 13: |ρ(13)| > " + sigThreshold]
)
}
}
// --- Regime label on last bar ---
if (showRegimeLabel && isLastBar) {
plotPriceLabel(
price=acfComposite,
text=regimeLabel,
type="callout",
color="#ffffff",
backgroundColor=regimeColor,
size=10,
fontWeight=700
)
}
// ---------------------------------------------------------------------------
// 12. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var sigCount = 0
if (sig1) { sigCount = sigCount + 1 }
if (sig2) { sigCount = sigCount + 1 }
if (sig3) { sigCount = sigCount + 1 }
if (sig5) { sigCount = sigCount + 1 }
if (sig8) { sigCount = sigCount + 1 }
if (sig13) { sigCount = sigCount + 1 }
plotTable(
data=[
["ACF Heatmap", regimeLabel],
["Lag 1", acf1],
["Lag 2", acf2],
["Lag 3", acf3],
["Lag 5", acf5],
["Lag 8", acf8],
["Lag 13", acf13],
["Composite", acfComposite],
["Significant lags", sigCount],
["Regime duration", regimeDuration],
["Max composite", maxComposite],
["Min composite", minComposite]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=transparency("#0f172a", 40),
headerBackgroundColor=transparency("#1e293b", 40),
borderColor=transparency("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}