adding missing validations

This commit is contained in:
Miha Kralj
2026-02-26 09:59:44 -08:00
parent 467a8c1cef
commit 9ab37c1200
231 changed files with 60015 additions and 302 deletions
@@ -0,0 +1,124 @@
using TradingPlatform.BusinessLayer;
using QuanTAlib;
namespace QuanTAlib.Tests;
public sealed class CoppockIndicatorTests
{
[Fact]
public void CoppockIndicator_Constructor_SetsDefaults()
{
var indicator = new CoppockIndicator();
Assert.Equal(14, indicator.LongRoc);
Assert.Equal(11, indicator.ShortRoc);
Assert.Equal(10, indicator.WmaPeriod);
Assert.True(indicator.ShowColdValues);
Assert.Equal("COPPOCK - Coppock Curve", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void CoppockIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new CoppockIndicator();
Assert.Equal(0, CoppockIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void CoppockIndicator_ShortName_IncludesParameters()
{
var indicator = new CoppockIndicator { LongRoc = 14, ShortRoc = 11, WmaPeriod = 10 };
indicator.Initialize();
Assert.Contains("COPPOCK", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("14", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void CoppockIndicator_SourceCodeLink_IsValid()
{
var indicator = new CoppockIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Coppock", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void CoppockIndicator_Initialize_CreatesOneSeries()
{
var indicator = new CoppockIndicator { LongRoc = 5, ShortRoc = 4, WmaPeriod = 4 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void CoppockIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new CoppockIndicator { LongRoc = 5, ShortRoc = 4, WmaPeriod = 4 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 30; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
}
[Fact]
public void CoppockIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new CoppockIndicator { LongRoc = 5, ShortRoc = 4, WmaPeriod = 4 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 15; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
indicator.HistoricalData.AddBar(now.AddMinutes(15), 115, 125, 105, 120);
var newArgs = new UpdateArgs(UpdateReason.NewBar);
indicator.ProcessUpdate(newArgs);
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
}
[Fact]
public void CoppockIndicator_DifferentSourceTypes_ProcessCorrectly()
{
foreach (var sourceType in new[] { SourceType.Open, SourceType.High, SourceType.Low, SourceType.Close })
{
var indicator = new CoppockIndicator
{
LongRoc = 5,
ShortRoc = 4,
WmaPeriod = 4,
Source = sourceType
};
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 25; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i * 0.5, 110 + i * 0.5, 90 + i * 0.5, 105 + i * 0.5);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
}
}
}
@@ -0,0 +1,64 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class CoppockIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Long ROC Period", sortIndex: 1, 1, 500, 1, 0)]
public int LongRoc { get; set; } = 14;
[InputParameter("Short ROC Period", sortIndex: 2, 1, 500, 1, 0)]
public int ShortRoc { get; set; } = 11;
[InputParameter("WMA Period", sortIndex: 3, 1, 500, 1, 0)]
public int WmaPeriod { get; set; } = 10;
[IndicatorExtensions.DataSourceInput(sortIndex: 4)]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Coppock _coppock = null!;
private readonly LineSeries _coppockSeries;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"COPPOCK ({LongRoc},{ShortRoc},{WmaPeriod})";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/coppock/Coppock.Quantower.cs";
public CoppockIndicator()
{
OnBackGround = true;
SeparateWindow = true;
Name = "COPPOCK - Coppock Curve";
Description = "WMA of the sum of two Rate-of-Change values (long and short lookback periods)";
_coppockSeries = new LineSeries(name: "Coppock", color: Color.Yellow, width: 2, style: LineStyle.Solid);
AddLineSeries(_coppockSeries);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_coppock = new Coppock(LongRoc, ShortRoc, WmaPeriod);
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
var priceSelector = Source.GetPriceSelector();
var item = HistoricalData[0, SeekOriginHistory.End];
double price = priceSelector(item);
_ = _coppock.Update(new TValue(item.TimeLeft, price), args.IsNewBar());
_coppockSeries.SetValue(_coppock.Last.Value, _coppock.IsHot, ShowColdValues);
}
}
+532
View File
@@ -0,0 +1,532 @@
using Xunit;
namespace QuanTAlib.Tests;
// ── A) Constructor Validation ────────────────────────────────────────────────
public sealed class CoppockConstructorTests
{
[Fact]
public void Constructor_ZeroLongRoc_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Coppock(longRoc: 0));
Assert.Equal("longRoc", ex.ParamName);
}
[Fact]
public void Constructor_NegativeLongRoc_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Coppock(longRoc: -1));
Assert.Equal("longRoc", ex.ParamName);
}
[Fact]
public void Constructor_ZeroShortRoc_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Coppock(shortRoc: 0));
Assert.Equal("shortRoc", ex.ParamName);
}
[Fact]
public void Constructor_NegativeShortRoc_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Coppock(shortRoc: -5));
Assert.Equal("shortRoc", ex.ParamName);
}
[Fact]
public void Constructor_ZeroWmaPeriod_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Coppock(wmaPeriod: 0));
Assert.Equal("wmaPeriod", ex.ParamName);
}
[Fact]
public void Constructor_NegativeWmaPeriod_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Coppock(wmaPeriod: -2));
Assert.Equal("wmaPeriod", ex.ParamName);
}
[Fact]
public void Constructor_Defaults_Creates()
{
var c = new Coppock();
Assert.NotNull(c);
Assert.Contains("Coppock", c.Name, StringComparison.Ordinal);
}
[Fact]
public void Constructor_WarmupPeriod_IsPositive()
{
var c = new Coppock();
Assert.True(c.WarmupPeriod > 0);
}
[Fact]
public void Constructor_CustomParams_NameReflectsThem()
{
var c = new Coppock(longRoc: 7, shortRoc: 5, wmaPeriod: 4);
Assert.Contains("7", c.Name, StringComparison.Ordinal);
Assert.Contains("5", c.Name, StringComparison.Ordinal);
Assert.Contains("4", c.Name, StringComparison.Ordinal);
}
[Fact]
public void Constructor_WarmupPeriod_DependsOnLongestPlusWma()
{
// WarmupPeriod = max(longRoc,shortRoc) + wmaPeriod - 1
var c = new Coppock(longRoc: 14, shortRoc: 11, wmaPeriod: 10);
Assert.Equal(14 + 10 - 1, c.WarmupPeriod);
}
}
// ── B) Basic Calculation ─────────────────────────────────────────────────────
public sealed class CoppockBasicTests
{
[Fact]
public void BasicCalculation_DoesNotCrash()
{
var c = new Coppock();
var result = c.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(result.Value, c.Last.Value);
}
[Fact]
public void FirstBar_OutputIsFinite()
{
var c = new Coppock();
var result = c.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Name_Available()
{
var c = new Coppock();
Assert.False(string.IsNullOrEmpty(c.Name));
}
[Fact]
public void Last_IsAccessible()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 20; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
Assert.True(double.IsFinite(c.Last.Value));
}
[Fact]
public void ConstantPrice_CoppockIsZero()
{
// All ROC = 0 → combined = 0 → WMA(0) = 0
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 20; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0));
}
Assert.Equal(0.0, c.Last.Value, 1e-10);
}
[Fact]
public void KnownValue_WarmupBarIsZero()
{
// Before warmup, output is 0 (during WMA fill)
var c = new Coppock(longRoc: 5, shortRoc: 3, wmaPeriod: 4);
var result = c.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.False(c.IsHot);
Assert.True(double.IsFinite(result.Value));
}
}
// ── C) State + Bar Correction ────────────────────────────────────────────────
public sealed class CoppockBarCorrectionTests
{
[Fact]
public void IsNew_True_AdvancesState()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 5; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i * 2), isNew: true);
}
double val1 = c.Last.Value;
c.Update(new TValue(DateTime.UtcNow, 115.0), isNew: true);
double val2 = c.Last.Value;
Assert.True(double.IsFinite(val1));
Assert.True(double.IsFinite(val2));
}
[Fact]
public void IsNew_False_Rollback()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
for (int i = 0; i < 10; i++)
{
var bar = gbm.Next(isNew: true);
c.Update(new TValue(bar.Time, bar.Close), isNew: true);
}
var nextBar = gbm.Next(isNew: true);
var originalInput = new TValue(nextBar.Time, nextBar.Close);
var val1 = c.Update(originalInput, isNew: true);
// Overwrite with different value
c.Update(new TValue(nextBar.Time, nextBar.Close + 50), isNew: false);
// Restore original → must match
var restored = c.Update(originalInput, isNew: false);
Assert.Equal(val1.Value, restored.Value, 1e-10);
}
[Fact]
public void IterativeCorrections_RestoreToOriginalState()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
TValue twentyInput = default;
for (int i = 0; i < 20; i++)
{
var bar = gbm.Next(isNew: true);
twentyInput = new TValue(bar.Time, bar.Close);
c.Update(twentyInput, isNew: true);
}
double stateAfterTwenty = c.Last.Value;
for (int i = 0; i < 9; i++)
{
var bar = gbm.Next(isNew: false);
c.Update(new TValue(bar.Time, bar.Close), isNew: false);
}
var finalResult = c.Update(twentyInput, isNew: false);
Assert.Equal(stateAfterTwenty, finalResult.Value, 1e-10);
}
[Fact]
public void Reset_ClearsState()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 20; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
c.Reset();
Assert.False(c.IsHot);
Assert.Equal(0.0, c.Last.Value);
}
}
// ── D) Warmup / Convergence ──────────────────────────────────────────────────
public sealed class CoppockWarmupTests
{
[Fact]
public void IsHot_InitiallyFalse()
{
var c = new Coppock();
Assert.False(c.IsHot);
}
[Fact]
public void IsHot_BecomesTrueAfterWarmupPeriodBars()
{
var c = new Coppock(longRoc: 5, shortRoc: 3, wmaPeriod: 4);
int warmup = c.WarmupPeriod;
for (int i = 1; i < warmup; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
Assert.False(c.IsHot, $"Should not be hot at bar {i} (need {warmup})");
}
c.Update(new TValue(DateTime.UtcNow, 100.0 + warmup));
Assert.True(c.IsHot);
}
[Fact]
public void WarmupPeriod_DependsOnParameters()
{
var c1 = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
var c2 = new Coppock(longRoc: 14, shortRoc: 11, wmaPeriod: 10);
Assert.True(c2.WarmupPeriod > c1.WarmupPeriod);
}
[Fact]
public void WarmupPeriod_ShortRocLonger_UsesShortRoc()
{
// When shortRoc > longRoc, warmup = shortRoc + wmaPeriod - 1
var c = new Coppock(longRoc: 5, shortRoc: 8, wmaPeriod: 4);
Assert.Equal(8 + 4 - 1, c.WarmupPeriod);
}
}
// ── E) Robustness ────────────────────────────────────────────────────────────
public sealed class CoppockRobustnessTests
{
[Fact]
public void NaN_UsesLastValidValue()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 10; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
c.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(c.Last.Value), "NaN input should not produce NaN output");
}
[Fact]
public void PositiveInfinity_UsesLastValidValue()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 10; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
c.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(c.Last.Value));
}
[Fact]
public void NegativeInfinity_UsesLastValidValue()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 10; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
c.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
Assert.True(double.IsFinite(c.Last.Value));
}
[Fact]
public void BatchNaN_SafeOutput()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
c.Update(new TValue(DateTime.UtcNow, 100.0));
for (int i = 0; i < 5; i++)
{
c.Update(new TValue(DateTime.UtcNow, double.NaN));
}
c.Update(new TValue(DateTime.UtcNow, 110.0));
Assert.True(double.IsFinite(c.Last.Value));
}
}
// ── F) Consistency (all API modes agree) ─────────────────────────────────────
public sealed class CoppockConsistencyTests
{
private static TSeries MakeSeries(double[] vals)
{
var times = new List<long>(vals.Length);
var values = new List<double>(vals.Length);
var t0 = DateTime.UtcNow;
for (int i = 0; i < vals.Length; i++)
{
times.Add(t0.AddSeconds(i).Ticks);
values.Add(vals[i]);
}
return new TSeries(times, values);
}
[Fact]
public void Streaming_Equals_Batch_TSeries()
{
int lr = 5, sr = 4, wp = 4;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 7);
int count = 60;
var prices = new double[count];
for (int i = 0; i < count; i++) { prices[i] = gbm.Next(isNew: true).Close; }
// Streaming
var cStream = new Coppock(lr, sr, wp);
var streamOut = new double[count];
for (int i = 0; i < count; i++)
{
cStream.Update(new TValue(DateTime.UtcNow.AddSeconds(i), prices[i]));
streamOut[i] = cStream.Last.Value;
}
// Batch TSeries
var series = MakeSeries(prices);
var cBatch = new Coppock(lr, sr, wp);
var batchOut = cBatch.Update(series);
for (int i = 0; i < count; i++)
{
Assert.Equal(streamOut[i], batchOut.Values[i], 1e-9);
}
}
[Fact]
public void Span_Equals_Streaming()
{
int lr = 5, sr = 4, wp = 4;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 11);
int count = 60;
var prices = new double[count];
for (int i = 0; i < count; i++) { prices[i] = gbm.Next(isNew: true).Close; }
// Span Batch
var spanOut = new double[count];
Coppock.Batch(prices, spanOut, lr, sr, wp);
// Streaming
var cStream = new Coppock(lr, sr, wp);
for (int i = 0; i < count; i++)
{
cStream.Update(new TValue(DateTime.UtcNow.AddSeconds(i), prices[i]));
Assert.Equal(spanOut[i], cStream.Last.Value, 1e-9);
}
}
[Fact]
public void Eventing_Equals_Manual_Streaming()
{
int lr = 5, sr = 4, wp = 4;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 13);
var series = new TSeries();
// Subscribe BEFORE adding data so Pub events fire
var cEvent = new Coppock(series, lr, sr, wp);
for (int i = 0; i < 40; i++)
{
var bar = gbm.Next(isNew: true);
series.Add(new TValue(bar.Time, bar.Close), isNew: true);
}
double eventLast = cEvent.Last.Value;
// Manual streaming replay
var cManual = new Coppock(lr, sr, wp);
foreach (var tv in series)
{
cManual.Update(tv, isNew: true);
}
Assert.Equal(eventLast, cManual.Last.Value, 1e-9);
}
}
// ── G) Span API Tests ────────────────────────────────────────────────────────
public sealed class CoppockSpanTests
{
[Fact]
public void Span_MismatchedOutputLength_ThrowsArgumentException()
{
double[] src = [1, 2, 3, 4, 5];
double[] output = new double[4]; // wrong length
var ex = Assert.Throws<ArgumentException>(() =>
Coppock.Batch(src, output));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Span_ZeroLongRoc_ThrowsArgumentException()
{
double[] src = [1, 2, 3];
double[] output = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Coppock.Batch(src, output, longRoc: 0));
Assert.Equal("longRoc", ex.ParamName);
}
[Fact]
public void Span_ZeroShortRoc_ThrowsArgumentException()
{
double[] src = [1, 2, 3];
double[] output = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Coppock.Batch(src, output, shortRoc: 0));
Assert.Equal("shortRoc", ex.ParamName);
}
[Fact]
public void Span_ZeroWmaPeriod_ThrowsArgumentException()
{
double[] src = [1, 2, 3];
double[] output = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Coppock.Batch(src, output, wmaPeriod: 0));
Assert.Equal("wmaPeriod", ex.ParamName);
}
[Fact]
public void Span_EmptyInput_NoException()
{
double[] src = [];
double[] output = [];
Coppock.Batch(src, output); // should not throw
Assert.Empty(src);
}
[Fact]
public void Span_NaNInput_SafeOutput()
{
var prices = new double[60];
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 99);
for (int i = 0; i < 60; i++) { prices[i] = gbm.Next(isNew: true).Close; }
prices[10] = double.NaN;
prices[25] = double.PositiveInfinity;
var output = new double[60];
Coppock.Batch(prices, output, longRoc: 5, shortRoc: 4, wmaPeriod: 4);
foreach (var v in output) { Assert.True(double.IsFinite(v)); }
}
[Fact]
public void Span_LargeInput_NoStackOverflow()
{
int n = 5000;
var prices = new double[n];
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.1, seed: 77);
for (int i = 0; i < n; i++) { prices[i] = gbm.Next(isNew: true).Close; }
var output = new double[n];
Coppock.Batch(prices, output); // default periods, large array
Assert.True(double.IsFinite(output[^1]));
}
}
// ── H) Chainability ──────────────────────────────────────────────────────────
public sealed class CoppockChainabilityTests
{
[Fact]
public void Pub_Fires_OnUpdate()
{
var c = new Coppock(longRoc: 3, shortRoc: 2, wmaPeriod: 3);
int fireCount = 0;
c.Pub += (object? _, in TValueEventArgs _e) => fireCount++;
for (int i = 0; i < 5; i++)
{
c.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
Assert.Equal(5, fireCount);
}
[Fact]
public void EventBasedChaining_WorksCorrectly()
{
var series = new TSeries();
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 5);
var c = new Coppock(series, longRoc: 3, shortRoc: 2, wmaPeriod: 3);
for (int i = 0; i < 25; i++)
{
var bar = gbm.Next(isNew: true);
series.Add(new TValue(bar.Time, bar.Close), isNew: true);
}
Assert.True(double.IsFinite(c.Last.Value));
}
}
@@ -0,0 +1,212 @@
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
/// <summary>
/// Coppock Validation Tests.
/// No external library (TA-Lib, Skender, Tulip, Ooples) implements the Coppock Curve,
/// so validation uses self-consistency checks: streaming==batch(TSeries)==batch(Span),
/// directional correctness, and constant-price identity.
/// </summary>
public sealed class CoppockValidationTests(ITestOutputHelper output)
{
private readonly ITestOutputHelper _output = output;
private static double[] GeneratePrices(int count, int seed = 42)
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2, seed: seed);
var prices = new double[count];
for (int i = 0; i < count; i++) { prices[i] = gbm.Next(isNew: true).Close; }
return prices;
}
private static TSeries MakeSeries(double[] vals)
{
var times = new List<long>(vals.Length);
var values = new List<double>(vals.Length);
var t0 = DateTime.UtcNow;
for (int i = 0; i < vals.Length; i++)
{
times.Add(t0.AddSeconds(i).Ticks);
values.Add(vals[i]);
}
return new TSeries(times, values);
}
// ── A) Streaming == Batch(TSeries) ────────────────────────────────────────
[Fact]
public void Validate_Streaming_Equals_Batch()
{
int lr = 5, sr = 4, wp = 4;
double[] prices = GeneratePrices(200);
// Streaming
var cStream = new Coppock(lr, sr, wp);
var streamOut = new double[prices.Length];
for (int i = 0; i < prices.Length; i++)
{
cStream.Update(new TValue(DateTime.UtcNow.AddSeconds(i), prices[i]));
streamOut[i] = cStream.Last.Value;
}
// Batch TSeries
var series = MakeSeries(prices);
var cBatch = new Coppock(lr, sr, wp);
var batchOut = cBatch.Update(series);
for (int i = 0; i < prices.Length; i++)
{
Assert.Equal(streamOut[i], batchOut.Values[i], 1e-6);
}
_output.WriteLine("Coppock Streaming == Batch(TSeries): PASSED");
}
// ── B) Batch(TSeries) == Span ─────────────────────────────────────────────
[Fact]
public void Validate_Batch_Equals_Span()
{
int lr = 5, sr = 4, wp = 4;
double[] prices = GeneratePrices(200, seed: 77);
// Span
var spanOut = new double[prices.Length];
Coppock.Batch(prices, spanOut, lr, sr, wp);
// Batch TSeries
var series = MakeSeries(prices);
var batchOut = Coppock.Batch(series, lr, sr, wp);
for (int i = 0; i < prices.Length; i++)
{
Assert.Equal(spanOut[i], batchOut.Values[i], 1e-9);
}
_output.WriteLine("Coppock Batch(TSeries) == Span: PASSED");
}
// ── C) Rising prices → positive ROC → positive Coppock ───────────────────
[Fact]
public void Validate_StrictlyRising_CoppockPositive()
{
double startPrice = 100.0;
int n = 60;
double[] prices = new double[n];
for (int i = 0; i < n; i++) { prices[i] = startPrice + i * 0.5; }
var spanOut = new double[n];
Coppock.Batch(prices, spanOut, longRoc: 5, shortRoc: 4, wmaPeriod: 4);
int warmup = new Coppock(5, 4, 4).WarmupPeriod;
for (int i = warmup; i < n; i++)
{
Assert.True(spanOut[i] > 0, $"Coppock should be positive at index {i}, got {spanOut[i]}");
}
_output.WriteLine("Coppock directional correctness (rising price → positive): PASSED");
}
// ── D) Falling prices → negative Coppock ─────────────────────────────────
[Fact]
public void Validate_StrictlyFalling_CoppockNegative()
{
double startPrice = 200.0;
int n = 60;
double[] prices = new double[n];
for (int i = 0; i < n; i++) { prices[i] = startPrice - i * 0.5; }
var spanOut = new double[n];
Coppock.Batch(prices, spanOut, longRoc: 5, shortRoc: 4, wmaPeriod: 4);
int warmup = new Coppock(5, 4, 4).WarmupPeriod;
for (int i = warmup; i < n; i++)
{
Assert.True(spanOut[i] < 0, $"Coppock should be negative at index {i}, got {spanOut[i]}");
}
_output.WriteLine("Coppock directional correctness (falling price → negative): PASSED");
}
// ── E) Constant price → Coppock = 0 ──────────────────────────────────────
[Fact]
public void Validate_ConstantPrice_CoppockZero()
{
int n = 60;
double[] prices = new double[n];
Array.Fill(prices, 100.0);
var spanOut = new double[n];
Coppock.Batch(prices, spanOut, longRoc: 5, shortRoc: 4, wmaPeriod: 4);
for (int i = 0; i < n; i++)
{
Assert.Equal(0.0, spanOut[i], 1e-10);
}
_output.WriteLine("Coppock constant price → Coppock=0: PASSED");
}
// ── F) Default parameters produce finite values ───────────────────────────
[Fact]
public void Validate_DefaultParameters_FiniteOutput()
{
double[] prices = GeneratePrices(500, seed: 123);
var spanOut = new double[prices.Length];
Coppock.Batch(prices, spanOut); // all defaults
int warmup = new Coppock().WarmupPeriod;
for (int i = warmup; i < prices.Length; i++)
{
Assert.True(double.IsFinite(spanOut[i]), $"Coppock[{i}] not finite: {spanOut[i]}");
}
_output.WriteLine($"Coppock default parameters (warmup={warmup}), 500 bars: all finite. PASSED");
}
// ── G) Different parameters produce distinct results ──────────────────────
[Fact]
public void Validate_DifferentParams_ProduceDifferentResults()
{
double[] prices = GeneratePrices(100, seed: 88);
var out1 = new double[prices.Length];
var out2 = new double[prices.Length];
Coppock.Batch(prices, out1, longRoc: 5, shortRoc: 4, wmaPeriod: 4);
Coppock.Batch(prices, out2, longRoc: 10, shortRoc: 8, wmaPeriod: 7);
int warmup = Math.Max(
new Coppock(5, 4, 4).WarmupPeriod,
new Coppock(10, 8, 7).WarmupPeriod);
bool anyDifferent = false;
for (int i = warmup; i < prices.Length; i++)
{
if (Math.Abs(out1[i] - out2[i]) > 1e-6) { anyDifferent = true; break; }
}
Assert.True(anyDifferent, "Different parameters should produce different Coppock values");
_output.WriteLine("Coppock different parameters → different results: PASSED");
}
// ── H) Static Batch(TSeries) and Calculate() produce same results ─────────
[Fact]
public void Validate_StaticBatch_Equals_Calculate()
{
int lr = 5, sr = 4, wp = 4;
double[] prices = GeneratePrices(100, seed: 55);
var series = MakeSeries(prices);
var batchOut = Coppock.Batch(series, lr, sr, wp);
var (calcOut, _) = Coppock.Calculate(series, lr, sr, wp);
for (int i = 0; i < prices.Length; i++)
{
Assert.Equal(batchOut.Values[i], calcOut.Values[i], 1e-9);
}
_output.WriteLine("Coppock static Batch == Calculate: PASSED");
}
}
+412
View File
@@ -0,0 +1,412 @@
// COPPOCK: Coppock Curve
// WMA of the sum of two Rate-of-Change values at different lookback periods.
// Formula: Coppock = WMA(ROC(longRoc) + ROC(shortRoc), wmaPeriod)
// Source: Edwin Coppock, "A Guide to the Use of Coppock Curve", Barron's (1962)
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// COPPOCK: Coppock Curve
/// </summary>
/// <remarks>
/// The Coppock Curve applies a Weighted Moving Average to the sum of two
/// Rate-of-Change calculations at different lookback periods, producing a
/// zero-centered oscillator. Zero-line crossovers from below signal long-term
/// buying opportunities on monthly charts.
///
/// Calculation:
/// 1. ROC_long = (price / price[longRoc] - 1) * 100
/// 2. ROC_short = (price / price[shortRoc] - 1) * 100
/// 3. Combined = ROC_long + ROC_short
/// 4. Coppock = WMA(Combined, wmaPeriod)
///
/// Default parameters: longRoc=14, shortRoc=11, wmaPeriod=10 (original monthly values)
/// WarmupPeriod = max(longRoc, shortRoc) + wmaPeriod - 1
///
/// Sources:
/// - Coppock, E.S.C. (1962). "A Guide to the Use of Coppock Curve." Barron's
/// - Kirkpatrick, C. &amp; Dahlquist, J. (2010). Technical Analysis, Chapter 15
/// </remarks>
[SkipLocalsInit]
public sealed class Coppock : ITValuePublisher
{
private const int DefaultLongRoc = 14;
private const int DefaultShortRoc = 11;
private const int DefaultWmaPeriod = 10;
private readonly int _longRoc;
private readonly int _shortRoc;
private readonly int _wmaPeriod;
private readonly double _wmaNorm; // W*(W+1)/2
// ROC lookback ring buffers: slot[head] = oldest price still needed
// Size = period+1 so we can store current + lookback[period] simultaneously
private readonly double[] _longBuf; // size = longRoc+1
private readonly double[] _shortBuf; // size = shortRoc+1
// WMA dual-running-sum ring buffer
private readonly double[] _wmaBuf; // size = wmaPeriod
// All scalar state grouped for _ps = _s snapshot (bar-correction).
// PrevLong / PrevShort / PrevWma: slot values BEFORE the last isNew=true write,
// used to restore ring-buffer slots on isNew=false rollback.
[StructLayout(LayoutKind.Auto)]
private record struct State(
int LongHead, int ShortHead,
double PrevLong, double PrevShort,
int WmaHead, int WmaCount,
double WmaPlainSum, double WmaWeightedSum,
double PrevWma,
int Count, double LastValidPrice);
private State _s;
private State _ps;
public string Name { get; }
public int WarmupPeriod { get; }
public TValue Last { get; private set; }
/// <summary>True when enough bars have been processed for valid output.</summary>
public bool IsHot => _s.Count >= WarmupPeriod;
public event TValuePublishedHandler? Pub;
public Coppock(int longRoc = DefaultLongRoc, int shortRoc = DefaultShortRoc, int wmaPeriod = DefaultWmaPeriod)
{
if (longRoc <= 0)
{
throw new ArgumentException("Long ROC period must be greater than 0", nameof(longRoc));
}
if (shortRoc <= 0)
{
throw new ArgumentException("Short ROC period must be greater than 0", nameof(shortRoc));
}
if (wmaPeriod <= 0)
{
throw new ArgumentException("WMA period must be greater than 0", nameof(wmaPeriod));
}
_longRoc = longRoc;
_shortRoc = shortRoc;
_wmaPeriod = wmaPeriod;
_wmaNorm = wmaPeriod * (wmaPeriod + 1) * 0.5;
_longBuf = new double[longRoc + 1];
_shortBuf = new double[shortRoc + 1];
_wmaBuf = new double[wmaPeriod];
// Warmup: need max(longRoc,shortRoc) bars before combined ROC is non-zero,
// then wmaPeriod bars to fill WMA window. Subtract 1 for the shared bar.
WarmupPeriod = Math.Max(longRoc, shortRoc) + wmaPeriod - 1;
_s = default;
_ps = _s;
Name = $"Coppock({longRoc},{shortRoc},{wmaPeriod})";
}
public Coppock(ITValuePublisher source, int longRoc = DefaultLongRoc, int shortRoc = DefaultShortRoc, int wmaPeriod = DefaultWmaPeriod)
: this(longRoc, shortRoc, wmaPeriod)
{
source.Pub += Handle;
}
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void PubEvent(TValue value, bool isNew) =>
Pub?.Invoke(this, new TValueEventArgs { Value = value, IsNew = isNew });
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_ps = _s;
}
else
{
// Restore ring-buffer slots overwritten by the last isNew=true call.
_longBuf[_ps.LongHead] = _s.PrevLong;
_shortBuf[_ps.ShortHead] = _s.PrevShort;
_wmaBuf[_ps.WmaHead] = _s.PrevWma;
_s = _ps;
}
// Local copy for JIT register promotion
int longH = _s.LongHead;
int shortH = _s.ShortHead;
int wmaH = _s.WmaHead;
int wmaCount = _s.WmaCount;
double plainSum = _s.WmaPlainSum;
double weightedSum = _s.WmaWeightedSum;
int count = _s.Count;
double lastValid = _s.LastValidPrice;
double price = input.Value;
if (!double.IsFinite(price))
{
price = double.IsFinite(lastValid) ? lastValid : 0.0;
}
else
{
lastValid = price;
}
if (isNew)
{
count++;
}
// ── ROC lookback ring buffers ─────────────────────────────────────────
// Capture slot value BEFORE writing (for restore on next isNew=false).
double prevLong = _longBuf[longH];
double prevShort = _shortBuf[shortH];
_longBuf[longH] = price;
_shortBuf[shortH] = price;
if (isNew)
{
longH = (longH + 1) % (_longRoc + 1);
shortH = (shortH + 1) % (_shortRoc + 1);
}
// ── Combined ROC ──────────────────────────────────────────────────────
double rocLong = prevLong != 0.0 ? 100.0 * (price - prevLong) / prevLong : 0.0;
double rocShort = prevShort != 0.0 ? 100.0 * (price - prevShort) / prevShort : 0.0;
double combined = rocLong + rocShort;
// ── WMA dual running sum (O(1) per bar) ───────────────────────────────
// When buffer is growing (wmaCount < wmaPeriod):
// plainSum += combined
// weightedSum += (wmaCount+1) * combined [1-based weight]
// When buffer is full (wmaCount == wmaPeriod):
// oldest evicted from slot wmaH
// plainSum = plainSum - oldest + combined
// weightedSum = weightedSum - (plainSum_before_eviction) + wmaPeriod * combined
double prevWma = _wmaBuf[wmaH];
double coppockVal;
if (wmaCount < _wmaPeriod)
{
plainSum += combined;
wmaCount++;
weightedSum += wmaCount * combined; // weight = position 1..wmaPeriod
double norm = wmaCount * (wmaCount + 1) * 0.5;
coppockVal = norm != 0.0 ? weightedSum / norm : 0.0;
}
else
{
double oldPlain = plainSum;
plainSum = plainSum - prevWma + combined;
weightedSum = weightedSum - oldPlain + _wmaPeriod * combined;
coppockVal = weightedSum / _wmaNorm;
}
_wmaBuf[wmaH] = combined;
if (isNew)
{
wmaH = (wmaH + 1) % _wmaPeriod;
}
// ── Write back state (including pre-write slot snapshots) ─────────────
_s = new State(
longH, shortH,
prevLong, prevShort,
wmaH, wmaCount,
plainSum, weightedSum,
prevWma,
count, lastValid);
Last = new TValue(input.Time, coppockVal);
PubEvent(Last, isNew);
return Last;
}
/// <summary>Updates streaming state from a <see cref="TSeries"/> and returns output series.</summary>
public TSeries Update(TSeries source)
{
int len = source.Count;
if (len == 0)
{
return new TSeries([], []);
}
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
Batch(source.Values, CollectionsMarshal.AsSpan(v), _longRoc, _shortRoc, _wmaPeriod);
source.Times.CopyTo(CollectionsMarshal.AsSpan(t));
// Prime streaming state to match end of batch
Reset();
for (int i = 0; i < len; i++)
{
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
}
return new TSeries(t, v);
}
/// <summary>Resets all internal state.</summary>
public void Reset()
{
Array.Clear(_longBuf);
Array.Clear(_shortBuf);
Array.Clear(_wmaBuf);
_s = default;
_ps = _s;
Last = default;
}
// ── Static Span Batch ────────────────────────────────────────────────────
/// <summary>
/// Calculates Coppock for the full source span. Uses <see cref="ArrayPool{T}"/> for all intermediate buffers.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(
ReadOnlySpan<double> source,
Span<double> output,
int longRoc = DefaultLongRoc,
int shortRoc = DefaultShortRoc,
int wmaPeriod = DefaultWmaPeriod)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (longRoc <= 0)
{
throw new ArgumentException("Long ROC period must be greater than 0", nameof(longRoc));
}
if (shortRoc <= 0)
{
throw new ArgumentException("Short ROC period must be greater than 0", nameof(shortRoc));
}
if (wmaPeriod <= 0)
{
throw new ArgumentException("WMA period must be greater than 0", nameof(wmaPeriod));
}
int len = source.Length;
if (len == 0)
{
return;
}
int lBufSize = longRoc + 1;
int sBufSize = shortRoc + 1;
double wmaNorm = wmaPeriod * (wmaPeriod + 1) * 0.5;
double[] longBuf = ArrayPool<double>.Shared.Rent(lBufSize);
double[] shortBuf = ArrayPool<double>.Shared.Rent(sBufSize);
double[] wmaBuf = ArrayPool<double>.Shared.Rent(wmaPeriod);
longBuf.AsSpan(0, lBufSize).Clear();
shortBuf.AsSpan(0, sBufSize).Clear();
wmaBuf.AsSpan(0, wmaPeriod).Clear();
try
{
int longH = 0, shortH = 0, wmaH = 0, wmaCount = 0;
double plainSum = 0.0, weightedSum = 0.0;
double lastValid = 0.0;
for (int i = 0; i < len; i++)
{
double price = source[i];
if (!double.IsFinite(price))
{
price = lastValid;
}
else
{
lastValid = price;
}
double prevLong = longBuf[longH];
double prevShort = shortBuf[shortH];
longBuf[longH] = price;
shortBuf[shortH] = price;
longH = (longH + 1) % lBufSize;
shortH = (shortH + 1) % sBufSize;
double rocLong = prevLong != 0.0 ? 100.0 * (price - prevLong) / prevLong : 0.0;
double rocShort = prevShort != 0.0 ? 100.0 * (price - prevShort) / prevShort : 0.0;
double combined = rocLong + rocShort;
double oldest = wmaBuf[wmaH];
double coppockVal;
if (wmaCount < wmaPeriod)
{
plainSum += combined;
wmaCount++;
weightedSum += wmaCount * combined;
double norm = wmaCount * (wmaCount + 1) * 0.5;
coppockVal = norm != 0.0 ? weightedSum / norm : 0.0;
}
else
{
double oldPlain = plainSum;
plainSum = plainSum - oldest + combined;
weightedSum = weightedSum - oldPlain + wmaPeriod * combined;
coppockVal = weightedSum / wmaNorm;
}
wmaBuf[wmaH] = combined;
wmaH = (wmaH + 1) % wmaPeriod;
output[i] = coppockVal;
}
}
finally
{
ArrayPool<double>.Shared.Return(longBuf);
ArrayPool<double>.Shared.Return(shortBuf);
ArrayPool<double>.Shared.Return(wmaBuf);
}
}
/// <summary>Calculates Coppock for an entire <see cref="TSeries"/>.</summary>
public static TSeries Batch(
TSeries source,
int longRoc = DefaultLongRoc,
int shortRoc = DefaultShortRoc,
int wmaPeriod = DefaultWmaPeriod)
{
if (source == null || source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
Batch(source.Values, CollectionsMarshal.AsSpan(v), longRoc, shortRoc, wmaPeriod);
source.Times.CopyTo(CollectionsMarshal.AsSpan(t));
return new TSeries(t, v);
}
/// <summary>Creates a Coppock indicator and calculates results for the source series.</summary>
public static (TSeries Results, Coppock Indicator) Calculate(
TSeries source,
int longRoc = DefaultLongRoc,
int shortRoc = DefaultShortRoc,
int wmaPeriod = DefaultWmaPeriod)
{
var indicator = new Coppock(longRoc, shortRoc, wmaPeriod);
var results = indicator.Update(source);
return (results, indicator);
}
}