//@version=5
// REG-14 Volatility Regime Switch — Quant Arena (https://quantarenas.com/code/)
// Converted from the Python implementation used on the site. Daily timeframe. Not investment advice.
// Converted by hand from Python and not compiled in TradingView by us: please report problems.
strategy("REG-14 Volatility Regime Switch", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0, process_orders_on_close=true)
// Position weight is 0, 0.25, 0.5, 0.75 or 1, rebalanced to that fraction of equity every bar with
// strategy.order, like the Python daily-weight backtest. Order quantities are fractional; some
// instruments in TradingView may round them.
// Volatility percentile = share of the last `percentile_window` vol values strictly below today's vol.

volLookback      = input.int(20, "Vol lookback", minval=2)
percentileWindow = input.int(252, "Percentile window", minval=20)
lowPercentile    = input.float(50, "Low percentile")
highPercentile   = input.float(80, "High percentile")

ret = close / close[1] - 1
vol = ta.stdev(ret, volLookback, false) * math.sqrt(252)

float volPct = na
if not na(vol[percentileWindow - 1])
    int below = 0
    for k = 0 to percentileWindow - 1
        if vol[k] < vol
            below += 1
    volPct := below / percentileWindow * 100

ma = ta.sma(close, 50)
uptrend = close > ma

warmup = math.max(volLookback, percentileWindow, 50)

var float w = 0.0
if bar_index >= warmup and not na(volPct)
    if volPct < lowPercentile
        w := uptrend ? 1.0 : 0.5
    else if volPct > highPercentile
        w := 0.0
    else
        w := uptrend ? 0.75 : 0.25

plot(volPct, "Vol percentile", color=color.blue)
plot(w * 100, "Weight %", color=color.orange)
hline(lowPercentile, "Low percentile", color=color.green)
hline(highPercentile, "High percentile", color=color.red)

targetQty = close > 0 ? strategy.equity * w / close : 0.0
deltaQty = targetQty - strategy.position_size
if math.abs(deltaQty) > 1e-9
    if deltaQty > 0
        strategy.order("Rebalance", strategy.long, qty=deltaQty)
    else
        strategy.order("Rebalance", strategy.short, qty=-deltaQty)
