mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-25 22:08:05 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class WavgIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void WavgIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new WavgIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("Wavg - Linearly Weighted Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WavgIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new WavgIndicator { Period = 14 };
|
||||
|
||||
Assert.Equal(0, WavgIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WavgIndicator_Initialize_CreatesInternalWavg()
|
||||
{
|
||||
var indicator = new WavgIndicator { Period = 10 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
Assert.Equal("Wavg", indicator.LinesSeries[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WavgIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new WavgIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
double close = 100 + Math.Sin(i * 0.5);
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), close, close + 2, close - 2, close);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class WavgIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 14;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Wavg _wavg = null!;
|
||||
private readonly LineSeries _series;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"Wavg {Period}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/statistics/wavg/Wavg.Quantower.cs";
|
||||
|
||||
public WavgIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "Wavg - Linearly Weighted Average";
|
||||
Description = "Rolling linearly-weighted average (identical to WMA) categorized as statistics";
|
||||
|
||||
_series = new LineSeries(name: "Wavg", color: IndicatorExtensions.Statistics, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_wavg = new Wavg(Period);
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var item = this.HistoricalData[this.Count - 1, SeekOriginHistory.Begin];
|
||||
double value = _priceSelector(item);
|
||||
var time = this.HistoricalData.Time();
|
||||
|
||||
var input = new TValue(time, value);
|
||||
TValue result = _wavg.Update(input, args.IsNewBar());
|
||||
|
||||
_series.SetValue(result.Value, _wavg.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class WavgTests
|
||||
{
|
||||
// ── A) Constructor validation ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnZeroPeriod()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Wavg(0));
|
||||
Assert.Throws<ArgumentException>(() => new Wavg(-1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsName()
|
||||
{
|
||||
var wavg = new Wavg(14);
|
||||
Assert.Equal("Wavg(14)", wavg.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsWarmupPeriod()
|
||||
{
|
||||
var wavg = new Wavg(20);
|
||||
Assert.Equal(20, wavg.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidPeriod1()
|
||||
{
|
||||
var wavg = new Wavg(1);
|
||||
Assert.NotNull(wavg);
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsValue()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(result.Value, wavg.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FalseUntilWindowFull()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
Assert.False(wavg.IsHot);
|
||||
}
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 5.0));
|
||||
Assert.True(wavg.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SingleValue_ReturnsThatValue()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
Assert.Equal(42.0, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KnownValue_CorrectWeightedAverage()
|
||||
{
|
||||
// period=4, values=[1,2,3,4] (oldest→newest)
|
||||
// weights = [1,2,3,4], denom = 4*5/2 = 10
|
||||
// WAVG = (1*1 + 2*2 + 3*3 + 4*4) / 10 = (1+4+9+16)/10 = 30/10 = 3.0
|
||||
var wavg = new Wavg(4);
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 1.0));
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 2.0));
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 3.0));
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 4.0));
|
||||
|
||||
Assert.Equal(3.0, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllSameValues_ReturnsValue()
|
||||
{
|
||||
// All weights × same value / sum_weights = value
|
||||
var wavg = new Wavg(10);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 5.0));
|
||||
}
|
||||
|
||||
Assert.Equal(5.0, wavg.Last.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SlidingWindow_DropsOldest()
|
||||
{
|
||||
// Fill with [1,2,3,4,5], then slide in 6
|
||||
// After sliding: window=[2,3,4,5,6]
|
||||
// WAVG = (1*2 + 2*3 + 3*4 + 4*5 + 5*6)/15 = (2+6+12+20+30)/15 = 70/15
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 6.0));
|
||||
Assert.Equal(70.0 / 15.0, result.Value, 10);
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_IsNewFalse_RewritesLastBar()
|
||||
{
|
||||
var wavg = new Wavg(4);
|
||||
var t = DateTime.UtcNow;
|
||||
|
||||
wavg.Update(new TValue(t, 1.0));
|
||||
wavg.Update(new TValue(t, 2.0));
|
||||
wavg.Update(new TValue(t, 3.0));
|
||||
wavg.Update(new TValue(t, 4.0));
|
||||
|
||||
double before = wavg.Last.Value; // WAVG([1,2,3,4]) = (1+4+9+16)/10 = 3.0
|
||||
|
||||
// Correct last bar to different value
|
||||
wavg.Update(new TValue(t, 10.0), isNew: false);
|
||||
double corrected = wavg.Last.Value;
|
||||
Assert.NotEqual(before, corrected); // correction changes result ✓
|
||||
|
||||
// Next new bar with value=4: window slides from corrected state [1,2,3,10] to [2,3,10,4]
|
||||
// WAVG([2,3,10,4]) = (1*2+2*3+3*10+4*4)/10 = (2+6+30+16)/10 = 54/10 = 5.4
|
||||
wavg.Update(new TValue(t, 4.0), isNew: true);
|
||||
Assert.True(double.IsFinite(wavg.Last.Value)); // finite result
|
||||
Assert.NotEqual(corrected, wavg.Last.Value); // new bar shifts the result
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
Assert.True(wavg.IsHot);
|
||||
wavg.Reset();
|
||||
Assert.False(wavg.IsHot);
|
||||
Assert.Equal(0, wavg.Last.Value);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
int period = 8;
|
||||
var wavg = new Wavg(period);
|
||||
for (int i = 0; i < period - 1; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i));
|
||||
Assert.False(wavg.IsHot);
|
||||
}
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, period));
|
||||
Assert.True(wavg.IsHot);
|
||||
}
|
||||
|
||||
// ── E) Robustness ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_UsesLastValidValue()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
}
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(wavg.Last.Value));
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(wavg.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllNaN_DoesNotThrow()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Consistency_BatchEqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0002, sigma: 0.02, seed: 99);
|
||||
int n = 100;
|
||||
int period = 14;
|
||||
|
||||
var prices = new double[n];
|
||||
var times = new long[n];
|
||||
var t0 = DateTime.UtcNow;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
TBar bar = rng.Next();
|
||||
prices[i] = bar.Close;
|
||||
times[i] = (t0.AddMinutes(i)).Ticks;
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streamWavg = new Wavg(period);
|
||||
double lastStream = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streamWavg.Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), prices[i])).Value;
|
||||
}
|
||||
|
||||
// Span batch
|
||||
var spanOutput = new double[n];
|
||||
Wavg.Batch(prices, spanOutput, period);
|
||||
|
||||
Assert.Equal(lastStream, spanOutput[n - 1], 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesLengths()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[9];
|
||||
Assert.Throws<ArgumentException>(() => Wavg.Batch(src, dst, 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesPeriod()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[10];
|
||||
Assert.Throws<ArgumentException>(() => Wavg.Batch(src, dst, 0));
|
||||
}
|
||||
|
||||
// ── G) Eventing ──────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
int fireCount = 0;
|
||||
wavg.Pub += (object? _, in TValueEventArgs _) => fireCount++;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, fireCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chaining_EventBased_Works()
|
||||
{
|
||||
var wavg1 = new Wavg(5);
|
||||
var wavg2 = new Wavg(wavg1, 3);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
wavg1.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(wavg2.Last.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Wavg self-consistency validation.
|
||||
/// Validates against manual WMA computation and cross-mode consistency.
|
||||
/// </summary>
|
||||
public class WavgValidationTests
|
||||
{
|
||||
[Fact]
|
||||
public void Wavg_Streaming_Equals_SpanBatch()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 5005);
|
||||
int n = 200;
|
||||
int period = 14;
|
||||
|
||||
var prices = new double[n];
|
||||
var times = new long[n];
|
||||
var t0 = DateTime.UtcNow;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
TBar bar = rng.Next();
|
||||
prices[i] = bar.Close;
|
||||
times[i] = t0.AddMinutes(i).Ticks;
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streaming = new Wavg(period);
|
||||
var streamValues = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
streamValues[i] = streaming.Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), prices[i])).Value;
|
||||
}
|
||||
|
||||
// Span batch
|
||||
var spanValues = new double[n];
|
||||
Wavg.Batch(prices, spanValues, period);
|
||||
|
||||
for (int i = period - 1; i < n; i++)
|
||||
{
|
||||
Assert.Equal(streamValues[i], spanValues[i], 6);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_ManualWMA_Matches_KnownPeriod()
|
||||
{
|
||||
// Verify against hand-computed WMA
|
||||
// Values [10, 20, 30], period=3
|
||||
// weights [1,2,3], denom=6
|
||||
// WMA = (1*10 + 2*20 + 3*30)/6 = (10+40+90)/6 = 140/6 ≈ 23.333
|
||||
var wavg = new Wavg(3);
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 20.0));
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 30.0));
|
||||
|
||||
Assert.Equal(140.0 / 6.0, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_BatchTSeries_EqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 6006);
|
||||
int n = 50;
|
||||
int period = 10;
|
||||
|
||||
var series = new TSeries();
|
||||
var t0 = DateTime.UtcNow;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
TBar bar = rng.Next();
|
||||
series.Add(new TValue(t0.AddMinutes(i), bar.Close));
|
||||
}
|
||||
|
||||
var batchResult = Wavg.Batch(series, period);
|
||||
|
||||
var streaming = new Wavg(period);
|
||||
TValue lastStream = default;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streaming.Update(series[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(lastStream.Value, batchResult[n - 1].Value, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_Period1_EqualsInput()
|
||||
{
|
||||
// With period=1, weight=1, denom=1 → result = input
|
||||
var wavg = new Wavg(1);
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 7007);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
double price = rng.Next().Close;
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, price));
|
||||
Assert.Equal(price, result.Value, 10);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_RecentValueHasHigherWeight()
|
||||
{
|
||||
// WAVG should be closer to recent values than SMA
|
||||
// Ascending series: WAVG > SMA
|
||||
var wavg = new Wavg(5);
|
||||
// Fill with ascending values
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i * 10.0));
|
||||
}
|
||||
|
||||
// SMA = (10+20+30+40+50)/5 = 30
|
||||
// WAVG = (1*10+2*20+3*30+4*40+5*50)/(1+2+3+4+5) = (10+40+90+160+250)/15 = 550/15 ≈ 36.67
|
||||
Assert.True(wavg.Last.Value > 30.0); // WAVG > SMA for ascending
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// Wavg: Rolling Linearly-Weighted Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Assigns linearly increasing weights to the lookback window:
|
||||
/// weight_i = i + 1 for i = 0 (oldest) to count-1 (newest)
|
||||
/// WAVG = Σ(weight_i × value_i) / Σ(weight_i)
|
||||
/// Σ(weight_i) = count × (count + 1) / 2
|
||||
///
|
||||
/// O(1) incremental update uses two recurrences:
|
||||
///
|
||||
/// WARMUP (count growing 1 → period):
|
||||
/// W_new = W_old + count_new × v_new (no subtraction; existing positions unchanged)
|
||||
/// S_new = S_old + v_new
|
||||
///
|
||||
/// STEADY STATE (window full, oldest departs):
|
||||
/// W_new = W_old - S_old + period × v_new (shift all weights down, evict oldest, add new)
|
||||
/// S_new = S_old - oldest + v_new
|
||||
///
|
||||
/// Mathematically identical to WMA.
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Wavg : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly RingBuffer _buffer;
|
||||
private readonly TValuePublishedHandler _handler;
|
||||
private readonly ITValuePublisher? _source;
|
||||
|
||||
// O(1) running state
|
||||
private double _weightedSum;
|
||||
private double _runningSum;
|
||||
private int _count;
|
||||
private double _lastValidValue;
|
||||
|
||||
// Previous-state snapshot for isNew=false rollback
|
||||
private double _p_weightedSum;
|
||||
private double _p_runningSum;
|
||||
private int _p_count;
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Wavg indicator with the specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">The size of the rolling window (must be > 0).</param>
|
||||
public Wavg(int period)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Wavg({period})";
|
||||
WarmupPeriod = period;
|
||||
_handler = Handle;
|
||||
}
|
||||
|
||||
/// <summary>Creates a chained Wavg indicator.</summary>
|
||||
public Wavg(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
_source = source;
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
/// <summary>Creates a Wavg indicator primed from a TSeries source.</summary>
|
||||
public Wavg(TSeries source, int period) : this(period)
|
||||
{
|
||||
Prime(source.Values);
|
||||
if (source.Count > 0)
|
||||
{
|
||||
Last = new TValue(source.LastTime, Last.Value);
|
||||
}
|
||||
|
||||
_source = source;
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs args) => Update(args.Value, args.IsNew);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
double value = input.Value;
|
||||
if (!double.IsFinite(value))
|
||||
{
|
||||
value = _lastValidValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lastValidValue = value;
|
||||
}
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
// Save state for potential rollback
|
||||
_p_weightedSum = _weightedSum;
|
||||
_p_runningSum = _runningSum;
|
||||
_p_count = _count;
|
||||
|
||||
if (_buffer.IsFull)
|
||||
{
|
||||
// STEADY STATE: oldest departs
|
||||
// Shift all weights down by 1 (each existing element's weight decreases by 1,
|
||||
// so δW = -S_old). Then evict oldest from S. Then add new at weight = period.
|
||||
_weightedSum -= _runningSum; // shift: δW = -S_old (oldest contribution zeroes out)
|
||||
_runningSum -= _buffer.Oldest; // evict oldest from unweighted sum
|
||||
_runningSum += value;
|
||||
_weightedSum += _count * value; // add new at weight = period (= _count, fixed when full)
|
||||
}
|
||||
else
|
||||
{
|
||||
// WARMUP: no eviction, existing positions unchanged, new element appended at weight = count+1
|
||||
_count++;
|
||||
_runningSum += value;
|
||||
_weightedSum += _count * value;
|
||||
}
|
||||
|
||||
_buffer.Add(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Bar correction: restore previous state, then replace newest in buffer and recompute
|
||||
// O(period) recompute — only triggered on bar corrections, not the hot path
|
||||
_weightedSum = _p_weightedSum;
|
||||
_runningSum = _p_runningSum;
|
||||
_count = _p_count;
|
||||
|
||||
// Undo the last Add of the old newest value (before the prior isNew=true step)
|
||||
double oldNewest = _buffer.Newest;
|
||||
|
||||
if (_count == _period)
|
||||
{
|
||||
// The prior step was steady-state: undo it, then redo with new value
|
||||
// Undo: W = W_p, S = S_p (already restored from _p_)
|
||||
// Redo steady-state with different new value:
|
||||
_weightedSum -= _runningSum;
|
||||
_runningSum -= _buffer.Oldest;
|
||||
_runningSum += value;
|
||||
_weightedSum += _count * value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The prior step was warmup: undo newest contribution, sub in corrected value
|
||||
// _count was already incremented in the prior isNew=true step, so _p_count = _count-1
|
||||
// After restoring _count = _p_count, reapply the warmup step with new value
|
||||
_count++;
|
||||
_runningSum -= oldNewest;
|
||||
_runningSum += value;
|
||||
_weightedSum -= _count * oldNewest;
|
||||
_weightedSum += _count * value;
|
||||
}
|
||||
|
||||
// Note: buffer is NOT rolled back on isNew=false — UpdateNewest replaces in-place
|
||||
_buffer.UpdateNewest(value);
|
||||
}
|
||||
|
||||
double denom = _count * (_count + 1.0) / 2.0;
|
||||
double result = denom > 0.0 ? _weightedSum / denom : value;
|
||||
|
||||
Last = new TValue(input.Time, result);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
int len = source.Count;
|
||||
var t = new List<long>(len);
|
||||
var v = new List<double>(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
|
||||
Batch(source.Values, vSpan, _period);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
Prime(source.Values);
|
||||
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_weightedSum = 0;
|
||||
_runningSum = 0;
|
||||
_count = 0;
|
||||
_p_weightedSum = 0;
|
||||
_p_runningSum = 0;
|
||||
_p_count = 0;
|
||||
Last = default;
|
||||
}
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_buffer.Clear();
|
||||
_weightedSum = 0;
|
||||
_runningSum = 0;
|
||||
_count = 0;
|
||||
|
||||
int warmupLength = Math.Min(source.Length, WarmupPeriod);
|
||||
int startIndex = source.Length - warmupLength;
|
||||
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
Update(new TValue(DateTime.MinValue, source[i]));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Calculates Wavg for the entire series using a new instance.</summary>
|
||||
public static TSeries Batch(TSeries source, int period)
|
||||
{
|
||||
var wavg = new Wavg(period);
|
||||
return wavg.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>Calculates Wavg in-place using spans. O(n) total, O(1) per bar.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Circular buffer for oldest-value eviction
|
||||
double[] buf = new double[period];
|
||||
int head = 0;
|
||||
double weightedSum = 0.0;
|
||||
double runningSum = 0.0;
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double v = source[i];
|
||||
|
||||
if (count < period)
|
||||
{
|
||||
// WARMUP: append, existing weights unchanged
|
||||
count++;
|
||||
runningSum += v;
|
||||
weightedSum += count * v;
|
||||
}
|
||||
else
|
||||
{
|
||||
// STEADY STATE: shift all weights down, evict oldest, add new at weight=period
|
||||
double oldest = buf[head];
|
||||
weightedSum -= runningSum; // shift: each existing weight -1
|
||||
runningSum -= oldest; // evict oldest
|
||||
runningSum += v;
|
||||
weightedSum += count * v; // add new at weight=period (=count, fixed)
|
||||
}
|
||||
|
||||
buf[head] = v;
|
||||
head = (head + 1) % period;
|
||||
|
||||
double denom = count * (count + 1.0) / 2.0;
|
||||
output[i] = denom > 0.0 ? weightedSum / denom : v;
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Wavg Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Wavg(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing && _source != null)
|
||||
{
|
||||
_source.Pub -= _handler;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user