mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-05 04:27:43 +00:00
86fe32a682
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: aider (openrouter/anthropic/claude-sonnet-4) <aider@aider.chat> Co-authored-by: Warp <agent@warp.dev>
44 lines
2.3 KiB
Plaintext
44 lines
2.3 KiB
Plaintext
// The MIT License (MIT)
|
|
// © mihakralj
|
|
//@version=6
|
|
indicator("Exponential Weighted MA Volatility", "EWMA Volty", overlay=false)
|
|
|
|
//@function Calculates Exponential Weighted Moving Average (EWMA) Volatility.
|
|
//@param src The source series for price data. Default is close.
|
|
//@param length The period length for the EWMA calculation.
|
|
//@param annualize Boolean to indicate if the volatility should be annualized. Default is true.
|
|
//@param annualPeriods Number of periods in a year for annualization. Default is 252 for daily data.
|
|
//@returns float The EWMA Volatility value.
|
|
//@optimized for performance and dirty data
|
|
ewmaVolty(series float src, simple int length, simple bool annualize = true, simple int annualPeriods = 252) =>
|
|
if length <= 0
|
|
runtime.error("Length must be greater than 0")
|
|
if annualize and annualPeriods <= 0
|
|
runtime.error("Annual periods must be greater than 0 if annualizing")
|
|
float logReturn = nz(math.log(src / src[1]),0.0)
|
|
float squaredReturn = logReturn * logReturn
|
|
var float raw_rma_sq_ret = 0.0, var float e_rma = 1.0
|
|
float rma_alpha = 1.0 / float(length)
|
|
if not na(squaredReturn)
|
|
raw_rma_sq_ret := na(raw_rma_sq_ret[1]) ? squaredReturn : (nz(raw_rma_sq_ret[1],squaredReturn) * (length - 1) + squaredReturn) / length
|
|
e_rma := na(e_rma[1]) ? (1.0 - rma_alpha) : (1.0 - rma_alpha) * nz(e_rma[1],1.0)
|
|
float EPSILON = 1e-10
|
|
float corrected_rma_sq_ret = e_rma > EPSILON and not na(raw_rma_sq_ret) ? raw_rma_sq_ret / (1.0 - e_rma) : raw_rma_sq_ret
|
|
float currentEwmaSqReturns = nz(corrected_rma_sq_ret, squaredReturn)
|
|
float volatility = currentEwmaSqReturns < 0 ? na : math.sqrt(currentEwmaSqReturns)
|
|
annualize and not na(volatility) ? volatility * math.sqrt(float(annualPeriods)) : volatility
|
|
|
|
// ---------- Main loop ----------
|
|
|
|
// Inputs
|
|
i_source = input.source(close, "Source")
|
|
i_length = input.int(20, "Length", minval=1, tooltip="Period for EWMA calculation")
|
|
i_annualize = input.bool(true, "Annualize Volatility", tooltip="Annualize the volatility output")
|
|
i_annualPeriods = input.int(252, "Annual Periods", minval=1, tooltip="Number of periods in a year for annualization (e.g., 252 for daily, 52 for weekly)")
|
|
|
|
// Calculation
|
|
ewmaVolatilityValue = ewmaVolty(i_source, i_length, i_annualize, i_annualPeriods)
|
|
|
|
// Plot
|
|
plot(ewmaVolatilityValue, "EWMA Volty", color=color.yellow, linewidth=2)
|