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

//@version=5
indicator("vix_vx_regression", overlay = true)

// regression function

import voided/regress/1


// inputs

len = input(252, "length")


// script

vix = request.security("VIX", "D", close - close[1])
vx1 = request.security("VX1!", "D", close - close[1])
vx2 = request.security("VX2!", "D", close - close[1])

[ vx1_alpha, vx1_beta, vx1_r2 ] = regress.regress(vix, vx1, len)
[ vx2_alpha, vx2_beta, vx2_r2 ] = regress.regress(vix, vx2, len)


// output

if barstate.islast

    lbl_clr = color.new(color.green, 70)

    fmt = "#.####"

    t = table.new(position.top_right, 3, 4)
    
    table.cell(t, 0, 0, str.tostring(len), bgcolor = color.new(color.fuchsia, 70))
    table.cell(t, 1, 0, "vx1", bgcolor = lbl_clr)
    table.cell(t, 2, 0, "vx2", bgcolor = lbl_clr)
    
    table.cell(t, 0, 1, "alpha", bgcolor = lbl_clr)
    table.cell(t, 1, 1, str.tostring(vx1_alpha, fmt))
    table.cell(t, 2, 1, str.tostring(vx2_alpha, fmt))

    table.cell(t, 0, 2, "beta", bgcolor = lbl_clr)
    table.cell(t, 1, 2, str.tostring(vx1_beta, fmt))
    table.cell(t, 2, 2, str.tostring(vx2_beta, fmt))
    
    table.cell(t, 0, 3, "r^2", bgcolor = lbl_clr)
    table.cell(t, 1, 3, str.tostring(vx1_r2, fmt))
    table.cell(t, 2, 3, str.tostring(vx2_r2, fmt))