diff --git a/QuanTAlib.sln b/QuanTAlib.sln index 4ae60645..a05d420b 100644 --- a/QuanTAlib.sln +++ b/QuanTAlib.sln @@ -9,8 +9,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B3 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoreTypes", "examples\CoreTypes\CoreTypes.csproj", "{8AB1BE0C-06AE-4EE2-B45A-4F8CE6381782}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "lib", "lib", "{3A8DF596-E814-FECC-DD4B-D8EF8AAC1A0D}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuanTAlib.Tests", "tests\QuanTAlib.Tests\QuanTAlib.Tests.csproj", "{43CA2584-D4AD-4082-AFF4-68B3D1239221}" diff --git a/examples/feeds/CsvFeedExample.csproj b/examples/feeds/CsvFeedExample.csproj index 94efec9e..9b84565c 100644 --- a/examples/feeds/CsvFeedExample.csproj +++ b/examples/feeds/CsvFeedExample.csproj @@ -11,6 +11,10 @@ + + + + PreserveNewest diff --git a/examples/feeds/GbmExample.csproj b/examples/feeds/GbmExample.csproj index dece856e..357ed889 100644 --- a/examples/feeds/GbmExample.csproj +++ b/examples/feeds/GbmExample.csproj @@ -12,4 +12,8 @@ + + + + diff --git a/tests/QuanTAlib.Tests/SimdExtensionsTests.cs b/lib/core/simd/SimdExtensions.Tests.cs similarity index 100% rename from tests/QuanTAlib.Tests/SimdExtensionsTests.cs rename to lib/core/simd/SimdExtensions.Tests.cs diff --git a/lib/core/SimdExtensions.cs b/lib/core/simd/SimdExtensions.cs similarity index 100% rename from lib/core/SimdExtensions.cs rename to lib/core/simd/SimdExtensions.cs diff --git a/tests/QuanTAlib.Tests/TBarTests.cs b/lib/core/tbar/TBar.Tests.cs similarity index 83% rename from tests/QuanTAlib.Tests/TBarTests.cs rename to lib/core/tbar/TBar.Tests.cs index 4e3ab3f0..a1c75380 100644 --- a/tests/QuanTAlib.Tests/TBarTests.cs +++ b/lib/core/tbar/TBar.Tests.cs @@ -60,5 +60,17 @@ namespace QuanTAlib.Tests var bar = new TBar(0, 100, 110, 90, 100, 1000); Assert.Equal(100.0, bar.HLCC4); // (110 + 90 + 100 + 100) / 4 } + + [Fact] + public void ImplicitConversion_ToTValue_ReturnsClosePriceWithTime() + { + long time = DateTime.UtcNow.Ticks; + var bar = new TBar(time, 100, 110, 90, 105, 1000); + + TValue tv = bar; + + Assert.Equal(time, tv.Time); + Assert.Equal(105.0, tv.Value); + } } } diff --git a/lib/core/tbar.cs b/lib/core/tbar/tbar.cs similarity index 77% rename from lib/core/tbar.cs rename to lib/core/tbar/tbar.cs index 4f51a63b..29571c45 100644 --- a/lib/core/tbar.cs +++ b/lib/core/tbar/tbar.cs @@ -26,12 +26,12 @@ public readonly struct TBar : IEquatable public TValue V { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new(Time, Volume); } // Computed properties (calculated on demand, no storage overhead) - public double HL2 => (High + Low) * 0.5; - public double OC2 => (Open + Close) * 0.5; - public double OHL3 => (Open + High + Low) / 3.0; - public double HLC3 => (High + Low + Close) / 3.0; - public double OHLC4 => (Open + High + Low + Close) * 0.25; - public double HLCC4 => (High + Low + Close + Close) * 0.25; + public double HL2 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (High + Low) * 0.5; } + public double OC2 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (Open + Close) * 0.5; } + public double OHL3 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (Open + High + Low) / 3.0; } + public double HLC3 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (High + Low + Close) / 3.0; } + public double OHLC4 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (Open + High + Low + Close) * 0.25; } + public double HLCC4 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (High + Low + Close + Close) * 0.25; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TBar(long time, double open, double high, double low, double close, double volume) @@ -58,6 +58,9 @@ public readonly struct TBar : IEquatable [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator double(TBar bar) => bar.Close; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator TValue(TBar bar) => new(bar.Time, bar.Close); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator DateTime(TBar bar) => new(bar.Time, DateTimeKind.Utc); diff --git a/tests/QuanTAlib.Tests/TBarSeriesTests.cs b/lib/core/tbarseries/TBarSeries.Tests.cs similarity index 100% rename from tests/QuanTAlib.Tests/TBarSeriesTests.cs rename to lib/core/tbarseries/TBarSeries.Tests.cs diff --git a/lib/core/tbarseries.cs b/lib/core/tbarseries/tbarseries.cs similarity index 100% rename from lib/core/tbarseries.cs rename to lib/core/tbarseries/tbarseries.cs diff --git a/tests/QuanTAlib.Tests/TSeriesTests.cs b/lib/core/tseries/TSeries.Tests.cs similarity index 100% rename from tests/QuanTAlib.Tests/TSeriesTests.cs rename to lib/core/tseries/TSeries.Tests.cs diff --git a/lib/core/tseries.cs b/lib/core/tseries/tseries.cs similarity index 100% rename from lib/core/tseries.cs rename to lib/core/tseries/tseries.cs diff --git a/tests/QuanTAlib.Tests/TValueTests.cs b/lib/core/tvalue/TValue.Tests.cs similarity index 100% rename from tests/QuanTAlib.Tests/TValueTests.cs rename to lib/core/tvalue/TValue.Tests.cs diff --git a/lib/core/tvalue.cs b/lib/core/tvalue/tvalue.cs similarity index 100% rename from lib/core/tvalue.cs rename to lib/core/tvalue/tvalue.cs diff --git a/tests/QuanTAlib.Tests/CsvFeedTests.cs b/lib/feeds/csv/CsvFeed.Tests.cs similarity index 100% rename from tests/QuanTAlib.Tests/CsvFeedTests.cs rename to lib/feeds/csv/CsvFeed.Tests.cs diff --git a/lib/feeds/CsvFeed.cs b/lib/feeds/csv/CsvFeed.cs similarity index 100% rename from lib/feeds/CsvFeed.cs rename to lib/feeds/csv/CsvFeed.cs diff --git a/tests/QuanTAlib.Tests/daily_IBM.csv b/lib/feeds/csv/daily_IBM.csv similarity index 100% rename from tests/QuanTAlib.Tests/daily_IBM.csv rename to lib/feeds/csv/daily_IBM.csv diff --git a/tests/QuanTAlib.Tests/GBMTests.cs b/lib/feeds/gbm/Gbm.Tests.cs similarity index 100% rename from tests/QuanTAlib.Tests/GBMTests.cs rename to lib/feeds/gbm/Gbm.Tests.cs diff --git a/lib/feeds/gbm.cs b/lib/feeds/gbm/gbm.cs similarity index 100% rename from lib/feeds/gbm.cs rename to lib/feeds/gbm/gbm.cs diff --git a/lib/quantalib.csproj b/lib/quantalib.csproj index 20e55cf4..8b8a1057 100644 --- a/lib/quantalib.csproj +++ b/lib/quantalib.csproj @@ -34,7 +34,7 @@ - + diff --git a/lib/trends_IIR/ema/Ema.Notebook.dib b/lib/trends_IIR/ema/Ema.Notebook.dib new file mode 100644 index 00000000..77bed0ba --- /dev/null +++ b/lib/trends_IIR/ema/Ema.Notebook.dib @@ -0,0 +1,218 @@ +#!meta + +{"kernelInfo":{"defaultKernelName":"csharp","items":[{"name":"csharp"},{"name":"fsharp","languageName":"F#","aliases":["f#","fs"]},{"name":"html","languageName":"HTML"},{"name":"http","languageName":"HTTP"},{"name":"javascript","languageName":"JavaScript","aliases":["js"]},{"name":"mermaid","languageName":"Mermaid"},{"name":"pwsh","languageName":"PowerShell","aliases":["powershell"]},{"name":"value"}]}} + +#!markdown + +# Exponential Moving Average (EMA) Examples + +This is a **.NET Interactive** notebook. To run it, you need the [Polyglot Notebooks](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.dotnet-interactive-vscode) extension installed in VS Code. + +For detailed documentation on the EMA indicator, including mathematical formulas and interpretation, please refer to [Ema.md](Ema.md). + +The **Exponential Moving Average (EMA)** is a weighted moving average that gives more importance to recent price data. Unlike the Simple Moving Average (SMA), which assigns equal weight to all data points, the EMA reacts more significantly to recent price changes. + +This notebook demonstrates: +1. **Manual Data Processing**: Understanding Batch vs. Streaming modes. +2. **Streaming with `isNew`**: Handling intra-bar updates. +3. **Large Dataset Processing**: Using Geometric Brownian Motion (GBM) generated data. +4. **Vectorized Operations**: Calculating multiple EMAs simultaneously. + +#!csharp + +// Reference the library +#r "..\..\bin\QuanTAlib.dll" + +using System; +using System.Linq; +using QuanTAlib; + +// Helper to print TSeries +void PrintSeries(TSeries series, int count = 5) +{ + Console.WriteLine($"Series Length: {series.Count}"); + foreach (var item in series.Take(count)) + { + Console.WriteLine($"Time: {item.Time:HH:mm:ss}, Value: {item.Value:F2}"); + } + if (series.Count > count) Console.WriteLine("..."); +} + +#!markdown + +## 1. Manual Data: Batch vs. Streaming + +We'll start with a small, manually created dataset to clearly see how Batch and Streaming operations work. + +### Batch Processing +Batch processing calculates the EMA for the entire dataset at once. This is efficient for historical analysis. + +#!csharp + +// Create a small manual dataset +var manualData = new TSeries(); +manualData.Add(DateTime.Now, 100.0); +manualData.Add(DateTime.Now.AddMinutes(1), 102.0); +manualData.Add(DateTime.Now.AddMinutes(2), 101.0); +manualData.Add(DateTime.Now.AddMinutes(3), 103.0); +manualData.Add(DateTime.Now.AddMinutes(4), 105.0); + +Console.WriteLine("--- Input Data ---"); +PrintSeries(manualData, 5); + +// Batch Calculation +Console.WriteLine("\n--- Batch EMA (Period 3) ---"); +var emaBatch = new Ema(3); +var resultBatch = emaBatch.Update(manualData); + +PrintSeries(resultBatch, 5); + +#!markdown + +### Streaming Processing +Streaming processing updates the EMA one data point at a time. This is essential for real-time trading systems where data arrives sequentially. + +#!csharp + +Console.WriteLine("\n--- Streaming EMA (Period 3) ---"); +var emaStream = new Ema(3); + +foreach (var item in manualData) +{ + var result = emaStream.Update(item); + Console.WriteLine($"Time: {item.Time:HH:mm:ss}, Input: {item.Value:F2}, EMA: {result.Value:F2}, IsHot: {emaStream.IsHot}"); +} + +// Verify that the last values match +var batchLast = resultBatch.Last().Value; +var streamLast = emaStream.Value.Value; +Console.WriteLine($"\nMatch: {Math.Abs(batchLast - streamLast) < 1e-10} (Batch: {batchLast:F2}, Stream: {streamLast:F2})"); + +#!markdown + +## 2. Streaming with `isNew` (Intra-bar Updates) + +In real-time feeds, you often receive multiple updates for the *same* bar (e.g., price changes within the current minute) before the bar closes. +* `isNew = true`: The input is a new bar (advances time). +* `isNew = false`: The input is an update to the current bar (recalculates without advancing). + +#!csharp + +Console.WriteLine("\n--- Streaming with Intra-bar Updates ---"); +var emaIntra = new Ema(3); + +// 1. Process the first 4 bars normally +for (int i = 0; i < 4; i++) +{ + emaIntra.Update(manualData[i]); +} +Console.WriteLine($"After 4th bar: {emaIntra.Value.Value:F2}"); + +// 2. Simulate intra-bar updates for the 5th bar (Final value is 105.0) +// Update 1: Price moves to 104.0 +var update1 = new TValue(manualData[4].Time, 104.0); +emaIntra.Update(update1, isNew: true); // First update for this bar is "New" +Console.WriteLine($"Update 1 (104.0): {emaIntra.Value.Value:F2}"); + +// Update 2: Price moves to 106.0 (Same time, same bar) +var update2 = new TValue(manualData[4].Time, 106.0); +emaIntra.Update(update2, isNew: false); // Not new, just an update +Console.WriteLine($"Update 2 (106.0): {emaIntra.Value.Value:F2}"); + +// Update 3: Final Close at 105.0 +var update3 = manualData[4]; +emaIntra.Update(update3, isNew: false); // Final update +Console.WriteLine($"Update 3 (105.0): {emaIntra.Value.Value:F2}"); + +// Verify match with batch result +Console.WriteLine($"Match with Batch: {Math.Abs(emaIntra.Value.Value - batchLast) < 1e-10}"); + +#!markdown + +## 3. Large Dataset: Geometric Brownian Motion (GBM) + +We'll generate a larger dataset (1000 bars) using a Geometric Brownian Motion generator to simulate realistic market data. + +#!csharp + +// Generate 1000 bars of data +var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2); +var gbmData = gbm.Fetch(1000, DateTime.Now.Ticks, TimeSpan.FromMinutes(1)); +var closeSeries = gbmData.Close; + +Console.WriteLine($"Generated {closeSeries.Count} bars of GBM data."); +Console.WriteLine($"First 5 values: {string.Join(", ", closeSeries.Take(5).Select(x => x.Value.ToString("F2")))}"); + +#!markdown + +### Batch vs. Streaming Performance on Large Data + +#!csharp + +// Batch +var emaLargeBatch = new Ema(20); +var batchLargeResult = emaLargeBatch.Update(closeSeries); +Console.WriteLine($"Batch Last Value: {batchLargeResult.Last().Value:F2}"); + +// Streaming +var emaLargeStream = new Ema(20); +TValue lastStreamVal = default; +foreach(var item in closeSeries) +{ + lastStreamVal = emaLargeStream.Update(item); +} +Console.WriteLine($"Streaming Last Value: {lastStreamVal.Value:F2}"); + +#!markdown + +## 4. Vectorized EMA (Multiple Periods) + +`EmaVector` allows calculating multiple EMAs (e.g., 9, 12, 26) simultaneously. This is optimized for performance using SIMD where available. + +### Vectorized Batch + +#!csharp + +int[] periods = { 9, 12, 26 }; +Console.WriteLine($"\n--- Vectorized Batch EMA (Periods: {string.Join(", ", periods)}) ---"); + +var emaVectorBatch = new EmaVector(periods); +var vectorBatchResults = emaVectorBatch.Calculate(closeSeries); + +for (int i = 0; i < periods.Length; i++) +{ + Console.WriteLine($"EMA({periods[i]}) Last Value: {vectorBatchResults[i].Last().Value:F2}"); +} + +#!markdown + +### Vectorized Streaming + +#!csharp + +Console.WriteLine($"\n--- Vectorized Streaming EMA (Periods: {string.Join(", ", periods)}) ---"); + +var emaVectorStream = new EmaVector(periods); +TValue[] lastVectorVal = null; + +foreach(var item in closeSeries) +{ + lastVectorVal = emaVectorStream.Update(item); +} + +for (int i = 0; i < periods.Length; i++) +{ + Console.WriteLine($"EMA({periods[i]}) Last Value: {lastVectorVal[i].Value:F2}"); +} + +// Verification +bool allMatch = true; +for (int i = 0; i < periods.Length; i++) +{ + if (Math.Abs(vectorBatchResults[i].Last().Value - lastVectorVal[i].Value) > 1e-10) + { + allMatch = false; + break; + } +} +Console.WriteLine($"\nAll Vectorized Stream/Batch values match: {allMatch}"); diff --git a/lib/trends_IIR/ema/Ema.Tests.cs b/lib/trends_IIR/ema/Ema.Tests.cs new file mode 100644 index 00000000..2cb381cd --- /dev/null +++ b/lib/trends_IIR/ema/Ema.Tests.cs @@ -0,0 +1,228 @@ +using System; +using Xunit; +using QuanTAlib; + +namespace QuanTAlib.Tests; + +public class EmaTests +{ + [Fact] + public void Ema_Constructor_Period_ValidatesInput() + { + Assert.Throws(() => new Ema(0)); + Assert.Throws(() => new Ema(-1)); + + var ema = new Ema(10); + Assert.NotNull(ema); + } + + [Fact] + public void Ema_Constructor_Alpha_ValidatesInput() + { + Assert.Throws(() => new Ema(0.0)); + Assert.Throws(() => new Ema(-0.1)); + Assert.Throws(() => new Ema(1.1)); + + var ema = new Ema(0.5); + Assert.NotNull(ema); + } + + [Fact] + public void Ema_Calc_ReturnsValue() + { + var ema = new Ema(10); + + Assert.Equal(0, ema.Value.Value); + + TValue result = ema.Update(new TValue(DateTime.Now, 100)); + + Assert.True(result.Value > 0); + Assert.Equal(result.Value, ema.Value.Value); + } + + [Fact] + public void Ema_Calc_IsNew_AcceptsParameter() + { + var ema = new Ema(10); + + ema.Update(new TValue(DateTime.Now, 100), isNew: true); + double value1 = ema.Value; + + ema.Update(new TValue(DateTime.Now, 105), isNew: true); + double value2 = ema.Value; + + // Values should change with new bars + Assert.NotEqual(value1, value2); + } + + [Fact] + public void Ema_Calc_IsNew_False_UpdatesValue() + { + var ema = new Ema(10); + + ema.Update(new TValue(DateTime.Now, 100)); + ema.Update(new TValue(DateTime.Now, 110), isNew: true); + double beforeUpdate = ema.Value; + + ema.Update(new TValue(DateTime.Now, 120), isNew: false); + double afterUpdate = ema.Value; + + // Update should change the value + Assert.NotEqual(beforeUpdate, afterUpdate); + } + + [Fact] + public void Ema_Reset_ClearsState() + { + var ema = new Ema(10); + + ema.Update(new TValue(DateTime.Now, 100)); + ema.Update(new TValue(DateTime.Now, 105)); + double valueBefore = ema.Value; + + ema.Reset(); + + Assert.Equal(0, ema.Value.Value); + + // After reset, should accept new values + ema.Update(new TValue(DateTime.Now, 50)); + Assert.NotEqual(0, ema.Value.Value); + Assert.NotEqual(valueBefore, ema.Value.Value); + } + + [Fact] + public void Ema_Properties_Accessible() + { + var ema = new Ema(10); + + Assert.Equal(0, ema.Value.Value); + Assert.False(ema.IsHot); + + ema.Update(new TValue(DateTime.Now, 100)); + + Assert.NotEqual(0, ema.Value.Value); + } + + [Fact] + public void Ema_IsHot_BecomesTrueAfterWarmup() + { + var ema = new Ema(10); + + // Initially IsHot should be false + Assert.False(ema.IsHot); + + // Feed values until it warms up + // Warmup condition is state.E <= 1e-10 + // state.E starts at 1.0 and decays by (1 - alpha) each step + // alpha = 2 / (10 + 1) = 2/11 ~= 0.1818 + // (1 - alpha) ~= 0.8181 + // 1.0 * (0.8181)^n <= 1e-10 + // n * log(0.8181) <= log(1e-10) + // n * -0.200 <= -23.02 + // n >= 115 steps roughly + + int steps = 0; + while (!ema.IsHot && steps < 1000) + { + ema.Update(new TValue(DateTime.Now, 100)); + steps++; + } + + Assert.True(ema.IsHot); + Assert.True(steps > 0); // Should take some steps + } + + [Fact] + public void Ema_PeriodEquivalence_BothConstructorsWork() + { + int period = 20; + double alpha = 2.0 / (period + 1); + + var emaPeriod = new Ema(period); + var emaAlpha = new Ema(alpha); + + // Both should accept Calc calls and produce same result + TValue result1 = emaPeriod.Update(new TValue(DateTime.Now, 100)); + TValue result2 = emaAlpha.Update(new TValue(DateTime.Now, 100)); + + Assert.Equal(result1.Value, result2.Value, 1e-10); + } + + [Fact] + public void Ema_IterativeCorrections_RestoreToOriginalState() + { + var ema = new Ema(10); + 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); + ema.Update(tenthInput, isNew: true); + } + + // Remember EMA state after 10 values + double emaAfterTen = ema.Value; + + // Generate 9 corrections with isNew=false (different values) + for (int i = 0; i < 9; i++) + { + var bar = gbm.Next(isNew: false); + ema.Update(new TValue(bar.Time, bar.Close), isNew: false); + } + + // Feed the remembered 10th input again with isNew=false + TValue finalEma = ema.Update(tenthInput, isNew: false); + + // EMA should match the original state after 10 values + Assert.Equal(emaAfterTen, finalEma.Value, 1e-10); + } + + [Fact] + public void Ema_BatchCalc_MatchesIterativeCalc() + { + var emaIterative = new Ema(10); + var emaBatch = new Ema(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); + } + + // Calculate iteratively + var iterativeResults = new TSeries(); + foreach (var item in series) + { + iterativeResults.Add(emaIterative.Update(item)); + } + + // Calculate batch + var batchResults = emaBatch.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 Ema_Result_ImplicitConversionToDouble() + { + var ema = new Ema(10); + ema.Update(new TValue(DateTime.Now, 100)); + + // This should compile and work because TValue has implicit conversion to double + double result = ema.Value; + + Assert.Equal(100.0, result, 1e-10); + } +} diff --git a/lib/trends_IIR/ema/Ema.Validation.Tests.cs b/lib/trends_IIR/ema/Ema.Validation.Tests.cs new file mode 100644 index 00000000..49b68ef8 --- /dev/null +++ b/lib/trends_IIR/ema/Ema.Validation.Tests.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Skender.Stock.Indicators; +using TALib; +using Tulip; +using Xunit; +using Xunit.Abstractions; +using QuanTAlib; + +namespace QuanTAlib.Tests; + +public class EmaValidationTests : IDisposable +{ + private readonly TBarSeries _bars; + private readonly TSeries _data; + private readonly List _skenderQuotes; + private readonly Random _rnd = new(42); + private readonly ITestOutputHelper _output; + + public EmaValidationTests(ITestOutputHelper output) + { + _output = output; + + // 1. Generate 1000 records using GBM feed + var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2); + _bars = gbm.Fetch(1000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1)); + + // 2. Extract Close TSeries + _data = _bars.Close; + + // 3. Prepare data for Skender (List) + _skenderQuotes = new List(); + for (int i = 0; i < _bars.Count; i++) + { + _skenderQuotes.Add(new Quote + { + Date = new DateTime(_bars.Open.Times[i]), + Open = (decimal)_bars.Open[i].Value, + High = (decimal)_bars.High[i].Value, + Low = (decimal)_bars.Low[i].Value, + Close = (decimal)_bars.Close[i].Value, + Volume = (decimal)_bars.Volume[i].Value + }); + } + } + + public void Dispose() + { + // Cleanup if needed + } + + [Fact] + public void Validate_Skender() + { + int[] periods = { 5, 10, 20, 50, 100 }; + + foreach (var period in periods) + { + // Calculate QuanTAlib EMA + var ema = new global::QuanTAlib.Ema(period); + var qResult = ema.Update(_data); + + // Calculate Skender EMA + var sResult = _skenderQuotes.GetEma(period).ToList(); + + // Compare last 100 records + VerifyData(qResult, sResult, period); + } + _output.WriteLine("EMA validated successfully against Skender"); + } + + [Fact] + public void Validate_Talib() + { + int[] periods = { 5, 10, 20, 50, 100 }; + + // Prepare data for TA-Lib (double[]) + double[] tData = _data.Select(x => x.Value).ToArray(); + double[] output = new double[tData.Length]; + + foreach (var period in periods) + { + // Calculate QuanTAlib EMA + var ema = new global::QuanTAlib.Ema(period); + var qResult = ema.Update(_data); + + // Calculate TA-Lib EMA + var retCode = TALib.Functions.Ema(tData, 0..^0, output, out var outRange, period); + + // Check success + Assert.Equal(Core.RetCode.Success, retCode); + + // TA-Lib skips the lookback period, so output[0] corresponds to input[lookback] + int lookback = TALib.Functions.EmaLookback(period); + + // Compare last 100 records + VerifyData_Talib(qResult, output, outRange, lookback, period); + } + _output.WriteLine("EMA validated successfully against TA-Lib"); + } + + [Fact] + public void Validate_Tulip() + { + int[] periods = { 5, 10, 20, 50, 100 }; + + // Prepare data for Tulip (double[]) + double[] tData = _data.Select(x => x.Value).ToArray(); + + foreach (var period in periods) + { + // Calculate QuanTAlib EMA + var ema = new global::QuanTAlib.Ema(period); + var qResult = ema.Update(_data); + + // Calculate Tulip EMA + var emaIndicator = Tulip.Indicators.ema; + double[][] inputs = { tData }; + double[] options = { (double)period }; + double[][] outputs = { new double[tData.Length] }; + + emaIndicator.Run(inputs, options, outputs); + var tResult = outputs[0]; + + // Compare last 100 records + VerifyData(qResult, tResult.ToList(), period); + } + _output.WriteLine("EMA validated successfully against Tulip"); + } + + private void VerifyData(TSeries qSeries, List tSeries, int period) + { + // Ensure we have enough data + Assert.Equal(qSeries.Count, tSeries.Count); + + int count = qSeries.Count; + int skip = count - 100; // Last 100 records + + for (int i = skip; i < count; i++) + { + double qValue = qSeries[i].Value; + double tValue = tSeries[i]; + if (tValue == 0) continue; + + Assert.Equal(tValue, qValue, 1e-6); + } + } + + private void VerifyData(TSeries qSeries, List sSeries, int period) + { + // Ensure we have enough data + Assert.Equal(qSeries.Count, sSeries.Count); + + int count = qSeries.Count; + int skip = count - 100; // Last 100 records + + for (int i = skip; i < count; i++) + { + double qValue = qSeries[i].Value; + double? sValue = sSeries[i].Ema; + + // Skip if Skender returns null (warmup period) + if (!sValue.HasValue) continue; + + // Assert equality with tolerance + Assert.Equal(sValue.Value, qValue, 1e-6); + } + } + + private void VerifyData_Talib(TSeries qSeries, double[] tOutput, Range outRange, int lookback, int period) + { + int count = qSeries.Count; + int skip = count - 100; // Last 100 records + + // outRange.End.Value is the number of elements written to tOutput + int validCount = outRange.End.Value - outRange.Start.Value; + + for (int i = skip; i < count; i++) + { + double qValue = qSeries[i].Value; + + // Calculate index in tOutput + // If i < lookback, we don't have a value from TA-Lib + if (i < lookback) continue; + + int tIndex = i - lookback; + + // Check if tIndex is within valid range + if (tIndex >= validCount) continue; + + double tValue = tOutput[tIndex]; + + // Assert equality with tolerance + Assert.Equal(tValue, qValue, 1e-6); + } + } +} diff --git a/lib/trends_IIR/ema/Ema.cs b/lib/trends_IIR/ema/Ema.cs new file mode 100644 index 00000000..d9241af7 --- /dev/null +++ b/lib/trends_IIR/ema/Ema.cs @@ -0,0 +1,163 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace QuanTAlib; + +public struct EmaState +{ + public double Ema; + public double E; + public bool IsHot; + + public static EmaState New() => new() { Ema = 0, E = 1.0, IsHot = false }; +} + +/// +/// Exponential Moving Average (EMA) - IIR filter with exponential warmup compensator. +/// Provides valid output from first bar with O(1) complexity. +/// +/// +/// Algorithm uses exponential smoothing with compensator for immediate valid results. +/// Reference: https://github.com/mihakralj/pinescript/blob/main/indicators/trends_IIR/ema.md +/// +public class Ema +{ + private readonly double _alpha; + private EmaState _state = EmaState.New(); + private EmaState _p_state = EmaState.New(); + + /// + /// Creates EMA with specified period. + /// Alpha = 2 / (period + 1) + /// + /// Period for EMA calculation (must be > 0) + public Ema(int period) + { + if (period <= 0) + throw new ArgumentException("Period must be greater than 0", nameof(period)); + + _alpha = 2.0 / (period + 1); + } + + /// + /// Creates EMA with specified alpha smoothing factor. + /// + /// Smoothing factor (0 < alpha <= 1) + public Ema(double alpha) + { + if (alpha <= 0 || alpha > 1) + throw new ArgumentException("Alpha must be between 0 and 1", nameof(alpha)); + + _alpha = alpha; + } + + /// + /// Current EMA value. + /// + public TValue Value { get; private set; } + + /// + /// True if the EMA has warmed up and is providing valid results. + /// + public bool IsHot => _state.IsHot; + + /// + /// Core EMA calculation kernel. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Compute(double input, double alpha, ref EmaState state) + { + state.Ema += alpha * (input - state.Ema); + + if (!state.IsHot) + { + state.E *= (1.0 - alpha); + state.IsHot = state.E <= 1e-10; + return state.Ema / (1.0 - state.E); + } + + return state.Ema; + } + + /// + /// Updates EMA with the given value. + /// + /// Input value + /// True for new bar, false for update to current bar (default: true) + /// Compensated EMA value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TValue Update(TValue input, bool isNew = true) + { + if (isNew) + { + _p_state = _state; + } + else + { + _state = _p_state; + } + + double val = Compute(input.Value, _alpha, ref _state); + Value = new TValue(input.Time, val); + return Value; + } + + /// + /// Updates EMA with the entire series. + /// + /// Input series + /// EMA series + public TSeries Update(TSeries source) + { + int len = source.Count; + var t = new List(len); + var v = new List(len); + CollectionsMarshal.SetCount(t, len); + CollectionsMarshal.SetCount(v, len); + + var tSpan = CollectionsMarshal.AsSpan(t); + var vSpan = CollectionsMarshal.AsSpan(v); + var sourceValues = source.Values; + var sourceTimes = source.Times; + + // Local state for batch processing + EmaState state = _state; + + for (int i = 0; i < len; i++) + { + double val = Compute(sourceValues[i], _alpha, ref state); + tSpan[i] = sourceTimes[i]; + vSpan[i] = val; + } + + // Update instance state to the final state + _state = state; + _p_state = state; // Assume last point is committed + + Value = new TValue(tSpan[len - 1], vSpan[len - 1]); + return new TSeries(t, v); + } + + /// + /// Calculates EMA for the entire series using a new instance. + /// + /// Input series + /// EMA period + /// EMA series + public static TSeries Calculate(TSeries source, int period) + { + var ema = new Ema(period); + return ema.Update(source); + } + + /// + /// Resets the EMA state. + /// + public void Reset() + { + _state = EmaState.New(); + _p_state = _state; + Value = default; + } +} diff --git a/lib/trends_IIR/ema/Ema.md b/lib/trends_IIR/ema/Ema.md new file mode 100644 index 00000000..200faba8 --- /dev/null +++ b/lib/trends_IIR/ema/Ema.md @@ -0,0 +1,136 @@ +# EMA: Exponential Moving Average + +[Pine Script Implementation of EMA](https://github.com/mihakralj/pinescript/blob/main/indicators/trends_IIR/ema.pine) + +## Overview and Purpose + +The Exponential Moving Average (EMA) is a fundamental technical indicator that calculates the average price over a specific period while giving more weight to recent price data. Introduced in the 1950s, EMA has become one of the most widely used technical indicators in financial markets due to its balance of responsiveness and stability. + +Unlike the Simple Moving Average (SMA) which assigns equal weight to all data points, the EMA emphasizes recent price action, allowing traders to identify trend changes earlier while still filtering out short-term market noise. Its mathematical elegance has made it a standard tool in signal processing beyond finance, including communications, control systems, and data analysis. + +## Core Concepts + +* **Weighted price action:** EMA gives greater importance to recent prices through exponential weighting, providing a more timely response to current market conditions +* **Smoothing mechanism:** Acts as a noise filter by reducing the impact of random price fluctuations while preserving meaningful trends +* **Universal application:** Functions effectively across all timeframes from intraday to monthly charts, with parameter adjustments +* **Foundation indicator:** Serves as the mathematical basis for numerous other technical indicators (MACD, PPO, etc.) + +EMA achieves its enhanced responsiveness by applying a smoothing factor (α) that determines how quickly older data points lose influence. This approach creates a moving average that reacts faster to price changes than an SMA of the same length while maintaining enough stability to identify the underlying trend. + +## Common Settings and Parameters + +| Parameter | Default | Function | When to Adjust | +|-----------|---------|----------|---------------| +| Length | 20 | Controls responsiveness/smoothness | Shorter for faster signals in active markets, longer for stable trends in ranging markets | +| Source | Close | Data point used for calculation | Change to HL2 or HLC3 for more balanced price representation | +| Alpha | 2/(length+1) | Determines weighting decay | Direct alpha manipulation allows for precise tuning beyond standard length settings | + +**Pro Tip:** Many professional traders use multiple EMAs simultaneously (e.g., 8, 21, 50) to identify potential support/resistance levels and trend strength based on their relative positioning. + +## Calculation and Mathematical Foundation + +**Simplified explanation:** +EMA works by calculating a weighted average where recent prices have more influence. The implementation uses an optimized form of the EMA calculation that is both computationally efficient and numerically stable. + +**Technical formula:** +The optimized EMA formula used in the implementation is: +$$EMA_t = \alpha \cdot P_t + (1 - \alpha) \cdot EMA_{t-1}$$ + +Where: + +* $\alpha = \frac{2}{N + 1}$ is the smoothing factor ($N$ is the period) +* $P_t$ is the current price value +* $EMA_{t-1}$ is the previous period's EMA value + +This form is algebraically equivalent to the traditional EMA formula but offers better computational efficiency and numerical stability. + +> 🔍 **Technical Note:** The implementation uses a sophisticated warm-up compensation method that provides accurate EMA values from the first bar. The compensation works by tracking an error term that decays exponentially: +> $$e_t = e_{t-1} \cdot (1 - \alpha)$$ +> $$Compensation = \frac{1}{1 - e_t}$$ +> $$EMA_{corrected} = Compensation \cdot EMA_{raw}$$ +> This compensation automatically adjusts during the warm-up phase and becomes negligible ($e \le 1e^{-10}$) once sufficient data has been processed, ensuring mathematically correct values throughout the entire data series without requiring a traditional warm-up period. + +## C# Implementation + +The library provides two implementations: a standard scalar version and a SIMD-optimized vector version for high-performance scenarios. + +### Single EMA (`Ema`) + +The `Ema` class calculates a single exponential moving average. + +```csharp +using QuanTAlib; + +// Initialize with period 10 +var ema = new Ema(10); + +// Or initialize with specific alpha +var emaAlpha = new Ema(0.5); + +// Streaming update +TValue result = ema.Update(new TValue(time, price)); +Console.WriteLine($"Current EMA: {result.Value}"); + +// Access current value property +Console.WriteLine($"Current Value: {ema.Value.Value}"); + +// Batch calculation +TSeries source = ...; +TSeries results = Ema.Calculate(source, 10); +``` + +### Multi-Alpha EMA (`EmaVector`) + +The `EmaVector` class is a SIMD-optimized implementation for calculating multiple EMAs with different periods on the same input series simultaneously. It leverages hardware intrinsics (AVX/SSE) for high performance. + +```csharp +using QuanTAlib; + +// Initialize with multiple periods +int[] periods = { 9, 12, 26 }; +var emaVector = new EmaVector(periods); + +// Streaming update +TValue[] results = emaVector.Update(new TValue(time, price)); + +// Access values +Console.WriteLine($"EMA(9): {results[0].Value}"); +Console.WriteLine($"EMA(12): {results[1].Value}"); +Console.WriteLine($"EMA(26): {results[2].Value}"); + +// Batch calculation +TSeries source = ...; +TSeries[] seriesResults = emaVector.Calculate(source); +``` + +### Performance Characteristics + +* **O(1) Complexity:** The calculation time is constant regardless of the period length. +* **SIMD Optimization:** `EmaVector` processes multiple periods in parallel using vector instructions, significantly reducing CPU cycles for multi-timeframe analysis. +* **Zero Allocation:** The streaming `Update` method is designed to be allocation-free (excluding the return struct). + +## Interpretation Details + +The EMA's primary value comes from its ability to identify trend direction and potential reversal points: + +* When price is above EMA, the short-term trend is generally bullish +* When price is below EMA, the short-term trend is generally bearish +* When a shorter-period EMA crosses above a longer-period EMA, it often signals the beginning of an uptrend +* When a shorter-period EMA crosses below a longer-period EMA, it often signals the beginning of a downtrend +* The slope of the EMA indicates trend strength and momentum + +EMAs work particularly well in trending markets but may generate false signals during sideways or choppy conditions. For optimal results, traders typically use EMA crossovers or EMA-price crossovers as part of a broader system that includes volume and momentum confirmation. + +## Limitations and Considerations + +* **Market conditions:** Less effective in choppy, sideways markets where price constantly crosses the average +* **Lag factor:** While less significant than SMA, EMA still exhibits some lag, especially with longer lookback periods +* **False signals:** Can produce whipsaws during consolidation phases or range-bound conditions +* **Parameter sensitivity:** Small changes in length or alpha can significantly alter behavior +* **Complementary tools:** Should be used with momentum indicators (RSI, MACD) or volume indicators for confirmation + +## References + +1. Murphy, J.J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. +2. Kaufman, P. (2013). *Trading Systems and Methods*, 5th Edition. Wiley Trading. +3. Ehlers, J. (2001). *Rocket Science for Traders*. John Wiley & Sons. diff --git a/lib/trends_IIR/ema/EmaVector.Tests.cs b/lib/trends_IIR/ema/EmaVector.Tests.cs new file mode 100644 index 00000000..9e532544 --- /dev/null +++ b/lib/trends_IIR/ema/EmaVector.Tests.cs @@ -0,0 +1,138 @@ +using System; +using System.Linq; +using Xunit; +using QuanTAlib; + +namespace QuanTAlib.Tests; + +public class EmaVectorTests +{ + [Fact] + public void Initialization_WithPeriods_SetsCorrectAlphas() + { + int[] periods = { 10, 20 }; + var emaVector = new EmaVector(periods); + + // We can't check private fields directly, but we can check results after 1 step + // Alpha = 2 / (P + 1) + // P=10 -> A=2/11 + // P=20 -> A=2/21 + + var res = emaVector.Update(new TValue(DateTime.Now, 100.0)); + + // First value should be 100.0 due to compensation + Assert.Equal(100.0, res[0].Value, 1e-9); + Assert.Equal(100.0, res[1].Value, 1e-9); + } + + [Fact] + public void Calc_Streaming_MatchesSingleEma() + { + int[] periods = { 5, 10, 20 }; + var emaVector = new EmaVector(periods); + var emaSingles = periods.Select(p => new Ema(p)).ToArray(); + + var values = new double[] { 10, 20, 30, 40, 50, 40, 30, 20, 10 }; + var time = DateTime.Now; + + foreach (var val in values) + { + var tVal = new TValue(time, val); + var multiRes = emaVector.Update(tVal); + + for (int i = 0; i < periods.Length; i++) + { + var singleRes = emaSingles[i].Update(tVal); + Assert.Equal(singleRes.Value, multiRes[i].Value, 1e-9); + Assert.Equal(singleRes.Time, multiRes[i].Time); + } + + time = time.AddMinutes(1); + } + } + + [Fact] + public void Calc_Series_MatchesSingleEma() + { + int[] periods = { 5, 10, 20 }; + var emaVector = new EmaVector(periods); + var emaSingles = periods.Select(p => new Ema(p)).ToArray(); + + int len = 100; + var t = new System.Collections.Generic.List(len); + var v = new System.Collections.Generic.List(len); + var now = DateTime.Now; + + for (int i = 0; i < len; i++) + { + t.Add(now.AddMinutes(i).Ticks); + v.Add(Math.Sin(i * 0.1) * 100); + } + + var series = new TSeries(t, v); + + var multiRes = emaVector.Calculate(series); + + for (int i = 0; i < periods.Length; i++) + { + var singleRes = emaSingles[i].Update(series); + + Assert.Equal(singleRes.Count, multiRes[i].Count); + for (int j = 0; j < len; j++) + { + Assert.Equal(singleRes.Values[j], multiRes[i].Values[j], 1e-8); + } + } + } + + [Fact] + public void Calc_Series_MatchesStreaming() + { + int[] periods = { 5, 10, 20 }; + var emaVectorBatch = new EmaVector(periods); + var emaVectorStream = new EmaVector(periods); + + int len = 100; + var t = new System.Collections.Generic.List(len); + var v = new System.Collections.Generic.List(len); + var now = DateTime.Now; + + for (int i = 0; i < len; i++) + { + t.Add(now.AddMinutes(i).Ticks); + v.Add(Math.Sin(i * 0.1) * 100); + } + + var series = new TSeries(t, v); + + // Batch calculation + var batchRes = emaVectorBatch.Calculate(series); + + // Streaming calculation + for (int i = 0; i < len; i++) + { + var tVal = new TValue(new DateTime(t[i]), v[i]); + var streamRes = emaVectorStream.Update(tVal); + + for (int j = 0; j < periods.Length; j++) + { + Assert.Equal(batchRes[j].Values[i], streamRes[j].Value, 1e-9); + } + } + } + + [Fact] + public void Reset_ClearsState() + { + int[] periods = { 10 }; + var emaVector = new EmaVector(periods); + + emaVector.Update(new TValue(DateTime.Now, 100.0)); + emaVector.Reset(); + + // After reset, next calculation should treat it as first value (warmup) + var res = emaVector.Update(new TValue(DateTime.Now, 200.0)); + + Assert.Equal(200.0, res[0].Value, 1e-9); + } +} diff --git a/lib/trends_IIR/ema/EmaVector.cs b/lib/trends_IIR/ema/EmaVector.cs new file mode 100644 index 00000000..359057d6 --- /dev/null +++ b/lib/trends_IIR/ema/EmaVector.cs @@ -0,0 +1,271 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace QuanTAlib; + +/// +/// Multi-Alpha Exponential Moving Average (EMA) - SIMD optimized. +/// Calculates multiple EMAs with different periods/alphas for the same input series in parallel. +/// +public class EmaVector +{ + private readonly double[] _alphas; + private readonly double[] _emas; + private readonly double[] _Es; + private readonly int _count; + + /// + /// Current EMA values for all periods. + /// + public TValue[] Values { get; private set; } + + /// + /// Initializes EmaVector with specified periods. + /// + /// Array of periods + public EmaVector(int[] periods) + { + _count = periods.Length; + _alphas = new double[_count]; + _emas = new double[_count]; + _Es = new double[_count]; + Values = new TValue[_count]; + + for (int i = 0; i < _count; i++) + { + if (periods[i] <= 0) throw new ArgumentException("Period must be greater than 0", nameof(periods)); + _alphas[i] = 2.0 / (periods[i] + 1); + ResetAt(i); + } + } + + /// + /// Initializes EmaVector with specified alphas. + /// + /// Array of alphas + public EmaVector(double[] alphas) + { + _count = alphas.Length; + _alphas = new double[_count]; + _emas = new double[_count]; + _Es = new double[_count]; + Values = new TValue[_count]; + + for (int i = 0; i < _count; i++) + { + if (alphas[i] <= 0 || alphas[i] > 1) throw new ArgumentException("Alpha must be between 0 and 1", nameof(alphas)); + _alphas[i] = alphas[i]; + ResetAt(i); + } + } + + private void ResetAt(int index) + { + _emas[index] = 0.0; + _Es[index] = 1.0; + } + + /// + /// Resets all EMA states. + /// + public void Reset() + { + for (int i = 0; i < _count; i++) + { + ResetAt(i); + } + Array.Clear(Values); + } + + /// + /// Updates EMAs with the given value. + /// + /// Input value + /// Array of compensated EMA values + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TValue[] Update(TValue input) + { + double val = input.Value; + + // SIMD Loop + int vecCount = Vector.Count; + int i = 0; + + if (Vector.IsHardwareAccelerated && _count >= vecCount) + { + var vecInput = new Vector(val); + var vecOne = Vector.One; + var vecEpsilon = new Vector(1e-10); + + for (; i <= _count - vecCount; i += vecCount) + { + // Load state + var vecAlpha = new Vector(_alphas, i); + var vecEma = new Vector(_emas, i); + var vecE = new Vector(_Es, i); + + // Update EMA + // ema += alpha * (input - ema) + vecEma += vecAlpha * (vecInput - vecEma); + + // Update E (warmup factor) + // E *= (1 - alpha) + vecE *= (vecOne - vecAlpha); + + // Calculate compensated result + // res = ema / (1 - E) + var vecCompensated = vecEma / (vecOne - vecE); + + // Check warmup condition: E > 1e-10 + var warmupMask = Vector.GreaterThan(vecE, vecEpsilon); + + // Select result + // Vector.ConditionalSelect requires Vector mask. + // Vector.GreaterThan returns Vector for double. + // We cast Vector to Vector to use as mask. + var vecResult = Vector.ConditionalSelect(Vector.AsVectorDouble(warmupMask), vecCompensated, vecEma); + + // Store state + vecEma.CopyTo(_emas, i); + vecE.CopyTo(_Es, i); + + // Store result + for (int j = 0; j < vecCount; j++) + { + Values[i + j] = new TValue(input.Time, vecResult[j]); + } + } + } + + // Scalar fallback for remaining items + for (; i < _count; i++) + { + double alpha = _alphas[i]; + _emas[i] += alpha * (val - _emas[i]); + + double result = _emas[i]; + if (_Es[i] > 1e-10) + { + _Es[i] *= (1.0 - alpha); + if (_Es[i] > 1e-10) + { + result = _emas[i] / (1.0 - _Es[i]); + } + } + + Values[i] = new TValue(input.Time, result); + } + + return Values; + } + + /// + /// Calculates EMAs for the entire series. + /// + /// Input series + /// Array of EMA series + public TSeries[] Calculate(TSeries source) + { + int len = source.Count; + var resultSeries = new TSeries[_count]; + + // Pre-allocate lists + var tLists = new List[_count]; + var vLists = new List[_count]; + + for (int i = 0; i < _count; i++) + { + tLists[i] = new List(len); + vLists[i] = new List(len); + CollectionsMarshal.SetCount(tLists[i], len); + CollectionsMarshal.SetCount(vLists[i], len); + } + + var sourceValues = source.Values; + var sourceTimes = source.Times; + + int vecCount = Vector.Count; + var vecOne = Vector.One; + var vecEpsilon = new Vector(1e-10); + + for (int t = 0; t < len; t++) + { + double val = sourceValues[t]; + long time = sourceTimes[t]; + var vecInput = new Vector(val); + + int i = 0; + if (Vector.IsHardwareAccelerated && _count >= vecCount) + { + for (; i <= _count - vecCount; i += vecCount) + { + var vecAlpha = new Vector(_alphas, i); + var vecEma = new Vector(_emas, i); + var vecE = new Vector(_Es, i); + + vecEma += vecAlpha * (vecInput - vecEma); + vecE *= (vecOne - vecAlpha); + + var vecCompensated = vecEma / (vecOne - vecE); + var warmupMask = Vector.GreaterThan(vecE, vecEpsilon); + var vecResult = Vector.ConditionalSelect(Vector.AsVectorDouble(warmupMask), vecCompensated, vecEma); + + vecEma.CopyTo(_emas, i); + vecE.CopyTo(_Es, i); + + // Scatter results to lists + for (int j = 0; j < vecCount; j++) + { + CollectionsMarshal.AsSpan(tLists[i + j])[t] = time; + CollectionsMarshal.AsSpan(vLists[i + j])[t] = vecResult[j]; + } + } + } + + for (; i < _count; i++) + { + double alpha = _alphas[i]; + _emas[i] += alpha * (val - _emas[i]); + + double result = _emas[i]; + if (_Es[i] > 1e-10) + { + _Es[i] *= (1.0 - alpha); + if (_Es[i] > 1e-10) + { + result = _emas[i] / (1.0 - _Es[i]); + } + } + + CollectionsMarshal.AsSpan(tLists[i])[t] = time; + CollectionsMarshal.AsSpan(vLists[i])[t] = result; + } + } + + // Create TSeries and update Values + for (int i = 0; i < _count; i++) + { + resultSeries[i] = new TSeries(tLists[i], vLists[i]); + var lastT = CollectionsMarshal.AsSpan(tLists[i])[len - 1]; + var lastV = CollectionsMarshal.AsSpan(vLists[i])[len - 1]; + Values[i] = new TValue(lastT, lastV); + } + + return resultSeries; + } + + /// + /// Calculates EMAs for the entire series using specified periods. + /// + /// Input series + /// Array of periods + /// Array of EMA series + public static TSeries[] Calculate(TSeries source, int[] periods) + { + var emaVector = new EmaVector(periods); + return emaVector.Calculate(source); + } +} diff --git a/tests/QuanTAlib.Tests/QuanTAlib.Tests.csproj b/tests/QuanTAlib.Tests/QuanTAlib.Tests.csproj index bec47c17..738f6fee 100644 --- a/tests/QuanTAlib.Tests/QuanTAlib.Tests.csproj +++ b/tests/QuanTAlib.Tests/QuanTAlib.Tests.csproj @@ -14,6 +14,9 @@ + + + @@ -28,8 +31,13 @@ - + + + + + PreserveNewest + daily_IBM.csv