Indicator · Pine Script v6 · Own pane

R² Coefficient of Determination (RSQUARED)

by mihakralj

This indicator calculates the R-squared coefficient of determination between a chosen price source and its exponential moving average over a specified lookback period.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code74
Settings2inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 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

74 lines of Pine Script v6 from lib/errors/rsquared/rsquared.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

rsquared.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("R² Coefficient of Determination (RSQUARED)", "RSQUARED")

//@function Calculates the R-squared (Coefficient of Determination) between two sources
//@param source1 First series to compare (actual)
//@param source2 Second series to compare (predicted)
//@param period Lookback period for averaging
//@returns R-squared value averaging over the specified period
rsquared(series float source1, series float source2, simple int period) =>
    if period <= 0
        runtime.error("Period must be greater than 0")
    int p = math.min(math.max(1, period), 4000)
    var float sum_source1 = 0.0
    var float[] buffer_source1 = array.new_float(p, na)
    var int head_source1 = 0
    var int valid_count_source1 = 0
    float oldest_source1 = array.get(buffer_source1, head_source1)
    if not na(oldest_source1)
        sum_source1 := sum_source1 - oldest_source1
        valid_count_source1 := valid_count_source1 - 1
    if not na(source1)
        sum_source1 := sum_source1 + source1
        valid_count_source1 := valid_count_source1 + 1
    array.set(buffer_source1, head_source1, source1)
    head_source1 := (head_source1 + 1) % p
    float mean_source1 = valid_count_source1 > 0 ? sum_source1 / valid_count_source1 : source1
    float squared_residual = math.pow(source1 - source2, 2)
    float total_ss = math.pow(source1 - mean_source1, 2)
    var float sum_squared_residual = 0.0
    var float[] buffer_squared_residual = array.new_float(p, na)
    var int head_squared_residual = 0
    var int valid_count_squared_residual = 0
    float oldest_squared_residual = array.get(buffer_squared_residual, head_squared_residual)
    if not na(oldest_squared_residual)
        sum_squared_residual := sum_squared_residual - oldest_squared_residual
        valid_count_squared_residual := valid_count_squared_residual - 1
    if not na(squared_residual)
        sum_squared_residual := sum_squared_residual + squared_residual
        valid_count_squared_residual := valid_count_squared_residual + 1
    array.set(buffer_squared_residual, head_squared_residual, squared_residual)
    head_squared_residual := (head_squared_residual + 1) % p
    var float sum_total_ss = 0.0
    var float[] buffer_total_ss = array.new_float(p, na)
    var int head_total_ss = 0
    var int valid_count_total_ss = 0
    float oldest_total_ss = array.get(buffer_total_ss, head_total_ss)
    if not na(oldest_total_ss)
        sum_total_ss := sum_total_ss - oldest_total_ss
        valid_count_total_ss := valid_count_total_ss - 1
    if not na(total_ss)
        sum_total_ss := sum_total_ss + total_ss
        valid_count_total_ss := valid_count_total_ss + 1
    array.set(buffer_total_ss, head_total_ss, total_ss)
    head_total_ss := (head_total_ss + 1) % p
    float rss = valid_count_squared_residual > 0 ? sum_squared_residual : squared_residual
    float tss = valid_count_total_ss > 0 ? sum_total_ss : total_ss
    tss != 0 ? 1 - (rss / tss) : 1.0


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

// Inputs
i_source1 = input.source(close, "Source")
i_period = input.int(100, "Period", minval=1)
i_source2 = ta.ema(i_source1, i_period)

// Calculation
score = rsquared(i_source1, i_source2, i_period)

// Plot
plot(score, "R²", color.new(color.red, 60, color=color.yellow, linewidth=2), linewidth = 2, style = plot.style_area)
plot(i_source2, "EMA", color.new(color.yellow, 0, linewidth=2), linewidth = 1, style = plot.style_line, force_overlay = true)

Overview

R² Coefficient of Determination (RSQUARED) plots the resulting statistical fit score as an area curve in a separate pane, alongside the moving average. Configurable inputs allow traders to adjust the price source and the averaging period. It provides no automated entry or exit signals and functions purely as a measure of trend fit rather than market direction.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Trend, Moving averages

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

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

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

SettingTypeDefaultVariable
Sourcesourceclosei_source1
Periodint100i_period
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

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
218 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

KamaFama

by Mastaaa1987
141 stars

KamaFama is an indicator that translates a Freqtrade trading strategy into Pine Script for visualization. It combines Kaufman Adaptive Moving Average (KAMA), MAMA/FAMA calculations derived via Hilbert Transform, Williams %R, and correlation trend filters to ev

Indicator v6 Moving averagesOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of KamaFama

MultiIndicator

by capissimo
114 stars

MultiIndicator combines multiple technical indicators into a single separate pane to save chart space. It calculates and displays market regime detection based on ordinary least squares regression, a Holt exponential smoothing crossover, normalized RSI, ADX, a

Indicator v4 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of MultiIndicator

Colored fill

by be-thomas
65 stars

This indicator plots two simple moving averages of close, one over five bars and one over twenty bars, in a separate pane. It shades the area between the two plots green when the shorter average is above the longer average and red when it is below. There are n

Indicator v4 Moving averagesTrend
Updated 4 days ago · GPL-3.0 GitHub repository of Colored fill

Hash Ribbons

by oguzhandilber
47 stars

This indicator plots the Hash Ribbon metric by calculating 30-day and 60-day simple moving averages of Bitcoin network hash rate data. Designed for long-term market cycle analysis, it draws in a separate pane and displays hash ribbons alongside optional buy si

Indicator v4 Moving averagesTrend Repaints
Updated 5 years ago · None stated GitHub repository of Hash Ribbons

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