Skip to Content
While25SDK docs
ExamplesIndicators

Trend significance: is the drift in the last N closes real, or noise?

Fits a least-squares line through the last `length` closes and draws the slope's t-statistic as a histogram in its own pane, with the +/-2 line shaded. Use it to compare trend strength across symbols: a t-statistic has no units.

Fits a least-squares line through the last length closes and draws the slope's t-statistic as a histogram in its own pane, with the +/-2 line shaded. Use it to compare trend strength across symbols: a t-statistic has no units.

Shows: Indicator, Plot(plot_type="histogram"), Level, Band, a callable warmup, while25.bars, pure helper functions.

View on GitHub

indicators/trend_significance.py
"""Trend significance: is the drift in the last N closes real, or noise?

Fits a least-squares line through the last `length` closes and draws the
slope's t-statistic as a histogram in its own pane, with the +/-2 line shaded.
Use it to compare trend strength across symbols: a t-statistic has no units.

Shows: Indicator, Plot(plot_type="histogram"), Level, Band, a callable warmup, while25.bars, pure helper functions.
"""
# Fits an ordinary least-squares line through the last `length` closes and divides
# the slope by its own standard error. What comes back is the slope's
# t-statistic: how many standard errors the fitted trend sits away from flat.
#
# A slope on its own says very little. Two instruments can both drift 0.4 points
# a bar and mean completely different things — one a clean ramp, the other a
# coin-flip that happened to land the same way twenty times. Dividing by the
# standard error is what separates them, and it is also why this reads the same
# on a $50 stock as on a 6,000-point index: a t-statistic carries no units,
# so there is nothing to normalise and nothing to re-tune per symbol.
#
# The sign is the direction; |t| is how firmly the window leans that way.
#
# WHAT THE +/-2 LINE DOES AND DOES NOT MEAN. Two is the textbook 5% critical
# value, and it earns that meaning only when the regression's residuals are
# independent. The residuals of a PRICE LEVEL are not — a price series is close
# to a random walk, so consecutive residuals are strongly autocorrelated and the
# statistic is inflated well past what the t-table assumes. Simulated here: on a
# driftless random walk |t| clears 2 about 72% of the time; on the i.i.d. noise
# the threshold is actually calibrated for, 6%. So read this as a RELATIVE
# strength-of-trend reading — comparable across symbols and across bars, which
# is the useful part — and not as a 5% significance test on price levels. If you
# want the textbook reading back, fit the same line to log RETURNS rather than
# closes: differencing is what removes the unit root.
#
# Runs on `pip install while25` alone. `t_statistic` and `t_series` are plain
# functions over plain lists, so the arithmetic can be tested without the platform.

import math

import while25
from while25 import Band, Indicator, Level, Plot
from while25.inputs import Int

# The conventional two-sigma line.
#
# NOT an input, deliberately. `levels` and `bands` are class attributes read
# once at registration, so they cannot follow a value the user edits in the
# config dialog. A dialog that moved the rule without moving the lines drawn
# for it would state the threshold in two places and be wrong in one of them.
THRESHOLD = 2.0

# The outer edge of the amber shading — a DRAWING bound, not a value bound:
# nothing here clamps a t-statistic, and the zone exists only to give the
# shaded rectangle a far side. Well past anything the pane autoscales to (a
# hard 20-bar ramp reaches |t| in the low hundreds), and finite and tame so
# the chart's price-to-pixel conversion stays in a sane numeric range.
ZONE_EDGE = 1000.0

# The platform's own chart tokens, so this reads as one of the built-ins
# rather than as a plugin in a colour of its own invention.
AMBER = "#E8A817"
DIM = "#524C46"

NAN = float("nan")


