Beta Calculator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © elio27

//@version=5
indicator(title="Beta Calculator", shorttitle="β calc", overlay=true)
sym = input.symbol(title="Symbol", defval="ETHUSDT", confirm=true)
market = input.symbol(title="Reference", defval="BTCUSDT", confirm=true)
lookback = input.int(title="Lookback candles", defval=60, confirm=true)


symPrice = request.security(sym, timeframe.period, close)
symReturn = (symPrice - symPrice[1]) / symPrice[1]
symReturnAverage = ta.sma(symReturn, lookback - 1)

marketPrice = request.security(market, timeframe.period, close)
marketReturn = (marketPrice - marketPrice[1]) / marketPrice[1]
marketReturnSquared = marketReturn * marketReturn
marketReturnAverage = ta.sma(marketReturn, lookback - 1)

sRmR = symReturn * marketReturn
marketReturnVariance = ta.sma(marketReturnSquared, lookback - 1) - marketReturnAverage*marketReturnAverage
covariance = ta.sma(sRmR, lookback - 1) - marketReturnAverage * symReturnAverage

beta = covariance / marketReturnVariance

tbl = table.new(position.middle_right, 1, 2)
table.cell(tbl, 0, 0, "Beta", bgcolor = #548C8C)
table.cell(tbl, 0, 1, str.tostring(beta), bgcolor=#82D9D9)
