MM Flow
FlowScripts

Perfected FlowScript

Global score

Global Score — Multi-Factor Composite is indexed as 294_global_score.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.3 KB

Lines

566

Native Signal Candidates

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

5/5 guarded

Extreme Bull

line 482:9

Trigger

(showShapes) && (crossUpExtreme)

Value

score

Deps

crossUpExtreme:var, showShapes:input

Extreme Bear

line 492:9

Trigger

(showShapes) && (crossDownExtreme)

Value

score

Deps

crossDownExtreme:var, showShapes:input

Bull Warning

line 502:9

Trigger

(showShapes) && (crossUpWarn && !crossUpExtreme)

Value

score

Deps

crossUpExtreme:var, crossUpWarn:var, showShapes:input

Bear Warning

line 512:9

Trigger

(showShapes) && (crossDownWarn && !crossDownExtreme)

Value

score

Deps

crossDownExtreme:var, crossDownWarn:var, showShapes:input

Neutral Return

line 522:9

Trigger

(showShapes) && (crossToNeutral)

Value

score

Deps

crossToNeutral:var, showShapes:input

294_global_score.flowscript

source path: kscripts/perfected/294_global_score.flowscript · sha256:986037186018b757915bed3111cc28eaa5c8a3cc7f524cf3befb2a6820dead86

hash verified
//@version=2
// ============================================================================
// Global Score — Multi-Factor Composite Momentum & Regime Detector
// Author: kiyotaka (@kiyotaka) | Enhanced by kScript Perfection Engineer
// Index: 294
// Tags: CORE, #composite, #multifactor, #zscore, #regime, #sentiment, #orderflow
//
// Production-quality multi-factor composite scoring indicator. Aggregates
// price momentum, RSI, volume delta, orderbook imbalance, volatility, and
// trend strength into a unified z-score normalized global score with dynamic
// regime detection, color-coded histogram, and shape-based alerts.
//
// Academic foundations:
//  1. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//     Stock Returns" (J. Finance, 61(4), 1645–1680). Foundational composite
//     sentiment index construction via PCA of multiple proxies. Validates the
//     multi-factor aggregation approach. [^1]
//  2. Wang, Zhuang & Feng (2022), "Intelligent Optimization Based Multi-Factor
//     Deep Learning Stock Selection Model" (Mathematics, 10(4), 566). Selects
//     26 effective factors, constructs composite score via GRU + Cuckoo Search.
//     Achieved Sharpe 127.08%, annualized return 40.66%. [^2]
//  3. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint"
//     (IEEE TSP). Normalized spread z_t = (z_t − μ_z) / σ_z with entry
//     thresholds at d × σ_z. Supports z-score normalization and statistical
//     band construction. [^3]
//  4. Fama & French (1993), "Common Risk Factors in the Returns on Stocks and
//     Bonds" (JFE, 33(1), 3–56). Multi-factor model explaining cross-sectional
//     return variation. Underpins factor-weighted composite scoring. [^4]
//  5. Mittal (2025), "Gold–Silver Pair Trading – Mean Reversion Strategy Using
//     Machine Learning". Z-score normalization combined with regime filtering
//     (Gradient Boosting, SVM). ML-filtered mean reversion outperforms static
//     approaches during high-volatility regimes. [^5]
//  6. Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability
//     in Technical Analysis". RSI outperforms MACD and Stochastic in signal
//     reliability; multi-indicator confirmation recommended. [^6]
// ============================================================================

define(
    title="Global Score — Multi-Factor Composite",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Z-Score Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback Period",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score Settings"
)
var scoreSmooth = input(
    name="scoreSmooth",
    type="number",
    defaultValue=3,
    label="Score Smoothing EMA",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score Settings"
)

// --- Factor Weights ---
var useEqualWeights = input(
    name="useEqualWeights",
    type="boolean",
    defaultValue=false,
    label="Use Equal Weights",
    group="Factor Weights"
)
var wMomentum = input(
    name="wMomentum",
    type="number",
    defaultValue=0.20,
    label="Momentum Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Factor Weights"
)
var wRsi = input(
    name="wRsi",
    type="number",
    defaultValue=0.20,
    label="RSI Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Factor Weights"
)
var wDelta = input(
    name="wDelta",
    type="number",
    defaultValue=0.20,
    label="Volume Delta Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Factor Weights"
)
var wObi = input(
    name="wObi",
    type="number",
    defaultValue=0.15,
    label="Orderbook Imbalance Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Factor Weights"
)
var wVol = input(
    name="wVol",
    type="number",
    defaultValue=0.10,
    label="Volume Anomaly Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Factor Weights"
)
var wVolatility = input(
    name="wVolatility",
    type="number",
    defaultValue=0.15,
    label="Volatility Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Factor Weights"
)

