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:
Miha Kralj
2026-01-18 19:02:03 -08:00
committed by GitHub
co-authored by Claude Opus 4.5 aider Warp
parent 5bcdf8d614
commit 86fe32a682
1750 changed files with 198235 additions and 80539 deletions
+125
View File
@@ -0,0 +1,125 @@
using TradingPlatform.BusinessLayer;
using QuanTAlib;
namespace QuanTAlib.Tests;
public class AdoscIndicatorTests
{
[Fact]
public void AdoscIndicator_Constructor_SetsDefaults()
{
var indicator = new AdoscIndicator();
Assert.Equal(3, indicator.FastPeriod);
Assert.Equal(10, indicator.SlowPeriod);
Assert.True(indicator.ShowColdValues);
Assert.Equal("ADOSC - Accumulation/Distribution Oscillator", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void AdoscIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new AdoscIndicator
{
SlowPeriod = 20,
};
Assert.Equal(0, AdoscIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void AdoscIndicator_SlowPeriod_CanBeChanged()
{
var indicator = new AdoscIndicator
{
SlowPeriod = 40,
};
Assert.Equal(40, indicator.SlowPeriod);
Assert.Equal(0, AdoscIndicator.MinHistoryDepths);
}
[Fact]
public void AdoscIndicator_SourceCodeLink_IsValid()
{
var indicator = new AdoscIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Adosc.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void AdoscIndicator_Initialize_CreatesInternalAdosc()
{
var indicator = new AdoscIndicator { FastPeriod = 5, SlowPeriod = 34 };
// Initialize should not throw
indicator.Initialize();
// After init, line series should exist
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void AdoscIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new AdoscIndicator { FastPeriod = 2, SlowPeriod = 5 };
indicator.Initialize();
// Add historical data
var now = DateTime.UtcNow;
// Need enough bars for Period
for (int i = 0; i < 20; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i, 1000 + i);
// Process update for each bar to simulate history loading
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
// Line series should have a value
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
}
[Fact]
public void AdoscIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new AdoscIndicator { FastPeriod = 2, SlowPeriod = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 20; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i, 1000 + i);
}
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
// Add new bar
indicator.HistoricalData.AddBar(now.AddMinutes(20), 120, 130, 110, 125, 1200);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void AdoscIndicator_Parameters_CanBeChanged()
{
var indicator = new AdoscIndicator { FastPeriod = 5, SlowPeriod = 34 };
Assert.Equal(5, indicator.FastPeriod);
Assert.Equal(34, indicator.SlowPeriod);
indicator.FastPeriod = 10;
indicator.SlowPeriod = 40;
Assert.Equal(10, indicator.FastPeriod);
Assert.Equal(40, indicator.SlowPeriod);
Assert.Equal(0, AdoscIndicator.MinHistoryDepths);
}
}
+54
View File
@@ -0,0 +1,54 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class AdoscIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Fast Period", sortIndex: 1, 1, 1000, 1, 0)]
public int FastPeriod { get; set; } = 3;
[InputParameter("Slow Period", sortIndex: 2, 1, 1000, 1, 0)]
public int SlowPeriod { get; set; } = 10;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Adosc _adosc = null!;
private readonly LineSeries _series;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"ADOSC {FastPeriod}:{SlowPeriod}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/volume/adosc/Adosc.Quantower.cs";
public AdoscIndicator()
{
OnBackGround = true;
SeparateWindow = true;
Name = "ADOSC - Accumulation/Distribution Oscillator";
Description = "Momentum indicator for the Accumulation/Distribution Line";
_series = new LineSeries(name: "ADOSC", color: Color.Orange, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_adosc = new Adosc(FastPeriod, SlowPeriod);
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
TBar bar = this.GetInputBar(args);
TValue result = _adosc.Update(bar, args.IsNewBar());
_series.SetValue(result.Value, _adosc.IsHot, ShowColdValues);
}
}
+220
View File
@@ -0,0 +1,220 @@
namespace QuanTAlib;
public class AdoscTests
{
private readonly GBM _gbm;
private readonly TBarSeries _bars;
public AdoscTests()
{
_gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
_bars = _gbm.Fetch(1000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
}
[Fact]
public void Constructor_ValidatesInput()
{
Assert.Throws<ArgumentException>(() => new Adosc(fastPeriod: 0));
Assert.Throws<ArgumentException>(() => new Adosc(slowPeriod: 0));
Assert.Throws<ArgumentException>(() => new Adosc(fastPeriod: 10, slowPeriod: 5));
}
[Fact]
public void Calc_ReturnsValue()
{
var adosc = new Adosc(3, 10);
var result = adosc.Update(_bars[0]);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Properties_Accessible()
{
var adosc = new Adosc(3, 10);
Assert.Equal("Adosc(3,10)", adosc.Name);
Assert.False(adosc.IsHot);
Assert.Equal(10, adosc.WarmupPeriod);
}
[Fact]
public void Calc_IsNew_AcceptsParameter()
{
var adosc = new Adosc(3, 10);
adosc.Update(_bars[0], isNew: true);
adosc.Update(_bars[1], isNew: true);
Assert.NotEqual(adosc.Last.Time, _bars[0].Time);
}
[Fact]
public void Calc_IsNew_False_UpdatesValue()
{
var adosc = new Adosc(3, 10);
adosc.Update(_bars[0], isNew: true);
var firstResult = adosc.Last.Value;
var modifiedBar = new TBar(_bars[0].Time, _bars[0].Open, _bars[0].High, _bars[0].Low, _bars[0].Close * 1.1, _bars[0].Volume);
adosc.Update(modifiedBar, isNew: false);
Assert.NotEqual(firstResult, adosc.Last.Value);
}
[Fact]
public void Reset_ClearsState()
{
var adosc = new Adosc(3, 10);
adosc.Update(_bars[0]);
adosc.Reset();
Assert.False(adosc.IsHot);
Assert.Equal(0, adosc.Last.Value);
}
[Fact]
public void IsHot_BecomesTrueWhenBufferFull()
{
var adosc = new Adosc(3, 10);
for (int i = 0; i < 20; i++)
{
adosc.Update(_bars[i]);
}
Assert.True(adosc.IsHot);
}
[Fact]
public void AllModes_ProduceSameResult()
{
var adosc = new Adosc(3, 10);
var batchResult = Adosc.Batch(_bars, 3, 10);
var streamResult = new List<double>();
foreach (var bar in _bars)
{
streamResult.Add(adosc.Update(bar).Value);
}
var spanOutput = new double[_bars.Count];
Adosc.Calculate(_bars.High.Values, _bars.Low.Values, _bars.Close.Values, _bars.Volume.Values, spanOutput, 3, 10);
for (int i = 0; i < _bars.Count; i++)
{
Assert.Equal(batchResult[i].Value, streamResult[i], 1e-9);
Assert.Equal(batchResult[i].Value, spanOutput[i], 1e-6);
}
}
[Fact]
public void NaN_Input_UsesLastValidValue()
{
var adosc = new Adosc(3, 10);
// Feed some valid data
for (int i = 0; i < 15; i++)
{
adosc.Update(_bars[i]);
}
// Create a bar with NaN close
var nanBar = new TBar(_bars[15].Time, _bars[15].Open, _bars[15].High, _bars[15].Low, double.NaN, _bars[15].Volume);
var result = adosc.Update(nanBar);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Infinity_Input_UsesLastValidValue()
{
var adosc = new Adosc(3, 10);
// Feed some valid data
for (int i = 0; i < 15; i++)
{
adosc.Update(_bars[i]);
}
// Create a bar with Infinity close
var infBar = new TBar(_bars[15].Time, _bars[15].Open, _bars[15].High, _bars[15].Low, double.PositiveInfinity, _bars[15].Volume);
var result = adosc.Update(infBar);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void IterativeCorrections_RestoreToOriginalState()
{
var adosc = new Adosc(3, 10);
// Feed 20 bars
TBar bar20 = default;
for (int i = 0; i < 20; i++)
{
bar20 = _bars[i];
adosc.Update(bar20, isNew: true);
}
// Remember state after 20 bars
double stateAfter20 = adosc.Last.Value;
// Apply 5 corrections with different values
for (int i = 0; i < 5; i++)
{
var correctedBar = new TBar(bar20.Time, bar20.Open * (1 + i * 0.01), bar20.High * (1 + i * 0.01),
bar20.Low * (1 + i * 0.01), bar20.Close * (1 + i * 0.01), bar20.Volume);
adosc.Update(correctedBar, isNew: false);
}
// Restore original bar
adosc.Update(bar20, isNew: false);
Assert.Equal(stateAfter20, adosc.Last.Value, 1e-10);
}
[Fact]
public void SpanBatch_CalculatesValidOutput()
{
double[] high = [100, 101, 102, 103, 104];
double[] low = [98, 99, 100, 101, 102];
double[] close = [99, 100, 101, 102, 103];
double[] volume = [1000, 1100, 1200, 1300, 1400];
double[] output = new double[5];
Adosc.Calculate(high, low, close, volume, output, 3, 5);
// Verify output is finite
for (int i = 0; i < output.Length; i++)
{
Assert.True(double.IsFinite(output[i]), $"Output at index {i} should be finite");
}
}
[Fact]
public void SpanBatch_MatchesTSeriesBatch()
{
var batchResult = Adosc.Batch(_bars, 3, 10);
var spanOutput = new double[_bars.Count];
Adosc.Calculate(_bars.High.Values, _bars.Low.Values, _bars.Close.Values, _bars.Volume.Values, spanOutput, 3, 10);
for (int i = 0; i < _bars.Count; i++)
{
Assert.Equal(batchResult[i].Value, spanOutput[i], 1e-6);
}
}
[Fact]
public void BatchCalc_MatchesIterativeCalc()
{
var iterativeAdosc = new Adosc(3, 10);
var iterativeResults = new List<double>();
foreach (var bar in _bars)
{
iterativeResults.Add(iterativeAdosc.Update(bar).Value);
}
var batchResult = Adosc.Batch(_bars, 3, 10);
for (int i = 0; i < _bars.Count; i++)
{
Assert.Equal(iterativeResults[i], batchResult[i].Value, 1e-10);
}
}
}
+187
View File
@@ -0,0 +1,187 @@
using QuanTAlib.Tests;
using Skender.Stock.Indicators;
using OoplesFinance.StockIndicators;
using OoplesFinance.StockIndicators.Models;
using OoplesFinance.StockIndicators.Enums;
namespace QuanTAlib;
public sealed class AdoscValidationTests : IDisposable
{
private readonly ValidationTestData _testData;
private bool _disposed;
public AdoscValidationTests()
{
_testData = new ValidationTestData(); // Default 5000 bars
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
_testData?.Dispose();
}
}
[Fact]
public void Validate_Against_TALib_Adosc()
{
const int fastPeriod = 3;
int slowPeriod = 10;
double[] high = _testData.Bars.High.Values.ToArray();
double[] low = _testData.Bars.Low.Values.ToArray();
double[] close = _testData.Bars.Close.Values.ToArray();
double[] volume = _testData.Bars.Volume.Values.ToArray();
double[] output = new double[close.Length];
var retCode = TALib.Functions.AdOsc(high, low, close, volume, 0..^0, output, out var outRange, fastPeriod, slowPeriod);
Assert.Equal(TALib.Core.RetCode.Success, retCode);
// 1. Batch Mode
var adosc = new Adosc(fastPeriod, slowPeriod);
var result = adosc.Update(_testData.Bars);
ValidationHelper.VerifyData(result, output, outRange, lookback: slowPeriod - 1, tolerance: ValidationHelper.TalibTolerance);
// 2. Streaming Mode
var adoscStream = new Adosc(fastPeriod, slowPeriod);
var streamResults = new List<double>();
foreach (var bar in _testData.Bars)
{
streamResults.Add(adoscStream.Update(bar).Value);
}
ValidationHelper.VerifyData(streamResults, output, outRange, lookback: slowPeriod - 1, tolerance: ValidationHelper.TalibTolerance);
// 3. Span Mode
double[] spanOutput = new double[close.Length];
Adosc.Calculate(high, low, close, volume, spanOutput, fastPeriod, slowPeriod);
ValidationHelper.VerifyData(spanOutput, output, outRange, lookback: slowPeriod - 1, tolerance: ValidationHelper.TalibTolerance);
}
[Fact]
public void Validate_Against_Tulip_Adosc()
{
int fastPeriod = 3;
int slowPeriod = 10;
double[] high = _testData.Bars.High.Values.ToArray();
double[] low = _testData.Bars.Low.Values.ToArray();
double[] close = _testData.Bars.Close.Values.ToArray();
double[] volume = _testData.Bars.Volume.Values.ToArray();
var adoscIndicator = Tulip.Indicators.adosc;
double[][] inputs = { high, low, close, volume };
double[] options = { fastPeriod, slowPeriod };
int start = adoscIndicator.Start(options);
double[][] outputs = { new double[close.Length - start] };
adoscIndicator.Run(inputs, options, outputs);
double[] output = outputs[0];
// 1. Batch Mode
var adosc = new Adosc(fastPeriod, slowPeriod);
var result = adosc.Update(_testData.Bars);
ValidationHelper.VerifyData(result, output, lookback: start, tolerance: ValidationHelper.TulipTolerance);
// 2. Streaming Mode
var adoscStream = new Adosc(fastPeriod, slowPeriod);
var streamResults = new List<double>();
foreach (var bar in _testData.Bars)
{
streamResults.Add(adoscStream.Update(bar).Value);
}
ValidationHelper.VerifyData(streamResults, output, lookback: start, tolerance: ValidationHelper.TulipTolerance);
// 3. Span Mode
double[] spanOutput = new double[close.Length];
Adosc.Calculate(high, low, close, volume, spanOutput, fastPeriod, slowPeriod);
ValidationHelper.VerifyData(spanOutput, output, lookback: start, tolerance: ValidationHelper.TulipTolerance);
}
[Fact]
public void Validate_Against_Skender_ChaikinOsc()
{
int fastPeriod = 3;
int slowPeriod = 10;
var skenderResults = _testData.SkenderQuotes.GetChaikinOsc(fastPeriod, slowPeriod).ToList();
// 1. Batch Mode
var adosc = new Adosc(fastPeriod, slowPeriod);
var result = adosc.Update(_testData.Bars);
ValidationHelper.VerifyData<ChaikinOscResult>(result, skenderResults, (x) => x.Oscillator, tolerance: ValidationHelper.SkenderTolerance);
// 2. Streaming Mode
var adoscStream = new Adosc(fastPeriod, slowPeriod);
var streamResults = new List<double>();
foreach (var bar in _testData.Bars)
{
streamResults.Add(adoscStream.Update(bar).Value);
}
ValidationHelper.VerifyData<ChaikinOscResult>(streamResults, skenderResults, (x) => x.Oscillator, tolerance: ValidationHelper.SkenderTolerance);
// 3. Span Mode
double[] high = _testData.Bars.High.Values.ToArray();
double[] low = _testData.Bars.Low.Values.ToArray();
double[] close = _testData.Bars.Close.Values.ToArray();
double[] volume = _testData.Bars.Volume.Values.ToArray();
double[] spanOutput = new double[close.Length];
Adosc.Calculate(high, low, close, volume, spanOutput, fastPeriod, slowPeriod);
ValidationHelper.VerifyData<ChaikinOscResult>(spanOutput, skenderResults, (x) => x.Oscillator, tolerance: ValidationHelper.SkenderTolerance);
}
[Fact]
public void Validate_Against_Ooples_ChaikinOscillator()
{
int fastPeriod = 3;
int slowPeriod = 10;
var ooplesData = _testData.SkenderQuotes.Select(q => new TickerData
{
Date = q.Date,
Open = (double)q.Open,
High = (double)q.High,
Low = (double)q.Low,
Close = (double)q.Close,
Volume = (double)q.Volume
}).ToList();
var stockData = new StockData(ooplesData);
var results = stockData.CalculateChaikinOscillator(MovingAvgType.ExponentialMovingAverage, fastPeriod, slowPeriod);
var output = results.OutputValues["ChaikinOsc"].ToArray();
// 1. Batch Mode
var adosc = new Adosc(fastPeriod, slowPeriod);
var result = adosc.Update(_testData.Bars);
ValidationHelper.VerifyData(result, output, lookback: 0, tolerance: ValidationHelper.OoplesTolerance);
// 2. Streaming Mode
var adoscStream = new Adosc(fastPeriod, slowPeriod);
var streamResults = new List<double>();
foreach (var bar in _testData.Bars)
{
streamResults.Add(adoscStream.Update(bar).Value);
}
ValidationHelper.VerifyData(streamResults, output, lookback: 0, tolerance: ValidationHelper.OoplesTolerance);
// 3. Span Mode
double[] high = _testData.Bars.High.Values.ToArray();
double[] low = _testData.Bars.Low.Values.ToArray();
double[] close = _testData.Bars.Close.Values.ToArray();
double[] volume = _testData.Bars.Volume.Values.ToArray();
double[] spanOutput = new double[close.Length];
Adosc.Calculate(high, low, close, volume, spanOutput, fastPeriod, slowPeriod);
ValidationHelper.VerifyData(spanOutput, output, lookback: 0, tolerance: ValidationHelper.OoplesTolerance);
}
}
+271
View File
@@ -0,0 +1,271 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ADOSC: Accumulation/Distribution Oscillator (Chaikin Oscillator)
/// </summary>
/// <remarks>
/// The Chaikin Oscillator is a momentum indicator for the Accumulation/Distribution Line (ADL).
/// It calculates the difference between two Exponential Moving Averages (EMAs) of the ADL.
///
/// Calculation:
/// ADOSC = EMA(Fast, ADL) - EMA(Slow, ADL)
///
/// Standard Parameters:
/// Fast Period: 3
/// Slow Period: 10
///
/// Sources:
/// https://www.investopedia.com/terms/c/chaikinoscillator.asp
/// https://school.stockcharts.com/doku.php?id=technical_indicators:chaikin_oscillator
/// </remarks>
[SkipLocalsInit]
public sealed class Adosc : ITValuePublisher
{
private readonly Adl _adl;
private readonly Ema _emaFast;
private readonly Ema _emaSlow;
/// <summary>
/// Display name for the indicator.
/// </summary>
public string Name { get; }
public event TValuePublishedHandler? Pub;
/// <summary>
/// Current ADOSC value.
/// </summary>
public TValue Last { get; private set; }
/// <summary>
/// True if the indicator has enough data to produce valid results.
/// </summary>
public bool IsHot => _emaSlow.IsHot;
/// <summary>
/// The number of bars required to warm up the indicator.
/// </summary>
public int WarmupPeriod { get; }
/// <summary>
/// Creates ADOSC with specified periods.
/// </summary>
/// <param name="fastPeriod">Fast EMA period (default 3)</param>
/// <param name="slowPeriod">Slow EMA period (default 10)</param>
public Adosc(int fastPeriod = 3, int slowPeriod = 10)
{
if (fastPeriod <= 0)
throw new ArgumentException("Fast period must be greater than 0", nameof(fastPeriod));
if (slowPeriod <= 0)
throw new ArgumentException("Slow period must be greater than 0", nameof(slowPeriod));
if (fastPeriod >= slowPeriod)
throw new ArgumentException("Fast period must be less than slow period", nameof(fastPeriod));
_adl = new Adl();
_emaFast = new Ema(fastPeriod);
_emaSlow = new Ema(slowPeriod);
WarmupPeriod = slowPeriod;
Name = $"Adosc({fastPeriod},{slowPeriod})";
}
/// <summary>
/// Resets the indicator state.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_adl.Reset();
_emaFast.Reset();
_emaSlow.Reset();
Last = default;
}
/// <summary>
/// Updates the indicator with a new ADL value.
/// </summary>
/// <param name="input">The new ADL value</param>
/// <param name="isNew">Whether this is a new value or an update to the last value</param>
/// <returns>The updated ADOSC value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
{
var eFast = _emaFast.Update(input, isNew);
var eSlow = _emaSlow.Update(input, isNew);
double adosc = eFast.Value - eSlow.Value;
Last = new TValue(input.Time, adosc);
Pub?.Invoke(this, new TValueEventArgs { Value = Last, IsNew = isNew });
return Last;
}
/// <summary>
/// Updates the indicator with a new bar.
/// </summary>
/// <param name="input">The new bar data</param>
/// <param name="isNew">Whether this is a new bar or an update to the last bar</param>
/// <returns>The updated ADOSC value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TBar input, bool isNew = true)
{
var adl = _adl.Update(input, isNew);
return Update(adl, isNew);
}
/// <summary>
/// Updates the indicator with a series of bars.
/// </summary>
/// <param name="source">The source series of bars</param>
/// <returns>The ADOSC series</returns>
public TSeries Update(TBarSeries source)
{
var t = new List<long>(source.Count);
var v = new List<double>(source.Count);
Reset();
for (int i = 0; i < source.Count; i++)
{
var val = Update(source[i], isNew: true);
t.Add(val.Time);
v.Add(val.Value);
}
return new TSeries(t, v);
}
/// <summary>
/// Calculates ADOSC for the entire series using a new instance.
/// </summary>
/// <param name="source">Input series</param>
/// <param name="fastPeriod">Fast EMA period (default 3)</param>
/// <param name="slowPeriod">Slow EMA period (default 10)</param>
/// <returns>ADOSC series</returns>
public static TSeries Batch(TBarSeries source, int fastPeriod = 3, int slowPeriod = 10)
{
var adosc = new Adosc(fastPeriod, slowPeriod);
return adosc.Update(source);
}
// EMA compensator threshold (same as in Ema.cs)
private const double COMPENSATOR_THRESHOLD = 1e-10;
/// <summary>
/// Calculates ADOSC for the entire span using a single-pass algorithm.
/// Zero allocation for maximum performance.
/// Uses compensator pattern from EMA for proper early-stage bias correction.
/// </summary>
/// <param name="high">High prices</param>
/// <param name="low">Low prices</param>
/// <param name="close">Close prices</param>
/// <param name="volume">Volume</param>
/// <param name="output">Output span</param>
/// <param name="fastPeriod">Fast EMA period (default 3)</param>
/// <param name="slowPeriod">Slow EMA period (default 10)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Calculate(ReadOnlySpan<double> high, ReadOnlySpan<double> low, ReadOnlySpan<double> close, ReadOnlySpan<double> volume, Span<double> output, int fastPeriod = 3, int slowPeriod = 10)
{
if (high.Length != low.Length || high.Length != close.Length ||
high.Length != volume.Length || high.Length != output.Length)
{
throw new ArgumentException("All spans must be of the same length.", nameof(output));
}
if (fastPeriod <= 0)
{
throw new ArgumentException("Fast period must be greater than 0", nameof(fastPeriod));
}
if (slowPeriod <= 0)
{
throw new ArgumentException("Slow period must be greater than 0", nameof(slowPeriod));
}
int len = high.Length;
if (len == 0) return;
// EMA parameters (same formula as Ema.cs: alpha = 2 / (period + 1))
double alphaFast = 2.0 / (fastPeriod + 1);
double alphaSlow = 2.0 / (slowPeriod + 1);
double decayFast = 1.0 - alphaFast;
double decaySlow = 1.0 - alphaSlow;
// State variables (no heap allocations)
double adl = 0;
double emaFast = 0;
double emaSlow = 0;
double eFast = 1.0; // Compensation factor for fast EMA (starts at 1, decays toward 0)
double eSlow = 1.0; // Compensation factor for slow EMA
bool fastCompensated = false;
bool slowCompensated = false;
// Single pass: compute ADL, both EMAs, and output in one loop
for (int i = 0; i < len; i++)
{
double h = high[i];
double l = low[i];
double c = close[i];
double vol = volume[i];
// 1. Compute Money Flow Multiplier and Volume
double hl = h - l;
double mfm = 0;
if (hl > double.Epsilon)
{
mfm = (c - l - (h - c)) / hl;
}
double mfv = mfm * vol;
// 2. Update ADL (cumulative)
adl += mfv;
// 3. Update Fast EMA with FMA (same pattern as Ema.cs Compute method)
// state.Ema = Math.FusedMultiplyAdd(state.Ema, decay, alpha * input)
emaFast = Math.FusedMultiplyAdd(emaFast, decayFast, alphaFast * adl);
// 4. Update Slow EMA with FMA
emaSlow = Math.FusedMultiplyAdd(emaSlow, decaySlow, alphaSlow * adl);
// 5. Compute compensated EMA values (same logic as Ema.cs Compute method)
// Compensator decays: e *= decay, then result = ema / (1 - e) until e <= threshold
double fastValue, slowValue;
if (!fastCompensated)
{
eFast *= decayFast;
if (eFast <= COMPENSATOR_THRESHOLD)
{
fastCompensated = true;
fastValue = emaFast;
}
else
{
fastValue = emaFast / (1.0 - eFast);
}
}
else
{
fastValue = emaFast;
}
if (!slowCompensated)
{
eSlow *= decaySlow;
if (eSlow <= COMPENSATOR_THRESHOLD)
{
slowCompensated = true;
slowValue = emaSlow;
}
else
{
slowValue = emaSlow / (1.0 - eSlow);
}
}
else
{
slowValue = emaSlow;
}
output[i] = fastValue - slowValue;
}
}
}
+67
View File
@@ -0,0 +1,67 @@
# ADOSC: Chaikin A/D Oscillator
> "Momentum precedes price. Volume momentum precedes price momentum."
The Chaikin Oscillator (ADOSC) is an indicator of an indicator. It applies the MACD formula to the Accumulation/Distribution Line (ADL) instead of the price.
While the ADL is great for spotting long-term flow, it can be sluggish. ADOSC acts as a turbocharger, measuring the *momentum* of that flow. It anticipates changes in the ADL, often signaling a reversal before the ADL itself turns.
## Historical Context
Marc Chaikin created this oscillator because he found the standard ADL too slow for timing entries. He realized that applying the moving average convergence/divergence (MACD) logic to the ADL would highlight the acceleration and deceleration of buying pressure.
## Architecture & Physics
ADOSC is a derivative indicator. It depends on:
1. **ADL**: The base volume flow metric.
2. **EMA**: Two exponential moving averages of that metric.
The physics here is identical to MACD:
* **Fast EMA (3)**: Represents the immediate, short-term money flow.
* **Slow EMA (10)**: Represents the established, medium-term money flow.
* **Difference**: The spread between them represents the momentum of accumulation.
## Mathematical Foundation
$$
ADOSC_t = EMA(ADL, 3)_t - EMA(ADL, 10)_t
$$
Where:
* $ADL$ is the Accumulation/Distribution Line.
* $EMA(X, N)$ is the Exponential Moving Average of X over N periods.
## Performance Profile
ADOSC is slightly heavier than ADL because it involves two EMAs.
| Metric | Score | Notes |
| :--- | :--- | :--- |
| **Throughput** | 15ns | 1 ADL update + 2 EMA updates |
| **Allocations** | 0 | Hot path is allocation-free |
| **Complexity** | O(1) | Constant time per update |
| **Accuracy** | 10/10 | Matches all major libraries |
| **Timeliness** | 10/10 | Leading indicator of momentum |
| **Overshoot** | 8/10 | Can be volatile in choppy markets |
| **Smoothness** | 8/10 | Smoothed by EMAs |
## Validation
Validation is performed against **TA-Lib**, **Skender**, **Tulip**, and **OoplesFinance**.
| Library | Status | Notes |
| :--- | :--- | :--- |
| **QuanTAlib** | ✅ | Validated. |
| **TA-Lib** | ✅ | Matches `AdOsc` exactly. |
| **Skender** | ✅ | Matches `ChaikinOsc`. |
| **Tulip** | ✅ | Matches `adosc`. |
| **Ooples** | ✅ | Matches `ChaikinOscillator`. |
### Common Pitfalls
* **Volatility**: ADOSC is extremely volatile. It whipsaws frequently. It should never be used in isolation.
* **Trend Confirmation**: Use it to confirm a trend, not to predict it. If price is rising but ADOSC is falling (divergence), the rally is running on fumes.
* **Zero Line**: Crosses above zero indicate that short-term accumulation is overpowering long-term accumulation (Bullish). Crosses below zero indicate the opposite (Bearish).