Market Beta/Beta Coefficient for CAPM [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
// @description In finance, the beta (β or market beta or beta coefficient) is a measure of how an 
//      individual asset moves (on average) when the overall stock market increases or decreases.
//      Thus, beta is a useful measure of the contribution of an individual asset to the risk 
//      of the market portfolio when it is added in small quantity. Thus, beta is referred to 
//      as an asset's non-diversifiable risk, its systematic risk, market risk, or hedge ratio. 
//      Beta is not a measure of idiosyncratic risk.
indicator('Market Beta/Beta Coefficient for CAPM [Loxx]', 
     shorttitle ="BETACAPM [Loxx]",
     overlay = false)

// @function beta = (Covarianc(x[], y[]) / Variance(y[]))
// @param x float[], ticker on screen
// @param y float[], benchmark of market, typically SPY
// @return float, beta (β or market beta or beta coefficient) 

beta1(float x, float y, int per) =>
    float avgX = ta.sma(x, per)
    float avgY = ta.sma(y, per)
    float sum1 = 0.
    float sum2 = 0.
    for i = 0 to  per - 1
        sum1 += (x[i] - avgX) * (y[i] - avgY)
    beta = (sum1 / per) / ta.variance(y, per)
    beta 


// Average sums of square differences from the mean
// ssxm = mean( (x-mean(x))^2 )
// ssxym = mean( (x-mean(x)) * (y-mean(y)) )

// @function beta = Average sums of square differences from the mean
// @param x float[], ticker on screen
// @param y float[], benchmark of market, typically SPY
// @return float, beta (β or market beta or beta coefficient) 
beta2(float x, float y, int per) =>
    float avgX = ta.sma(x, per)
    float avgY = ta.sma(y, per)
    float sum1 = 0.
    float sum2 = 0.
    for i = 0 to per - 1
        sum1 += math.pow(nz(x[i]) - avgX, 2)
        sum2 += (nz(x[i]) - avgX) * (nz(y[i]) - avgY)
    float ssxm = sum1 / per
    float ssxym = sum2 / per
    float slope = ssxym / ssxm
    slope 

per = input(60, "Period")
string spyinput = input.symbol("SPY", "Benchmark")
string timeframe = input.timeframe("", "Timeframe")

float spyin = request.security(spyinput, timeframe, close)


src = math.log(close/close[1])
spy = math.log(spyin/spyin[1])

float beta1 = beta1(src, spy, per)
float beta2 = beta2(spy, src, per)

plot(beta1)
plot(beta2)

var testTable = table.new(position = position.top_right, columns = 1, rows = 2, bgcolor = color.black, border_width = 1)
if barstate.islast
    table.cell(table_id = testTable, 
         column = 0, 
         row = 0, 
         text = "Current Market Beta/Beta Coefficient for CAPM (version 1): " + str.tostring(beta1, "#.####"),
         text_size = size.normal, 
         bgcolor=color.yellow)
    table.cell(table_id = testTable, 
         column = 0, 
         row = 1, 
         text = "Current Market Beta/Beta Coefficient for CAPM (version 2): " + str.tostring(beta2, "#.####"),
         text_size = size.normal, 
         bgcolor=color.yellow)