Skip to Main Content
Back to website
Indicator Disclaimer | Report this indicator

Fundamental data tells you what a business already is. This tells you where it's turning.

Most fundamental tools plot a line and leave the reading to you. Inflection Radar scores five engines of the business — Growth, Margins, Cash Flow, Efficiency, Balance Sheet — on a 0–100 scale, then tracks whether the composite is accelerating or deteriorating quarter over quarter.

What makes it different: acceleration, not level

The core measure isn't growth. It's the change in growth — this quarter's year-over-year rate against last quarter's. A company growing 20% is a fact. A company that grew 12% last quarter and 20% this one is an inflection, and that's the thing worth catching early.

Everything in the panel builds on that distinction. The composite is a level. The Fundamental Pulse across four quarters is the trajectory. Fund Momentum weights the most recent change most heavily.

The dashboard

Three gauges across the top: Quality, Inflection, Fund Momentum.

Five engine meters below, each with its score, direction arrow, and the numbers behind it — so you can see that Margins read 88 because operating margin is 11.1% and up 35.8 points year over year, not just that it scored well.

A four-quarter pulse showing where the composite has been. Key fundamentals compared against a year ago. A written thesis naming which engine leads and which drags.

Honest about its own data

Coverage is measured and displayed: 80 inputs checked, and the panel reports what percentage resolved. Below 60% it refuses to render a regime at all and says LIMITED DATA rather than producing a confident score from gaps. A failed data request shows a banner instead of a blank chart.

Scanner — three conditions

Bullish Fundamental Divergence — fundamentals improving while price falls over the quarter, with the composite at or above 55. The setup nothing else screens for.

Bearish Fundamental Divergence — the mirror. Price up, fundamentals down.

Fundamental Score Strong — a state condition, so a scan returns a usable list rather than the handful of names that crossed a boundary this quarter. Threshold is yours.

Every signal requires adequate data coverage, so a thin ticker can't appear in a scan on the strength of missing values.

Daily charts

Anything comparing fundamentals to price uses a 63-bar lookback — one quarter of trading days. That only means something on a daily chart, so the divergence read and the on-chart inflection labels are daily-only by design. The panel says so rather than quietly producing a number.

Settings

Dashboard position. UI scale. Toggles for the metric cards, the pulse, and the on-chart labels. Score threshold for the scan.

#TSBuild26

// ============================================================================
// FUNDAMENTAL INFLECTION RADAR v2.0a
// TrendSpider Custom Indicator #TSBuild26
//
// Scores five fundamental engines — Growth, Margins, Cash Flow, Efficiency,
// Balance Sheet — on a 0-100 scale, then tracks whether the composite is
// ACCELERATING or DETERIORATING quarter over quarter. Acceleration (the
// change in the rate of change) is what marks an inflection; the level alone
// only tells you where a business already was.
//
// Output: an on-chart dashboard, two inflection labels, and three scanner
// signals. The divergence signals — fundamentals improving while price falls,
// or the reverse — are the read nothing else screens for.
//
// ---------------------------------------------------------------------------
// DESIGN NOTES worth keeping in mind before editing:
//
// METRICS is at 20, the API cap. Nothing can be added without removing
// something, and an UNRECOGNISED ID MAKES THE WHOLE CALL THROW — not partial,
// not degraded. Test any new ID in isolation first.
//
// Fetch failure is handled by try/catch, not assert(). On failure
// `fundamentals` becomes an empty object, which drives coverage to 0% and
// routes the panel down the LIMITED DATA path rather than blanking it.
//
// paint() runs UNCONDITIONALLY. Wrapping it in a conditional is what store
// review flagged on Volume Pace. When no trigger fires the series is all-null
// and nothing renders.
//
// isDailyChart governs EVERYTHING that compares fundamentals against price or
// bar position — the divergence read, both divergence signals, and both
// labels. The 63-bar lookback is a quarter of trading days, which only means
// that on a daily chart.
//
// Engine weighting is deliberately untouched. Tuning weights without a
// failing case is how a scoring model ends up fitted to whichever tickers
// happened to get looked at. Revisit only for a clear weighting failure.
// ============================================================================


describe_indicator('Fundamental Inflection Radar', { shortName: '◉ Inflection Radar v2.0a' });
// Hidden — this exists only so the platform has a series to register. Without
// `hidden` it shows in the chart legend as a togglable yellow line.
paint(close.map(function() { return NaN; }), {
  name: 'FundRef', style: 'line', color: '#04FF00', hidden: true
});


// ============================================================================
// SETTINGS
// ============================================================================

const dashboardPosition = input.select(
    'Dashboard Position',
    'top_right',
    [
        'top_right',
        'top_left',
        'bottom_right',
        'bottom_left'
    ]
);

const showMetricCards = input.boolean(
    'Show Metric Cards',
    true
);

const showPulse = input.boolean(
    'Show Fundamental Pulse',
    true
);

const showSignal = input.boolean(
    'Show Inflection Trigger',
    true
);

const uiScalePct = input.number(
    'UI Scale %',
    85,
    {
        min: 40,
        max: 200,
        step: 5
    }
);


// ============================================================================
// UI SCALE
// ============================================================================
// Every size in this file routes through these. Hardcoded pixel values were
// why the panel could not be made to fit a screen.

function sv(n) {

    return Math.max(
        1,
        Math.round(
            n * uiScalePct / 100
        )
    );
}


function px(n) {

    return sv(n) + 'px';
}


function pad(
    vertical,
    horizontal
) {

    return px(vertical) + ' ' + px(horizontal);
}


// Scanner threshold. Drives the one STATE signal — the two divergence signals
// key off logic already defined in the PRICE RELATIONSHIP section and
// deliberately take no inputs of their own.

const scanStrongScore = input.number(
    'Scan: Strong Score Min',
    70,
    {
        min: 50,
        max: 95,
        step: 5
    }
);


// ============================================================================
// FUNDAMENTAL DATA
// ============================================================================

const METRICS = [

    // Growth
    'revenue',
    'eps_diluted',

    // Margins
    'gross_profit_margin',
    'operating_margin',
    'fcf_margin',
    'ebitda_margin',

    // Cash quality
    'free_cash_flow',
    'fcf_to_net_income',
    'ocf_to_net_income',
    'ocf_to_sales',

    // Efficiency
    'return_on_invested_capital',
    'cash_roi',
    'asset_turnover',
    'return_on_assets',

    // Balance sheet
    'current_ratio',
    'net_debt_ebitda',
    'debt_to_equity',
    'cash_flow_to_debt_ratio',
    'altman_z_score',

    // Dilution
    'sbc_to_revenue'
];


let fundamentalsRaw = null;

let fetchErrorText = '';


try {

    fundamentalsRaw = await request.fundamental(
        current.ticker,
        METRICS,
        12
    );

} catch (fetchFailure) {

    fetchErrorText =
        (
            fetchFailure &&
            fetchFailure.message
        )
            ? fetchFailure.message
            : 'request.fundamental threw';
}


if (
    !fetchErrorText &&
    fundamentalsRaw &&
    fundamentalsRaw.error
) {

    fetchErrorText =
        String(
            fundamentalsRaw.error
        );
}


if (
    !fetchErrorText &&
    !fundamentalsRaw
) {

    fetchErrorText =
        'no data returned';
}


// An empty object makes every fv() lookup return null, which drives coverage
// to 0%, trips minimumCoverageMet, and routes the dashboard down the
// LIMITED DATA path that already exists. The panel degrades instead of
// disappearing, and the banner below says why.
const fundamentals =
    fetchErrorText
        ? {}
        : fundamentalsRaw;


// ============================================================================
// BASIC HELPERS
// ============================================================================

function fv(
    metric,
    offset = 0
) {

    const data =
        fundamentals[metric];

    if (
        !data ||
        !data[offset]
    ) {
        return null;
    }

    const value =
        data[offset].value;

    return Number.isFinite(value)
        ? value
        : null;
}


function clamp(
    value,
    min,
    max
) {

    if (!Number.isFinite(value)) {
        return null;
    }

    return Math.max(
        min,
        Math.min(
            max,
            value
        )
    );
}


// ============================================================================
// VALID-ONLY AVERAGING
// ============================================================================

function avgValid(values) {

    const valid =
        values.filter(
            value =>
                Number.isFinite(value)
        );

    if (!valid.length) {
        return null;
    }

    return valid.reduce(
        (sum, value) =>
            sum + value,
        0
    ) / valid.length;
}


