Supertrend Multiasset Correlation - vanAmsen 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vanAmsen

//@version=5
indicator("vanAmsen - Supertrend Multiasset Correlation", overlay = true)

// ------- INPUT SETTINGS -------

// Existing inputs
atrPeriod = input.int(10, title="ATR Length", tooltip="Specifies the period over which the Average True Range (ATR) is calculated.", minval=1)
factor = input.float(6, title="Factor", tooltip="Multiplier factor for the ATR to define the distance of the Supertrend line from the price.", minval=0.1, step=0.1)
upColor = input.color(color.rgb(122,244,122), title="Up Color", tooltip="Color for the Supertrend line when the trend is upwards or bullish.")
downColor = input.color(color.rgb(244,122,122), title="Down Color", tooltip="Color for the Supertrend line when the trend is downwards or bearish.")
correlationLength = input.int(100, title="Correlation Length", tooltip="Length for the correlation calculation.", minval=1)

// New input for showTable
showTable = input.bool(true, title="Show Table", tooltip="Display the correlation prediction table.")

// Input symbols
ticker0 = input.symbol("VUG", title="Ticker 0")
ticker1 = input.symbol("VTV", title="Ticker 1")
ticker2 = input.symbol("XLF", title="Ticker 2")
ticker3 = input.symbol("XLV", title="Ticker 3")
ticker4 = input.symbol("XLE", title="Ticker 4")
ticker5 = input.symbol("XLK", title="Ticker 5")
ticker6 = input.symbol("XLY", title="Ticker 6")
ticker7 = input.symbol("XLI", title="Ticker 7")
ticker8 = input.symbol("XLB", title="Ticker 8")
ticker9 = input.symbol("TLT", title="Ticker 9")
ticker10 = input.symbol("IAU", title="Ticker 10")
ticker11 = input.symbol("XLU", title="Ticker 11")
// ... Add more ticker inputs as needed ...


// ------- INITIALIZATION -------

// Prediction initialization
var float prediction = na
prediction := 0.0

// Table & Array setups
var table tbl = table.new(position.top_right, 4, 15)
var dirArray = array.new<float>(13, na)
var corrArray = array.new<float>(13, na)
var predArray = array.new<float>(13, na)

// ------- FUNCTION DEFINITIONS -------

// Calculate correlation prediction for a given ticker based on ROC (Rate of Change)
correlationPrediction(ticker) =>
    [tickerSupertrend, tickerDirection] = request.security(ticker, timeframe.period, ta.supertrend(factor, atrPeriod))
    currentROC = ta.roc(close, 1) // Rate of Change for main asset for 1 day
    tickerROC = request.security(ticker, timeframe.period, ta.roc(close, 1)) // Rate of Change for ticker for 1 day
    tickerCorrelation = ta.correlation(currentROC, tickerROC, correlationLength)
    tickerCorrelation * tickerCorrelation * tickerDirection

// Update table with ticker correlation data based on ROC (Rate of Change)
correlationPredictionAndUpdateTable(ticker, colIndex) =>
    [tickerSupertrend, tickerDirection] = request.security(ticker, timeframe.period, ta.supertrend(factor, atrPeriod))
    currentROC = ta.roc(close, 1) // Rate of Change for main asset for 1 day
    tickerROC = request.security(ticker, timeframe.period, ta.roc(close, 1)) // Rate of Change for ticker for 1 day
    tickerCorrelation = ta.correlation(currentROC, tickerROC, correlationLength)
    tickerDirection := tickerDirection*-1

    correlatedPred = tickerCorrelation * tickerCorrelation * tickerDirection
    
    // Update table
    table.cell(tbl, 0, colIndex, ticker, bgcolor=color.silver, text_color=color.black)
    table.cell(tbl, 1, colIndex, str.tostring(tickerDirection), bgcolor=tickerDirection > 0 ? upColor : downColor)
    table.cell(tbl, 2, colIndex, str.tostring(tickerCorrelation, "#.00"), bgcolor=tickerCorrelation > 0 ? upColor : downColor)
    table.cell(tbl, 3, colIndex, str.tostring(correlatedPred, "#.00"), bgcolor=correlatedPred > 0 ? upColor : downColor)
    
    // Store in arrays
    array.set(dirArray, colIndex-1, tickerDirection)
    array.set(corrArray, colIndex-1, tickerCorrelation)
    array.set(predArray, colIndex-1, correlatedPred)
    
    [tickerDirection, tickerCorrelation, correlatedPred]  // Return as tuple

// ------- MAIN LOGIC -------

// Accumulate predictions
prediction := correlationPrediction(syminfo.ticker) + correlationPrediction(ticker0) + correlationPrediction(ticker1) + correlationPrediction(ticker2) + 
              correlationPrediction(ticker3) + correlationPrediction(ticker4) + correlationPrediction(ticker5) + 
              correlationPrediction(ticker6) + correlationPrediction(ticker7) + correlationPrediction(ticker8) + 
              correlationPrediction(ticker9) + correlationPrediction(ticker10) + correlationPrediction(ticker11)

prediction := prediction / 13
// Determine the plot position based on prediction
atrValue = ta.atr(correlationLength)
plotPosition = prediction < 0 ? close - (atrValue * (-prediction+1)) : close + (atrValue * (1+prediction))

plot(plotPosition, color=prediction < 0 ? upColor : downColor, title="Prediction", linewidth=1)

// Display table if condition met
if showTable and session.islastbar
    
    // Headers
    table.cell(tbl, 0, 0, "Tkr", bgcolor=color.silver, text_color=color.black)     // Ticker
    table.cell(tbl, 1, 0, "Dir", bgcolor=color.silver, text_color=color.black)    // Direction
    table.cell(tbl, 2, 0, "Corr", bgcolor=color.silver, text_color=color.black)   // Correlation
    table.cell(tbl, 3, 0, "Pred", bgcolor=color.silver, text_color=color.black)   // Prediction

    // Populate the table with data for each ticker
    correlationPredictionAndUpdateTable(syminfo.ticker, 1)
    correlationPredictionAndUpdateTable(ticker0, 2)
    correlationPredictionAndUpdateTable(ticker1, 3)
    correlationPredictionAndUpdateTable(ticker2, 4)
    correlationPredictionAndUpdateTable(ticker3, 5)
    correlationPredictionAndUpdateTable(ticker4, 6)
    correlationPredictionAndUpdateTable(ticker5, 7)
    correlationPredictionAndUpdateTable(ticker6, 8)
    correlationPredictionAndUpdateTable(ticker7, 9)
    correlationPredictionAndUpdateTable(ticker8, 10)
    correlationPredictionAndUpdateTable(ticker9, 11)
    correlationPredictionAndUpdateTable(ticker10, 12)
    correlationPredictionAndUpdateTable(ticker11, 13)

    // Calculate averages
    avgDirection = array.avg(dirArray)
    avgCorrelation = array.avg(corrArray)
    avgPrediction = array.avg(predArray)

    // Add the average values to the table
    table.cell(tbl, 0, 14, "Avg", bgcolor=color.silver, text_color=color.black)
    table.cell(tbl, 1, 14, str.tostring(avgDirection, "#.00"), bgcolor=avgDirection > 0 ? upColor : downColor)
    table.cell(tbl, 2, 14, str.tostring(avgCorrelation, "#.00"), bgcolor=avgCorrelation > 0 ? upColor : downColor)
    table.cell(tbl, 3, 14, str.tostring(avgPrediction, "#.00"), bgcolor=avgPrediction > 0 ? upColor : downColor)
