OPEN-SOURCE SCRIPT

Value at Risk (VaR/CVaR) - Stop Loss Tool

111
This script calculates Value at Risk (VaR) and Conditional Value at Risk (CVaR) over a configurable T-bar forward horizon, based on historical T-bar log returns. It plots projected price thresholds that reflect the worst X% of historical return outcomes, helping set statistically grounded stop-loss levels.

A 95% 5-day VaR of −3% means: “In the worst 5% of all historical 5-day periods, losses were 3% or more.” If you're bullish, and your thesis is correct, price should not behave like one of those worst-case scenarios. So if the market starts trading below that 5-day VaR level, it may indicate that your long bias is invalidated, and a stop-loss near that level can help protect against further downside consistent with tail-risk behavior.

How it's different:
Unlike ATR or standard deviation-based methods, which measure recent volatility magnitude, VaR/CVaR incorporate both the magnitude and **likelihood** (5% chance for example) of adverse moves. This makes it better suited for risk-aware position sizing and exits grounded in actual historical return distributions.

How to use for stop placement:
- Set your holding horizon (T) and confidence level (e.g., 95%) in the inputs.
- The script plots a price level below which only the worst 5% (or chosen %) of T-bar returns have historically occurred (VaR).
- If price approaches or breaches the VaR line, your bullish/bearish thesis may be invalidated.
- CVaR gives a deeper threshold: the average loss **if** things go worse than VaR — useful for a secondary or emergency stop.

FURTHER NOTES FROM SOURCE CODE:
//======================================================================//
// If you're bullish (expecting the price to go up), then under normal circumstances, prices should not behave like they do on the worst-case days.
// If they are — you're probably wrong, or something unexpected is happening. Basically, returns shouldn't be exhibiting downside tail-like behavior if you're bullish.
// VaR(95%, T) gives the threshold below which the price falls only 5% of the time historically, over T days/bars and considering N historical samples.
// CVaR tells you the expected/average price level if that adverse move continues

// Caveats:
// For a variety of reasons, VaR underestimates volatility, despite using historical returns directly rather than making normality assumptions
// as is the case with the standard historicalvol/bollinger band/stdev/ATR approaches)

// Volatility begets volatility (volatility clustering), and VaR is not a conditional probability on recent volatility so it likely underestimates the true volatility of an adverse event
// Regieme shifts occur (bullish phase after prolonged bearish behavior), so upside/short VaR would underestimate the best-case days in the beginning of that move, depending on lookahead horizon/sampling period
// News/events happen, and maybe your sampling period doesn't contain enough event-driven returns to form reliable stats
// In general of course, this tool assumes past return distributions are reflective of forward risk (not the case in non-stationary time series)
// Thus, this tool is not predictive — it shows historical tail risk, not guaranteed outcomes.
// Also, when forming log-returns, overlapping windows of returns are used (to get more samples), but this introduces autocorrelation (if it wasn't there already). This means again, the true VaR is underestimated.

// Description:
// This script calculates and plots both Value at Risk (VaR) and
// Conditional Value at Risk (CVaR) for a given confidence level, using
// historical log returns. It computes both long-side (left tail) and
// short-side (right tail) risk, and converts them into price thresholds (red and green lines respectively).
//
// Key Concepts:
// - VaR: "There is a 95% chance the loss will be less than this value over T days. Represents the 95th-percentile worst empirical returns observed in the sampling period, over T bars.
// - CVaR: "Given that the loss exceeds the VaR, the average of those worst 5% losses is this value. (blue line)" Expected tail loss. If the worst case breached, how bad can it get on average
// - For shorts, the script computes the mirror (right-tail) equivalents.
// - Use T-day log returns if estimating risk over multiple days forward.
// - You can see instances where the VaR for time T, was surpassed historically with the "backtest" boolean
//
// Usage for Stop-Loss:
// - LONG POSITIONS:
// • 95th percentile means, 5% of the time (1 in 20 times) you'd expect to get a VaR level loss (touch the red line), over the next T bars.
// • VaR threshold = minimum price expected with (1 – confidence)% chance.
// • CVaR threshold = expected price if that worst-case zone is breached.
// → Use as potential stop-loss (VaR) or disaster stop (CVaR). If you're bullish (and you're right), price should not be exhibiting returns consistent with the worst 5% of days/T_bars historically.
//======================================================================//

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.