function weightedAverage(
    values,
    weights
) {

    let weightedSum = 0;
    let weightSum = 0;

    for (
        let i = 0;
        i < values.length;
        i++
    ) {

        if (
            Number.isFinite(values[i]) &&
            Number.isFinite(weights[i])
        ) {

            weightedSum +=
                values[i] *
                weights[i];

            weightSum +=
                weights[i];
        }
    }

    if (weightSum === 0) {
        return null;
    }

    return (
        weightedSum /
        weightSum
    );
}


// ============================================================================
// PERCENT NORMALIZATION
// ============================================================================

function normalizePercentValue(value) {

    if (!Number.isFinite(value)) {
        return null;
    }

    return value * 100;
}


function pctValue(
    metric,
    offset = 0
) {

    return normalizePercentValue(
        fv(
            metric,
            offset
        )
    );
}


// ============================================================================
// DATA COVERAGE
// ============================================================================

const COVERAGE_OFFSETS = [
    0,
    1,
    4,
    5
];


function calculateDataCoverage() {

    let available = 0;
    let possible = 0;

    for (
        let metricIndex = 0;
        metricIndex < METRICS.length;
        metricIndex++
    ) {

        for (
            let offsetIndex = 0;
            offsetIndex < COVERAGE_OFFSETS.length;
            offsetIndex++
        ) {

            possible += 1;

            const coverageValue =
                fv(
                    METRICS[metricIndex],
                    COVERAGE_OFFSETS[offsetIndex]
                );

            if (
                Number.isFinite(
                    coverageValue
                )
            ) {

                available += 1;
            }
        }
    }


    return {

        available:
            available,

        possible:
            possible,

        percent:
            possible > 0
                ? (
                    available /
                    possible
                ) * 100
                : 0

    };
}


const coverage =
    calculateDataCoverage();


const dataCoveragePct =
    coverage.percent;


function coverageLabel(percent) {

    if (percent >= 90) {
        return 'HIGH';
    }

    if (percent >= 75) {
        return 'MODERATE';
    }

    if (percent >= 60) {
        return 'LOW';
    }

    return 'INSUFFICIENT';
}


function coverageColor(percent) {

    if (percent >= 90) {
        return '#13e69b';
    }

    if (percent >= 75) {
        return '#72d65c';
    }

    if (percent >= 60) {
        return '#f5c84b';
    }

    return '#ff4964';
}


const dataConfidence =
    coverageLabel(
        dataCoveragePct
    );


const dataCoverageColor =
    coverageColor(
        dataCoveragePct
    );


const minimumCoverageMet =
    dataCoveragePct >= 60;


// ============================================================================
// FORMATTING
// ============================================================================

function fmt(
    value,
    decimals = 1
) {

    if (!Number.isFinite(value)) {
        return '—';
    }

    return value.toFixed(decimals);
}


function fmtPct(
    value,
    decimals = 1
) {

    if (!Number.isFinite(value)) {
        return '—';
    }

    return `${
        value >= 0
            ? '+'
            : ''
    }${value.toFixed(decimals)}%`;
}


function fmtPlainPct(
    value,
    decimals = 1
) {

    if (!Number.isFinite(value)) {
        return '—';
    }

    return `${value.toFixed(decimals)}%`;
}


function fmtRatio(
    value,
    decimals = 2
) {

    if (!Number.isFinite(value)) {
        return '—';
    }

    return `${value.toFixed(decimals)}x`;
}


function signedText(
    value,
    suffix = ''
) {

    if (!Number.isFinite(value)) {
        return 'N/A';
    }

    return `${
        value > 0
            ? '+'
            : ''
    }${value.toFixed(1)}${suffix}`;
}


// ============================================================================
// COLORS / ZONES
// ============================================================================

function scoreColor(score) {

    if (!Number.isFinite(score)) {
        return '#8292a5';
    }

    if (score >= 75) {
        return '#13e69b';
    }

    if (score >= 60) {
        return '#72d65c';
    }

    if (score >= 45) {
        return '#f5c84b';
    }

    if (score >= 30) {
        return '#ff8c42';
    }

    return '#ff4964';
}


function inactiveMeterColor() {

    return '#243249';
}


function scoreZone(score) {

    if (!Number.isFinite(score)) {
        return 'N/A';
    }

    if (score >= 75) {
        return 'ELITE';
    }

    if (score >= 60) {
        return 'STRONG';
    }

    if (score >= 45) {
        return 'NEUTRAL';
    }

    if (score >= 30) {
        return 'SOFT';
    }

    return 'WEAK';
}


// ============================================================================
// GENERIC LEVEL SCORING
// ============================================================================

function levelScore(
    value,
    badLevel,
    goodLevel
) {

    if (!Number.isFinite(value)) {
        return null;
    }

    if (goodLevel === badLevel) {
        return null;
    }

    return clamp(
        (
            (
                value -
                badLevel
            ) /
            (
                goodLevel -
                badLevel
            )
        ) * 100,
        0,
        100
    );
}


function inverseLevelScore(
    value,
    goodLevel,
    badLevel
) {

    if (!Number.isFinite(value)) {
        return null;
    }

    if (goodLevel === badLevel) {
        return null;
    }

    return clamp(
        (
            (
                badLevel -
                value
            ) /
            (
                badLevel -
                goodLevel
            )
        ) * 100,
        0,
        100
    );
}


// ============================================================================
// YOY FUNCTIONS
// ============================================================================

function yoy(
    metric,
    offset = 0
) {

    const now =
        fv(
            metric,
            offset
        );

    const yearAgo =
        fv(
            metric,
            offset + 4
        );

    if (
        !Number.isFinite(now) ||
        !Number.isFinite(yearAgo) ||
        yearAgo === 0
    ) {
        return null;
    }

    return (
        100 *
        (
            now -
            yearAgo
        ) /
        Math.abs(yearAgo)
    );
}


function pctYoYChange(
    metric,
    offset = 0
) {

    const now =
        pctValue(
            metric,
            offset
        );

    const yearAgo =
        pctValue(
            metric,
            offset + 4
        );

    if (
        !Number.isFinite(now) ||
        !Number.isFinite(yearAgo)
    ) {
        return null;
    }

    return (
        now -
        yearAgo
    );
}


function rawYoYChange(
    metric,
    offset = 0
) {

    const now =
        fv(
            metric,
            offset
        );

    const yearAgo =
        fv(
            metric,
            offset + 4
        );

    if (
        !Number.isFinite(now) ||
        !Number.isFinite(yearAgo)
    ) {
        return null;
    }

    return (
        now -
        yearAgo
    );
}


// ============================================================================
// ACCELERATION
// ============================================================================

function growthAcceleration(
    metric,
    offset = 0
) {

    const currentGrowth =
        yoy(
            metric,
            offset
        );

    const priorGrowth =
        yoy(
            metric,
            offset + 1
        );

    if (
        !Number.isFinite(currentGrowth) ||
        !Number.isFinite(priorGrowth)
    ) {
        return null;
    }

    return (
        currentGrowth -
        priorGrowth
    );
}


function pctAcceleration(
    metric,
    offset = 0
) {

    const currentYoY =
        pctYoYChange(
            metric,
            offset
        );

    const previousYoY =
        pctYoYChange(
            metric,
            offset + 1
        );

    if (
        !Number.isFinite(currentYoY) ||
        !Number.isFinite(previousYoY)
    ) {
        return null;
    }

    return (
        currentYoY -
        previousYoY
    );
}


// ============================================================================
// GROWTH SCORING
// ============================================================================

function growthLevelScore(value) {

    if (!Number.isFinite(value)) {
        return null;
    }

    if (value <= -20) {
        return 5;
    }

    if (value <= -10) {

        return (
            5 +
            (
                (value + 20) /
                10
            ) * 20
        );
    }

    if (value <= 0) {

        return (
            25 +
            (
                (value + 10) /
                10
            ) * 20
        );
    }

    if (value <= 10) {

        return (
            45 +
            (
                value /
                10
            ) * 15
        );
    }

    if (value <= 20) {

        return (
            60 +
            (
                (value - 10) /
                10
            ) * 12
        );
    }

    if (value <= 40) {

        return (
            72 +
            (
                (value - 20) /
                20
            ) * 16
        );
    }

    if (value <= 60) {

        return (
            88 +
            (
                (value - 40) /
                20
            ) * 12
        );
    }

    return 100;
}


function growthAccelerationScore(
    metric,
    offset = 0
) {

    const acceleration =
        growthAcceleration(
            metric,
            offset
        );

    if (!Number.isFinite(acceleration)) {
        return null;
    }

    return clamp(
        50 +
        acceleration * 2,
        0,
        100
    );
}


// ============================================================================
// YOY SCORING
// ============================================================================