// --- Thresholds ---
var extremeUpper = input(
    name="extremeUpper",
    type="number",
    defaultValue=2.0,
    label="Extreme Upper Threshold (σ)",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Thresholds"
)
var extremeLower = input(
    name="extremeLower",
    type="number",
    defaultValue=-2.0,
    label="Extreme Lower Threshold (σ)",
    constraints={min: -4.0, max: -1.0, step: 0.1},
    group="Thresholds"
)
var warnUpper = input(
    name="warnUpper",
    type="number",
    defaultValue=1.0,
    label="Warning Upper Threshold (σ)",
    constraints={min: 0.5, max: 2.0, step: 0.1},
    group="Thresholds"
)
var warnLower = input(
    name="warnLower",
    type="number",
    defaultValue=-1.0,
    label="Warning Lower Threshold (σ)",
    constraints={min: -2.0, max: -0.5, step: 0.1},
    group="Thresholds"
)

// --- Display ---
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Score Histogram",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show Score Ribbon",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)
var showComponents = input(
    name="showComponents",
    type="boolean",
    defaultValue=false,
    label="Show Component Z-Scores",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var strongBullColor = input(
    name="strongBullColor",
    type="color",
    defaultValue="#00e676",
    label="Strong Bull Color",
    group="Colors"
)
var strongBearColor = input(
    name="strongBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Strong Bear Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries volume = bars.volume

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(volume[0])) {
    return
}

// Orderbook data (best-effort; gracefully degrade if unavailable)
timeseries book = source("orderbook", currentSymbol, currentExchange)

// -----------------------------------------------------------------------------
// 3. FACTOR COMPUTATION
// -----------------------------------------------------------------------------
// --- Factor 1: Price Momentum (returns normalized) ---
timeseries ret = px[1] > 0 ? (px - px[1]) / px[1] : 0.0
timeseries momentum = ret * 100  // percent returns

// --- Factor 2: RSI (normalized to [-1, +1]) ---
timeseries rsiRaw = rsi(px, 14)
timeseries rsiNorm = (rsiRaw - 50) / 50

// --- Factor 3: Volume Delta (buy pressure estimate) ---
timeseries range = hi - lo
timeseries buyVol = range > 0 ? volume * (px - lo) / range : volume / 2
timeseries sellVol = volume - buyVol
timeseries deltaRaw = (buyVol - sellVol) / (volume + 0.001)
timeseries deltaNorm = deltaRaw

// --- Factor 4: Orderbook Imbalance (OBI) ---
timeseries bids = sumBids(book, 3)
timeseries asks = sumAsks(book, 3)
timeseries obiRaw = (bids - asks) / (bids + asks + 0.001)
timeseries obiNorm = obiRaw

// --- Factor 5: Volume Anomaly (volume z-score) ---
timeseries volMean = sma(volume, lookback)
timeseries volStd = stddev(volume, lookback)
timeseries volZ = volStd > 0 ? (volume - volMean) / volStd : 0
timeseries volAnomaly = volZ

// --- Factor 6: Volatility (ATR-based, normalized) ---
timeseries prevClose = isnan(px[1]) ? px : px[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, 14)
timeseries atrMean = sma(atr, lookback)
timeseries atrStd = stddev(atr, lookback)
timeseries volaNorm = atrStd > 0 ? (atr - atrMean) / atrStd : 0

// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION (per factor, rolling lookback)
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018): z_t = (x_t − μ_t) / σ_t over lookback window.
// This ensures each factor is expressed in standard-deviation units.

// Momentum Z
timeseries mMean = sma(momentum, lookback)
timeseries mStd = stddev(momentum, lookback)
timeseries mZ = mStd > 0 ? (momentum - mMean) / mStd : 0