def t_statistic(window):
    """The t-statistic of an OLS slope fitted through `window`.

    x is the bar's offset inside the window (0, 1, ... n-1), so the line is
    fitted against bar count rather than clock time — the chart's own spacing,
    which is what keeps an overnight gap from registering as a flat stretch.

        b  = Sxy / Sxx                        the slope
        SE = sqrt( SSE / ((n - 2) * Sxx) )    its standard error
        t  = b / SE

    Two passes (means first, then deviations) rather than the textbook
    sum-of-squares shortcut: Sum(y^2) - n*mean^2 loses most of its significant
    digits when y is an index level near 24,000 and its variance is a few
    points, which is exactly the series this gets pointed at.

    Returned unclamped. A 20-bar window on a clean ramp genuinely reaches |t|
    in the hundreds, and saturating that at some tidy number would report a
    figure the data did not produce.
    """
    n = len(window)
    if n < 3:                       # df = n - 2 has to be at least 1
        return NAN

    x_mean = (n - 1) / 2.0
    y_mean = math.fsum(window) / n

    sxx = 0.0
    sxy = 0.0
    syy = 0.0
    for i, y in enumerate(window):
        dx = i - x_mean
        dy = y - y_mean
        sxx += dx * dx
        sxy += dx * dy
        syy += dy * dy

    if sxx <= 0.0:                  # unreachable for n >= 3; guards the divide
        return NAN

    slope = sxy / sxx

    # Residual sum of squares by the identity SSE = Syy - b*Sxy, floored at
    # zero: on a near-perfect fit the subtraction can land a hair below it.
    sse = max(syy - slope * sxy, 0.0)

    if sse <= 0.0:
        # Nothing left over, so the standard error is exactly zero.
        #
        # Flat window: the slope is zero too, so this is 0/0 — and "no trend"
        # is the true reading rather than a hole in the histogram.
        if slope == 0.0:
            return 0.0
        # A bit-exact straight line: the t-statistic is infinite. NaN rather
        # than infinity — NaN is the chart's declared gap marker, and an inf
        # would travel the wire only to be dropped by the renderer's own
        # isFinite check, arriving at the same blank bar by a route nothing
        # documents. Reaching this needs closes that are linear to the last
        # bit, which means a synthetic or stuck feed, not a market.
        return NAN

    std_err = math.sqrt(sse / ((n - 2) * sxx))
    return slope / std_err


def t_series(closes, length):
    """`t_statistic` over a rolling window, NaN until the window first fills.

    NaN rather than 0.0 for the warm-up: zero is a real reading here (a window
    with no discernible lean), so padding with one would draw nineteen bars of
    "no trend" that were never computed.
    """
    out = [NAN] * len(closes)
    for i in range(length - 1, len(closes)):
        out[i] = t_statistic(closes[i - length + 1:i + 1])
    return out


class TrendSignificance(Indicator):
    id = "trend_significance"
    label = "Trend Significance"

    # Its own pane. A t-statistic shares no axis with price — drawn over the
    # candles it would sit in a band a few ticks tall and read as a flat line.
    overlay = False

    inputs = [Int("length", default=20, minimum=3, maximum=500, step=1)]

    # One plot, drawn as bars around zero. Both directions take the same dim
    # colour: above and below the zero line already says which way, and a
    # second hue there would compete with the amber that marks significance.
    plots = [Plot("t", plot_type="histogram", color=DIM, color_down=DIM)]

    levels = [Level(0.0, color=DIM, width=1, style="solid"),
              Level(THRESHOLD, color=AMBER, style="dashed"),
              Level(-THRESHOLD, color=AMBER, style="dashed")]

    # Amber past +/-2, so a bar that clears the threshold is standing in a
    # shaded zone rather than asking the reader to measure it against an axis.
    bands = [Band(ZONE_EDGE, THRESHOLD, color=AMBER, opacity=0.07),
             Band(-THRESHOLD, -ZONE_EDGE, color=AMBER, opacity=0.07)]

    precision = 2

    warmup = lambda params: int(params.get("length", 20))

    def compute(self, ctx):
        rows = while25.bars

        # The chart's own wire times, so every value lands on the candle it was
        # computed from even after a scrollback.
        self.times = [int(r["time"]) for r in rows]

        length = int(while25.params["length"])
        closes = [float(r["close"]) for r in rows]
        return {"t": t_series(closes, length)}