function pctYoYScore(
    metric,
    offset = 0,
    fullMove = 5
) {

    const change =
        pctYoYChange(
            metric,
            offset
        );

    if (!Number.isFinite(change)) {
        return null;
    }

    return clamp(
        50 +
        (
            change /
            fullMove
        ) * 25,
        0,
        100
    );
}


function pctAccelerationScore(
    metric,
    offset = 0,
    fullMove = 3
) {

    const acceleration =
        pctAcceleration(
            metric,
            offset
        );

    if (!Number.isFinite(acceleration)) {
        return null;
    }

    return clamp(
        50 +
        (
            acceleration /
            fullMove
        ) * 25,
        0,
        100
    );
}


function rawYoYScore(
    metric,
    offset = 0,
    fullMove = 0.25
) {

    const change =
        rawYoYChange(
            metric,
            offset
        );

    if (!Number.isFinite(change)) {
        return null;
    }

    return clamp(
        50 +
        (
            change /
            fullMove
        ) * 25,
        0,
        100
    );
}


function inverseRawYoYScore(
    metric,
    offset = 0,
    fullMove = 0.25
) {

    const change =
        rawYoYChange(
            metric,
            offset
        );

    if (!Number.isFinite(change)) {
        return null;
    }

    return clamp(
        50 -
        (
            change /
            fullMove
        ) * 25,
        0,
        100
    );
}


// ============================================================================
// CAPPED CASH CONVERSION
// ============================================================================

function cashConversionScore(
    metric,
    offset = 0
) {

    const raw =
        fv(
            metric,
            offset
        );

    if (!Number.isFinite(raw)) {
        return null;
    }

    const value =
        clamp(
            raw,
            -1,
            1.5
        );


    if (value <= 0) {
        return 5;
    }

    if (value <= 0.5) {

        return (
            5 +
            (
                value /
                0.5
            ) * 30
        );
    }

    if (value <= 0.8) {

        return (
            35 +
            (
                (
                    value -
                    0.5
                ) /
                0.3
            ) * 25
        );
    }

    if (value <= 1.0) {

        return (
            60 +
            (
                (
                    value -
                    0.8
                ) /
                0.2
            ) * 20
        );
    }

    if (value <= 1.5) {

        return (
            80 +
            (
                (
                    value -
                    1.0
                ) /
                0.5
            ) * 20
        );
    }

    return 100;
}


function cashConversionYoYScore(
    metric,
    offset = 0
) {

    const currentScore =
        cashConversionScore(
            metric,
            offset
        );

    const yearAgoScore =
        cashConversionScore(
            metric,
            offset + 4
        );

    if (
        !Number.isFinite(currentScore) ||
        !Number.isFinite(yearAgoScore)
    ) {
        return null;
    }

    return clamp(
        50 +
        (
            currentScore -
            yearAgoScore
        ),
        0,
        100
    );
}


// ============================================================================
// BALANCE SHEET SCORING
// ============================================================================

function netDebtScore(
    offset = 0
) {

    const value =
        fv(
            'net_debt_ebitda',
            offset
        );

    if (!Number.isFinite(value)) {
        return null;
    }

    if (value <= 0) {
        return 100;
    }

    if (value <= 1) {
        return 90;
    }

    if (value <= 2) {
        return 72;
    }

    if (value <= 3) {
        return 55;
    }

    if (value <= 4) {
        return 35;
    }

    if (value <= 5) {
        return 20;
    }

    return 5;
}


function currentRatioScore(
    offset = 0
) {

    const value =
        fv(
            'current_ratio',
            offset
        );

    if (!Number.isFinite(value)) {
        return null;
    }

    if (value < 0.75) {
        return 10;
    }

    if (value < 1.0) {
        return 30;
    }

    if (value < 1.5) {
        return 60;
    }

    if (value < 2.0) {
        return 80;
    }

    return 90;
}


function altmanScore(
    offset = 0
) {

    const value =
        fv(
            'altman_z_score',
            offset
        );

    return levelScore(
        value,
        1.0,
        4.0
    );
}


function debtEquityScore(
    offset = 0
) {

    const value =
        fv(
            'debt_to_equity',
            offset
        );

    if (!Number.isFinite(value)) {
        return null;
    }

    if (value < 0) {
        return 45;
    }

    return inverseLevelScore(
        value,
        0.25,
        2.0
    );
}


// ============================================================================
// ENGINE FUNCTIONS
// ============================================================================

function growthScore(
    offset = 0
) {

    const revenueGrowth =
        yoy(
            'revenue',
            offset
        );

    const dilutedEpsGrowth =
        yoy(
            'eps_diluted',
            offset
        );


    const revenueGrowthScore =
        growthLevelScore(
            revenueGrowth
        );


    const revenueAccelScore =
        growthAccelerationScore(
            'revenue',
            offset
        );


    const dilutedEpsGrowthScore =
        growthLevelScore(
            dilutedEpsGrowth
        );


    const dilutedEpsAccelScore =
        growthAccelerationScore(
            'eps_diluted',
            offset
        );


    return weightedAverage(
        [
            revenueGrowthScore,
            revenueAccelScore,
            dilutedEpsGrowthScore,
            dilutedEpsAccelScore
        ],
        [
            0.35,
            0.30,
            0.20,
            0.15
        ]
    );
}


function marginScore(
    offset = 0
) {

    const grossMargin =
        pctValue(
            'gross_profit_margin',
            offset
        );

    const operatingMargin =
        pctValue(
            'operating_margin',
            offset
        );

    const fcfMargin =
        pctValue(
            'fcf_margin',
            offset
        );

    const ebitdaMargin =
        pctValue(
            'ebitda_margin',
            offset
        );


    return avgValid([

        levelScore(
            grossMargin,
            15,
            70
        ),

        pctYoYScore(
            'gross_profit_margin',
            offset,
            6
        ),

        pctAccelerationScore(
            'gross_profit_margin',
            offset,
            3
        ),

        levelScore(
            operatingMargin,
            0,
            30
        ),

        pctYoYScore(
            'operating_margin',
            offset,
            6
        ),

        pctAccelerationScore(
            'operating_margin',
            offset,
            3
        ),

        levelScore(
            fcfMargin,
            -5,
            25
        ),

        pctYoYScore(
            'fcf_margin',
            offset,
            8
        ),

        pctAccelerationScore(
            'fcf_margin',
            offset,
            4
        ),

        levelScore(
            ebitdaMargin,
            0,
            35
        ),

        pctYoYScore(
            'ebitda_margin',
            offset,
            7
        )

    ]);
}


function cashFlowScore(
    offset = 0
) {

    const fcfMargin =
        pctValue(
            'fcf_margin',
            offset
        );

    const ocfSales =
        pctValue(
            'ocf_to_sales',
            offset
        );

    const fcfGrowth =
        yoy(
            'free_cash_flow',
            offset
        );


    return avgValid([

        levelScore(
            fcfMargin,
            -5,
            25
        ),

        pctYoYScore(
            'fcf_margin',
            offset,
            8
        ),

        pctAccelerationScore(
            'fcf_margin',
            offset,
            4
        ),

        growthLevelScore(
            fcfGrowth
        ),

        cashConversionScore(
            'fcf_to_net_income',
            offset
        ),

        cashConversionScore(
            'ocf_to_net_income',
            offset
        ),

        cashConversionYoYScore(
            'fcf_to_net_income',
            offset
        ),

        cashConversionYoYScore(
            'ocf_to_net_income',
            offset
        ),

        levelScore(
            ocfSales,
            0,
            25
        ),

        pctYoYScore(
            'ocf_to_sales',
            offset,
            8
        )

    ]);
}


function efficiencyScore(
    offset = 0
) {

    const roic =
        pctValue(
            'return_on_invested_capital',
            offset
        );

    const cashRoi =
        pctValue(
            'cash_roi',
            offset
        );

    const roa =
        pctValue(
            'return_on_assets',
            offset
        );


    return avgValid([

        levelScore(
            roic,
            3,
            25
        ),

        pctYoYScore(
            'return_on_invested_capital',
            offset,
            6
        ),

        pctAccelerationScore(
            'return_on_invested_capital',
            offset,
            3
        ),

        levelScore(
            cashRoi,
            3,
            25
        ),

        pctYoYScore(
            'cash_roi',
            offset,
            6
        ),

        pctAccelerationScore(
            'cash_roi',
            offset,
            3
        ),

        levelScore(
            roa,
            2,
            15
        ),

        pctYoYScore(
            'return_on_assets',
            offset,
            4
        ),

        rawYoYScore(
            'asset_turnover',
            offset,
            0.20
        )

    ]);
}


