Skip to Content
While25SDK docs
ExamplesIndicators

Return z-score in its own pane

How unusual the latest N-bar return is against the returns of the recent past, in standard deviations, drawn as a histogram coloured by sign, with lines at +/-2 and the zone between +/-1 shaded. The scale is fixed so two charts read alike, and it recomputes as the bar forms.

How unusual the latest N-bar return is against the returns of the recent past, in standard deviations, drawn as a histogram coloured by sign, with lines at +/-2 and the zone between +/-1 shaded. The scale is fixed so two charts read alike, and it recomputes as the bar forms.

Shows: Indicator in its own pane (overlay=False), Plot(plot_type="histogram", color_down=), Plot(plot_type="stepline"), Level, Band, y_min / y_max, precision, intrabar=True, while25.forming.

View on GitHub

indicators/return_zscore.py
"""Return z-score in its own pane

How unusual the latest N-bar return is against the returns of the recent
past, in standard deviations, drawn as a histogram coloured by sign, with
lines at +/-2 and the zone between +/-1 shaded. The scale is fixed so two
charts read alike, and it recomputes as the bar forms.

Shows: Indicator in its own pane (overlay=False), Plot(plot_type="histogram", color_down=), Plot(plot_type="stepline"), Level, Band, y_min / y_max, precision, intrabar=True, while25.forming.
"""
import math

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


def returns(closes, horizon):
    """Each bar's log return over the last `horizon` bars; None before that."""
    out = [None] * len(closes)
    for i in range(horizon, len(closes)):
        a, b = closes[i - horizon], closes[i]
        out[i] = math.log(b / a) if a > 0 and b > 0 else None
    return out


def zscores(series, window):
    """Each value against the `window` values before it; None while there
    are too few, or when they do not vary."""
    out = [None] * len(series)
    for i in range(len(series)):
        past = [x for x in series[max(0, i - window):i] if x is not None]
        x = series[i]
        if x is None or len(past) < window:
            continue
        mean = sum(past) / len(past)
        sd = (sum((p - mean) ** 2 for p in past) / len(past)) ** 0.5
        out[i] = None if sd == 0 else max(-4.0, min(4.0, (x - mean) / sd))
    return out


class ReturnZScore(Indicator):
    id = "return_zscore"
    label = "Return z-score"
    overlay = False
    intrabar = True
    y_min, y_max, precision = -4, 4, 2

    inputs = [Int("horizon", default=5, minimum=1, maximum=100, label="Return over N bars"),
              Int("window", default=100, minimum=10, maximum=1000, label="Compared with N returns")]

    plots = [Plot("z", color="#34D399", color_down="#F87171", plot_type="histogram"),
             Plot("zero", color="#8A8279", plot_type="stepline", width=1)]
    levels = [Level(2, color="#E8A817"), Level(-2, color="#E8A817")]
    bands = [Band(1, -1, color="#8A8279", opacity=0.06)]

    warmup = lambda params: int(params.get("horizon", 5)) + int(params.get("window", 100))  # noqa: E731

    def compute(self, ctx):
        p = while25.params
        rows = list(while25.bars)
        if while25.forming is not None:         # the bar still forming, intrabar
            rows.append(while25.forming)
        z = zscores(returns([r["close"] for r in rows], p["horizon"]), p["window"])
        self.times = [int(r["time"]) for r in rows]
        return {"z": z, "zero": [0.0] * len(rows)}