HPK Crash Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JoeCA9772

//@version=5
indicator("HPK Crash Indicator", overlay=true)

//
return_period = input(252, title="Period for Return")
volatility_period = input(21, title="Period for Volatility")

// thresholds
return_bound = input.float(2, title="Z-Score Bound for Return")
volatility_bound = input.float(2, title="Z-Score Bound for Volatility")

// regime length
window = input(1260, title="Trailing Window")

// additional feature
include_surges = input.bool(true, "Include Surge Warnings")

//
return_ = math.log(close / close[return_period])
volatility = ta.stdev(close / close[1], volatility_period)

// regime z-scores
return_z = (return_ - ta.sma(return_, window)) / ta.stdev(return_, window) 
volatility_z = (volatility - ta.sma(volatility, window)) / ta.stdev(volatility, window)

// thresholds met?
warning = (return_z > return_bound) and (volatility_z > volatility_bound) ? true : false
surge_warning = include_surges and (return_z < (-1 * return_bound)) and (volatility_z > volatility_bound) ? true : false

// plot(s)
bgcolor(warning ? color.new(color.red, 85) : na)
bgcolor(surge_warning ? color.new(color.green, 85) : na)