function balanceScore(
    offset = 0
) {

    return avgValid([

        currentRatioScore(
            offset
        ),

        rawYoYScore(
            'current_ratio',
            offset,
            0.50
        ),

        netDebtScore(
            offset
        ),

        debtEquityScore(
            offset
        ),

        inverseRawYoYScore(
            'debt_to_equity',
            offset,
            0.50
        ),

        rawYoYScore(
            'cash_flow_to_debt_ratio',
            offset,
            0.30
        ),

        altmanScore(
            offset
        )

    ]);
}


function compositeScore(
    offset = 0
) {

    return avgValid([

        growthScore(
            offset
        ),

        marginScore(
            offset
        ),

        cashFlowScore(
            offset
        ),

        efficiencyScore(
            offset
        ),

        balanceScore(
            offset
        )

    ]);
}


// ============================================================================
// CURRENT / PRIOR ENGINE SCORES
// ============================================================================

const growth =
    growthScore(0);

const margins =
    marginScore(0);

const cashFlow =
    cashFlowScore(0);

const efficiency =
    efficiencyScore(0);

const balance =
    balanceScore(0);


const growthPrev =
    growthScore(1);

const marginsPrev =
    marginScore(1);

const cashFlowPrev =
    cashFlowScore(1);

const efficiencyPrev =
    efficiencyScore(1);

const balancePrev =
    balanceScore(1);


// ============================================================================
// COMPOSITE HISTORY
// ============================================================================

const composite =
    compositeScore(0);

const composite1 =
    compositeScore(1);

const composite2 =
    compositeScore(2);

const composite3 =
    compositeScore(3);


const scoreChange1 =
    (
        Number.isFinite(composite) &&
        Number.isFinite(composite1)
    )
        ? composite - composite1
        : null;


const scoreChange2 =
    (
        Number.isFinite(composite1) &&
        Number.isFinite(composite2)
    )
        ? composite1 - composite2
        : null;


const scoreChange3 =
    (
        Number.isFinite(composite2) &&
        Number.isFinite(composite3)
    )
        ? composite2 - composite3
        : null;


// ============================================================================
// QUALITY
// ============================================================================

const currentRoic =
    pctValue(
        'return_on_invested_capital'
    );


const currentSbc =
    pctValue(
        'sbc_to_revenue'
    );


const quality =
    avgValid([

        cashConversionScore(
            'fcf_to_net_income'
        ),

        cashConversionScore(
            'ocf_to_net_income'
        ),

        levelScore(
            currentRoic,
            3,
            25
        ),

        inverseLevelScore(
            currentSbc,
            2,
            15
        ),

        balance

    ]);


// ============================================================================
// FUNDAMENTAL MOMENTUM
// ============================================================================

const fundMomentum =
    (
        Number.isFinite(scoreChange1) &&
        Number.isFinite(scoreChange2)
    )
        ? clamp(
            50 +
            scoreChange1 * 1.5 +
            scoreChange2 * 0.75,
            0,
            100
        )
        : null;


// ============================================================================
// REGIME
// ============================================================================

let regime =
    'STABLE';


if (
    !minimumCoverageMet ||
    !Number.isFinite(composite)
) {

    regime =
        'LIMITED DATA';

}

else if (
    composite >= 70 &&
    Number.isFinite(composite1) &&
    composite > composite1
) {

    regime =
        'STRONG ACCELERATION';

}

else if (
    composite >= 60 &&
    Number.isFinite(composite1) &&
    composite > composite1
) {

    regime =
        'ACCELERATING';

}

else if (
    composite >= 55
) {

    regime =
        'POSITIVE';

}

else if (
    composite <= 30 &&
    Number.isFinite(composite1) &&
    composite < composite1
) {

    regime =
        'STRONG DETERIORATION';

}

else if (
    composite < 45 &&
    Number.isFinite(composite1) &&
    composite < composite1
) {

    regime =
        'DETERIORATING';

}

else if (
    Number.isFinite(composite1) &&
    composite < composite1
) {

    regime =
        'DECELERATING';

}


// ============================================================================
// ENGINE DIRECTION
// ============================================================================

function improvingEngine(
    score,
    priorScore
) {

    if (
        !Number.isFinite(score) ||
        !Number.isFinite(priorScore)
    ) {
        return false;
    }

    return (
        score >
        priorScore + 2
    );
}


function worseningEngine(
    score,
    priorScore
) {

    if (
        !Number.isFinite(score) ||
        !Number.isFinite(priorScore)
    ) {
        return false;
    }

    return (
        score <
        priorScore - 2
    );
}


function flatEngine(
    score,
    priorScore
) {

    if (
        !Number.isFinite(score) ||
        !Number.isFinite(priorScore)
    ) {
        return false;
    }

    return (
        !improvingEngine(
            score,
            priorScore
        ) &&
        !worseningEngine(
            score,
            priorScore
        )
    );
}


function directionArrow(
    score,
    priorScore
) {

    if (
        !Number.isFinite(score) ||
        !Number.isFinite(priorScore)
    ) {
        return '•';
    }

    if (
        score >
        priorScore + 2
    ) {
        return '▲';
    }

    if (
        score <
        priorScore - 2
    ) {
        return '▼';
    }

    return '→';
}


const enginePairs = [

    [
        growth,
        growthPrev
    ],

    [
        margins,
        marginsPrev
    ],

    [
        cashFlow,
        cashFlowPrev
    ],

    [
        efficiency,
        efficiencyPrev
    ],

    [
        balance,
        balancePrev
    ]

];


const improvingEngines =
    enginePairs.filter(
        pair =>
            improvingEngine(
                pair[0],
                pair[1]
            )
    ).length;


const worseningEngines =
    enginePairs.filter(
        pair =>
            worseningEngine(
                pair[0],
                pair[1]
            )
    ).length;


const flatEngines =
    enginePairs.filter(
        pair =>
            flatEngine(
                pair[0],
                pair[1]
            )
    ).length;


const unavailableEngineComparisons =
    enginePairs.filter(
        pair =>
            !Number.isFinite(pair[0]) ||
            !Number.isFinite(pair[1])
    ).length;


// ============================================================================
// LEVEL AGREEMENT
// ============================================================================

const pillarScores = [

    growth,
    margins,
    cashFlow,
    efficiency,
    balance

];


const validPillarScores =
    pillarScores.filter(
        value =>
            Number.isFinite(value)
    );


const bullishPillars =
    validPillarScores.filter(
        value =>
            value >= 55
    ).length;


const strongBullishPillars =
    validPillarScores.filter(
        value =>
            value >= 70
    ).length;


const bearishPillars =
    validPillarScores.filter(
        value =>
            value <= 45
    ).length;


const strongBearishPillars =
    validPillarScores.filter(
        value =>
            value <= 30
    ).length;


// ============================================================================
// CONVICTION
// ============================================================================

let conviction =
    'LOW';


let convictionBias =
    'MIXED';


if (!minimumCoverageMet) {

    conviction =
        'LOW';

    convictionBias =
        'MIXED';

}

else if (
    bullishPillars >= 4 &&
    improvingEngines >= 3
) {

    conviction =
        strongBullishPillars >= 3
            ? 'VERY HIGH'
            : 'HIGH';

    convictionBias =
        'BULLISH';

}

else if (
    bearishPillars >= 4 &&
    worseningEngines >= 3
) {

    conviction =
        strongBearishPillars >= 3
            ? 'VERY HIGH'
            : 'HIGH';

    convictionBias =
        'BEARISH';

}

else if (
    bullishPillars >= 3 &&
    improvingEngines >= 3
) {

    conviction =
        'MODERATE';

    convictionBias =
        'BULLISH';

}

else if (
    bearishPillars >= 3 &&
    worseningEngines >= 3
) {

    conviction =
        'MODERATE';

    convictionBias =
        'BEARISH';

}

else if (
    improvingEngines >= 4
) {

    conviction =
        'MODERATE';

    convictionBias =
        'IMPROVING';

}

else if (
    worseningEngines >= 4
) {

    conviction =
        'MODERATE';

    convictionBias =
        'WEAKENING';

}


// ============================================================================
// PRICE RELATIONSHIP — DAILY+ ONLY
// ============================================================================

// The lookback is 63 bars — one quarter of trading days, which is why it
// pairs with quarterly fundamentals. That only holds on a DAILY chart. On a
// weekly it measures fifteen months and on a monthly over five years, neither
// of which is what "price has been falling" means next to a quarterly report.
// Intraday is worse still: 63 bars on a 5-minute chart is five hours.
//
// constants.resolution is a NUMBER of minutes for intraday and a LETTER for
// higher timeframes, so a numeric test catches intraday and a 'D' test
// isolates daily.
const isIntradayChart =
    !isNaN(
        constants.resolution
    );