// RSI Z
timeseries rMean = sma(rsiNorm, lookback)
timeseries rStd = stddev(rsiNorm, lookback)
timeseries rZ = rStd > 0 ? (rsiNorm - rMean) / rStd : 0

// Delta Z
timeseries dMean = sma(deltaNorm, lookback)
timeseries dStd = stddev(deltaNorm, lookback)
timeseries dZ = dStd > 0 ? (deltaNorm - dMean) / dStd : 0

// OBI Z
timeseries oMean = sma(obiNorm, lookback)
timeseries oStd = stddev(obiNorm, lookback)
timeseries oZ = oStd > 0 ? (obiNorm - oMean) / oStd : 0

// Volume Z (already computed)
timeseries vZ = volAnomaly

// Volatility Z (already computed)
timeseries vlZ = volaNorm

// -----------------------------------------------------------------------------
// 5. COMPOSITE GLOBAL SCORE
// -----------------------------------------------------------------------------
// Weighted aggregation. If equal weights, use uniform; otherwise use user
// weights with normalization to sum to 1.0.
var totalWeight = useEqualWeights ? 1.0 : (wMomentum + wRsi + wDelta + wObi + wVol + wVolatility)
var normW = useEqualWeights ? (1.0 / 6.0) : (wMomentum / totalWeight)
var normR = useEqualWeights ? (1.0 / 6.0) : (wRsi / totalWeight)
var normD = useEqualWeights ? (1.0 / 6.0) : (wDelta / totalWeight)
var normO = useEqualWeights ? (1.0 / 6.0) : (wObi / totalWeight)
var normV = useEqualWeights ? (1.0 / 6.0) : (wVol / totalWeight)
var normVL = useEqualWeights ? (1.0 / 6.0) : (wVolatility / totalWeight)

timeseries scoreRaw = mZ * normW + rZ * normR + dZ * normD + oZ * normO + vZ * normV + vlZ * normVL

// Smooth the score with EMA
timeseries score = ema(scoreRaw, scoreSmooth)

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification based on composite score thresholds:
//   Strong Bull: score > extremeUpper
//   Bull:        score > warnUpper AND score <= extremeUpper
//   Neutral:     score between warnLower and warnUpper
//   Bear:        score < warnLower AND score >= extremeLower
//   Strong Bear: score < extremeLower

var regimeStrongBull = score > extremeUpper
var regimeBull = score > warnUpper && score <= extremeUpper
var regimeNeutral = score >= warnLower && score <= warnUpper
var regimeBear = score < warnLower && score >= extremeLower
var regimeStrongBear = score < extremeLower

var regimeColor = regimeStrongBull ? strongBullColor : (regimeBull ? bullColor : (regimeStrongBear ? strongBearColor : (regimeBear ? bearColor : neutralColor)))

// -----------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossings of warning and extreme thresholds
var crossUpWarn = score > warnUpper && score[1] <= warnUpper
var crossUpExtreme = score > extremeUpper && score[1] <= extremeUpper
var crossDownWarn = score < warnLower && score[1] >= warnLower
var crossDownExtreme = score < extremeLower && score[1] >= extremeLower

// Return to neutral
var crossToNeutral = (score >= warnLower && score <= warnUpper) && (score[1] > warnUpper || score[1] < warnLower)

// -----------------------------------------------------------------------------
// 8. STATIC STATE: Historical extremes & tracking
// -----------------------------------------------------------------------------
static maxScore = -9999.0
static minScore = 9999.0
static maxScoreBar = 0
static minScoreBar = 0
static barCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1
    if (score > maxScore) {
        maxScore = score
        maxScoreBar = barCount
    }
    if (score < minScore) {
        minScore = score
        minScoreBar = barCount
    }
}

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Midline (zero) ---
hline(value=0, color="#ffffff20", width=1)

// --- Warning thresholds ---
hline(value=warnUpper, color=transparency(bullColor, 60), width=1)
hline(value=warnLower, color=transparency(bearColor, 60), width=1)

// --- Extreme thresholds ---
hline(value=extremeUpper, color=transparency(strongBullColor, 40), width=1)
hline(value=extremeLower, color=transparency(strongBearColor, 40), width=1)

