Files
QuanTAlib/lib/volatility/Rv.cs
T

153 lines
5.1 KiB
C#
Raw Normal View History

2024-10-27 16:11:08 -07:00
using System.Runtime.CompilerServices;
2024-10-04 21:31:25 -07:00
namespace QuanTAlib;
2024-10-05 15:20:13 -07:00
/// <summary>
2024-10-27 09:38:53 -07:00
/// RV: Realized Volatility
/// A precise volatility measure that captures actual observed price fluctuations
/// using high-frequency returns. RV provides a more accurate assessment of true
/// market volatility compared to traditional estimators.
2024-10-05 15:20:13 -07:00
/// </summary>
/// <remarks>
2024-10-27 09:38:53 -07:00
/// The RV calculation process:
/// 1. Computes log returns
/// 2. Squares each return
/// 3. Maintains rolling sum
/// 4. Takes square root of average
/// 5. Optionally annualizes
///
/// Key characteristics:
/// - Model-free measurement
/// - High-frequency capable
/// - Rolling calculation
/// - Memory efficient
/// - Optional annualization
///
/// Formula:
/// RV = √(Σ(ln(P[t]/P[t-1]))²/n) * √252
/// where:
/// P = price
/// n = number of observations
/// 252 = trading days per year
///
/// Market Applications:
/// - High-frequency trading
/// - Options pricing
/// - Risk forecasting
/// - Market microstructure
/// - Volatility trading
///
/// Sources:
/// Andersen, Bollerslev - "Answering the Skeptics"
/// https://en.wikipedia.org/wiki/Realized_volatility
///
/// Note: Efficient implementation using rolling sums
2024-10-05 15:20:13 -07:00
/// </remarks>
2024-10-27 16:11:08 -07:00
[SkipLocalsInit]
public sealed class Rv : AbstractBase
2024-10-06 06:59:26 +00:00
{
2024-10-04 21:31:25 -07:00
private readonly int Period;
private readonly bool IsAnnualized;
private readonly CircularBuffer _returns;
private double _previousClose;
private double _sumSquaredReturns;
2024-10-27 16:11:08 -07:00
private const int TradingDaysPerYear = 252;
private const double Epsilon = 1e-10;
private const bool DefaultIsAnnualized = true;
2024-10-04 21:31:25 -07:00
2024-10-27 09:38:53 -07:00
/// <param name="period">The number of periods for volatility calculation.</param>
/// <param name="isAnnualized">Whether to annualize the result (default true).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 2.</exception>
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rv(int period, bool isAnnualized = DefaultIsAnnualized)
2024-10-06 06:59:26 +00:00
{
if (period < 2)
{
2024-10-27 09:38:53 -07:00
throw new ArgumentOutOfRangeException(nameof(period),
"Period must be greater than or equal to 2.");
2024-10-04 21:31:25 -07:00
}
Period = period;
IsAnnualized = isAnnualized;
2024-10-27 09:38:53 -07:00
WarmupPeriod = period + 1; // Need extra point for first return
2024-10-04 21:31:25 -07:00
_returns = new CircularBuffer(period);
Name = $"Realized(period={period}, annualized={isAnnualized})";
Init();
}
2024-10-27 09:38:53 -07:00
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for volatility calculation.</param>
/// <param name="isAnnualized">Whether to annualize the result (default true).</param>
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rv(object source, int period, bool isAnnualized = DefaultIsAnnualized) : this(period, isAnnualized)
2024-10-26 23:54:55 -07:00
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-10-06 06:59:26 +00:00
public override void Init()
{
2024-10-04 21:31:25 -07:00
base.Init();
_returns.Clear();
_previousClose = 0;
_sumSquaredReturns = 0;
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-10-06 06:59:26 +00:00
protected override void ManageState(bool isNew)
{
if (isNew)
{
2024-10-04 21:31:25 -07:00
_lastValidValue = Input.Value;
_index++;
}
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double CalculateLogReturn(double currentPrice, double previousPrice)
{
return previousPrice > Epsilon ? Math.Log(currentPrice / previousPrice) : 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double CalculateVolatility(double sumSquaredReturns, int period, bool isAnnualized)
{
double variance = sumSquaredReturns / period;
double volatility = Math.Sqrt(variance);
return isAnnualized ? volatility * Math.Sqrt(TradingDaysPerYear) : volatility;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
2024-10-06 06:59:26 +00:00
protected override double Calculation()
{
2024-10-04 21:31:25 -07:00
ManageState(Input.IsNew);
double volatility = 0;
2024-10-27 16:11:08 -07:00
if (_previousClose > Epsilon)
2024-10-06 06:59:26 +00:00
{
2024-10-27 09:38:53 -07:00
// Calculate log return
2024-10-27 16:11:08 -07:00
double logReturn = CalculateLogReturn(Input.Value, _previousClose);
2024-10-04 21:31:25 -07:00
2024-10-06 06:59:26 +00:00
if (_returns.Count == Period)
{
2024-10-27 09:38:53 -07:00
// Maintain rolling sum by removing oldest squared return
2024-10-27 16:11:08 -07:00
double oldReturn = _returns[0];
_sumSquaredReturns -= oldReturn * oldReturn;
2024-10-04 21:31:25 -07:00
}
2024-10-27 09:38:53 -07:00
// Add new return and update sum
2024-10-04 21:31:25 -07:00
_returns.Add(logReturn, Input.IsNew);
2024-10-27 16:11:08 -07:00
_sumSquaredReturns += logReturn * logReturn;
2024-10-04 21:31:25 -07:00
2024-10-06 06:59:26 +00:00
if (_returns.Count == Period)
{
2024-10-27 09:38:53 -07:00
// Calculate realized volatility
2024-10-27 16:11:08 -07:00
volatility = CalculateVolatility(_sumSquaredReturns, Period, IsAnnualized);
2024-10-04 21:31:25 -07:00
}
}
_previousClose = Input.Value;
IsHot = _index >= WarmupPeriod;
return volatility;
}
2024-10-26 23:54:55 -07:00
}