const isDailyChart =
    !isIntradayChart &&
    String(
        constants.resolution
    ).toUpperCase() === 'D';


const priceRelationshipEnabled =
    isDailyChart &&
    minimumCoverageMet;


let priceRelationship =
    !isDailyChart
        ? 'DAILY ONLY'
        : (
            minimumCoverageMet
                ? 'ALIGNED'
                : 'LIMITED DATA'
        );


let priceRelationshipColor =
    !isDailyChart
        ? '#8292a5'
        : (
            minimumCoverageMet
                ? '#42a5ff'
                : '#ff4964'
        );


let priceChange =
    null;


if (priceRelationshipEnabled) {

    const priceNow =
        close[
            close.length - 1
        ];


    const lookback =
        Math.min(
            63,
            close.length - 1
        );


    const pricePast =
        close[
            close.length -
            1 -
            lookback
        ];


    priceChange =
        (
            Number.isFinite(priceNow) &&
            Number.isFinite(pricePast) &&
            pricePast !== 0
        )
            ? (
                100 *
                (
                    priceNow -
                    pricePast
                ) /
                pricePast
            )
            : null;


    if (
        Number.isFinite(priceChange) &&
        Number.isFinite(composite) &&
        Number.isFinite(composite1) &&
        priceChange < 0 &&
        composite > composite1 &&
        composite >= 55
    ) {

        priceRelationship =
            'BULL DIVERGENCE';

        priceRelationshipColor =
            '#13e69b';

    }

    else if (
        Number.isFinite(priceChange) &&
        Number.isFinite(composite) &&
        Number.isFinite(composite1) &&
        priceChange > 0 &&
        composite < composite1 &&
        composite <= 45
    ) {

        priceRelationship =
            'BEAR DIVERGENCE';

        priceRelationshipColor =
            '#ff4964';

    }

}


// ============================================================================
// THESIS GENERATION
// ============================================================================

function strongestEngineName() {

    const candidates = [

        [
            'Growth',
            growth
        ],

        [
            'Margins',
            margins
        ],

        [
            'Cash Flow',
            cashFlow
        ],

        [
            'Efficiency',
            efficiency
        ],

        [
            'Balance Sheet',
            balance
        ]

    ];


    const valid =
        candidates.filter(
            item =>
                Number.isFinite(
                    item[1]
                )
        );


    if (!valid.length) {
        return 'N/A';
    }


    let bestName =
        valid[0][0];

    let bestScore =
        valid[0][1];


    for (
        let i = 1;
        i < valid.length;
        i++
    ) {

        if (
            valid[i][1] >
            bestScore
        ) {

            bestName =
                valid[i][0];

            bestScore =
                valid[i][1];
        }
    }


    return bestName;
}


function weakestEngineName() {

    const candidates = [

        [
            'Growth',
            growth
        ],

        [
            'Margins',
            margins
        ],

        [
            'Cash Flow',
            cashFlow
        ],

        [
            'Efficiency',
            efficiency
        ],

        [
            'Balance Sheet',
            balance
        ]

    ];


    const valid =
        candidates.filter(
            item =>
                Number.isFinite(
                    item[1]
                )
        );


    if (!valid.length) {
        return 'N/A';
    }


    let weakName =
        valid[0][0];

    let weakScore =
        valid[0][1];


    for (
        let i = 1;
        i < valid.length;
        i++
    ) {

        if (
            valid[i][1] <
            weakScore
        ) {

            weakName =
                valid[i][0];

            weakScore =
                valid[i][1];
        }
    }


    return weakName;
}


function fundamentalThesis() {

    if (fetchErrorText) {

        return (
            `Fundamental data could not be retrieved for ${current.ticker}.`
        );
    }


    if (!minimumCoverageMet) {

        return (
            `Insufficient fundamental coverage (${fmt(
                dataCoveragePct,
                0
            )}%) for a reliable regime assessment.`
        );
    }


    const strongest =
        strongestEngineName();

    const weakest =
        weakestEngineName();


    if (
        Number.isFinite(composite) &&
        composite >= 70 &&
        improvingEngines >= 3
    ) {

        return (
            `Broad fundamental strength led by ${strongest}; business momentum is accelerating.`
        );
    }


    if (
        Number.isFinite(composite) &&
        composite >= 55 &&
        improvingEngines >= 3
    ) {

        return (
            `${strongest} leads while multiple engines improve; fundamental setup is strengthening.`
        );
    }


    if (
        Number.isFinite(composite) &&
        composite <= 45 &&
        worseningEngines >= 3
    ) {

        return (
            `${strongest} remains the key support, but ${weakest} and other engines are weakening.`
        );
    }


    if (
        Number.isFinite(composite) &&
        composite <= 45
    ) {

        return (
            `${strongest} is the main strength while ${weakest} remains the largest fundamental drag.`
        );
    }


    return (
        `Fundamentals are mixed: ${strongest} leads while ${weakest} remains the weakest engine.`
    );
}


const thesisText =
    fundamentalThesis();


// ============================================================================
// DIAGNOSTIC LINES
// ============================================================================

function growthReason() {

    const rev =
        yoy(
            'revenue'
        );

    const revAccel =
        growthAcceleration(
            'revenue'
        );

    const dilutedEps =
        yoy(
            'eps_diluted'
        );


    return (
        `Rev ${signedText(rev, '%')}   |   ` +
        `Accel ${signedText(revAccel, 'pp')}   |   ` +
        `Dil EPS ${signedText(dilutedEps, '%')}`
    );
}


function marginReason() {

    const op =
        pctValue(
            'operating_margin'
        );

    const opYoY =
        pctYoYChange(
            'operating_margin'
        );

    const fcf =
        pctValue(
            'fcf_margin'
        );


    return (
        `Op ${fmtPlainPct(op)}   |   ` +
        `YoY ${signedText(opYoY, 'pp')}   |   ` +
        `FCF ${fmtPlainPct(fcf)}`
    );
}


function cashReason() {

    const fcf =
        pctValue(
            'fcf_margin'
        );

    const fcfNI =
        fv(
            'fcf_to_net_income'
        );

    const ocfNI =
        fv(
            'ocf_to_net_income'
        );


    return (
        `FCF Mgn ${fmtPlainPct(fcf)}   |   ` +
        `FCF/NI ${fmtRatio(fcfNI)}   |   ` +
        `OCF/NI ${fmtRatio(ocfNI)}`
    );
}


function efficiencyReason() {

    const roicValue =
        pctValue(
            'return_on_invested_capital'
        );

    const roicYoY =
        pctYoYChange(
            'return_on_invested_capital'
        );

    const roa =
        pctValue(
            'return_on_assets'
        );


    return (
        `ROIC ${fmtPlainPct(roicValue)}   |   ` +
        `YoY ${signedText(roicYoY, 'pp')}   |   ` +
        `ROA ${fmtPlainPct(roa)}`
    );
}


function balanceReason() {

    const netDebt =
        fv(
            'net_debt_ebitda'
        );

    const currentRatioValue =
        fv(
            'current_ratio'
        );

    const altman =
        fv(
            'altman_z_score'
        );


    return (
        `Net Debt ${fmtRatio(netDebt)}   |   ` +
        `Current ${fmt(currentRatioValue, 2)}   |   ` +
        `Z ${fmt(altman, 1)}`
    );
}


// ============================================================================
// GAUGE FACTORY
// ============================================================================

function gaugeChart(
    score,
    color,
    label,
    width = px(135),
    height = px(105)
) {

    const safeScore =
        Number.isFinite(score)
            ? clamp(
                score,
                0,
                100
            )
            : 0;


    return {

        width:
            width,

        height:
            height,

        type:
            'doughnut',

        options: {

            responsive:
                true,

            cutout:
                '75%',

            rotation:
                -90,

            circumference:
                180,

            plugins: {

                legend: {
                    display: false
                },

                tooltip: {
                    enabled: false
                }

            }

        },

        data: {

            labels: [
                label,
                'Remaining'
            ],

            datasets: [{

                data: [
                    safeScore,
                    100 - safeScore
                ],

                backgroundColor: [
                    color,
                    '#243249'
                ],

                borderWidth:
                    0

            }]

        }

    };

}


// ============================================================================
// SEGMENTED METERS
// ============================================================================

function segmentCell(
    active,
    color
) {

    return {

        text:
            '  ',

        background:
            active
                ? color
                : inactiveMeterColor(),

        padding:
            pad(6, 8)
    };
}


