mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-25 22:08:05 +00:00
SIMD Refactor: Merge simd-dev into dev (#55)
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>
This commit is contained in:
co-authored by
Claude Opus 4.5
aider
Warp
parent
5bcdf8d614
commit
86fe32a682
@@ -0,0 +1,161 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class SmaIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void SmaIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new SmaIndicator();
|
||||
|
||||
Assert.Equal(10, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("SMA - Simple Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmaIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new SmaIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, SmaIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmaIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new SmaIndicator { Period = 15 };
|
||||
|
||||
Assert.Contains("SMA", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmaIndicator_Initialize_CreatesInternalSma()
|
||||
{
|
||||
var indicator = new SmaIndicator { Period = 10 };
|
||||
|
||||
// Initialize should not throw
|
||||
indicator.Initialize();
|
||||
|
||||
// After init, line series should exist
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new SmaIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
// Add historical data
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
// Process update
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
|
||||
// Line series should have a value
|
||||
Assert.Equal(1, indicator.LinesSeries[0].Count);
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmaIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new SmaIndicator { 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 SmaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new SmaIndicator { 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 SmaIndicator_MultipleUpdates_ProducesCorrectSmaSequence()
|
||||
{
|
||||
var indicator = new SmaIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
double[] closes = { 100, 102, 104, 103, 105 };
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// All values should be finite
|
||||
for (int i = 0; i < closes.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(closes.Length - 1 - i)));
|
||||
}
|
||||
|
||||
// Last SMA(3) should be average of last 3 values: (103 + 105 + 104) / 3 ≈ 104
|
||||
// Actually: (104 + 103 + 105) / 3 = 104
|
||||
double lastSma = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(lastSma >= 103 && lastSma <= 105);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SmaIndicator_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 SmaIndicator { 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 SmaIndicator_Period_CanBeChanged()
|
||||
{
|
||||
var indicator = new SmaIndicator { Period = 5 };
|
||||
Assert.Equal(5, indicator.Period);
|
||||
|
||||
indicator.Period = 20;
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(0, SmaIndicator.MinHistoryDepths);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class SmaIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 10;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Sma _sma = 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 => $"SMA {Period}:{_sourceName}";
|
||||
|
||||
public SmaIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "SMA - Simple Moving Average";
|
||||
Description = "Simple Moving Average";
|
||||
_series = new LineSeries(name: $"SMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
_sourceName = Source.ToString();
|
||||
_sma = new Sma(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 = _sma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
|
||||
_series.SetValue(value, _sma.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,597 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
#pragma warning disable S2245 // Random is acceptable for simulation/testing purposes
|
||||
public class SmaTests
|
||||
{
|
||||
[Fact]
|
||||
public void Sma_Constructor_ValidatesInput()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Sma(0));
|
||||
Assert.Throws<ArgumentException>(() => new Sma(-1));
|
||||
|
||||
var sma = new Sma(10);
|
||||
Assert.NotNull(sma);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Calc_ReturnsValue()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
Assert.Equal(0, sma.Last.Value);
|
||||
|
||||
TValue result = sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
|
||||
Assert.True(result.Value > 0);
|
||||
Assert.Equal(result.Value, sma.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_FirstValue_ReturnsItself()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
TValue result = sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
|
||||
Assert.Equal(100.0, result.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Calc_IsNew_AcceptsParameter()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
|
||||
double value1 = sma.Last.Value;
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 200), isNew: true);
|
||||
double value2 = sma.Last.Value;
|
||||
|
||||
// Values should change with new bars
|
||||
Assert.NotEqual(value1, value2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Calc_IsNew_False_UpdatesValue()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 110), isNew: true);
|
||||
double beforeUpdate = sma.Last.Value;
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 120), isNew: false);
|
||||
double afterUpdate = sma.Last.Value;
|
||||
|
||||
// Update should change the value
|
||||
Assert.NotEqual(beforeUpdate, afterUpdate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Reset_ClearsState()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 105));
|
||||
double valueBefore = sma.Last.Value;
|
||||
|
||||
sma.Reset();
|
||||
|
||||
Assert.Equal(0, sma.Last.Value);
|
||||
|
||||
// After reset, should accept new values
|
||||
sma.Update(new TValue(DateTime.UtcNow, 50));
|
||||
Assert.NotEqual(0, sma.Last.Value);
|
||||
Assert.NotEqual(valueBefore, sma.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Properties_Accessible()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
Assert.Equal(0, sma.Last.Value);
|
||||
Assert.False(sma.IsHot);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
|
||||
Assert.NotEqual(0, sma.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_IsHot_BecomesTrueWhenBufferFull()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
Assert.False(sma.IsHot);
|
||||
|
||||
for (int i = 1; i <= 4; i++)
|
||||
{
|
||||
sma.Update(new TValue(DateTime.UtcNow, i * 10));
|
||||
Assert.False(sma.IsHot);
|
||||
}
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 50));
|
||||
Assert.True(sma.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_CalculatesCorrectAverage()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 10));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 20));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 30));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 40));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 50));
|
||||
|
||||
// SMA(5) of 10,20,30,40,50 = 150/5 = 30
|
||||
Assert.Equal(30.0, sma.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_SlidingWindow_Works()
|
||||
{
|
||||
var sma = new Sma(3);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 10));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 20));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 30));
|
||||
|
||||
// SMA(3) of 10,20,30 = 60/3 = 20
|
||||
Assert.Equal(20.0, sma.Last.Value, 1e-10);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 40));
|
||||
|
||||
// SMA(3) of 20,30,40 = 90/3 = 30
|
||||
Assert.Equal(30.0, sma.Last.Value, 1e-10);
|
||||
|
||||
sma.Update(new TValue(DateTime.UtcNow, 50));
|
||||
|
||||
// SMA(3) of 30,40,50 = 120/3 = 40
|
||||
Assert.Equal(40.0, sma.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_IterativeCorrections_RestoreToOriginalState()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
|
||||
|
||||
// Feed 10 new values
|
||||
TValue tenthInput = default;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
tenthInput = new TValue(bar.Time, bar.Close);
|
||||
sma.Update(tenthInput, isNew: true);
|
||||
}
|
||||
|
||||
// Remember SMA state after 10 values
|
||||
double smaAfterTen = sma.Last.Value;
|
||||
|
||||
// Generate 9 corrections with isNew=false (different values)
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: false);
|
||||
sma.Update(new TValue(bar.Time, bar.Close), isNew: false);
|
||||
}
|
||||
|
||||
// Feed the remembered 10th input again with isNew=false
|
||||
TValue finalSma = sma.Update(tenthInput, isNew: false);
|
||||
|
||||
// SMA should match the original state after 10 values
|
||||
Assert.Equal(smaAfterTen, finalSma.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_BatchCalc_MatchesIterativeCalc()
|
||||
{
|
||||
var smaIterative = new Sma(10);
|
||||
var smaBatch = new Sma(10);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
|
||||
|
||||
// Generate data
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
series.Add(bar.Time, bar.Close);
|
||||
}
|
||||
|
||||
Assert.True(series.Count > 0);
|
||||
|
||||
// Calculate iteratively
|
||||
var iterativeResults = new TSeries();
|
||||
foreach (var item in series)
|
||||
{
|
||||
iterativeResults.Add(smaIterative.Update(item));
|
||||
}
|
||||
|
||||
// Calculate batch
|
||||
var batchResults = smaBatch.Update(series);
|
||||
|
||||
// Compare
|
||||
Assert.Equal(iterativeResults.Count, batchResults.Count);
|
||||
for (int i = 0; i < iterativeResults.Count; i++)
|
||||
{
|
||||
Assert.Equal(iterativeResults[i].Value, batchResults[i].Value, 1e-10);
|
||||
Assert.Equal(iterativeResults[i].Time, batchResults[i].Time);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Result_ImplicitConversionToDouble()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
|
||||
// This should compile and work because TValue has implicit conversion to double
|
||||
double result = sma.Last.Value;
|
||||
|
||||
Assert.Equal(100.0, result, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
// Feed some valid values
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 110));
|
||||
|
||||
// Feed NaN - should use last valid value (110)
|
||||
var resultAfterNaN = sma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
|
||||
// Result should be finite (not NaN)
|
||||
Assert.True(double.IsFinite(resultAfterNaN.Value));
|
||||
Assert.NotEqual(0, resultAfterNaN.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Infinity_Input_UsesLastValidValue()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
// Feed some valid values
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 110));
|
||||
|
||||
// Feed positive infinity - should use last valid value
|
||||
var resultAfterPosInf = sma.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(resultAfterPosInf.Value));
|
||||
|
||||
// Feed negative infinity - should use last valid value
|
||||
var resultAfterNegInf = sma.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
|
||||
Assert.True(double.IsFinite(resultAfterNegInf.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_MultipleNaN_ContinuesWithLastValid()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
// Feed valid values
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 110));
|
||||
sma.Update(new TValue(DateTime.UtcNow, 120));
|
||||
|
||||
// Feed multiple NaN values
|
||||
var r1 = sma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
var r2 = sma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
var r3 = sma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
|
||||
// All results should be finite
|
||||
Assert.True(double.IsFinite(r1.Value));
|
||||
Assert.True(double.IsFinite(r2.Value));
|
||||
Assert.True(double.IsFinite(r3.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_BatchCalc_HandlesNaN()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
// Create series with NaN values interspersed
|
||||
var series = new TSeries();
|
||||
series.Add(DateTime.UtcNow.Ticks, 100);
|
||||
series.Add(DateTime.UtcNow.Ticks + 1, 110);
|
||||
series.Add(DateTime.UtcNow.Ticks + 2, double.NaN);
|
||||
series.Add(DateTime.UtcNow.Ticks + 3, 120);
|
||||
series.Add(DateTime.UtcNow.Ticks + 4, double.PositiveInfinity);
|
||||
series.Add(DateTime.UtcNow.Ticks + 5, 130);
|
||||
|
||||
var results = sma.Update(series);
|
||||
|
||||
// All results should be finite
|
||||
foreach (var result in results)
|
||||
{
|
||||
Assert.True(double.IsFinite(result.Value), $"Expected finite value but got {result.Value}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Reset_ClearsLastValidValue()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
|
||||
// Feed values including NaN
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
|
||||
// Reset
|
||||
sma.Reset();
|
||||
|
||||
// After reset, first valid value should establish new baseline
|
||||
var result = sma.Update(new TValue(DateTime.UtcNow, 50));
|
||||
Assert.Equal(50.0, result.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_StaticBatch_Works()
|
||||
{
|
||||
var series = new TSeries();
|
||||
series.Add(DateTime.UtcNow.Ticks, 10);
|
||||
series.Add(DateTime.UtcNow.Ticks + 1, 20);
|
||||
series.Add(DateTime.UtcNow.Ticks + 2, 30);
|
||||
series.Add(DateTime.UtcNow.Ticks + 3, 40);
|
||||
series.Add(DateTime.UtcNow.Ticks + 4, 50);
|
||||
|
||||
var results = Sma.Batch(series, 3);
|
||||
|
||||
Assert.Equal(5, results.Count);
|
||||
// SMA(3) for last value: (30+40+50)/3 = 40
|
||||
Assert.Equal(40.0, results.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Period1_ReturnsInputValues()
|
||||
{
|
||||
var sma = new Sma(1);
|
||||
|
||||
Assert.Equal(100.0, sma.Update(new TValue(DateTime.UtcNow, 100)).Value, 1e-10);
|
||||
Assert.Equal(200.0, sma.Update(new TValue(DateTime.UtcNow, 200)).Value, 1e-10);
|
||||
Assert.Equal(150.0, sma.Update(new TValue(DateTime.UtcNow, 150)).Value, 1e-10);
|
||||
}
|
||||
|
||||
// ============== Span API Tests ==============
|
||||
|
||||
[Fact]
|
||||
public void Sma_SpanBatch_ValidatesInput()
|
||||
{
|
||||
double[] source = [1, 2, 3, 4, 5];
|
||||
double[] output = new double[5];
|
||||
double[] wrongSizeOutput = new double[3];
|
||||
|
||||
// Period must be > 0
|
||||
Assert.Throws<ArgumentException>(() => Sma.Batch(source.AsSpan(), output.AsSpan(), 0));
|
||||
Assert.Throws<ArgumentException>(() => Sma.Batch(source.AsSpan(), output.AsSpan(), -1));
|
||||
|
||||
// Output must be same length as source
|
||||
Assert.Throws<ArgumentException>(() => Sma.Batch(source.AsSpan(), wrongSizeOutput.AsSpan(), 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_SpanBatch_MatchesTSeriesBatch()
|
||||
{
|
||||
var series = new TSeries();
|
||||
double[] source = new double[100];
|
||||
double[] output = new double[100];
|
||||
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
source[i] = bar.Close;
|
||||
series.Add(bar.Time, bar.Close);
|
||||
}
|
||||
|
||||
// Calculate with TSeries API
|
||||
var tseriesResult = Sma.Batch(series, 10);
|
||||
|
||||
// Calculate with Span API
|
||||
Sma.Batch(source.AsSpan(), output.AsSpan(), 10);
|
||||
|
||||
// Compare results
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
Assert.Equal(tseriesResult[i].Value, output[i], 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_SpanBatch_CalculatesCorrectly()
|
||||
{
|
||||
double[] source = [10, 20, 30, 40, 50];
|
||||
double[] output = new double[5];
|
||||
|
||||
Sma.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
// SMA(3) warmup: 10, (10+20)/2=15, (10+20+30)/3=20, then sliding: (20+30+40)/3=30, (30+40+50)/3=40
|
||||
Assert.Equal(10.0, output[0], 1e-10);
|
||||
Assert.Equal(15.0, output[1], 1e-10);
|
||||
Assert.Equal(20.0, output[2], 1e-10);
|
||||
Assert.Equal(30.0, output[3], 1e-10);
|
||||
Assert.Equal(40.0, output[4], 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_SpanBatch_ZeroAllocation()
|
||||
{
|
||||
double[] source = new double[10000];
|
||||
|
||||
double[] output = new double[10000];
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
source[i] = gbm.Next().Close;
|
||||
|
||||
// Warm up
|
||||
Sma.Batch(source.AsSpan(), output.AsSpan(), 100);
|
||||
|
||||
// This test verifies the method runs without throwing
|
||||
// (allocation is measured by BenchmarkDotNet, not unit tests)
|
||||
Assert.True(double.IsFinite(output[^1]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_SpanBatch_HandlesNaN()
|
||||
{
|
||||
double[] source = [100, 110, double.NaN, 120, 130];
|
||||
double[] output = new double[5];
|
||||
|
||||
Sma.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
// All outputs should be finite
|
||||
foreach (var val in output)
|
||||
{
|
||||
Assert.True(double.IsFinite(val), $"Expected finite value but got {val}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_SpanBatch_Period1_ReturnsInput()
|
||||
{
|
||||
double[] source = [10, 20, 30, 40, 50];
|
||||
double[] output = new double[5];
|
||||
|
||||
Sma.Batch(source.AsSpan(), output.AsSpan(), 1);
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
Assert.Equal(source[i], output[i], 1e-10);
|
||||
}
|
||||
}
|
||||
[Fact]
|
||||
public void Sma_AllModes_ProduceSameResult()
|
||||
{
|
||||
// Arrange
|
||||
const int period = 10;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
var bars = gbm.Fetch(1000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var series = bars.Close;
|
||||
|
||||
// 1. Batch Mode
|
||||
var batchSeries = Sma.Batch(series, period);
|
||||
double expected = batchSeries.Last.Value;
|
||||
|
||||
// 2. Span Mode
|
||||
var tValues = series.Values.ToArray();
|
||||
var spanInput = new ReadOnlySpan<double>(tValues);
|
||||
var spanOutput = new double[tValues.Length];
|
||||
Sma.Batch(spanInput, spanOutput, period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming Mode
|
||||
var streamingInd = new Sma(period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
streamingInd.Update(series[i]);
|
||||
}
|
||||
double streamingResult = streamingInd.Last.Value;
|
||||
|
||||
// 4. Eventing Mode
|
||||
var pubSource = new TSeries();
|
||||
var eventingInd = new Sma(pubSource, period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
pubSource.Add(series[i]);
|
||||
}
|
||||
double eventingResult = eventingInd.Last.Value;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, spanResult, precision: 9);
|
||||
Assert.Equal(expected, streamingResult, precision: 9);
|
||||
Assert.Equal(expected, eventingResult, precision: 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chainability_Works()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var sma = new Sma(source, 10);
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(100, sma.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_IsSetCorrectly()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
Assert.Equal(10, sma.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_SetsStateCorrectly()
|
||||
{
|
||||
var sma = new Sma(5);
|
||||
double[] history = [10, 20, 30, 40, 50]; // SMA(5) = 30
|
||||
|
||||
sma.Prime(history);
|
||||
|
||||
Assert.True(sma.IsHot);
|
||||
Assert.Equal(30.0, sma.Last.Value, 1e-10);
|
||||
|
||||
// Verify it continues correctly
|
||||
sma.Update(new TValue(DateTime.UtcNow, 60)); // 20,30,40,50,60 -> 40
|
||||
Assert.Equal(40.0, sma.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_WithInsufficientHistory_IsNotHot()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
double[] history = [10, 20, 30, 40, 50];
|
||||
|
||||
sma.Prime(history);
|
||||
|
||||
Assert.False(sma.IsHot);
|
||||
Assert.Equal(30.0, sma.Last.Value, 1e-10); // It still calculates what it can
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_HandlesNaN_InHistory()
|
||||
{
|
||||
var sma = new Sma(3);
|
||||
double[] history = [10, 20, double.NaN, 40];
|
||||
// 10
|
||||
// 10, 20
|
||||
// 10, 20, 20 (NaN replaced by 20) -> Avg(10,20,20) = 16.666...
|
||||
// 20, 20, 40 -> Avg(20,20,40) = 26.666...
|
||||
|
||||
sma.Prime(history);
|
||||
|
||||
Assert.True(sma.IsHot);
|
||||
Assert.Equal(80.0 / 3.0, sma.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsCorrectResultsAndHotIndicator()
|
||||
{
|
||||
var series = new TSeries();
|
||||
for (int i = 1; i <= 10; i++) series.Add(DateTime.UtcNow, i * 10);
|
||||
// 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
|
||||
|
||||
// SMA(5)
|
||||
var (results, indicator) = Sma.Calculate(series, 5);
|
||||
|
||||
// Check results
|
||||
Assert.Equal(10, results.Count);
|
||||
Assert.Equal(30.0, results[4].Value); // 5th element (index 4) is SMA(10..50) = 30
|
||||
Assert.Equal(80.0, results.Last.Value); // Last element is SMA(60..100) = 80
|
||||
|
||||
// Check indicator state
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.Equal(80.0, indicator.Last.Value);
|
||||
Assert.Equal(5, indicator.WarmupPeriod);
|
||||
|
||||
// Verify indicator continues correctly
|
||||
indicator.Update(new TValue(DateTime.UtcNow, 110));
|
||||
// Window was [60, 70, 80, 90, 100] -> Avg 80
|
||||
// New Window [70, 80, 90, 100, 110] -> Avg 90
|
||||
Assert.Equal(90.0, indicator.Last.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Skender.Stock.Indicators;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class SmaToleranceTests : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData;
|
||||
|
||||
public SmaToleranceTests()
|
||||
{
|
||||
_testData = new ValidationTestData();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_testData.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Check_Skender_Tolerance()
|
||||
{
|
||||
const int period = 20;
|
||||
var sma = new Sma(period);
|
||||
var qResult = sma.Update(_testData.Data);
|
||||
var sResult = _testData.SkenderQuotes.GetSma(period).ToList();
|
||||
|
||||
ValidationHelper.VerifyData(qResult, sResult, (s) => s.Sma);
|
||||
|
||||
// Add explicit assertion to satisfy SonarQube
|
||||
Assert.True(qResult.Count > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
using OoplesFinance.StockIndicators;
|
||||
using OoplesFinance.StockIndicators.Models;
|
||||
using Skender.Stock.Indicators;
|
||||
using TALib;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class SmaValidationTests : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData;
|
||||
private readonly ITestOutputHelper _output;
|
||||
private bool _disposed;
|
||||
|
||||
public SmaValidationTests(ITestOutputHelper output)
|
||||
{
|
||||
_output = output;
|
||||
_testData = new ValidationTestData();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
_testData?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Skender_Batch()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (batch TSeries)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResult = sma.Update(_testData.Data);
|
||||
|
||||
// Calculate Skender SMA
|
||||
var sResult = _testData.SkenderQuotes.GetSma(period).ToList();
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResult, sResult, (s) => s.Sma);
|
||||
}
|
||||
_output.WriteLine("SMA Batch(TSeries) validated successfully against Skender");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Skender_Streaming()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (streaming)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(sma.Update(item).Value);
|
||||
}
|
||||
|
||||
// Calculate Skender SMA
|
||||
var sResult = _testData.SkenderQuotes.GetSma(period).ToList();
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResults, sResult, (s) => s.Sma);
|
||||
}
|
||||
_output.WriteLine("SMA Streaming validated successfully against Skender");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Skender_Span()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data for Span API
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (Span API)
|
||||
double[] qOutput = new double[sourceData.Length];
|
||||
global::QuanTAlib.Sma.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
|
||||
|
||||
// Calculate Skender SMA
|
||||
var sResult = _testData.SkenderQuotes.GetSma(period).ToList();
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qOutput, sResult, (s) => s.Sma);
|
||||
}
|
||||
_output.WriteLine("SMA Span validated successfully against Skender");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Talib_Batch()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data for TA-Lib (double[])
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
double[] output = new double[tData.Length];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (batch TSeries)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResult = sma.Update(_testData.Data);
|
||||
|
||||
// Calculate TA-Lib SMA
|
||||
var retCode = TALib.Functions.Sma<double>(tData, 0..^0, output, out var outRange, period);
|
||||
Assert.Equal(Core.RetCode.Success, retCode);
|
||||
|
||||
int lookback = TALib.Functions.SmaLookback(period);
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResult, output, outRange, lookback);
|
||||
}
|
||||
_output.WriteLine("SMA Batch(TSeries) validated successfully against TA-Lib");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Talib_Streaming()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data for TA-Lib (double[])
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
double[] output = new double[tData.Length];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (streaming)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(sma.Update(item).Value);
|
||||
}
|
||||
|
||||
// Calculate TA-Lib SMA
|
||||
var retCode = TALib.Functions.Sma<double>(tData, 0..^0, output, out var outRange, period);
|
||||
Assert.Equal(Core.RetCode.Success, retCode);
|
||||
|
||||
int lookback = TALib.Functions.SmaLookback(period);
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResults, output, outRange, lookback);
|
||||
}
|
||||
_output.WriteLine("SMA Streaming validated successfully against TA-Lib");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Talib_Span()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
double[] talibOutput = new double[sourceData.Length];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (Span API)
|
||||
double[] qOutput = new double[sourceData.Length];
|
||||
global::QuanTAlib.Sma.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
|
||||
|
||||
// Calculate TA-Lib SMA
|
||||
var retCode = TALib.Functions.Sma<double>(sourceData, 0..^0, talibOutput, out var outRange, period);
|
||||
Assert.Equal(Core.RetCode.Success, retCode);
|
||||
|
||||
int lookback = TALib.Functions.SmaLookback(period);
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qOutput, talibOutput, outRange, lookback);
|
||||
}
|
||||
_output.WriteLine("SMA Span validated successfully against TA-Lib");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Tulip_Batch()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data for Tulip (double[])
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (batch TSeries)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResult = sma.Update(_testData.Data);
|
||||
|
||||
// Calculate Tulip SMA
|
||||
var smaIndicator = Tulip.Indicators.sma;
|
||||
double[][] inputs = { tData };
|
||||
double[] options = { period };
|
||||
int lookback = period - 1;
|
||||
double[][] outputs = { new double[tData.Length - lookback] };
|
||||
|
||||
smaIndicator.Run(inputs, options, outputs);
|
||||
var tResult = outputs[0];
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResult, tResult, lookback);
|
||||
}
|
||||
_output.WriteLine("SMA Batch(TSeries) validated successfully against Tulip");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Tulip_Streaming()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data for Tulip (double[])
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (streaming)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(sma.Update(item).Value);
|
||||
}
|
||||
|
||||
// Calculate Tulip SMA
|
||||
var smaIndicator = Tulip.Indicators.sma;
|
||||
double[][] inputs = { tData };
|
||||
double[] options = { period };
|
||||
int lookback = period - 1;
|
||||
double[][] outputs = { new double[tData.Length - lookback] };
|
||||
|
||||
smaIndicator.Run(inputs, options, outputs);
|
||||
var tResult = outputs[0];
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResults, tResult, lookback);
|
||||
}
|
||||
_output.WriteLine("SMA Streaming validated successfully against Tulip");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Tulip_Span()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (Span API)
|
||||
double[] qOutput = new double[sourceData.Length];
|
||||
global::QuanTAlib.Sma.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
|
||||
|
||||
// Calculate Tulip SMA
|
||||
var smaIndicator = Tulip.Indicators.sma;
|
||||
double[][] inputs = { sourceData };
|
||||
double[] options = { period };
|
||||
int lookback = period - 1;
|
||||
double[][] outputs = { new double[sourceData.Length - lookback] };
|
||||
|
||||
smaIndicator.Run(inputs, options, outputs);
|
||||
var tResult = outputs[0];
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qOutput, tResult, lookback);
|
||||
}
|
||||
_output.WriteLine("SMA Span validated successfully against Tulip");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Ooples_Batch()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
// Prepare data for Ooples (List<TickerData>)
|
||||
// Ooples requires TickerData which has Close, High, Low, Open, Volume, Date
|
||||
var ooplesData = _testData.SkenderQuotes.Select(q => new TickerData
|
||||
{
|
||||
Date = q.Date,
|
||||
Close = (double)q.Close,
|
||||
High = (double)q.High,
|
||||
Low = (double)q.Low,
|
||||
Open = (double)q.Open,
|
||||
Volume = (double)q.Volume
|
||||
}).ToList();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Calculate QuanTAlib SMA (batch TSeries)
|
||||
var sma = new global::QuanTAlib.Sma(period);
|
||||
var qResult = sma.Update(_testData.Data);
|
||||
|
||||
// Calculate Ooples SMA
|
||||
var stockData = new StockData(ooplesData);
|
||||
var sResult = stockData.CalculateSimpleMovingAverage(period).OutputValues.Values.First();
|
||||
|
||||
// Compare last 100 records
|
||||
ValidationHelper.VerifyData(qResult, sResult, (s) => s, 100, ValidationHelper.OoplesTolerance);
|
||||
}
|
||||
_output.WriteLine("SMA Batch(TSeries) validated successfully against Ooples");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class SmaZeroDivTests
|
||||
{
|
||||
[Fact]
|
||||
public void Sma_Update_WithIsNewFalse_OnEmptyBuffer_DoesNotThrow()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
|
||||
// Buffer is empty initially.
|
||||
// Calling Update with isNew=false should not cause division by zero.
|
||||
// It should return NaN or 0 or Last, but definitely not throw or return Infinity.
|
||||
|
||||
var result = sma.Update(new TValue(DateTime.UtcNow, 100), isNew: false);
|
||||
|
||||
// Since buffer count is 0, we expect NaN based on our fix.
|
||||
Assert.True(double.IsNaN(result.Value), $"Expected NaN but got {result.Value}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sma_Update_WithIsNewFalse_AfterReset_DoesNotThrow()
|
||||
{
|
||||
var sma = new Sma(10);
|
||||
sma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
sma.Reset();
|
||||
|
||||
// Buffer is empty after Reset.
|
||||
var result = sma.Update(new TValue(DateTime.UtcNow, 200), isNew: false);
|
||||
|
||||
Assert.True(double.IsNaN(result.Value), $"Expected NaN but got {result.Value}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
using System.Buffers;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Runtime.Intrinsics.Arm;
|
||||
using System.Runtime.Intrinsics.X86;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// SMA: Simple Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>SMA calculates the arithmetic mean of the last n values.
|
||||
/// Uses a RingBuffer for storage and manual running sum for O(1) complexity per update.</para>
|
||||
/// <para>Calculation:
|
||||
/// SMA = (P_n + P_(n-1) + ... + P_1) / n</para>
|
||||
///
|
||||
/// O(1) update:
|
||||
/// S_new = S_old - oldest + newest
|
||||
/// SMA = S_new / n
|
||||
///
|
||||
/// IsHot:
|
||||
/// Becomes true when the buffer is full (period samples processed).
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Sma : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly RingBuffer _buffer;
|
||||
private readonly TValuePublishedHandler _handler;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(double Sum, double LastValidValue, int TickCount);
|
||||
private State _state;
|
||||
private State _p_state;
|
||||
|
||||
private const int ResyncInterval = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// Creates SMA with specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">Number of values to average (must be > 0)</param>
|
||||
public Sma(int period)
|
||||
{
|
||||
if (period <= 0)
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
|
||||
_period = period;
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Sma({period})";
|
||||
WarmupPeriod = period;
|
||||
_handler = Handle;
|
||||
}
|
||||
|
||||
public Sma(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
public Sma(TSeries source, int period) : this(period)
|
||||
{
|
||||
Prime(source.Values);
|
||||
if (source.Count > 0)
|
||||
{
|
||||
Last = new TValue(source.LastTime, Last.Value);
|
||||
}
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Mode B: Streaming (Stateful)
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// <summary>
|
||||
/// True if the SMA has enough data to produce valid results.
|
||||
/// SMA is "hot" when the buffer is full (has received at least 'period' values).
|
||||
/// </summary>
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Mode C: Priming (The Bridge)
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the indicator state using the provided history.
|
||||
/// Efficiently processes only the last 'Period' values required to sync the buffer.
|
||||
/// </summary>
|
||||
/// <param name="source">Historical data (only the last 'period' is actually needed)</param>
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0) return;
|
||||
|
||||
// Reset state
|
||||
_buffer.Clear();
|
||||
_state = default;
|
||||
_p_state = default;
|
||||
|
||||
// We only need the last 'period' values to fully restore state
|
||||
// If history is shorter than period, we take it all.
|
||||
int warmupLength = Math.Min(source.Length, WarmupPeriod);
|
||||
int startIndex = source.Length - warmupLength;
|
||||
|
||||
// 1. Seed the LastValidValue (crucial for NaN handling)
|
||||
// We must look backwards from start of our warmup window to find a valid predecessor
|
||||
_state.LastValidValue = double.NaN;
|
||||
for (int i = startIndex - 1; i >= 0; i--)
|
||||
{
|
||||
if (double.IsFinite(source[i]))
|
||||
{
|
||||
_state.LastValidValue = source[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If we didn't find a valid value in history, try finding one inside the warmup window
|
||||
if (double.IsNaN(_state.LastValidValue))
|
||||
{
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
if (double.IsFinite(source[i]))
|
||||
{
|
||||
_state.LastValidValue = source[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Feed the RingBuffer and State
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
double val = GetValidValue(source[i]);
|
||||
UpdateState(val);
|
||||
}
|
||||
|
||||
// 3. Finalize State
|
||||
// Calculate the initial "Last" value so the indicator is ready to be read immediately
|
||||
double result = _buffer.Count > 0 ? _state.Sum / _buffer.Count : double.NaN;
|
||||
|
||||
// Note: We can't infer accurate Time from a simple Span<double>,
|
||||
// so we leave 'Last' with default time or user updates it on next Tick.
|
||||
Last = new TValue(DateTime.MinValue, result);
|
||||
|
||||
// Backup state for the next update cycle
|
||||
_p_state = _state;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a valid input value, using last-value substitution for non-finite inputs.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private double GetValidValue(double input)
|
||||
{
|
||||
if (double.IsFinite(input))
|
||||
{
|
||||
_state.LastValidValue = input;
|
||||
return input;
|
||||
}
|
||||
return _state.LastValidValue;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void UpdateState(double val)
|
||||
{
|
||||
double removedValue = _buffer.Count == _buffer.Capacity ? _buffer.Oldest : 0.0;
|
||||
|
||||
_state.Sum = Math.FusedMultiplyAdd(-1.0, removedValue, _state.Sum + val);
|
||||
|
||||
_buffer.Add(val);
|
||||
|
||||
_state.TickCount++;
|
||||
if (_buffer.IsFull && _state.TickCount >= ResyncInterval)
|
||||
{
|
||||
_state.TickCount = 0;
|
||||
_state.Sum = _buffer.RecalculateSum();
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
if (isNew)
|
||||
{
|
||||
// Capture previous state BEFORE any mutation
|
||||
_p_state = _state;
|
||||
|
||||
double val = GetValidValue(input.Value);
|
||||
UpdateState(val);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
// Restore scalar state to pre-mutation values (except Sum which we'll recalculate)
|
||||
var restoredState = _p_state;
|
||||
|
||||
double val = GetValidValue(input.Value);
|
||||
|
||||
// Update the buffer's newest value - this also updates buffer's internal sum
|
||||
_buffer.UpdateNewest(val);
|
||||
|
||||
// Use buffer's authoritative sum (UpdateNewest already did the differential update internally)
|
||||
_state = restoredState with { Sum = _buffer.Sum };
|
||||
// Note: Resync is only done on isNew=true path via UpdateState()
|
||||
}
|
||||
|
||||
double result = _buffer.Count > 0 ? _state.Sum / _buffer.Count : double.NaN;
|
||||
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);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Mode A: Batch (Stateless)
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// <summary>
|
||||
/// Calculates SMA for the entire series using a new instance.
|
||||
/// </summary>
|
||||
/// <param name="source">Input series</param>
|
||||
/// <param name="period">SMA period</param>
|
||||
/// <returns>SMA series</returns>
|
||||
public static TSeries Batch(TSeries source, int period)
|
||||
{
|
||||
var sma = new Sma(period);
|
||||
return sma.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates SMA in-place, writing results to pre-allocated output span.
|
||||
/// Zero-allocation method for maximum performance.
|
||||
/// Uses stackalloc circular buffer for NaN-safe sliding window calculation.
|
||||
/// Automatically uses SIMD acceleration for large, clean datasets.
|
||||
/// </summary>
|
||||
/// <param name="source">Input values</param>
|
||||
/// <param name="output">Output span (must be same length as source)</param>
|
||||
/// <param name="period">SMA period (must be > 0)</param>
|
||||
[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;
|
||||
|
||||
// Try SIMD path for large, clean datasets
|
||||
// Requirements: SIMD support, large enough dataset, no NaN values
|
||||
const int SimdThreshold = 256;
|
||||
if (len >= SimdThreshold && !source.ContainsNonFinite())
|
||||
{
|
||||
if (Avx512F.IsSupported)
|
||||
{
|
||||
CalculateAvx512Core(source, output, period);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Avx2.IsSupported)
|
||||
{
|
||||
CalculateAvx2Core(source, output, period);
|
||||
return;
|
||||
}
|
||||
|
||||
if (AdvSimd.Arm64.IsSupported)
|
||||
{
|
||||
CalculateNeonCore(source, output, period);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Scalar path with NaN handling
|
||||
CalculateScalarCore(source, output, period);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a high-performance SIMD batch calculation on history and returns
|
||||
/// a "Hot" Sma instance ready to process the next tick immediately.
|
||||
/// </summary>
|
||||
/// <param name="source">Historical time series</param>
|
||||
/// <param name="period">SMA Period</param>
|
||||
/// <returns>A tuple containing the full calculation results and the hot indicator instance</returns>
|
||||
public static (TSeries Results, Sma Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var sma = new Sma(period);
|
||||
TSeries results = sma.Update(source);
|
||||
return (results, sma);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void CalculateScalarCore(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
int len = source.Length;
|
||||
|
||||
const int StackAllocThreshold = 256;
|
||||
double[]? rented = period > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
|
||||
Span<double> buffer = rented != null
|
||||
? rented.AsSpan(0, period)
|
||||
: stackalloc double[period];
|
||||
|
||||
try
|
||||
{
|
||||
double sum = 0;
|
||||
double lastValid = double.NaN;
|
||||
|
||||
// Find first valid value to seed lastValid
|
||||
for (int k = 0; k < len; k++)
|
||||
{
|
||||
if (double.IsFinite(source[k]))
|
||||
{
|
||||
lastValid = source[k];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int bufferIndex = 0;
|
||||
int i = 0;
|
||||
|
||||
int warmupEnd = Math.Min(period, len);
|
||||
for (; i < warmupEnd; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
lastValid = val;
|
||||
else
|
||||
val = lastValid;
|
||||
|
||||
sum += val;
|
||||
buffer[i] = val;
|
||||
output[i] = sum / (i + 1);
|
||||
}
|
||||
|
||||
int tickCount = 0;
|
||||
for (; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
lastValid = val;
|
||||
else
|
||||
val = lastValid;
|
||||
|
||||
sum = Math.FusedMultiplyAdd(-1.0, buffer[bufferIndex], sum + val);
|
||||
buffer[bufferIndex] = val;
|
||||
|
||||
bufferIndex++;
|
||||
if (bufferIndex >= period)
|
||||
bufferIndex = 0;
|
||||
|
||||
output[i] = sum / period;
|
||||
|
||||
tickCount++;
|
||||
if (tickCount >= ResyncInterval)
|
||||
{
|
||||
tickCount = 0;
|
||||
double recalcSum = 0;
|
||||
for (int k = 0; k < period; k++)
|
||||
{
|
||||
recalcSum += buffer[k];
|
||||
}
|
||||
sum = recalcSum;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rented != null)
|
||||
ArrayPool<double>.Shared.Return(rented);
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private static void CalculateAvx512Core(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
int len = source.Length;
|
||||
const int VectorWidth = 8;
|
||||
|
||||
ref double srcRef = ref MemoryMarshal.GetReference(source);
|
||||
ref double outRef = ref MemoryMarshal.GetReference(output);
|
||||
|
||||
double invPeriod = 1.0 / period;
|
||||
|
||||
int warmupEnd = Math.Min(period, len);
|
||||
double sum = 0;
|
||||
for (int i = 0; i < warmupEnd; i++)
|
||||
{
|
||||
sum += Unsafe.Add(ref srcRef, i);
|
||||
Unsafe.Add(ref outRef, i) = sum / (i + 1);
|
||||
}
|
||||
|
||||
if (len <= period)
|
||||
return;
|
||||
|
||||
var vInvPeriod = Vector512.Create(invPeriod);
|
||||
int simdEnd = period + (len - period) / VectorWidth * VectorWidth;
|
||||
int tickCount = 0;
|
||||
|
||||
for (int i = period; i < simdEnd; i += VectorWidth)
|
||||
{
|
||||
var vNew = Vector512.LoadUnsafe(ref Unsafe.Add(ref srcRef, i));
|
||||
var vOld = Vector512.LoadUnsafe(ref Unsafe.Add(ref srcRef, i - period));
|
||||
|
||||
var vDelta = Avx512F.Subtract(vNew, vOld);
|
||||
|
||||
// Prefix sum of Delta
|
||||
var vShift1 = Vector512.Create(0.0, vDelta.GetElement(0), vDelta.GetElement(1), vDelta.GetElement(2), vDelta.GetElement(3), vDelta.GetElement(4), vDelta.GetElement(5), vDelta.GetElement(6));
|
||||
var vP1 = Avx512F.Add(vDelta, vShift1);
|
||||
|
||||
var vShift2 = Vector512.Create(0.0, 0.0, vP1.GetElement(0), vP1.GetElement(1), vP1.GetElement(2), vP1.GetElement(3), vP1.GetElement(4), vP1.GetElement(5));
|
||||
var vP2 = Avx512F.Add(vP1, vShift2);
|
||||
|
||||
var vShift4 = Vector512.Create(0.0, 0.0, 0.0, 0.0, vP2.GetElement(0), vP2.GetElement(1), vP2.GetElement(2), vP2.GetElement(3));
|
||||
var vP4 = Avx512F.Add(vP2, vShift4);
|
||||
|
||||
var vSumPrev = Vector512.Create(sum);
|
||||
var vSums = Avx512F.Add(vSumPrev, vP4);
|
||||
|
||||
var vResult = Avx512F.Multiply(vSums, vInvPeriod);
|
||||
vResult.StoreUnsafe(ref Unsafe.Add(ref outRef, i));
|
||||
|
||||
sum = vSums.GetElement(7);
|
||||
|
||||
tickCount += VectorWidth;
|
||||
if (tickCount >= ResyncInterval)
|
||||
{
|
||||
tickCount = 0;
|
||||
int lastIdx = i + VectorWidth - 1;
|
||||
double recalcSum = 0;
|
||||
for (int k = 0; k < period; k++)
|
||||
{
|
||||
recalcSum += Unsafe.Add(ref srcRef, lastIdx - k);
|
||||
}
|
||||
sum = recalcSum;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = simdEnd; i < len; i++)
|
||||
{
|
||||
double newVal = Unsafe.Add(ref srcRef, i);
|
||||
double oldVal = Unsafe.Add(ref srcRef, i - period);
|
||||
sum = Math.FusedMultiplyAdd(-1.0, oldVal, sum + newVal);
|
||||
Unsafe.Add(ref outRef, i) = sum * invPeriod;
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private static void CalculateAvx2Core(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
int len = source.Length;
|
||||
const int VectorWidth = 4;
|
||||
|
||||
ref double srcRef = ref MemoryMarshal.GetReference(source);
|
||||
ref double outRef = ref MemoryMarshal.GetReference(output);
|
||||
|
||||
double invPeriod = 1.0 / period;
|
||||
|
||||
int warmupEnd = Math.Min(period, len);
|
||||
double sum = 0;
|
||||
for (int i = 0; i < warmupEnd; i++)
|
||||
{
|
||||
sum += Unsafe.Add(ref srcRef, i);
|
||||
Unsafe.Add(ref outRef, i) = sum / (i + 1);
|
||||
}
|
||||
|
||||
if (len <= period)
|
||||
return;
|
||||
|
||||
var vInvPeriod = Vector256.Create(invPeriod);
|
||||
var vZero = Vector256<double>.Zero;
|
||||
int simdEnd = period + (len - period) / VectorWidth * VectorWidth;
|
||||
int tickCount = 0;
|
||||
|
||||
for (int i = period; i < simdEnd; i += VectorWidth)
|
||||
{
|
||||
var vNew = Vector256.LoadUnsafe(ref Unsafe.Add(ref srcRef, i));
|
||||
var vOld = Vector256.LoadUnsafe(ref Unsafe.Add(ref srcRef, i - period));
|
||||
|
||||
var vDelta = Avx.Subtract(vNew, vOld);
|
||||
|
||||
var vShift1 = Avx2.Permute4x64(vDelta.AsUInt64(), 0b_10_01_00_00).AsDouble(); // skipcq: CS-R1131
|
||||
vShift1 = Avx.Blend(vZero, vShift1, 0b_1110);
|
||||
var vP1 = Avx.Add(vDelta, vShift1);
|
||||
|
||||
var vShift2 = Avx2.Permute4x64(vP1.AsUInt64(), 0b_01_00_00_00).AsDouble(); // skipcq: CS-R1131
|
||||
vShift2 = Avx.Blend(vZero, vShift2, 0b_1100);
|
||||
var vP2 = Avx.Add(vP1, vShift2);
|
||||
|
||||
var vSumPrev = Vector256.Create(sum);
|
||||
var vSums = Avx.Add(vSumPrev, vP2);
|
||||
|
||||
var vResult = Fma.MultiplyAdd(vSums, vInvPeriod, vZero);
|
||||
vResult.StoreUnsafe(ref Unsafe.Add(ref outRef, i));
|
||||
|
||||
sum = vSums.GetElement(3);
|
||||
|
||||
tickCount += VectorWidth;
|
||||
if (tickCount >= ResyncInterval)
|
||||
{
|
||||
tickCount = 0;
|
||||
int lastIdx = i + VectorWidth - 1;
|
||||
double recalcSum = 0;
|
||||
for (int k = 0; k < period; k++)
|
||||
{
|
||||
recalcSum += Unsafe.Add(ref srcRef, lastIdx - k);
|
||||
}
|
||||
sum = recalcSum;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = simdEnd; i < len; i++)
|
||||
{
|
||||
double newVal = Unsafe.Add(ref srcRef, i);
|
||||
double oldVal = Unsafe.Add(ref srcRef, i - period);
|
||||
sum = Math.FusedMultiplyAdd(-1.0, oldVal, sum + newVal);
|
||||
Unsafe.Add(ref outRef, i) = sum * invPeriod;
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private static void CalculateNeonCore(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
int len = source.Length;
|
||||
const int VectorWidth = 2;
|
||||
|
||||
ref double srcRef = ref MemoryMarshal.GetReference(source);
|
||||
ref double outRef = ref MemoryMarshal.GetReference(output);
|
||||
|
||||
double invPeriod = 1.0 / period;
|
||||
|
||||
int warmupEnd = Math.Min(period, len);
|
||||
double sum = 0;
|
||||
for (int i = 0; i < warmupEnd; i++)
|
||||
{
|
||||
sum += Unsafe.Add(ref srcRef, i);
|
||||
Unsafe.Add(ref outRef, i) = sum / (i + 1);
|
||||
}
|
||||
|
||||
if (len <= period)
|
||||
return;
|
||||
|
||||
var vInvPeriod = Vector128.Create(invPeriod);
|
||||
int simdEnd = period + (len - period) / VectorWidth * VectorWidth;
|
||||
int tickCount = 0;
|
||||
|
||||
for (int i = period; i < simdEnd; i += VectorWidth)
|
||||
{
|
||||
var vNew = Vector128.LoadUnsafe(ref Unsafe.Add(ref srcRef, i));
|
||||
var vOld = Vector128.LoadUnsafe(ref Unsafe.Add(ref srcRef, i - period));
|
||||
|
||||
var vDelta = AdvSimd.Arm64.Subtract(vNew, vOld);
|
||||
|
||||
// Prefix sum of Delta: [d0, d0+d1]
|
||||
double d0 = vDelta.GetElement(0);
|
||||
double d1 = vDelta.GetElement(1);
|
||||
double ps0 = sum + d0;
|
||||
double ps1 = ps0 + d1;
|
||||
|
||||
var vSums = Vector128.Create(ps0, ps1);
|
||||
|
||||
var vResult = AdvSimd.Arm64.Multiply(vSums, vInvPeriod);
|
||||
vResult.StoreUnsafe(ref Unsafe.Add(ref outRef, i));
|
||||
|
||||
sum = ps1;
|
||||
|
||||
tickCount += VectorWidth;
|
||||
if (tickCount >= ResyncInterval)
|
||||
{
|
||||
tickCount = 0;
|
||||
int lastIdx = i + VectorWidth - 1;
|
||||
double recalcSum = 0;
|
||||
for (int k = 0; k < period; k++)
|
||||
{
|
||||
recalcSum += Unsafe.Add(ref srcRef, lastIdx - k);
|
||||
}
|
||||
sum = recalcSum;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = simdEnd; i < len; i++)
|
||||
{
|
||||
double newVal = Unsafe.Add(ref srcRef, i);
|
||||
double oldVal = Unsafe.Add(ref srcRef, i - period);
|
||||
sum = Math.FusedMultiplyAdd(-1.0, oldVal, sum + newVal);
|
||||
Unsafe.Add(ref outRef, i) = sum * invPeriod;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the SMA state.
|
||||
/// </summary>
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_state = default;
|
||||
_p_state = default;
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
# SMA: Simple Moving Average
|
||||
|
||||
> "The vanilla ice cream of technical analysis. Boring, ubiquitous, and the only thing your grandfather and your high-frequency trading bot agree on."
|
||||
|
||||
The Simple Moving Average (SMA) is the unweighted arithmetic mean of the last $N$ data points. It acts as a low-pass filter, smoothing out high-frequency noise to reveal the underlying trend. While conceptually simple, efficient implementation on modern hardware requires careful attention to memory access patterns and vectorization.
|
||||
|
||||
## Historical Context
|
||||
|
||||
The concept of a moving average dates back to 1901 (R.H. Hooker) for smoothing weather data, but it became a staple of financial analysis in the mid-20th century. It is the baseline against which all other averages are compared.
|
||||
|
||||
## Architecture & Physics
|
||||
|
||||
The naive implementation of SMA sums $N$ numbers at every step, resulting in $O(N)$ complexity. QuanTAlib uses an optimized $O(1)$ approach.
|
||||
|
||||
### O(1) Running Sum
|
||||
|
||||
A running `Sum` and a `RingBuffer` of history are maintained.
|
||||
$$ Sum_{new} = Sum_{old} - Value_{oldest} + Value_{new} $$
|
||||
$$ SMA = \frac{Sum_{new}}{N} $$
|
||||
|
||||
This ensures that calculating an SMA(200) takes the exact same time as an SMA(10).
|
||||
|
||||
### Drift Correction
|
||||
|
||||
Floating-point addition is not associative. Repeatedly adding and subtracting values from a running sum introduces cumulative error (drift) over millions of ticks. QuanTAlib implements a periodic **Resync** mechanism (every 1000 ticks) that recalculates the sum from scratch to ensure precision remains within `1e-9` of the true mean.
|
||||
|
||||
### SIMD Optimization
|
||||
|
||||
For batch processing of large datasets, `Sma.Batch` utilizes `System.Runtime.Intrinsics` (AVX2/AVX-512) to process multiple data points in parallel, significantly outperforming scalar loops.
|
||||
|
||||
## Mathematical Foundation
|
||||
|
||||
### 1. The Mean
|
||||
|
||||
$$ SMA_t = \frac{1}{N} \sum_{i=0}^{N-1} P_{t-i} $$
|
||||
|
||||
## Performance Profile
|
||||
|
||||
### Operation Count (Streaming Mode, O(1) Running Sum)
|
||||
|
||||
| Operation | Count | Cost (cycles) | Subtotal |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| SUB (Sum - oldest) | 1 | 1 | 1 |
|
||||
| ADD (Sum + newest) | 1 | 1 | 1 |
|
||||
| DIV (Sum / N) | 1 | 15 | 15 |
|
||||
| **Total (hot)** | **3** | — | **~17 cycles** |
|
||||
|
||||
Every 1000 bars, a resync recalculates the sum to prevent drift:
|
||||
|
||||
| Operation | Count | Cost (cycles) | Subtotal |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| ADD (N values) | N | 1 | N |
|
||||
| DIV (Sum / N) | 1 | 15 | 15 |
|
||||
| **Resync cost** | **N+1** | — | **~N+15 cycles** |
|
||||
|
||||
**Amortized cost:** ~17 + (N+15)/1000 ≈ **~17 cycles/bar** for typical use.
|
||||
|
||||
### Batch Mode (SIMD Analysis)
|
||||
|
||||
SMA batch processing is highly vectorizable using running sum + prefix sum techniques:
|
||||
|
||||
| Operation | Scalar Ops | SIMD Ops (AVX2) | Speedup |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| Initial N-sum | N | N/8 | 8× |
|
||||
| Running update (per bar) | 3 | ~1 | ~3× |
|
||||
| Division | 1 | 1/8 (batched) | 8× |
|
||||
|
||||
For 512 bars:
|
||||
|
||||
| Mode | Cycles/bar | Total | Notes |
|
||||
| :--- | :---: | :---: | :--- |
|
||||
| Scalar streaming | ~17 | ~8,700 | O(1) per bar |
|
||||
| SIMD batch | ~3 | ~1,500 | Vectorized running sum |
|
||||
| **Improvement** | **5.8×** | — | Batch wins for large N |
|
||||
|
||||
### Quality Metrics
|
||||
|
||||
| Metric | Score | Notes |
|
||||
| :--- | :---: | :--- |
|
||||
| **Accuracy** | 10/10 | Exact arithmetic mean |
|
||||
| **Timeliness** | 3/10 | Significant lag (~N/2 bars) |
|
||||
| **Overshoot** | 10/10 | Never overshoots input range |
|
||||
| **Smoothness** | 5/10 | Smooth but susceptible to drop-off jumps |
|
||||
|
||||
### Benchmark Results
|
||||
|
||||
| Metric | Value | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| **Throughput** | ~100M bars/sec | SIMD batch mode |
|
||||
| **Allocations** | 0 bytes | Zero-allocation in hot paths |
|
||||
| **Complexity** | O(1) | Constant time regardless of period N |
|
||||
| **State Size** | 8 + 8N bytes | Sum + RingBuffer |
|
||||
|
||||
## Validation
|
||||
|
||||
| Library | Status | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| **TA-Lib** | ✅ | Matches `TA_SMA` exactly. |
|
||||
| **Skender** | ✅ | Matches `GetSma` exactly. |
|
||||
| **Tulip** | ✅ | Matches `sma` exactly. |
|
||||
| **Ooples** | ✅ | Matches `CalculateSimpleMovingAverage`. |
|
||||
|
||||
## C# Implementation Considerations
|
||||
|
||||
### RingBuffer for O(1) Running Sum
|
||||
|
||||
The implementation maintains a `RingBuffer` of the most recent $N$ values alongside a running `Sum`. On each update, the oldest value is subtracted and the newest added—eliminating the need to iterate over the entire window:
|
||||
|
||||
```csharp
|
||||
Sum = Math.FusedMultiplyAdd(-_buffer[^1], 1, Sum + p);
|
||||
_buffer.Add(p, isNew);
|
||||
```
|
||||
|
||||
Using `FusedMultiplyAdd` for the combined subtraction/addition improves numerical stability compared to separate operations.
|
||||
|
||||
### State Record Struct
|
||||
|
||||
Minimal state is captured in a `record struct` for efficient bar correction:
|
||||
|
||||
```csharp
|
||||
private record struct State(double Sum, double LastValidValue, int TickCount);
|
||||
```
|
||||
|
||||
When `isNew=false`, the implementation restores `_p_state` to revert any partial calculation—enabling accurate bar correction when the same timestamp updates multiple times.
|
||||
|
||||
### Periodic Resync for Drift Correction
|
||||
|
||||
Floating-point drift accumulates over millions of additions/subtractions. The implementation resyncs every 1000 ticks:
|
||||
|
||||
```csharp
|
||||
if (_state.TickCount >= ResyncPeriod)
|
||||
{
|
||||
_state = _state with { Sum = _buffer.Span.Sum(), TickCount = 0 };
|
||||
}
|
||||
```
|
||||
|
||||
This bounds cumulative error to within `1e-9` of true mean regardless of stream length.
|
||||
|
||||
### Multi-Architecture SIMD Implementation
|
||||
|
||||
The static `Calculate` method dispatches to architecture-specific implementations:
|
||||
|
||||
```csharp
|
||||
if (Avx512F.IsSupported) CalculateAvx512Core(source, output, period);
|
||||
else if (Avx2.IsSupported) CalculateAvx2Core(source, output, period);
|
||||
else if (AdvSimd.Arm64.IsSupported) CalculateNeonCore(source, output, period);
|
||||
else CalculateScalarCore(source, output, period);
|
||||
```
|
||||
|
||||
- **AVX-512**: Processes 8 doubles simultaneously with 512-bit vectors
|
||||
- **AVX2**: Processes 4 doubles with 256-bit vectors
|
||||
- **NEON (ARM64)**: Processes 2 doubles with 128-bit vectors
|
||||
- **Scalar fallback**: Portable loop for unsupported architectures
|
||||
|
||||
### Prefix-Sum Vectorization
|
||||
|
||||
For batch processing, the SIMD paths use a prefix-sum technique that enables parallel computation of running sums. The initial window sum is computed with vectorized horizontal addition, then subsequent values use the optimized running-sum pattern.
|
||||
|
||||
### ArrayPool for Memory Efficiency
|
||||
|
||||
Large period buffers are rented from `ArrayPool<double>` rather than allocated, reducing GC pressure during batch operations. Combined with `stackalloc` for small intermediate buffers, this achieves zero-allocation in hot paths.
|
||||
|
||||
### NaN Handling with Last-Valid Substitution
|
||||
|
||||
Non-finite inputs are replaced with the last valid value stored in state:
|
||||
|
||||
```csharp
|
||||
p = double.IsFinite(p) ? p : _state.LastValidValue;
|
||||
```
|
||||
|
||||
This prevents NaN propagation through the running sum without requiring expensive validation on every buffer access.
|
||||
|
||||
### Memory Layout
|
||||
|
||||
| Component | Size | Purpose |
|
||||
| :--- | :--- | :--- |
|
||||
| `_buffer` (RingBuffer) | 32 + 8×period bytes | Sliding window history |
|
||||
| `_state` | ~24 bytes | Sum, LastValidValue, TickCount |
|
||||
| `_p_state` | ~24 bytes | Previous state for rollback |
|
||||
| Scalars | ~16 bytes | Period, reciprocal |
|
||||
| **Total** | **~96 + 8N bytes** | Per-instance footprint |
|
||||
|
||||
For SMA(200), total memory is approximately 1.7 KB per instance.
|
||||
|
||||
### Common Pitfalls
|
||||
|
||||
1. **Lag**: SMA has the most lag of all moving averages (Lag $\approx N/2$).
|
||||
2. **Drop-off Effect**: An old, large outlier dropping out of the window causes the SMA to jump, even if the current price is flat. This "Barker effect" is why EMAs are often preferred.
|
||||
3. **NaN Handling**: A single `NaN` in the history window corrupts the entire SMA. QuanTAlib handles this by substituting the last valid value.
|
||||
@@ -0,0 +1,41 @@
|
||||
// The MIT License (MIT)
|
||||
// © mihakralj
|
||||
//@version=6
|
||||
indicator("Simple Moving Average (SMA)", "SMA", overlay=true)
|
||||
|
||||
//@function Calculates SMA using simple smoothing with compensator
|
||||
//@doc https://github.com/mihakralj/pinescript/blob/main/indicators/trends_FIR/sma.md
|
||||
//@param source Series to calculate SMA from
|
||||
//@param period Lookback period - FIR window size
|
||||
//@returns SMA value, calculates from first bar using available data
|
||||
//@optimized Uses circular buffer and running sum for O(1) complexity
|
||||
sma(series float source, simple int period) =>
|
||||
if period <= 0
|
||||
runtime.error("Period must be greater than 0")
|
||||
int p = period
|
||||
var array<float> buffer = array.new_float(p, na)
|
||||
var int head = 0
|
||||
var float sum = 0.0
|
||||
var int count = 0
|
||||
float oldest = array.get(buffer, head)
|
||||
if not na(oldest)
|
||||
sum -= oldest
|
||||
else
|
||||
count += 1
|
||||
float current = nz(source)
|
||||
sum += current
|
||||
array.set(buffer, head, current)
|
||||
head := (head + 1) % p
|
||||
sum / math.max(1, count)
|
||||
|
||||
// ---------- Main loop ----------
|
||||
|
||||
// Inputs
|
||||
i_period = input.int(10, "Period", minval=1)
|
||||
i_source = input.source(close, "Source")
|
||||
|
||||
// Calculation
|
||||
sma_value = sma(i_source, i_period)
|
||||
|
||||
// Plot
|
||||
plot(sma_value, "SMA", color=color.yellow, linewidth=2)
|
||||
Reference in New Issue
Block a user