Add TBar, TBarSeries, TSeries, TValue, and IFeed implementations with comprehensive documentation and examples

- Introduced TBar struct for efficient OHLCV data representation.
- Implemented TBarSeries class for high-performance collection of TBar instances using Structure of Arrays (SoA) layout.
- Added TSeries class for time-series data management with zero-copy access.
- Created TValue struct for time-value pairs with implicit conversions.
- Defined IFeed interface for consistent data feed implementations.
- Developed CsvFeed class for loading historical OHLCV data from CSV files.
- Implemented GBM class for generating synthetic financial data using Geometric Brownian Motion.
- Added Quantower project files for Averages indicator with necessary dependencies and configurations.
- Included extensive usage examples and notebooks for TBar, TBarSeries, TSeries, TValue, and feed implementations.
This commit is contained in:
Miha Kralj
2025-11-27 19:51:43 -08:00
parent 1c8f514756
commit 74b49d2bb4
37 changed files with 1379 additions and 462 deletions
+218
View File
@@ -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}");
+58
View File
@@ -0,0 +1,58 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
public class EmaIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 1, 1000, 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 Ema? ma;
protected LineSeries? Series;
protected string? SourceName;
public int MinHistoryDepths => Period;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"EMA {Period}:{SourceName}";
public EmaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
SourceName = Source.ToString();
Name = "EMA - Exponential Moving Average";
Description = "Exponential Moving Average";
Series = new(name: $"EMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(Series);
}
protected override void OnInit()
{
ma = new Ema(Period);
SourceName = Source.ToString();
base.OnInit();
}
protected override void OnUpdate(UpdateArgs args)
{
TValue input = this.GetInputValue(args, Source);
bool isNew = args.Reason == UpdateReason.NewBar || args.Reason == UpdateReason.HistoricalBar;
TValue result = ma!.Update(input, isNew);
Series!.SetValue(result.Value);
Series!.SetMarker(0, Color.Transparent); //OnPaintChart draws the line, hidden here
}
public override void OnPaintChart(PaintChartEventArgs args)
{
base.OnPaintChart(args);
this.PaintSmoothCurve(args, Series!, 0, showColdValues: ShowColdValues, tension: 0.2);
}
}
+228
View File
@@ -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<ArgumentException>(() => new Ema(0));
Assert.Throws<ArgumentException>(() => new Ema(-1));
var ema = new Ema(10);
Assert.NotNull(ema);
}
[Fact]
public void Ema_Constructor_Alpha_ValidatesInput()
{
Assert.Throws<ArgumentException>(() => new Ema(0.0));
Assert.Throws<ArgumentException>(() => new Ema(-0.1));
Assert.Throws<ArgumentException>(() => 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);
}
}
+198
View File
@@ -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<Quote> _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<Quote>)
_skenderQuotes = new List<Quote>();
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<double> 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<EmaResult> 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);
}
}
}
+163
View File
@@ -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 };
}
/// <summary>
/// Exponential Moving Average (EMA) - IIR filter with exponential warmup compensator.
/// Provides valid output from first bar with O(1) complexity.
/// </summary>
/// <remarks>
/// Algorithm uses exponential smoothing with compensator for immediate valid results.
/// Reference: https://github.com/mihakralj/pinescript/blob/main/indicators/trends_IIR/ema.md
/// </remarks>
public class Ema
{
private readonly double _alpha;
private EmaState _state = EmaState.New();
private EmaState _p_state = EmaState.New();
/// <summary>
/// Creates EMA with specified period.
/// Alpha = 2 / (period + 1)
/// </summary>
/// <param name="period">Period for EMA calculation (must be > 0)</param>
public Ema(int period)
{
if (period <= 0)
throw new ArgumentException("Period must be greater than 0", nameof(period));
_alpha = 2.0 / (period + 1);
}
/// <summary>
/// Creates EMA with specified alpha smoothing factor.
/// </summary>
/// <param name="alpha">Smoothing factor (0 < alpha <= 1)</param>
public Ema(double alpha)
{
if (alpha <= 0 || alpha > 1)
throw new ArgumentException("Alpha must be between 0 and 1", nameof(alpha));
_alpha = alpha;
}
/// <summary>
/// Current EMA value.
/// </summary>
public TValue Value { get; private set; }
/// <summary>
/// True if the EMA has warmed up and is providing valid results.
/// </summary>
public bool IsHot => _state.IsHot;
/// <summary>
/// Core EMA calculation kernel.
/// </summary>
[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;
}
/// <summary>
/// Updates EMA with the given value.
/// </summary>
/// <param name="input">Input value</param>
/// <param name="isNew">True for new bar, false for update to current bar (default: true)</param>
/// <returns>Compensated EMA value</returns>
[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;
}
/// <summary>
/// Updates EMA with the entire series.
/// </summary>
/// <param name="source">Input series</param>
/// <returns>EMA series</returns>
public TSeries Update(TSeries source)
{
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);
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);
}
/// <summary>
/// Calculates EMA for the entire series using a new instance.
/// </summary>
/// <param name="source">Input series</param>
/// <param name="period">EMA period</param>
/// <returns>EMA series</returns>
public static TSeries Calculate(TSeries source, int period)
{
var ema = new Ema(period);
return ema.Update(source);
}
/// <summary>
/// Resets the EMA state.
/// </summary>
public void Reset()
{
_state = EmaState.New();
_p_state = _state;
Value = default;
}
}
+136
View File
@@ -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.
+138
View File
@@ -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<long>(len);
var v = new System.Collections.Generic.List<double>(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<long>(len);
var v = new System.Collections.Generic.List<double>(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);
}
}
+271
View File
@@ -0,0 +1,271 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// Multi-Alpha Exponential Moving Average (EMA) - SIMD optimized.
/// Calculates multiple EMAs with different periods/alphas for the same input series in parallel.
/// </summary>
public class EmaVector
{
private readonly double[] _alphas;
private readonly double[] _emas;
private readonly double[] _Es;
private readonly int _count;
/// <summary>
/// Current EMA values for all periods.
/// </summary>
public TValue[] Values { get; private set; }
/// <summary>
/// Initializes EmaVector with specified periods.
/// </summary>
/// <param name="periods">Array of periods</param>
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);
}
}
/// <summary>
/// Initializes EmaVector with specified alphas.
/// </summary>
/// <param name="alphas">Array of alphas</param>
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;
}
/// <summary>
/// Resets all EMA states.
/// </summary>
public void Reset()
{
for (int i = 0; i < _count; i++)
{
ResetAt(i);
}
Array.Clear(Values);
}
/// <summary>
/// Updates EMAs with the given value.
/// </summary>
/// <param name="input">Input value</param>
/// <returns>Array of compensated EMA values</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue[] Update(TValue input)
{
double val = input.Value;
// SIMD Loop
int vecCount = Vector<double>.Count;
int i = 0;
if (Vector.IsHardwareAccelerated && _count >= vecCount)
{
var vecInput = new Vector<double>(val);
var vecOne = Vector<double>.One;
var vecEpsilon = new Vector<double>(1e-10);
for (; i <= _count - vecCount; i += vecCount)
{
// Load state
var vecAlpha = new Vector<double>(_alphas, i);
var vecEma = new Vector<double>(_emas, i);
var vecE = new Vector<double>(_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<T> mask.
// Vector.GreaterThan returns Vector<long> for double.
// We cast Vector<long> to Vector<double> 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;
}
/// <summary>
/// Calculates EMAs for the entire series.
/// </summary>
/// <param name="source">Input series</param>
/// <returns>Array of EMA series</returns>
public TSeries[] Calculate(TSeries source)
{
int len = source.Count;
var resultSeries = new TSeries[_count];
// Pre-allocate lists
var tLists = new List<long>[_count];
var vLists = new List<double>[_count];
for (int i = 0; i < _count; i++)
{
tLists[i] = new List<long>(len);
vLists[i] = new List<double>(len);
CollectionsMarshal.SetCount(tLists[i], len);
CollectionsMarshal.SetCount(vLists[i], len);
}
var sourceValues = source.Values;
var sourceTimes = source.Times;
int vecCount = Vector<double>.Count;
var vecOne = Vector<double>.One;
var vecEpsilon = new Vector<double>(1e-10);
for (int t = 0; t < len; t++)
{
double val = sourceValues[t];
long time = sourceTimes[t];
var vecInput = new Vector<double>(val);
int i = 0;
if (Vector.IsHardwareAccelerated && _count >= vecCount)
{
for (; i <= _count - vecCount; i += vecCount)
{
var vecAlpha = new Vector<double>(_alphas, i);
var vecEma = new Vector<double>(_emas, i);
var vecE = new Vector<double>(_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;
}
/// <summary>
/// Calculates EMAs for the entire series using specified periods.
/// </summary>
/// <param name="source">Input series</param>
/// <param name="periods">Array of periods</param>
/// <returns>Array of EMA series</returns>
public static TSeries[] Calculate(TSeries source, int[] periods)
{
var emaVector = new EmaVector(periods);
return emaVector.Calculate(source);
}
}