function engineMeter(
    label,
    score,
    previousScore,
    reason
) {

    const color =
        scoreColor(
            score
        );


    const activeSegments =
        Number.isFinite(score)
            ? Math.round(
                clamp(
                    score,
                    0,
                    100
                ) / 10
            )
            : 0;


    const segments = [];


    for (
        let i = 0;
        i < 10;
        i++
    ) {

        segments.push(
            segmentCell(
                i < activeSegments,
                color
            )
        );
    }


    return {

        table: {

            rows: [

                {

                    cells: [

                        {

                            text:
                                `${label}   ${scoreZone(score)}`,

                            fontWeight:
                                'bold',

                            color:
                                '#c3cfdb',

                            padding:
                                pad(5, 6)
                        },

                        {

                            colspan:
                                9,

                            text:
                                `${fmt(
                                    score,
                                    0
                                )} ${
                                    directionArrow(
                                        score,
                                        previousScore
                                    )
                                }`,

                            fontWeight:
                                'bold',

                            fontSize:
                                sv(13),

                            color:
                                color,

                            textAlign:
                                'right',

                            padding:
                                pad(5, 8)
                        }

                    ]

                },

                {

                    cells:
                        segments

                },

                {

                    cells: [{

                        colspan:
                            10,

                        text:
                            reason,

                        color:
                            '#96a5b5',

                        fontSize:
                            sv(10),

                        padding:
                            pad(4, 6)
                    }]

                }

            ]

        }

    };
}


// ============================================================================
// FUNDAMENTAL PULSE
// ============================================================================

function pulseDeltaArrow(delta) {

    if (!Number.isFinite(delta)) {
        return '•';
    }

    if (delta > 2) {
        return '▲';
    }

    if (delta < -2) {
        return '▼';
    }

    return '→';
}


function pulseDeltaColor(delta) {

    if (!Number.isFinite(delta)) {
        return '#8292a5';
    }

    if (delta > 2) {
        return '#13e69b';
    }

    if (delta < -2) {
        return '#ff4964';
    }

    return '#f5c84b';
}


function pulseDeltaText(delta) {

    if (!Number.isFinite(delta)) {
        return 'N/A';
    }

    return `${Math.abs(delta).toFixed(1)} pts`;
}


function pulseBlock(
    label,
    score,
    delta,
    isNow = false,
    isStart = false
) {

    const color =
        scoreColor(
            score
        );


    const deltaColor =
        pulseDeltaColor(
            delta
        );


    const blockBackground =
        isNow
            ? '#21415d'
            : '#101d2b';


    return {

        table: {

            rows: [

                {

                    cells: [{

                        text:
                            label,

                        fontWeight:
                            'bold',

                        fontSize:
                            isNow
                                ? sv(13)
                                : sv(10),

                        color:
                            isNow
                                ? '#ffffff'
                                : '#9aa9ba',

                        textAlign:
                            'center',

                        padding:
                            isNow
                                ? pad(7, 9)
                                : pad(4, 6),

                        background:
                            blockBackground
                    }]

                },

                {

                    cells: [{

                        text:
                            fmt(
                                score,
                                0
                            ),

                        fontWeight:
                            'bold',

                        fontSize:
                            isNow
                                ? sv(22)
                                : sv(15),

                        color:
                            color,

                        textAlign:
                            'center',

                        padding:
                            isNow
                                ? pad(9, 10)
                                : pad(6, 7),

                        background:
                            blockBackground
                    }]

                },

                {

                    cells: [{

                        text:
                            scoreZone(
                                score
                            ),

                        fontWeight:
                            'bold',

                        fontSize:
                            isNow
                                ? sv(10)
                                : sv(9),

                        color:
                            color,

                        textAlign:
                            'center',

                        padding:
                            pad(2, 5),

                        background:
                            blockBackground
                    }]

                },

                {

                    cells: [{

                        text:
                            isStart
                                ? 'START'
                                : `${
                                    pulseDeltaArrow(
                                        delta
                                    )
                                } ${
                                    pulseDeltaText(
                                        delta
                                    )
                                }`,

                        fontWeight:
                            'bold',

                        fontSize:
                            isNow
                                ? sv(12)
                                : sv(9),

                        color:
                            isStart
                                ? '#8292a5'
                                : deltaColor,

                        textAlign:
                            'center',

                        padding:
                            isNow
                                ? pad(7, 8)
                                : pad(4, 5),

                        background:
                            blockBackground
                    }]

                }

            ]

        }

    };
}


// ============================================================================
// CURRENT / YOY DISPLAY METRICS
// ============================================================================

const revenueGrowth =
    yoy(
        'revenue'
    );


const priorYoYRevenueGrowth =
    yoy(
        'revenue',
        1
    );


const fcfMargin =
    pctValue(
        'fcf_margin'
    );


const fcfMarginYearAgo =
    pctValue(
        'fcf_margin',
        4
    );


const roic =
    pctValue(
        'return_on_invested_capital'
    );


const roicYearAgo =
    pctValue(
        'return_on_invested_capital',
        4
    );


const sbc =
    pctValue(
        'sbc_to_revenue'
    );


const sbcYearAgo =
    pctValue(
        'sbc_to_revenue',
        4
    );


const netDebtEbitda =
    fv(
        'net_debt_ebitda'
    );


const netDebtEbitdaYearAgo =
    fv(
        'net_debt_ebitda',
        4
    );


// ============================================================================
// METRIC CARD HELPERS
// ============================================================================

function comparisonArrow(
    currentValue,
    referenceValue,
    lowerIsBetter = false
) {

    if (
        !Number.isFinite(currentValue) ||
        !Number.isFinite(referenceValue)
    ) {
        return '•';
    }


    if (lowerIsBetter) {

        if (currentValue < referenceValue) {
            return '▲';
        }

        if (currentValue > referenceValue) {
            return '▼';
        }

        return '→';
    }


    if (currentValue > referenceValue) {
        return '▲';
    }

    if (currentValue < referenceValue) {
        return '▼';
    }

    return '→';
}


function comparisonColor(
    currentValue,
    referenceValue,
    lowerIsBetter = false
) {

    if (
        !Number.isFinite(currentValue) ||
        !Number.isFinite(referenceValue)
    ) {
        return '#8292a5';
    }


    const improving =
        lowerIsBetter
            ? currentValue <
                referenceValue
            : currentValue >
                referenceValue;


    if (
        currentValue ===
        referenceValue
    ) {
        return '#f5c84b';
    }


    return improving
        ? '#13e69b'
        : '#ff4964';
}


function comparisonMetricCard(
    label,
    currentValue,
    referenceValue,
    formatter,
    referenceLabel,
    lowerIsBetter = false
) {

    const arrow =
        comparisonArrow(
            currentValue,
            referenceValue,
            lowerIsBetter
        );


    const color =
        comparisonColor(
            currentValue,
            referenceValue,
            lowerIsBetter
        );


    return {

        table: {

            rows: [

                {

                    cells: [{

                        text:
                            label,

                        fontWeight:
                            'bold',

                        color:
                            '#aebaca',

                        padding:
                            pad(3, 5),

                        textAlign:
                            'center'
                    }]

                },

                {

                    cells: [{

                        text:
                            `${formatter(
                                currentValue
                            )} ${arrow}`,

                        color:
                            color,

                        fontWeight:
                            'bold',

                        fontSize:
                            sv(13),

                        padding:
                            pad(4, 5),

                        textAlign:
                            'center'
                    }]

                },

                {

                    cells: [{

                        text:
                            `${referenceLabel} ${formatter(
                                referenceValue
                            )}`,

                        color:
                            '#8292a5',

                        padding:
                            pad(2, 5),

                        textAlign:
                            'center'
                    }]

                }

            ]

        }

    };
}


// ============================================================================
// REGIME / BIAS COLORS
// ============================================================================

const regimeColor =
    regime === 'LIMITED DATA'
        ? '#ff4964'
        : scoreColor(
            composite
        );


let regimeBackground =
    '#101d2b';


if (
    regime ===
    'LIMITED DATA'
) {

    regimeBackground =
        '#32171a';

}

else if (
    regime ===
    'STRONG ACCELERATION'
) {

    regimeBackground =
        '#0b352a';

}

else if (
    regime ===
    'ACCELERATING'
) {

    regimeBackground =
        '#103126';

}

else if (
    regime ===
    'STRONG DETERIORATION'
) {

    regimeBackground =
        '#3a1019';

}

else if (
    regime ===
    'DETERIORATING'
) {

    regimeBackground =
        '#32171a';

}


