Indicator · Pine Script v6 · Own pane

One-Sample t-Test (ZTEST)

by mihakralj

This indicator calculates the one-sample t-statistic comparing the rolling mean of a selected price or return series against a hypothesized population mean.

View on GitHub

GitHub stars47on the repository
Pine versionv6current
Lines of code75
Settings3inputs
LicenceMIT
Last update8 months ago28 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

75 lines of Pine Script v6 from indicators/statistics/ztest.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

ztest.pine
// The MIT License (MIT)
// © mihakralj
//@version=6
indicator("One-Sample t-Test (ZTEST)", "t-TEST", overlay=false)

//@function Calculates the t-statistic for a one-sample hypothesis test
//@param source Source series to test (use returns for meaningful results)
//@param period Lookback period for calculating sample mean and standard deviation
//@param mu0 Hypothesized population mean to test against
//@returns t-statistic (positive values indicate sample mean > mu0, negative indicate sample mean < mu0)
//@optimized Uses circular buffer with running sums for O(1) complexity, Bessel correction for sample variance
ztest(series float source, simple int period, simple float mu0) =>
    if period <= 1
        runtime.error("Period must be greater than 1")
    
    int p = period
    var array<float> buffer = array.new_float(0)
    var int head = 0
    var int n = 0
    var float sum = 0.0
    var float sumSq = 0.0
    
    if array.size(buffer) != p
        buffer := array.new_float(p, na)
        head := 0
        n := 0
        sum := 0.0
        sumSq := 0.0
    
    float oldest = array.get(buffer, head)
    if not na(oldest)
        sum -= oldest
        sumSq -= oldest * oldest
        n -= 1
    
    if not na(source)
        sum += source
        sumSq += source * source
        n += 1
        array.set(buffer, head, source)
    else
        array.set(buffer, head, na)
    
    head := (head + 1) % p
    
    float result = na
    if n >= 2
        float nf = float(n)
        float mean = sum / nf
        float variance = math.max(0.0, (sumSq / nf) - (mean * mean)) * (nf / (nf - 1.0))
        float stddev = math.sqrt(variance)
        float standard_error = stddev / math.sqrt(nf)
        
        if standard_error > 1e-10
            result := (mean - mu0) / standard_error
    
    result

// ---------- Main loop ----------

// Inputs
i_source = input.source(close, "Source")
i_period = input.int(30, "Period", minval=2, tooltip="Minimum 30 recommended for z-critical approximation")
i_mu0 = input.float(0.0, "Hypothesized Mean (μ₀)", step=0.01, tooltip="Use 0 when testing returns")

// Calculation
t_stat = ztest(i_source, i_period, i_mu0)

// Plot
plot(t_stat, "t-statistic", color=color.yellow, linewidth=2)
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dotted)
hline(2.04, "95% ~t(30)", color=color.new(color.green, 70), linestyle=hline.style_dashed)
hline(-2.04, "95% ~t(30)", color=color.new(color.green, 70), linestyle=hline.style_dashed)
hline(2.75, "99% ~t(30)", color=color.new(color.red, 70), linestyle=hline.style_dashed)
hline(-2.75, "99% ~t(30)", color=color.new(color.red, 70), linestyle=hline.style_dashed)

Overview

One-Sample t-Test (ZTEST) uses an O(1) circular buffer with running sums and Bessel's correction to compute sample variance efficiently. Users can customize the source series, lookback period, and hypothesized mean parameter. The calculated t-statistic is plotted in a separate pane alongside horizontal reference lines representing the zero baseline and approximate critical threshold values for 95% and 99% confidence levels.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

pinescriptpinescript-indicatorstechnical-analysistradingview-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosei_source
Periodint30i_period
Hypothesized Mean (μ₀)float0.0i_mu0
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
549 stars

Range Volume Change compares volume inside a chosen session window with the same window on the previous day and plots that change as a percentage. It accumulates volume during the window and, when enabled, volume outside it, drawing growing columns in a separa

Indicator v5 VolumeSessions & time Repaints
Updated 10 months ago · None stated GitHub repository of Range Volume Change

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers