Indicator · Pine Script v6 · Own pane

Beta Function (BETA)

by mihakralj

This indicator calculates a rolling financial beta that compares percentage returns of a selected source with percentage returns of a second symbol, defaulting to SPY.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code71
Settings3inputs
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

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

beta.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Beta Function (BETA)", "BETA", overlay=false)

//@function Calculates the financial Beta indicator comparing src1 volatility to src2
//@param src1 series float Series to analyze
//@param src2 series float src2 series to compare against
//@param period simple int Lookback period for calculation
//@returns float Beta value showing src1 volatility relative to src2
//@optimized for performance and dirty data
beta(series float src1, series float src2, simple int period) =>
    if period <= 0
        runtime.error("Period must be greater than 0")
    var float last_src1 = na
    var float last_src2 = na
    src1_return = last_src1 != 0 and not na(last_src1) ? (src1 - last_src1) / last_src1 : na
    bench_return = last_src2 != 0 and not na(last_src2) ? (src2 - last_src2) / last_src2 : na
    last_src1 := src1
    last_src2 := src2
    var int count = 0
    var float sum_sr = 0.0, var float sum_br = 0.0
    var float sum_sr2 = 0.0, var float sum_br2 = 0.0
    var float sum_sbr = 0.0
    var sr_buf = array.new_float(period)
    var br_buf = array.new_float(period)
    var int index = 0
    if not na(src1_return) and not na(bench_return)
        old_sr = array.get(sr_buf, index)
        old_br = array.get(br_buf, index)
        if count >= period
            sum_sr -= old_sr, sum_br -= old_br
            sum_sr2 -= old_sr * old_sr, sum_br2 -= old_br * old_br
            sum_sbr -= old_sr * old_br
        else
            count += 1
        sum_sr += src1_return, sum_br += bench_return
        sum_sr2 += src1_return * src1_return
        sum_br2 += bench_return * bench_return
        sum_sbr += src1_return * bench_return
        array.set(sr_buf, index, src1_return)
        array.set(br_buf, index, bench_return)
        index := (index + 1) % period
    if count > 0
        mean_sr = sum_sr / count
        mean_br = sum_br / count
        cov = (sum_sbr / count) - (mean_sr * mean_br)
        var_bench = (sum_br2 / count) - (mean_br * mean_br)
        if var_bench > 1e-10
            cov / var_bench
        else
            na
    else
        na


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

// Inputs
i_symbol = input.symbol("SPY", "src2 Symbol")
i_period = input.int(14, "Period", minval=1)
i_src1 = input.source(close, "src1")

// Get src2 data
src2Price = request.security(i_symbol, timeframe.period, close)

// Calculate beta
beta_value = beta(i_src1, src2Price, i_period)

// Plot
plot(beta_value, "Beta", color=color.yellow, linewidth=2)

Overview

Beta Function (BETA) keeps a circular buffer of returns over a user-set period and plots the result as a yellow line in a separate pane. The period, source series, and comparison symbol are the main settings. It returns no value when the lookback is not yet filled or the benchmark variance is too small.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Volatility & bands

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
src2 SymbolsymbolSPYi_symbol
Periodint14i_period
src1sourceclosei_src1
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

This indicator calculates the distribution of close-to-close percentage changes using rate of change on closing prices. It bins percentage changes into intervals of 0.25 percent increments from negative to positive values and plots a normalized cumulative hist

Indicator v4 Volatility & bands
Updated 10 days ago · GPL-3.0 GitHub repository of Close-to-Close % Change Distribution

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper
330 stars

This indicator plots candle range and open-to-close movement as percentages in a separate pane. Range is the high-low difference divided by the low, and change is the close-open difference divided by the open. Both series draw as columns. Teal columns show ran

Indicator v5 Volatility & bands
Updated 2 months ago · None stated GitHub repository of Percent & Volatility [Alorse]

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

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation

MACD-V

by harryguiacorn
219 stars

MACD-V is a volatility-normalized momentum indicator based on research by Alex Spiroglou. It calculates the standard MACD histogram and normalizes it by dividing by the Average True Range (ATR). Plotted in a separate pane as a colored histogram, it includes us

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of MACD-V

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