let convictionColor =
    '#f5c84b';


if (
    convictionBias ===
    'BULLISH' ||
    convictionBias ===
    'IMPROVING'
) {

    convictionColor =
        '#13e69b';

}

else if (
    convictionBias ===
    'BEARISH' ||
    convictionBias ===
    'WEAKENING'
) {

    convictionColor =
        '#ff4964';

}


// ============================================================================
// DASHBOARD
// ============================================================================

const dashboardRows = [];


// ============================================================================
// HEADER
// ============================================================================

dashboardRows.push({

    cells: [{

        colspan:
            3,

        text:
            `◉ FUNDAMENTAL INFLECTION RADAR — ${current.ticker}  v2.0a`,

        fontWeight:
            'bold',

        fontSize:
            sv(16),

        color:
            '#ddfbff',

        background:
            '#102b3c',

        padding:
            pad(9, 12)
    }]

});


// ============================================================================
// STATUS
// ============================================================================

dashboardRows.push({

    cells: [{

        colspan:
            3,

        text:
            `REGIME: ${regime}   |   BIAS: ${convictionBias}   |   ${conviction} CONVICTION`,

        fontWeight:
            'bold',

        fontSize:
            sv(12),

        color:
            regimeColor,

        background:
            regimeBackground,

        textAlign:
            'center',

        padding:
            pad(7, 10)
    }]

});


// ============================================================================
// DATA COVERAGE
// ============================================================================

// Coverage and price share one row — both are status rather than findings,
// and as separate full-width rows they pushed the first real data 30px
// further down. The price cell carries just the state: on a non-daily chart
// the old row spanned the whole panel to say "DAILY CHART ONLY".
dashboardRows.push({

    cells: [

        {

            colspan:
                2,

            text:
                `COVERAGE ${fmt(
                    dataCoveragePct,
                    0
                )}%  ·  ${dataConfidence}  ·  ${coverage.available}/${coverage.possible}`,

            fontWeight:
                'bold',

            color:
                dataCoverageColor,

            background:
                '#0b1823',

            textAlign:
                'center',

            padding:
                pad(5, 8)
        },

        {

            text:
                `PRICE: ${priceRelationship}`,

            fontWeight:
                'bold',

            color:
                priceRelationshipColor,

            background:
                '#08141e',

            textAlign:
                'center',

            padding:
                pad(5, 8)
        }

    ]

});


// Only shown when the request itself failed. Without it, a failed fetch is
// indistinguishable from a ticker that genuinely has no coverage.
if (fetchErrorText) {

    dashboardRows.push({

        cells: [{

            colspan:
                3,

            text:
                `⚠ FUNDAMENTAL DATA UNAVAILABLE — ${fetchErrorText}`,

            fontWeight:
                'bold',

            color:
                '#ff4964',

            background:
                '#2a0f12',

            textAlign:
                'center',

            padding:
                pad(6, 8)
        }]

    });

}


// ============================================================================
// THESIS
// ============================================================================

dashboardRows.push({

    cells: [{

        colspan:
            3,

        text:
            thesisText,

        color:
            '#c7d2df',

        background:
            '#101a24',

        textAlign:
            'center',

        padding:
            pad(8, 10),

        fontSize:
            sv(11)
    }]

});


// ============================================================================
// GAUGES
// ============================================================================

dashboardRows.push({

    cells: [

        // QUALITY

        {

            table: {

                rows: [

                    {

                        cells: [{

                            text:
                                'QUALITY',

                            fontWeight:
                                'bold',

                            color:
                                '#aebaca',

                            textAlign:
                                'center',

                            padding:
                                px(4)
                        }]

                    },

                    {

                        cells: [{

                            chart:
                                gaugeChart(
                                    quality,
                                    scoreColor(
                                        quality
                                    ),
                                    'Quality',
                                    px(130),
                                    px(100)
                                )

                        }]

                    },

                    {

                        cells: [{

                            text:
                                `${fmt(
                                    quality,
                                    0
                                )} / 100`,

                            color:
                                scoreColor(
                                    quality
                                ),

                            fontWeight:
                                'bold',

                            textAlign:
                                'center'
                        }]

                    },

                    {

                        cells: [{

                            text:
                                scoreZone(
                                    quality
                                ),

                            color:
                                scoreColor(
                                    quality
                                ),

                            fontSize:
                                sv(9),

                            textAlign:
                                'center'
                        }]

                    }

                ]

            }

        },


        // INFLECTION

        {

            table: {

                rows: [

                    {

                        cells: [{

                            text:
                                'INFLECTION',

                            fontWeight:
                                'bold',

                            color:
                                '#aebaca',

                            textAlign:
                                'center',

                            padding:
                                px(4)
                        }]

                    },

                    {

                        cells: [{

                            chart:
                                gaugeChart(
                                    composite,
                                    scoreColor(
                                        composite
                                    ),
                                    'Inflection',
                                    px(190),
                                    px(135)
                                )

                        }]

                    },

                    {

                        cells: [{

                            text:
                                `${fmt(
                                    composite,
                                    0
                                )} / 100`,

                            fontWeight:
                                'bold',

                            fontSize:
                                sv(20),

                            color:
                                scoreColor(
                                    composite
                                ),

                            textAlign:
                                'center',

                            padding:
                                px(2)
                        }]

                    },

                    {

                        cells: [{

                            text:
                                scoreZone(
                                    composite
                                ),

                            fontWeight:
                                'bold',

                            color:
                                scoreColor(
                                    composite
                                ),

                            textAlign:
                                'center',

                            padding:
                                px(2)
                        }]

                    },

                    {

                        cells: [{

                            text:
                                Number.isFinite(scoreChange1)
                                    ? `${
                                        scoreChange1 >= 0
                                            ? '▲'
                                            : '▼'
                                    } ${
                                        fmt(
                                            Math.abs(
                                                scoreChange1
                                            ),
                                            1
                                        )
                                    } pts vs prior Q`
                                    : 'Prior-Q comparison unavailable',

                            fontWeight:
                                'bold',

                            color:
                                Number.isFinite(scoreChange1)
                                    ? (
                                        scoreChange1 >= 0
                                            ? '#13e69b'
                                            : '#ff4964'
                                    )
                                    : '#8292a5',

                            textAlign:
                                'center',

                            padding:
                                px(3),

                            fontSize:
                                sv(10)
                        }]

                    }

                ]

            }

        },


        // FUNDAMENTAL MOMENTUM

        {

            table: {

                rows: [

                    {

                        cells: [{

                            text:
                                'FUND MOMENTUM',

                            fontWeight:
                                'bold',

                            color:
                                '#aebaca',

                            textAlign:
                                'center',

                            padding:
                                px(4)
                        }]

                    },

                    {

                        cells: [{

                            chart:
                                gaugeChart(
                                    fundMomentum,
                                    '#3fa7ff',
                                    'Fundamental Momentum',
                                    px(130),
                                    px(100)
                                )

                        }]

                    },

                    {

                        cells: [{

                            text:
                                `${fmt(
                                    fundMomentum,
                                    0
                                )} / 100`,

                            color:
                                Number.isFinite(fundMomentum)
                                    ? '#3fa7ff'
                                    : '#8292a5',

                            fontWeight:
                                'bold',

                            textAlign:
                                'center'
                        }]

                    },

                    {

                        cells: [{

                            text:
                                scoreZone(
                                    fundMomentum
                                ),

                            color:
                                Number.isFinite(fundMomentum)
                                    ? '#3fa7ff'
                                    : '#8292a5',

                            fontSize:
                                sv(9),

                            textAlign:
                                'center'
                        }]

                    }

                ]

            }

        }

    ]

});


// ============================================================================
// FUNDAMENTAL ENGINES
// ============================================================================

dashboardRows.push({

    cells: [{

        colspan:
            3,

        text:
            'FUNDAMENTAL ENGINES',

        fontWeight:
            'bold',

        color:
            '#aebaca',

        padding:
            pad(7, 8)
    }]

});


dashboardRows.push({

    cells: [{

        colspan:
            3,

        table: {

            rows: [

                {

                    cells: [{

                        colspan:
                            3,

                        table:
                            engineMeter(
                                'GROWTH',
                                growth,
                                growthPrev,
                                growthReason()
                            ).table

                    }]

                },


                {

                    cells: [{

                        colspan:
                            3,

                        table:
                            engineMeter(
                                'MARGINS',
                                margins,
                                marginsPrev,
                                marginReason()
                            ).table

                    }]

                },


                {

                    cells: [{

                        colspan:
                            3,

                        table:
                            engineMeter(
                                'CASH FLOW',
                                cashFlow,
                                cashFlowPrev,
                                cashReason()
                            ).table

                    }]

                },


                {

                    cells: [{

                        colspan:
                            3,

                        table:
                            engineMeter(
                                'EFFICIENCY',
                                efficiency,
                                efficiencyPrev,
                                efficiencyReason()
                            ).table

                    }]

                },


                {

                    cells: [{

                        colspan:
                            3,

                        table:
                            engineMeter(
                                'BALANCE',
                                balance,
                                balancePrev,
                                balanceReason()
                            ).table

                    }]

                }

            ]

        }

    }]

});