// --- Score Ribbon (score vs zero, fill) ---
if (showRibbon) {
    var ribbonBull = score >= 0
    plotLine(
        value=[score, 0],
        width=1,
        colors=[transparency(regimeColor, 30), transparency(neutralColor, 10)],
        colorIndex=ribbonBull ? 0 : 0,
        fill=true,
        label=["Global Score", "Zero Line"],
        desc=["Composite multi-factor global score (z-score normalized)", "Zero reference line"]
    )
}

// --- Global Score Line (regime-colored) ---
plotLine(
    value=score,
    width=2,
    colors=[regimeColor],
    label=["Global Score"],
    desc=["Composite z-score from momentum, RSI, delta, OBI, volume, volatility (smoothed " + scoreSmooth + ")"]
)

// --- Component Z-Scores (optional, thin lines) ---
if (showComponents) {
    plotLine(
        value=mZ,
        width=1,
        colors=["#42a5f5"],
        label=["Momentum Z"],
        desc=["Price momentum z-score"]
    )
    plotLine(
        value=rZ,
        width=1,
        colors=["#ab47bc"],
        label=["RSI Z"],
        desc=["RSI normalized z-score"]
    )
    plotLine(
        value=dZ,
        width=1,
        colors=["#ffa726"],
        label=["Delta Z"],
        desc=["Volume delta z-score"]
    )
    plotLine(
        value=oZ,
        width=1,
        colors=["#66bb6a"],
        label=["OBI Z"],
        desc=["Orderbook imbalance z-score"]
    )
    plotLine(
        value=vZ,
        width=1,
        colors=["#ef5350"],
        label=["Volume Z"],
        desc=["Volume anomaly z-score"]
    )
    plotLine(
        value=vlZ,
        width=1,
        colors=["#ec407a"],
        label=["Volatility Z"],
        desc=["ATR volatility z-score"]
    )
}

// --- Score Histogram ---
if (showHistogram) {
    var histBull = score >= 0
    plotBar(
        value=score,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Score Histogram"],
        desc=["Histogram of composite global score (positive = bullish, negative = bearish)"]
    )
}

// --- Alert Shapes (extreme crossings) ---
if (showShapes) {
    if (crossUpExtreme) {
        plotShape(
            value=score,
            shape="triangleup",
            colorIndex=strongBullColor,
            width=2,
            label=["Extreme Bull"],
            desc=["Global score crossed above extreme upper threshold (" + extremeUpper + "σ). Strong bullish regime."]
        )
    }
    if (crossDownExtreme) {
        plotShape(
            value=score,
            shape="triangledown",
            colorIndex=strongBearColor,
            width=2,
            label=["Extreme Bear"],
            desc=["Global score crossed below extreme lower threshold (" + extremeLower + "σ). Strong bearish regime."]
        )
    }
    if (crossUpWarn && !crossUpExtreme) {
        plotShape(
            value=score,
            shape="arrowup",
            colorIndex=bullColor,
            width=1,
            label=["Bull Warning"],
            desc=["Global score crossed above warning upper threshold (" + warnUpper + "σ). Bullish bias."]
        )
    }
    if (crossDownWarn && !crossDownExtreme) {
        plotShape(
            value=score,
            shape="arrowdown",
            colorIndex=bearColor,
            width=1,
            label=["Bear Warning"],
            desc=["Global score crossed below warning lower threshold (" + warnLower + "σ). Bearish bias."]
        )
    }
    if (crossToNeutral) {
        plotShape(
            value=score,
            shape="circle",
            colorIndex=neutralColor,
            width=1,
            label=["Neutral Return"],
            desc=["Global score returned to neutral zone."]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeStrongBull ? "STRONG BULL" : (regimeBull ? "BULLISH" : (regimeStrongBear ? "STRONG BEAR" : (regimeBear ? "BEARISH" : "NEUTRAL")))
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["Global Score — Composite", regimeText],
            ["Score", score[0]],
            ["Momentum Z", mZ[0]],
            ["RSI Z", rZ[0]],
            ["Delta Z", dZ[0]],
            ["OBI Z", oZ[0]],
            ["Volume Z", vZ[0]],
            ["Volatility Z", vlZ[0]],
            ["Max Score (hist)", maxScore],
            ["Min Score (hist)", minScore]
        ],
        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
    )
}