Add TRAMA implementation and comprehensive tests

- Implemented the TRAMA (Trend Regularity Adaptive Moving Average) class with adaptive EMA logic.
- Added unit tests for TRAMA functionality, including constructor validation, basic calculations, state management, and robustness checks.
- Created validation tests to ensure consistency across different modes of operation (streaming, batch, and static calculations).
- Enhanced documentation for TRAMA, including performance profiles and quality metrics.
- Updated workspace configuration by removing unnecessary folder references.
This commit is contained in:
Miha Kralj
2026-02-21 20:45:38 -08:00
parent 90d5638008
commit 7253f61299
199 changed files with 29577 additions and 234 deletions
+159
View File
@@ -0,0 +1,159 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class SwmaIndicatorTests
{
[Fact]
public void SwmaIndicator_Constructor_SetsDefaults()
{
var indicator = new SwmaIndicator();
Assert.Equal(4, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("SWMA - Symmetric Weighted Moving Average", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void SwmaIndicator_MinHistoryDepths_IsZero()
{
var indicator = new SwmaIndicator { Period = 10 };
Assert.Equal(0, SwmaIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void SwmaIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new SwmaIndicator { Period = 6 };
Assert.Contains("SWMA", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("6", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void SwmaIndicator_SourceCodeLink_IsValid()
{
var indicator = new SwmaIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Swma.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void SwmaIndicator_Initialize_CreatesInternalSwma()
{
var indicator = new SwmaIndicator { Period = 4 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void SwmaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new SwmaIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
Assert.Equal(1, indicator.LinesSeries[0].Count);
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
}
[Fact]
public void SwmaIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new SwmaIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void SwmaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new SwmaIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
double firstValue = indicator.LinesSeries[0].GetValue(0);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
double secondValue = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(firstValue));
Assert.True(double.IsFinite(secondValue));
}
[Fact]
public void SwmaIndicator_MultipleUpdates_ProducesCorrectSequence()
{
var indicator = new SwmaIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
double[] closes = { 100, 102, 104, 103, 105, 107, 106 };
foreach (var close in closes)
{
indicator.HistoricalData.AddBar(now, close, close + 2, close - 2, close);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
now = now.AddMinutes(1);
}
for (int i = 0; i < closes.Length; i++)
{
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(closes.Length - 1 - i)));
}
}
[Fact]
public void SwmaIndicator_DifferentSourceTypes_Work()
{
var sources = new[] { SourceType.Open, SourceType.High, SourceType.Low, SourceType.Close, SourceType.HL2, SourceType.HLC3 };
foreach (var source in sources)
{
var indicator = new SwmaIndicator { Period = 3, Source = source };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 110, 90, 105);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)),
$"Source {source} should produce finite value");
}
}
[Fact]
public void SwmaIndicator_Period_CanBeChanged()
{
var indicator = new SwmaIndicator { Period = 4 };
Assert.Equal(4, indicator.Period);
indicator.Period = 10;
Assert.Equal(10, indicator.Period);
Assert.Equal(0, SwmaIndicator.MinHistoryDepths);
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class SwmaIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 2, 2000, 1, 0)]
public int Period { get; set; } = 4;
[IndicatorExtensions.DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Swma _swma = null!;
private readonly LineSeries _series;
private string _sourceName = null!;
private Func<IHistoryItem, double> _priceSelector = null!;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"SWMA {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/swma/Swma.Quantower.cs";
public SwmaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "SWMA - Symmetric Weighted Moving Average";
Description = "Symmetric Weighted Moving Average";
_series = new LineSeries(name: $"SWMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_priceSelector = Source.GetPriceSelector();
_sourceName = Source.ToString();
_swma = new Swma(Period);
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
bool isNew = args.IsNewBar();
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
double value = _swma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
_series.SetValue(value, _swma.IsHot, ShowColdValues);
}
}
+563
View File
@@ -0,0 +1,563 @@
namespace QuanTAlib.Tests;
public class SwmaTests
{
private static TSeries MakeSeries(int count = 500)
{
var gbm = new GBM(startPrice: 100, seed: 42);
var series = new TSeries();
for (int i = 0; i < count; i++)
{
series.Add(gbm.Next());
}
return series;
}
// === A) Constructor validation ===
[Fact]
public void Constructor_DefaultPeriod_Is4()
{
var swma = new Swma();
Assert.Equal("Swma(4)", swma.Name);
}
[Fact]
public void Constructor_CustomPeriod_SetsCorrectly()
{
var swma = new Swma(period: 10);
Assert.Equal("Swma(10)", swma.Name);
}
[Fact]
public void Constructor_Period2_IsValid()
{
var swma = new Swma(period: 2);
Assert.Equal("Swma(2)", swma.Name);
}
[Fact]
public void Constructor_PeriodBelow2_Throws()
{
var ex = Assert.Throws<ArgumentException>(() => new Swma(period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodZero_Throws()
{
var ex = Assert.Throws<ArgumentException>(() => new Swma(period: 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_NegativePeriod_Throws()
{
var ex = Assert.Throws<ArgumentException>(() => new Swma(period: -5));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_SetsWarmupPeriod()
{
var swma = new Swma(period: 8);
Assert.Equal(8, swma.WarmupPeriod);
}
// === B) Basic calculation ===
[Fact]
public void Update_ReturnsTValue()
{
var swma = new Swma(period: 4);
var result = swma.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_Last_IsAccessible()
{
var swma = new Swma(period: 4);
swma.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(swma.Last.Value));
}
[Fact]
public void Update_ConstantInput_ReturnsConstant()
{
var swma = new Swma(period: 4);
for (int i = 0; i < 10; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 50.0));
}
Assert.Equal(50.0, swma.Last.Value, 1e-10);
}
[Fact]
public void Update_Period4_KnownWeights_MatchesPine()
{
// PineScript ta.swma: period=4, weights [1,2,2,1]/6
var swma = new Swma(period: 4);
double[] vals = { 10, 20, 30, 40 };
for (int i = 0; i < vals.Length; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
}
// Expected: (1*10 + 2*20 + 2*30 + 1*40) / 6 = (10+40+60+40)/6 = 150/6 = 25.0
Assert.Equal(25.0, swma.Last.Value, 1e-10);
}
[Fact]
public void Update_Period3_KnownWeights()
{
// Period=3: half=1.0, weights: w(0)=1+1-|0-1|=1, w(1)=1+1-0=2, w(2)=1+1-|2-1|=1 => [1,2,1]/4
var swma = new Swma(period: 3);
double[] vals = { 10, 20, 30 };
for (int i = 0; i < vals.Length; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
}
// Expected: (1*10 + 2*20 + 1*30) / 4 = (10+40+30)/4 = 80/4 = 20.0
Assert.Equal(20.0, swma.Last.Value, 1e-10);
}
[Fact]
public void Update_Period2_KnownWeights()
{
// Period=2: half=0.5, weights: w(0)=0.5+1-|0-0.5|=1.0, w(1)=0.5+1-|1-0.5|=1.0 => [1,1]/2
var swma = new Swma(period: 2);
double[] vals = { 10, 20 };
for (int i = 0; i < vals.Length; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
}
// Expected: (1*10 + 1*20) / 2 = 15.0 (same as SMA)
Assert.Equal(15.0, swma.Last.Value, 1e-10);
}
// === C) State + bar correction ===
[Fact]
public void Update_IsNew_True_AdvancesState()
{
var swma = new Swma(period: 4);
swma.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(1), 110.0), isNew: true);
var r1 = swma.Last;
// New value should advance
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(2), 120.0), isNew: true);
Assert.NotEqual(r1.Value, swma.Last.Value);
}
[Fact]
public void Update_IsNew_False_Rewrites()
{
var swma = new Swma(period: 4);
for (int i = 0; i < 5; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i), isNew: true);
}
var afterNew = swma.Last;
// Correction with same value should return same result
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 104.0), isNew: false);
Assert.Equal(afterNew.Value, swma.Last.Value, 1e-10);
}
[Fact]
public void Update_IterativeCorrections_Restore()
{
var swma = new Swma(period: 4);
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < 10; i++)
{
swma.Update(gbm.Next(), isNew: true);
}
var baseline = swma.Last;
// Apply multiple corrections
swma.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
swma.Update(new TValue(DateTime.UtcNow, 888.0), isNew: false);
swma.Update(new TValue(DateTime.UtcNow, 777.0), isNew: false);
// Restore with isNew=false using original value
swma.Update(new TValue(baseline.Time, baseline.Value), isNew: false);
// State should be preserved across corrections (buffer not mutated)
Assert.True(double.IsFinite(swma.Last.Value));
}
[Fact]
public void Reset_ClearsState()
{
var swma = new Swma(period: 4);
for (int i = 0; i < 10; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.True(swma.IsHot);
swma.Reset();
Assert.False(swma.IsHot);
Assert.Equal(default, swma.Last);
}
// === D) Warmup/convergence ===
[Fact]
public void IsHot_FlipsAtPeriod()
{
var swma = new Swma(period: 5);
for (int i = 0; i < 4; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
Assert.False(swma.IsHot);
}
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 104.0));
Assert.True(swma.IsHot);
}
[Fact]
public void WarmupPeriod_MatchesPeriod()
{
var swma = new Swma(period: 7);
Assert.Equal(7, swma.WarmupPeriod);
}
[Fact]
public void DuringWarmup_ReturnsRawValue()
{
var swma = new Swma(period: 5);
var result = swma.Update(new TValue(DateTime.UtcNow, 42.0));
Assert.Equal(42.0, result.Value, 1e-10);
}
// === E) Robustness ===
[Fact]
public void Update_NaN_UsesLastValid()
{
var swma = new Swma(period: 4);
for (int i = 0; i < 5; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(5), double.NaN));
// After NaN, last-valid substitution should produce finite result
Assert.True(double.IsFinite(swma.Last.Value));
}
[Fact]
public void Update_Infinity_UsesLastValid()
{
var swma = new Swma(period: 4);
for (int i = 0; i < 5; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(5), double.PositiveInfinity));
Assert.True(double.IsFinite(swma.Last.Value));
}
[Fact]
public void Update_NegativeInfinity_UsesLastValid()
{
var swma = new Swma(period: 4);
for (int i = 0; i < 5; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(5), double.NegativeInfinity));
Assert.True(double.IsFinite(swma.Last.Value));
}
[Fact]
public void Update_FirstValueNaN_ReturnsNaN()
{
var swma = new Swma(period: 4);
var result = swma.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsNaN(result.Value));
}
[Fact]
public void Batch_BatchNaN_Safe()
{
double[] source = { 10, 20, double.NaN, 40, 50, 60 };
double[] output = new double[source.Length];
Swma.Batch(source, output, period: 3);
for (int i = 0; i < output.Length; i++)
{
Assert.True(double.IsFinite(output[i]), $"output[{i}] should be finite");
}
}
// === F) Consistency (4 modes match) ===
[Fact]
public void AllModes_ProduceSameResults()
{
var src = MakeSeries(100);
int period = 6;
// Mode 1: Streaming
var streaming = new Swma(period);
var streamResults = new List<double>();
for (int i = 0; i < src.Count; i++)
{
streamResults.Add(streaming.Update(src[i]).Value);
}
// Mode 2: Batch TSeries
var batchResults = Swma.Batch(src, period);
// Mode 3: Span API
var spanOutput = new double[src.Count];
Swma.Batch(src.Values, spanOutput, period);
// Mode 4: Event-based
var publisher = new TSeries();
var eventResults = new List<double>();
var eventSwma = new Swma(publisher, period);
eventSwma.Pub += (object? sender, in TValueEventArgs e) => eventResults.Add(e.Value.Value);
for (int i = 0; i < src.Count; i++)
{
publisher.Add(src[i]);
}
// Compare all modes
Assert.Equal(src.Count, batchResults.Count);
Assert.Equal(src.Count, eventResults.Count);
for (int i = 0; i < src.Count; i++)
{
double s = streamResults[i];
double b = batchResults[i].Value;
double sp = spanOutput[i];
double ev = eventResults[i];
if (double.IsNaN(s))
{
Assert.True(double.IsNaN(b), $"batch[{i}] should be NaN");
Assert.True(double.IsNaN(sp), $"span[{i}] should be NaN");
Assert.True(double.IsNaN(ev), $"event[{i}] should be NaN");
}
else
{
Assert.Equal(s, b, 1e-10);
Assert.Equal(s, sp, 1e-10);
Assert.Equal(s, ev, 1e-10);
}
}
}
// === G) Span API tests ===
[Fact]
public void Batch_Span_MismatchedLengths_Throws()
{
double[] source = { 1, 2, 3 };
double[] output = new double[2];
var ex = Assert.Throws<ArgumentException>(() => Swma.Batch(source, output, period: 2));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_PeriodBelow2_Throws()
{
double[] source = { 1, 2, 3 };
double[] output = new double[3];
var ex = Assert.Throws<ArgumentException>(() => Swma.Batch(source, output, period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_EmptyInput_NoOutput()
{
Swma.Batch(ReadOnlySpan<double>.Empty, Span<double>.Empty, period: 4);
Assert.True(true); // No exception = pass
}
[Fact]
public void Batch_Span_MatchesTSeries()
{
var src = MakeSeries(200);
int period = 5;
var tsResult = Swma.Batch(src, period);
var spanOutput = new double[src.Count];
Swma.Batch(src.Values, spanOutput, period);
for (int i = 0; i < src.Count; i++)
{
Assert.Equal(tsResult[i].Value, spanOutput[i], 1e-10);
}
}
[Fact]
public void Batch_Span_NaN_HandledGracefully()
{
double[] source = { 10, double.NaN, 30, 40, 50 };
double[] output = new double[5];
Swma.Batch(source, output, period: 3);
// After NaN substitution, all outputs should be finite
for (int i = 0; i < output.Length; i++)
{
Assert.True(double.IsFinite(output[i]), $"output[{i}] should be finite");
}
}
[Fact]
public void Batch_Span_LargeData_NoStackOverflow()
{
int count = 10_000;
double[] source = new double[count];
double[] output = new double[count];
for (int i = 0; i < count; i++)
{
source[i] = 100.0 + (i % 50);
}
Swma.Batch(source, output, period: 20);
Assert.True(double.IsFinite(output[^1]));
}
// === H) Chainability ===
[Fact]
public void Pub_FiresOnUpdate()
{
var swma = new Swma(period: 4);
int pubCount = 0;
swma.Pub += (object? sender, in TValueEventArgs e) => pubCount++;
swma.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(1, pubCount);
}
[Fact]
public void EventBased_Chaining_Works()
{
var publisher = new TSeries();
var swma = new Swma(publisher, period: 4);
int resultCount = 0;
swma.Pub += (object? sender, in TValueEventArgs e) => resultCount++;
for (int i = 0; i < 10; i++)
{
publisher.Add(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.Equal(10, resultCount);
}
// === Additional: Calculate API ===
[Fact]
public void Calculate_ReturnsResultsAndIndicator()
{
var src = MakeSeries(50);
var (results, indicator) = Swma.Calculate(src, period: 5);
Assert.Equal(50, results.Count);
Assert.True(indicator.IsHot);
}
// === Dispose ===
[Fact]
public void Dispose_UnsubscribesFromSource()
{
var publisher = new TSeries();
var swma = new Swma(publisher, period: 4);
int pubCount = 0;
swma.Pub += (object? sender, in TValueEventArgs e) => pubCount++;
publisher.Add(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(1, pubCount);
swma.Dispose();
publisher.Add(new TValue(DateTime.UtcNow.AddSeconds(1), 200.0));
Assert.Equal(1, pubCount); // Should not increment after dispose
}
// === Prime ===
[Fact]
public void Prime_SetsStateFromSpan()
{
var swma = new Swma(period: 4);
double[] data = { 10, 20, 30, 40, 50 };
swma.Prime(data);
Assert.True(swma.IsHot);
Assert.True(double.IsFinite(swma.Last.Value));
}
// === Triangular weight properties ===
[Fact]
public void Weights_AreSymmetric()
{
// Verify symmetry: output of mirror-reversed input equals original
var swma1 = new Swma(period: 5);
var swma2 = new Swma(period: 5);
double[] vals = { 10, 20, 30, 40, 50 };
double[] reversed = { 50, 40, 30, 20, 10 };
for (int i = 0; i < 5; i++)
{
swma1.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
swma2.Update(new TValue(DateTime.UtcNow.AddSeconds(i), reversed[i]));
}
// For symmetric filter with symmetric-around-center input:
// swma({10,20,30,40,50}) + swma({50,40,30,20,10}) should equal 2 * swma({30,30,30,30,30})
// Both outputs should be finite
Assert.True(double.IsFinite(swma1.Last.Value));
Assert.True(double.IsFinite(swma2.Last.Value));
// sum of outputs = 2 * center value (30) for symmetric weights
Assert.Equal(60.0, swma1.Last.Value + swma2.Last.Value, 1e-10);
}
[Fact]
public void Output_BoundedByInputRange()
{
// All weights non-negative: output is convex combination, bounded by min/max input
var swma = new Swma(period: 5);
double[] vals = { 10, 20, 30, 40, 50 };
for (int i = 0; i < vals.Length; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
}
Assert.InRange(swma.Last.Value, 10.0, 50.0);
}
[Fact]
public void Update_TSeries_EmptySource_ReturnsEmpty()
{
var swma = new Swma(period: 4);
var empty = new TSeries();
var result = swma.Update(empty);
Assert.Empty(result);
}
[Fact]
public void Update_TSeries_ProducesCorrectLength()
{
var src = MakeSeries(100);
var swma = new Swma(period: 4);
var result = swma.Update(src);
Assert.Equal(100, result.Count);
}
}
@@ -0,0 +1,254 @@
namespace QuanTAlib.Tests;
public class SwmaValidationTests
{
private static TSeries MakeSeries(int count = 500)
{
var gbm = new GBM(startPrice: 100, seed: 42);
var series = new TSeries();
for (int i = 0; i < count; i++)
{
series.Add(gbm.Next());
}
return series;
}
// === Self-consistency: Batch vs Streaming vs Span ===
[Fact]
public void Batch_Matches_Streaming()
{
var src = MakeSeries(500);
int period = 6;
var batchResult = Swma.Batch(src, period);
var streaming = new Swma(period);
var streamResults = new TSeries();
for (int i = 0; i < src.Count; i++)
{
streamResults.Add(streaming.Update(src[i]));
}
for (int i = 0; i < src.Count; i++)
{
Assert.Equal(batchResult[i].Value, streamResults[i].Value, 1e-10);
}
}
[Fact]
public void Span_Matches_Streaming()
{
var src = MakeSeries(500);
int period = 8;
var streaming = new Swma(period);
var streamResults = new List<double>();
for (int i = 0; i < src.Count; i++)
{
streamResults.Add(streaming.Update(src[i]).Value);
}
var spanOutput = new double[src.Count];
Swma.Batch(src.Values, spanOutput, period);
for (int i = 0; i < src.Count; i++)
{
Assert.Equal(streamResults[i], spanOutput[i], 1e-10);
}
}
[Fact]
public void Calculate_Matches_Batch()
{
var src = MakeSeries(300);
int period = 5;
var batchResult = Swma.Batch(src, period);
var (calcResult, _) = Swma.Calculate(src, period);
Assert.Equal(batchResult.Count, calcResult.Count);
for (int i = 0; i < batchResult.Count; i++)
{
Assert.Equal(batchResult[i].Value, calcResult[i].Value, 1e-10);
}
}
// === Mathematical properties ===
[Fact]
public void ConstantInput_ReturnsConstant_AllPeriods()
{
double constant = 42.0;
int[] periods = { 2, 3, 4, 5, 10, 20 };
foreach (int period in periods)
{
var swma = new Swma(period);
for (int i = 0; i < period + 5; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), constant));
}
Assert.Equal(constant, swma.Last.Value, 1e-10);
}
}
[Fact]
public void OutputBounded_ByInputRange()
{
var src = MakeSeries(500);
int period = 10;
var result = Swma.Batch(src, period);
// After warmup, output should be bounded by local window min/max
for (int i = period - 1; i < src.Count; i++)
{
double min = double.MaxValue;
double max = double.MinValue;
for (int j = i - period + 1; j <= i; j++)
{
double v = src[j].Value;
if (v < min) { min = v; }
if (v > max) { max = v; }
}
Assert.InRange(result[i].Value, min - 1e-10, max + 1e-10);
}
}
[Theory]
[InlineData(3)]
[InlineData(5)]
[InlineData(7)]
[InlineData(11)]
public void SymmetricWeights_SymmetricInput_ProducesCenter(int period)
{
// For symmetric weights and linearly increasing input fully filling the window,
// the weighted average equals the center value
var swma = new Swma(period);
for (int i = 0; i < period; i++)
{
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), (double)(i + 1)));
}
// Linear input [1..period]: center = (period+1)/2.0
double expectedCenter = (period + 1) / 2.0;
Assert.Equal(expectedCenter, swma.Last.Value, 1e-10);
}
[Fact]
public void Period4_PineScript_Equivalence()
{
// PineScript ta.swma: weights [1, 2, 2, 1] / 6
var swma = new Swma(period: 4);
double[] values = { 100, 102, 98, 104, 106, 103, 101, 105 };
var results = new List<double>();
for (int i = 0; i < values.Length; i++)
{
results.Add(swma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), values[i])).Value);
}
// Manual Pine calculation for bar 3 (index 3): (1*100 + 2*102 + 2*98 + 1*104)/6
double expected3 = (100.0 + 204.0 + 196.0 + 104.0) / 6.0;
Assert.Equal(expected3, results[3], 1e-10);
// bar 4: (1*102 + 2*98 + 2*104 + 1*106)/6
double expected4 = (102.0 + 196.0 + 208.0 + 106.0) / 6.0;
Assert.Equal(expected4, results[4], 1e-10);
}
// === Stress and edge cases ===
[Fact]
public void LargePeriod_Handles()
{
int period = 200;
var src = MakeSeries(500);
var result = Swma.Batch(src, period);
Assert.Equal(500, result.Count);
Assert.True(double.IsFinite(result[^1].Value));
}
[Fact]
public void AllNaN_Input_ReturnsNaN()
{
double[] source = new double[10];
Array.Fill(source, double.NaN);
double[] output = new double[10];
Swma.Batch(source, output, period: 3);
for (int i = 0; i < output.Length; i++)
{
Assert.True(double.IsNaN(output[i]));
}
}
[Fact]
public void MixedNaN_Recovers()
{
var swma = new Swma(period: 3);
swma.Update(new TValue(DateTime.UtcNow, 10.0));
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(1), 20.0));
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(2), 30.0));
// Now NaN
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(3), double.NaN));
Assert.True(double.IsFinite(swma.Last.Value));
// Recover with valid value
swma.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 40.0));
Assert.True(double.IsFinite(swma.Last.Value));
}
[Fact]
public void DifferentPeriods_ProduceDifferentResults()
{
var src = MakeSeries(100);
var r4 = Swma.Batch(src, 4);
var r8 = Swma.Batch(src, 8);
// After both are hot, results should differ
bool anyDifferent = false;
for (int i = 20; i < src.Count; i++)
{
if (Math.Abs(r4[i].Value - r8[i].Value) > 1e-6)
{
anyDifferent = true;
break;
}
}
Assert.True(anyDifferent);
}
[Fact]
public void BarCorrection_ProducesSameAsNewSequence()
{
var src = MakeSeries(50);
int period = 5;
// Path 1: All new bars
var swma1 = new Swma(period);
for (int i = 0; i < src.Count; i++)
{
swma1.Update(src[i], isNew: true);
}
// Path 2: Bar correction on last bar
var swma2 = new Swma(period);
for (int i = 0; i < src.Count - 1; i++)
{
swma2.Update(src[i], isNew: true);
}
// Simulate tick corrections then final new bar
swma2.Update(new TValue(DateTime.UtcNow, 999.0), isNew: true);
swma2.Update(src[^1], isNew: false); // Correct last
// The correction path rewrites the last value
Assert.Equal(swma1.Last.Value, swma2.Last.Value, 1e-10);
}
}
+415
View File
@@ -0,0 +1,415 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// SWMA: Symmetric Weighted Moving Average
/// </summary>
/// <remarks>
/// FIR filter with triangular (symmetric) weights peaking at the center.
/// Weight formula: w(i) = half + 1 - |i - half| where half = (period-1)/2.0
/// All weights are non-negative; output is a convex combination bounded by input range.
/// Equivalent to SMA of SMA (double rectangular convolution).
///
/// Default period=4 (PineScript ta.swma uses fixed period=4 with weights [1,2,2,1]/6).
/// Minimum period=2.
/// </remarks>
/// <seealso href="Swma.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Swma : AbstractBase
{
private readonly int _period;
private readonly double[] _weights;
private readonly RingBuffer _buffer;
private readonly ITValuePublisher? _source;
private readonly TValuePublishedHandler? _pubHandler;
private bool _isNew = true;
private bool _disposed;
private double _lastValidValue = double.NaN;
private double _p_lastValidValue = double.NaN;
public bool IsNew => _isNew;
public override bool IsHot => _buffer.IsFull;
/// <summary>
/// Creates SWMA with specified period.
/// </summary>
/// <param name="period">Lookback period (must be >= 2)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Swma(int period = 4)
{
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
_period = period;
Name = $"Swma({_period})";
WarmupPeriod = _period;
_buffer = new RingBuffer(_period);
_weights = new double[_period];
ComputeTriangularWeights(_weights, _period);
}
/// <summary>
/// Creates SWMA connected to a data source for event-based updates.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Swma(ITValuePublisher source, int period = 4) : this(period)
{
_source = source;
_pubHandler = Handle;
_source.Pub += _pubHandler;
}
/// <summary>
/// Computes symmetric triangular weights.
/// w(i) = half + 1 - |i - half| where half = (period-1)/2.0
/// Normalized to sum=1.0.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ComputeTriangularWeights(Span<double> weights, int period)
{
double half = (period - 1) * 0.5;
double wsum = 0.0;
for (int i = 0; i < period; i++)
{
double w = half + 1.0 - Math.Abs(i - half);
weights[i] = w;
wsum += w;
}
// Normalize to sum=1.0
if (wsum > double.Epsilon)
{
double inv = 1.0 / wsum;
for (int i = 0; i < period; i++)
{
weights[i] *= inv;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
_isNew = isNew;
return Update(input, isNew, publish: true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private TValue Update(TValue input, bool isNew, bool publish)
{
if (isNew)
{
_p_lastValidValue = _lastValidValue;
}
else
{
_lastValidValue = _p_lastValidValue;
}
double val = GetValidValue(input.Value);
if (!double.IsFinite(val))
{
Last = new TValue(input.Time, double.NaN);
if (publish) { PubEvent(Last, isNew); }
return Last;
}
if (isNew)
{
_lastValidValue = val;
_buffer.Add(val);
int count = _buffer.Count;
double result;
if (count < _period)
{
result = val;
}
else
{
result = ConvolveFull(_buffer, _weights);
}
Last = new TValue(input.Time, result);
if (publish) { PubEvent(Last, isNew); }
return Last;
}
else
{
// Bar correction: snapshot, compute, restore
_buffer.Snapshot();
double prevLast = _lastValidValue;
double prevPLast = _p_lastValidValue;
_lastValidValue = val;
_buffer.UpdateNewest(val);
int count = _buffer.Count;
double result;
if (count < _period)
{
result = val;
}
else
{
result = ConvolveFull(_buffer, _weights);
}
Last = new TValue(input.Time, result);
// Restore buffer and state
_buffer.Restore();
_lastValidValue = prevLast;
_p_lastValidValue = prevPLast;
if (publish) { PubEvent(Last, isNew); }
return Last;
}
}
public override TSeries Update(TSeries source)
{
if (source.Count == 0)
{
return new TSeries([], []);
}
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);
// Restore state by replaying last period bars
Reset();
int startIndex = Math.Max(0, len - _period);
for (int i = startIndex; i < len; i++)
{
Update(source[i], isNew: true, publish: false);
}
return new TSeries(t, v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetValidValue(double input)
{
if (double.IsFinite(input))
{
return input;
}
return double.IsFinite(_lastValidValue) ? _lastValidValue : double.NaN;
}
/// <summary>
/// FIR convolution using SIMD DotProduct over circular buffer.
/// Weight[0] corresponds to oldest bar, Weight[period-1] to newest.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double ConvolveFull(RingBuffer buffer, double[] weights)
{
ReadOnlySpan<double> internalBuf = buffer.InternalBuffer;
int head = buffer.StartIndex;
int period = buffer.Capacity;
int part1Len = period - head;
double sum1 = internalBuf.Slice(head, part1Len).DotProduct(weights.AsSpan(0, part1Len));
double sum2 = internalBuf[..head].DotProduct(weights.AsSpan(part1Len));
return sum1 + sum2;
}
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
foreach (var value in source)
{
Update(new TValue(DateTime.MinValue, value));
}
}
/// <summary>
/// Calculates SWMA from a TSeries using streaming updates.
/// </summary>
public static TSeries Batch(TSeries source, int period = 4)
{
var swma = new Swma(period);
return swma.Update(source);
}
/// <summary>
/// Calculates Symmetric Weighted Moving Average over a span of values.
/// </summary>
/// <param name="source">Input values</param>
/// <param name="output">Output buffer (must be same length as source)</param>
/// <param name="period">Period for weight calculation (must be >= 2)</param>
/// <param name="nanValue">Value to use for NaN substitution (default: NaN)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 4, double nanValue = double.NaN)
{
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (source.Length == 0)
{
return;
}
int len = source.Length;
const int StackallocThreshold = 256;
// Allocate weights
double[]? weightsRented = period > StackallocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
Span<double> weights = period <= StackallocThreshold
? stackalloc double[period]
: weightsRented!.AsSpan(0, period);
// Allocate ring buffer
double[]? ringRented = period > StackallocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
Span<double> ring = period <= StackallocThreshold
? stackalloc double[period]
: ringRented!.AsSpan(0, period);
// Allocate NaN-corrected values array
double[]? cleanRented = len > StackallocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
Span<double> clean = len <= StackallocThreshold
? stackalloc double[len]
: cleanRented!.AsSpan(0, len);
ComputeTriangularWeights(weights, period);
try
{
// Build NaN-corrected values array
double lastValid = nanValue;
for (int i = 0; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
{
lastValid = val;
clean[i] = val;
}
else if (double.IsFinite(lastValid))
{
clean[i] = lastValid;
}
else
{
clean[i] = double.NaN;
}
}
// Apply SWMA FIR convolution
int ringIdx = 0;
int count = 0;
for (int i = 0; i < len; i++)
{
double val = clean[i];
ring[ringIdx] = val;
ringIdx++;
if (ringIdx >= period)
{
ringIdx = 0;
}
if (count < period)
{
count++;
}
if (count < period)
{
// Warmup: return raw value
output[i] = val;
continue;
}
// Full window: DotProduct convolution over circular buffer
// ringIdx points to next-write = oldest entry
int part1Len = period - ringIdx;
ReadOnlySpan<double> ringRo = ring;
double sum = ringRo.Slice(ringIdx, part1Len).DotProduct(weights.Slice(0, part1Len))
+ ringRo[..ringIdx].DotProduct(weights.Slice(part1Len));
output[i] = sum;
}
}
finally
{
if (weightsRented != null)
{
ArrayPool<double>.Shared.Return(weightsRented);
}
if (ringRented != null)
{
ArrayPool<double>.Shared.Return(ringRented);
}
if (cleanRented != null)
{
ArrayPool<double>.Shared.Return(cleanRented);
}
}
}
/// <summary>
/// Creates a SWMA indicator and calculates results from source.
/// </summary>
public static (TSeries Results, Swma Indicator) Calculate(TSeries source, int period = 4)
{
var indicator = new Swma(period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
public override void Reset()
{
_buffer.Clear();
_lastValidValue = double.NaN;
_p_lastValidValue = double.NaN;
Last = default;
}
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing && _source != null && _pubHandler != null)
{
_source.Pub -= _pubHandler;
}
_disposed = true;
}
base.Dispose(disposing);
}
}