// ============================================================================
// FUNDAMENTAL PULSE
// ============================================================================

if (showPulse) {

    dashboardRows.push({

        cells: [{

            colspan:
                3,

            text:
                'FUNDAMENTAL PULSE — 4 QUARTERS',

            fontWeight:
                'bold',

            color:
                '#aebaca',

            padding:
                pad(8, 8)
        }]

    });


    dashboardRows.push({

        cells: [{

            colspan:
                3,

            table: {

                rows: [

                    {

                        cells: [

                            pulseBlock(
                                'Q-3',
                                composite3,
                                null,
                                false,
                                true
                            ),

                            pulseBlock(
                                'Q-2',
                                composite2,
                                scoreChange3,
                                false,
                                false
                            ),

                            pulseBlock(
                                'Q-1',
                                composite1,
                                scoreChange2,
                                false,
                                false
                            ),

                            pulseBlock(
                                'NOW',
                                composite,
                                scoreChange1,
                                true,
                                false
                            )

                        ]

                    }

                ]

            }

        }]

    });

}


// ============================================================================
// KEY FUNDAMENTALS — CURRENT VS 1Y
// ============================================================================

if (showMetricCards) {

    dashboardRows.push({

        cells: [{

            colspan:
                3,

            text:
                'KEY FUNDAMENTALS — CURRENT VS 1Y',

            fontWeight:
                'bold',

            color:
                '#aebaca',

            padding:
                pad(7, 8)
        }]

    });


    dashboardRows.push({

        cells: [

            comparisonMetricCard(

                'Revenue Growth',

                revenueGrowth,

                priorYoYRevenueGrowth,

                value =>
                    fmtPct(
                        value
                    ),

                'Prior YoY'

            ),


            comparisonMetricCard(

                'FCF Margin',

                fcfMargin,

                fcfMarginYearAgo,

                value =>
                    fmtPlainPct(
                        value
                    ),

                '1Y Ago'

            ),


            comparisonMetricCard(

                'ROIC',

                roic,

                roicYearAgo,

                value =>
                    fmtPlainPct(
                        value
                    ),

                '1Y Ago'

            )

        ]

    });


    dashboardRows.push({

        cells: [

            comparisonMetricCard(

                'SBC / Revenue',

                sbc,

                sbcYearAgo,

                value =>
                    fmtPlainPct(
                        value
                    ),

                '1Y Ago',

                true

            ),


            comparisonMetricCard(

                'Net Debt / EBITDA',

                netDebtEbitda,

                netDebtEbitdaYearAgo,

                value =>
                    fmtRatio(
                        value
                    ),

                '1Y Ago',

                true

            ),


            {

                table: {

                    rows: [

                        {

                            cells: [{

                                text:
                                    'ENGINE FLOW',

                                fontWeight:
                                    'bold',

                                color:
                                    '#aebaca',

                                textAlign:
                                    'center',

                                padding:
                                    pad(3, 5)
                            }]

                        },

                        {

                            cells: [{

                                text:
                                    `${improvingEngines} Improving | ${worseningEngines} Weakening`,

                                fontWeight:
                                    'bold',

                                color:
                                    convictionColor,

                                textAlign:
                                    'center',

                                padding:
                                    pad(6, 5),

                                fontSize:
                                    sv(10)
                            }]

                        },

                        {

                            cells: [{

                                text:
                                    unavailableEngineComparisons > 0
                                        ? `${flatEngines} Flat | ${unavailableEngineComparisons} N/A`
                                        : `${flatEngines} Flat`,

                                color:
                                    '#8292a5',

                                textAlign:
                                    'center',

                                padding:
                                    pad(2, 5)
                            }]

                        }

                    ]

                }

            }

        ]

    });

}


// ============================================================================
// PAINT DASHBOARD
// ============================================================================

paint_overlay(

    'Table',

    {

        position:
            dashboardPosition,

        order:
            'above_all'

    },

    {

        fontSize:
            sv(11),

        border:
            px(1) + ' solid #31506a',

        background:
            'rgba(5, 17, 27, 0.96)',

        rows:
            dashboardRows

    }

);


// ============================================================================
// INFLECTION TRIGGERS
// ============================================================================
// Triggers are computed independently of showSignal. That input controls the
// on-chart LABELS only — a scanner user has no interest in whether labels are
// drawn, so gating the registered signal on a display toggle would be
// surprising behaviour.

const bullishTrigger =
    minimumCoverageMet &&
    Number.isFinite(composite) &&
    Number.isFinite(composite1) &&
    composite >= 60 &&
    composite1 < 60;


const bearishTrigger =
    minimumCoverageMet &&
    Number.isFinite(composite) &&
    Number.isFinite(composite1) &&
    composite <= 40 &&
    composite1 > 40;


// ============================================================================
// ON-CHART INFLECTION LABELS — DAILY ONLY
// ============================================================================
// paint() runs UNCONDITIONALLY. The platform registers the series on every
// pass, and wrapping paint in a conditional is what store review flagged on
// Volume Pace (fixed in its v1.0a). When no trigger fires, the series is
// all-null and nothing renders.
//
// DAILY ONLY, for the same reason the divergence read is. A label pins to the
// last bar; on a 10-minute chart that bar is ten minutes, so a quarterly
// event would be marked on an intraday candle — and because the composite
// does not move intraday, it would sit there on every low-timeframe chart
// permanently. isDailyChart governs every fundamentals-vs-price comparison in
// this file.

const bullishLabels =
    series_of(null);


if (
    showSignal &&
    isDailyChart &&
    bullishTrigger
) {

    bullishLabels[
        bullishLabels.length - 1
    ] =
        '▲ FUNDAMENTAL INFLECTION';
}


paint(

    bullishLabels,

    {

        style:
            'labels_below',

        color:
            '#13e69b',

        name:
            'Inflection Label'

    }

);


const bearishLabels =
    series_of(null);


if (
    showSignal &&
    isDailyChart &&
    bearishTrigger
) {

    bearishLabels[
        bearishLabels.length - 1
    ] =
        '▼ FUNDAMENTAL DETERIORATION';
}


paint(

    bearishLabels,

    {

        style:
            'labels_above',

        color:
            '#ff4964',

        name:
            'Deterioration Label'

    }

);


// ============================================================================
// SCANNER SIGNALS
// ============================================================================
// THREE conditions, deliberately. v1.2 had nine and several answered the same
// question — the user then has to decide which to trust, which is a worse
// experience than having fewer that each do something specific.
//
// Every signal requires minimumCoverageMet. A ticker whose data did not
// resolve should not appear in a scan on the strength of absent values.

function registerFlag(
    active,
    name
) {

    const flagSeries =
        close.map(
            function () {
                return 0;
            }
        );

    if (active) {

        flagSeries[
            flagSeries.length - 1
        ] = 1;
    }

    register_signal(
        flagSeries,
        name
    );
}


// ── Divergence ──────────────────────────────────────────────────────────────
// The reason this indicator exists. Fundamentals improving while price falls
// is the setup nothing else screens for, and the bar is deliberately high:
// price down over the quarter, composite up from last quarter, AND composite
// at or above 55 — so it is not merely "less bad on a falling stock".
//
// Computed in the PRICE RELATIONSHIP section, which means these are inert on
// anything but a daily chart. That is correct, not a limitation: the lookback
// is a quarter of trading days by design.

registerFlag(
    priceRelationship === 'BULL DIVERGENCE',
    'Bullish Fundamental Divergence'
);


registerFlag(
    priceRelationship === 'BEAR DIVERGENCE',
    'Bearish Fundamental Divergence'
);


// ── State ───────────────────────────────────────────────────────────────────
// One state condition so a scan returns a usable list. The crossing signals
// this replaces fired only on the quarter a boundary was crossed, which meant
// most scans came back empty. "Currently strong" catches the same names a
// quarter later and misses nothing.

registerFlag(
    minimumCoverageMet &&
    Number.isFinite(composite) &&
    composite >= scanStrongScore,
    'Fundamental Score Strong'
);