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


//@version=4
study(title="Spot-Vol Correlation", shorttitle="Spot-Vol Corr", overlay=false)

// Inputs
symbol1 = input(defval="CBOE:VIX", title="First Symbol", type=input.symbol)
symbol2 = input(defval="SPY", title="Second Symbol", type=input.symbol)
length = input(defval=10, title="Length of Calculation Period", minval=1)
upperBound = input(defval=-0.60, title="Upper Bound of Normal Zone", type=input.float)
lowerBound = input(defval=-1.00, title="Lower Bound of Normal Zone", type=input.float)

// Fetch data for the symbols
asset1 = security(symbol1, timeframe.period, close)
asset2 = security(symbol2, timeframe.period, close)

// Calculate percentage change for both assets
pct_change1 = (asset1 - asset1[1]) / asset1[1] * 100
pct_change2 = (asset2 - asset2[1]) / asset2[1] * 100

// Calculate correlation value
correlationValue = correlation(pct_change1, pct_change2, length)

// Determine plot color
plotColor = (pct_change1 < 0 and pct_change2 > 0) or (pct_change1 > 0 and pct_change2 < 0) ? color.green : color.red

// Plotting
correlationPlot = plot(correlationValue, title="Correlation Coefficient", color=plotColor, linewidth=2)
plot_upper = plot(upperBound, color=color.new(color.blue, 100)) // fully transparent (invisible) plot for upper bound
plot_lower = plot(lowerBound, color=color.new(color.blue, 100)) // fully transparent (invisible) plot for lower bound

// Fill normal zone
fill(plot_upper, plot_lower, color=color.new(color.green, 90), title="Fill between Normal Zone")
hline(0, "Zero", color=color.gray)
