Files

154 lines
4.9 KiB
C#
Raw Permalink Normal View History

2024-10-27 16:11:08 -07:00
using System.Runtime.CompilerServices;
2024-09-22 17:31:24 -07:00
namespace QuanTAlib;
2024-10-05 15:20:13 -07:00
/// <summary>
2024-10-27 09:38:53 -07:00
/// SKEW: Distribution Asymmetry Measure
/// A statistical measure that quantifies the asymmetry of a probability distribution
/// around its mean. Skewness indicates whether deviations from the mean are more
/// likely in one direction than the other.
2024-10-05 15:20:13 -07:00
/// </summary>
/// <remarks>
2024-10-27 09:38:53 -07:00
/// The Skew calculation process:
/// 1. Calculates mean of the data
/// 2. Computes deviations from mean
/// 3. Calculates third moment (cubed deviations)
/// 4. Normalizes by standard deviation cubed
2024-10-11 18:02:09 -07:00
///
2024-10-27 09:38:53 -07:00
/// Key characteristics:
/// - Measures distribution asymmetry
/// - Positive values indicate right skew
/// - Negative values indicate left skew
/// - Zero indicates symmetry
/// - Scale-independent measure
2024-10-11 18:02:09 -07:00
///
2024-10-27 09:38:53 -07:00
/// Formula:
/// skew = [√(n(n-1))/(n-2)] * [m₃/s³]
/// where:
/// m₃ = third moment about the mean
/// s = standard deviation
/// n = sample size
///
/// Market Applications:
/// - Risk assessment in returns
/// - Options pricing models
/// - Trading strategy development
/// - Portfolio risk management
/// - Market sentiment analysis
///
/// Sources:
/// Fisher-Pearson standardized moment coefficient
/// https://en.wikipedia.org/wiki/Skewness
/// "The Analysis of Financial Time Series" - Ruey S. Tsay
///
/// Note: Requires minimum of 3 data points for calculation
2024-10-05 15:20:13 -07:00
/// </remarks>
2024-10-27 16:11:08 -07:00
[SkipLocalsInit]
public sealed class Skew : AbstractBase
2024-10-06 06:59:26 +00:00
{
2024-09-30 15:53:48 -07:00
private readonly int Period;
2024-09-23 22:08:40 -07:00
private readonly CircularBuffer _buffer;
2024-10-27 16:11:08 -07:00
private const double Epsilon = 1e-10;
private const int MinimumPoints = 3;
2024-09-22 17:31:24 -07:00
2024-10-27 09:38:53 -07:00
/// <param name="period">The number of points to consider for skewness calculation.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 3.</exception>
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-10-06 14:44:43 -07:00
public Skew(int period)
2024-10-06 06:59:26 +00:00
{
2024-10-27 16:11:08 -07:00
if (period < MinimumPoints)
2024-10-06 06:59:26 +00:00
{
2024-10-27 09:38:53 -07:00
throw new ArgumentOutOfRangeException(nameof(period),
"Period must be greater than or equal to 3 for skewness calculation.");
2024-09-22 17:31:24 -07:00
}
Period = period;
2024-10-27 16:11:08 -07:00
WarmupPeriod = MinimumPoints;
2024-09-22 17:31:24 -07:00
_buffer = new CircularBuffer(period);
Name = $"Skew(period={period})";
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 points to consider for skewness calculation.</param>
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-10-06 06:59:26 +00:00
public Skew(object source, int period) : this(period)
{
2024-09-22 17:31:24 -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-09-22 17:31:24 -07:00
base.Init();
_buffer.Clear();
}
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-09-22 17:31:24 -07:00
_lastValidValue = Input.Value;
_index++;
}
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double CalculateMean(ReadOnlySpan<double> values)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
{
sum += values[i];
}
return sum / values.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static (double m3, double m2) CalculateMoments(ReadOnlySpan<double> values, double mean)
{
double sumCubedDeviations = 0;
double sumSquaredDeviations = 0;
for (int i = 0; i < values.Length; i++)
{
double deviation = values[i] - mean;
double squared = deviation * deviation;
sumSquaredDeviations += squared;
sumCubedDeviations += squared * deviation;
}
double n = values.Length;
return (sumCubedDeviations / n, sumSquaredDeviations / n);
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double CalculateSkewness(double m3, double m2, int n)
{
double s3 = Math.Pow(m2, 1.5);
if (s3 < Epsilon)
return 0;
return (Math.Sqrt(n * (n - 1)) / (n - 2)) * (m3 / s3);
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
2024-10-06 06:59:26 +00:00
protected override double Calculation()
{
2024-09-22 17:31:24 -07:00
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double skew = 0;
2024-10-27 16:11:08 -07:00
if (_buffer.Count >= MinimumPoints) // Need at least 3 points for skewness
2024-10-27 09:38:53 -07:00
{
2024-10-27 16:11:08 -07:00
ReadOnlySpan<double> values = _buffer.GetSpan();
double mean = CalculateMean(values);
var (m3, m2) = CalculateMoments(values, mean);
skew = CalculateSkewness(m3, m2, values.Length);
2024-09-22 17:31:24 -07:00
}
IsHot = _buffer.Count >= Period;
return skew;
}
2024-10-11 18:02:09 -07:00
}