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
+173
View File
@@ -0,0 +1,173 @@
using TradingPlatform.BusinessLayer;
using QuanTAlib;
namespace QuanTAlib.Tests;
public sealed class CtiIndicatorTests
{
[Fact]
public void CtiIndicator_Constructor_SetsDefaults()
{
var indicator = new CtiIndicator();
Assert.Equal(20, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("CTI - Correlation Trend Indicator", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void CtiIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new CtiIndicator { Period = 20 };
Assert.Equal(0, CtiIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void CtiIndicator_ShortName_IncludesParameters()
{
var indicator = new CtiIndicator { Period = 20 };
indicator.Initialize();
Assert.Contains("CTI", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("20", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void CtiIndicator_SourceCodeLink_IsValid()
{
var indicator = new CtiIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Cti.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void CtiIndicator_Initialize_CreatesInternalCti()
{
var indicator = new CtiIndicator { Period = 10 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void CtiIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new CtiIndicator { Period = 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);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
double value = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(value));
}
[Fact]
public void CtiIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new CtiIndicator { Period = 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);
}
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.HistoricalData.AddBar(now.AddMinutes(20), 120, 130, 110, 125);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void CtiIndicator_ProcessUpdate_Tick_ComputesValue()
{
var indicator = new CtiIndicator { Period = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
// Simulate a tick update on current bar
indicator.HistoricalData.AddBar(now.AddMinutes(10), 110, 120, 100, 115);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
double value = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(value));
}
[Fact]
public void CtiIndicator_Parameters_CanBeChanged()
{
var indicator = new CtiIndicator();
indicator.Period = 30;
Assert.Equal(30, indicator.Period);
}
[Fact]
public void CtiIndicator_DifferentSources_Work()
{
var now = DateTime.UtcNow;
foreach (var source in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
{
var indicator = new CtiIndicator { Period = 5, Source = source };
indicator.Initialize();
for (int i = 0; i < 10; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double value = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(value));
}
}
[Fact]
public void CtiIndicator_OutputBounded_MinusOneToOne()
{
var indicator = new CtiIndicator { Period = 10 };
indicator.Initialize();
var now = DateTime.UtcNow;
// Perfect ascending price series
for (int i = 0; i < 30; i++)
{
double price = 100.0 + i;
indicator.HistoricalData.AddBar(now.AddMinutes(i), price, price + 1, price - 1, price);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
for (int i = 0; i < indicator.LinesSeries[0].Count; i++)
{
double value = indicator.LinesSeries[0].GetValue(i);
if (double.IsFinite(value))
{
Assert.InRange(value, -1.0, 1.0);
}
}
}
}
+63
View File
@@ -0,0 +1,63 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class CtiIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 2, 1000, 1, 0)]
public int Period { get; set; } = 20;
[IndicatorExtensions.DataSourceInput(sortIndex: 2)]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Cti _cti = null!;
private readonly LineSeries _series;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"CTI ({Period})";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/cti/Cti.Quantower.cs";
public CtiIndicator()
{
OnBackGround = true;
SeparateWindow = true;
Name = "CTI - Correlation Trend Indicator";
Description = "Pearson correlation between price and a perfect linear time index";
_series = new LineSeries("CTI", Color.Yellow, 2, LineStyle.Solid);
AddLineSeries(_series);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_cti = new Cti(Period);
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);
TValue input = new(item.TimeLeft, price);
TValue result = _cti.Update(input, args.IsNewBar());
if (!_cti.IsHot && !ShowColdValues)
{
return;
}
_series.SetValue(result.Value);
}
}
+450
View File
@@ -0,0 +1,450 @@
using Xunit;
namespace QuanTAlib.Tests;
public sealed class CtiTests
{
private const int DefaultPeriod = 20;
private const double Tolerance = 1e-10;
// ───── A) Constructor validation ─────
[Fact]
public void Constructor_PeriodOne_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Cti(period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodZero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Cti(period: 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_NegativePeriod_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Cti(period: -5));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_ValidPeriod_SetsProperties()
{
var cti = new Cti(period: 10);
Assert.Equal(10, cti.Period);
Assert.Equal("Cti(10)", cti.Name);
Assert.Equal(10, cti.WarmupPeriod);
}
// ───── B) Basic calculation ─────
[Fact]
public void Update_ReturnsTValue()
{
var cti = new Cti(DefaultPeriod);
var result = cti.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.IsType<TValue>(result);
}
[Fact]
public void Update_Last_IsAccessible()
{
var cti = new Cti(DefaultPeriod);
cti.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.NotEqual(default, cti.Last);
Assert.False(cti.IsHot);
Assert.Equal($"Cti({DefaultPeriod})", cti.Name);
}
[Fact]
public void Update_OutputBounded_MinusOneToOne()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.3, seed: 42);
var bars = gbm.Fetch(500, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var cti = new Cti(DefaultPeriod);
foreach (var bar in bars.Close)
{
cti.Update(bar);
if (cti.IsHot)
{
Assert.InRange(cti.Last.Value, -1.0, 1.0);
}
}
}
[Fact]
public void Update_PerfectAscending_CTI_Equals_One()
{
// Perfect arithmetic sequence → perfect positive linear correlation → CTI = 1.0
var cti = new Cti(period: 10);
for (int i = 1; i <= 15; i++)
{
cti.Update(new TValue(DateTime.UtcNow, i * 1.0));
}
Assert.True(cti.IsHot);
Assert.Equal(1.0, cti.Last.Value, 10);
}
[Fact]
public void Update_PerfectDescending_CTI_Equals_MinusOne()
{
// Perfect descending sequence → CTI = -1.0
var cti = new Cti(period: 10);
for (int i = 15; i >= 1; i--)
{
cti.Update(new TValue(DateTime.UtcNow, i * 1.0));
}
Assert.True(cti.IsHot);
Assert.Equal(-1.0, cti.Last.Value, 10);
}
[Fact]
public void Update_ConstantInput_CTI_IsNotNaN()
{
// Constant price → denomY = 0 → ComputePearson returns 0.0, not NaN
var cti = new Cti(period: 5);
for (int i = 0; i < 10; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 50.0));
}
Assert.True(double.IsFinite(cti.Last.Value));
Assert.Equal(0.0, cti.Last.Value, Tolerance);
}
// ───── C) State + bar correction ─────
[Fact]
public void Update_IsNew_True_AdvancesState()
{
var cti = new Cti(DefaultPeriod);
cti.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
cti.Update(new TValue(DateTime.UtcNow, 110.0), isNew: true);
Assert.NotEqual(default, cti.Last);
}
[Fact]
public void Update_IsNew_False_RollsBack()
{
var cti = new Cti(period: 5);
for (int i = 0; i < 6; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
}
// Bar correction: rewrite last bar
cti.Update(new TValue(DateTime.UtcNow, 105.0), isNew: false);
var corrected = cti.Last;
// Same correction again → same result
cti.Update(new TValue(DateTime.UtcNow, 105.0), isNew: false);
var corrected2 = cti.Last;
Assert.Equal(corrected.Value, corrected2.Value, Tolerance);
}
[Fact]
public void Update_IterativeCorrections_Restore()
{
var cti = new Cti(period: 5);
double[] data = [100, 102, 104, 106, 108, 110];
for (int i = 0; i < data.Length; i++)
{
cti.Update(new TValue(DateTime.UtcNow, data[i]), isNew: true);
}
var baseline = cti.Last.Value;
// Apply three corrections, then restore original value
cti.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
cti.Update(new TValue(DateTime.UtcNow, 888.0), isNew: false);
cti.Update(new TValue(DateTime.UtcNow, data[^1]), isNew: false);
Assert.Equal(baseline, cti.Last.Value, Tolerance);
}
[Fact]
public void Reset_ClearsState()
{
var cti = new Cti(DefaultPeriod);
for (int i = 0; i < 25; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
Assert.True(cti.IsHot);
cti.Reset();
Assert.False(cti.IsHot);
Assert.Equal(default, cti.Last);
}
// ───── D) Warmup/convergence ─────
[Fact]
public void IsHot_FlipsAfterPeriodBars()
{
var cti = new Cti(period: 5);
for (int i = 0; i < 4; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 100.0 + i));
Assert.False(cti.IsHot);
}
cti.Update(new TValue(DateTime.UtcNow, 104.0));
Assert.True(cti.IsHot);
}
[Fact]
public void WarmupPeriod_MatchesPeriod()
{
var cti = new Cti(period: 20);
Assert.Equal(20, cti.WarmupPeriod);
}
// ───── E) Robustness ─────
[Fact]
public void Update_NaN_UsesLastValid()
{
var cti = new Cti(period: 5);
for (int i = 0; i < 6; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
_ = cti.Last.Value;
cti.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(cti.Last.Value));
}
[Fact]
public void Update_Infinity_UsesLastValid()
{
var cti = new Cti(period: 5);
for (int i = 0; i < 6; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
cti.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(cti.Last.Value));
cti.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
Assert.True(double.IsFinite(cti.Last.Value));
}
[Fact]
public void Update_BatchNaN_Safe()
{
var cti = new Cti(period: 5);
for (int i = 0; i < 3; i++)
{
cti.Update(new TValue(DateTime.UtcNow, double.NaN));
}
Assert.True(double.IsFinite(cti.Last.Value));
}
// ───── F) Consistency (4 modes match) ─────
[Fact]
public void AllModes_ProduceSameResults()
{
int period = 10;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
var bars = gbm.Fetch(500, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
// 1. Streaming
var streaming = new Cti(period);
var streamResults = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
streamResults[i] = streaming.Update(source[i]).Value;
}
// 2. Batch TSeries
TSeries batchSeries = Cti.Batch(source, period);
// 3. Batch Span
var spanOutput = new double[source.Count];
Cti.Batch(source.Values, spanOutput, period);
// 4. Event-based
var eventSource = new TSeries();
var eventIndicator = new Cti(eventSource, period);
var eventResults = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
eventSource.Add(source[i]);
eventResults[i] = eventIndicator.Last.Value;
}
for (int i = period; i < source.Count; i++)
{
Assert.Equal(streamResults[i], batchSeries.Values[i], Tolerance);
Assert.Equal(streamResults[i], spanOutput[i], Tolerance);
Assert.Equal(streamResults[i], eventResults[i], Tolerance);
}
}
// ───── G) Span API tests ─────
[Fact]
public void Batch_Span_MismatchedLength_ThrowsArgumentException()
{
var source = new double[10];
var output = new double[5];
var ex = Assert.Throws<ArgumentException>(() => Cti.Batch(source.AsSpan(), output.AsSpan(), DefaultPeriod));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_PeriodOne_ThrowsArgumentException()
{
var source = new double[10];
var output = new double[10];
var ex = Assert.Throws<ArgumentException>(() => Cti.Batch(source.AsSpan(), output.AsSpan(), 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_Empty_NoException()
{
double[] source = [];
double[] output = [];
var ex = Record.Exception(() => Cti.Batch(source.AsSpan(), output.AsSpan(), DefaultPeriod));
Assert.Null(ex);
}
[Fact]
public void Batch_Span_MatchesTSeries()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 7);
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
int period = 10;
TSeries batchTs = Cti.Batch(source, period);
var spanOutput = new double[source.Count];
Cti.Batch(source.Values, spanOutput, period);
for (int i = 0; i < source.Count; i++)
{
Assert.Equal(batchTs.Values[i], spanOutput[i], Tolerance);
}
}
[Fact]
public void Batch_Span_NaN_Handled()
{
double[] src = [1, 2, double.NaN, 4, 5, 6, 7, 8, 9, 10];
var output = new double[src.Length];
var ex = Record.Exception(() => Cti.Batch(src.AsSpan(), output.AsSpan(), 5));
Assert.Null(ex);
Assert.True(output.All(double.IsFinite));
}
[Fact]
public void Batch_Span_PerfectAscending_OutputsOne()
{
int period = 5;
double[] src = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var output = new double[src.Length];
Cti.Batch(src.AsSpan(), output.AsSpan(), period);
// After warmup, all values should be 1.0
for (int i = period - 1; i < src.Length; i++)
{
Assert.Equal(1.0, output[i], 10);
}
}
[Fact]
public void Batch_Span_LargeDataset_NoStackOverflow()
{
double[] src = new double[10000];
double[] output = new double[10000];
for (int i = 0; i < src.Length; i++)
{
src[i] = 100.0 + i * 0.01;
}
var ex = Record.Exception(() => Cti.Batch(src.AsSpan(), output.AsSpan(), DefaultPeriod));
Assert.Null(ex);
}
// ───── H) Chainability ─────
[Fact]
public void PubEvent_FiresOnUpdate()
{
var cti = new Cti(DefaultPeriod);
int firedCount = 0;
cti.Pub += (object? _, in TValueEventArgs _) => firedCount++;
cti.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(1, firedCount);
}
[Fact]
public void EventChaining_Works()
{
var source = new TSeries();
var cti = new Cti(source, period: 5);
var downstream = new TSeries();
cti.Pub += (object? _, in TValueEventArgs e) => downstream.Add(e.Value);
for (int i = 0; i < 10; i++)
{
source.Add(new TValue(DateTime.UtcNow, 100.0 + i));
}
Assert.Equal(10, downstream.Count);
}
// ───── Calculate ─────
[Fact]
public void Calculate_ReturnsResultsAndHotIndicator()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
var (results, indicator) = Cti.Calculate(source, period: 5);
Assert.Equal(source.Count, results.Count);
Assert.True(indicator.IsHot);
}
// ───── Update(TSeries) ─────
[Fact]
public void UpdateTSeries_MatchesStreaming()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
int period = 10;
var streaming = new Cti(period);
var streamResults = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
streamResults[i] = streaming.Update(source[i]).Value;
}
var batch = new Cti(period);
TSeries batchResults = batch.Update(source);
for (int i = period; i < source.Count; i++)
{
Assert.Equal(streamResults[i], batchResults.Values[i], Tolerance);
}
}
}
+241
View File
@@ -0,0 +1,241 @@
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public sealed class CtiValidationTests : IDisposable
{
private readonly ValidationTestData _testData;
private readonly ITestOutputHelper _output;
private bool _disposed;
public CtiValidationTests(ITestOutputHelper output)
{
_output = output;
_testData = new ValidationTestData();
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
_testData?.Dispose();
}
}
[Fact]
public void Validate_Streaming_Batch_Span_Agree()
{
int period = 20;
// Streaming
var streaming = new Cti(period);
var streamValues = new List<double>(_testData.Data.Count);
foreach (var item in _testData.Data)
{
streamValues.Add(streaming.Update(item).Value);
}
// Batch (TSeries)
TSeries batchSeries = Cti.Batch(_testData.Data, period);
// Span
double[] src = _testData.RawData.ToArray();
double[] spanOutput = new double[src.Length];
Cti.Batch(src.AsSpan(), spanOutput.AsSpan(), period);
// Batch and span should be identical (same code path through RingBuffer)
// Streaming uses O(1) incremental updates with ResyncInterval=1000
int start = Math.Max(0, src.Length - 200);
for (int i = start; i < src.Length; i++)
{
Assert.Equal(batchSeries[i].Value, spanOutput[i], 12);
Assert.Equal(batchSeries[i].Value, streamValues[i], 4);
}
_output.WriteLine("CTI validation: streaming, batch, and span outputs agree within tolerance.");
}
[Fact]
public void Validate_PerfectCorrelation_Ascending()
{
// Arithmetic sequence: each element is exactly i+1
// Expected: Pearson r = 1.0 exactly (perfect positive linear correlation)
int period = 15;
var cti = new Cti(period);
double lastValue = 0.0;
for (int i = 1; i <= 50; i++)
{
cti.Update(new TValue(DateTime.UtcNow, i * 1.0));
if (cti.IsHot)
{
lastValue = cti.Last.Value;
}
}
Assert.Equal(1.0, lastValue, 10);
_output.WriteLine($"CTI ascending sequence: {lastValue:F15}");
}
[Fact]
public void Validate_PerfectCorrelation_Descending()
{
// Descending arithmetic sequence → perfect negative correlation → CTI = -1.0
int period = 15;
var cti = new Cti(period);
double lastValue = 0.0;
for (int i = 50; i >= 1; i--)
{
cti.Update(new TValue(DateTime.UtcNow, i * 1.0));
if (cti.IsHot)
{
lastValue = cti.Last.Value;
}
}
Assert.Equal(-1.0, lastValue, 10);
_output.WriteLine($"CTI descending sequence: {lastValue:F15}");
}
[Fact]
public void Validate_ConstantInput_ReturnsZero()
{
// Constant price: variance = 0 → denomY = 0 → return 0
int period = 10;
var cti = new Cti(period);
for (int i = 0; i < 30; i++)
{
cti.Update(new TValue(DateTime.UtcNow, 100.0));
}
Assert.True(cti.IsHot);
Assert.Equal(0.0, cti.Last.Value, 10);
}
[Fact]
public void Validate_Output_AlwaysBounded()
{
// With random GBM data, output must stay in [-1, +1]
var gbm = new GBM(startPrice: 100.0, mu: 0.0, sigma: 0.5, seed: 999);
var bars = gbm.Fetch(2000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
foreach (int period in new[] { 5, 10, 20, 50, 100 })
{
TSeries batch = Cti.Batch(bars.Close, period);
foreach (var tv in batch)
{
Assert.InRange(tv.Value, -1.0, 1.0);
}
}
}
[Fact]
public void Validate_Batch_Calculate_Agree()
{
int period = 14;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.2, seed: 77);
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
TSeries batchResult = Cti.Batch(source, period);
var (calcResult, _) = Cti.Calculate(source, period);
for (int i = period; i < source.Count; i++)
{
Assert.Equal(batchResult[i].Value, calcResult[i].Value, 10);
}
}
[Fact]
public void Validate_BarCorrection_Consistency()
{
// After bar correction restores original value, result must equal baseline
int period = 10;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 31);
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
var cti = new Cti(period);
for (int i = 0; i < source.Count - 1; i++)
{
cti.Update(source[i], isNew: true);
}
// Final bar
cti.Update(source[^1], isNew: true);
double baseline = cti.Last.Value;
// Correct and revert
cti.Update(new TValue(source[^1].Time, 99999.0), isNew: false);
cti.Update(new TValue(source[^1].Time, source[^1].Value), isNew: false);
Assert.Equal(baseline, cti.Last.Value, 7);
}
[Fact]
public void Validate_DifferentPeriods_Produce_Different_Results()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.2, seed: 55);
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
TSeries r5 = Cti.Batch(source, 5);
TSeries r20 = Cti.Batch(source, 20);
TSeries r50 = Cti.Batch(source, 50);
// Different periods should generally not produce identical results
double sum5 = 0, sum20 = 0, sum50 = 0;
for (int i = 50; i < source.Count; i++)
{
sum5 += r5[i].Value;
sum20 += r20[i].Value;
sum50 += r50[i].Value;
}
// Sums at different periods should differ
Assert.NotEqual(sum5, sum20);
Assert.NotEqual(sum20, sum50);
}
[Fact]
public void Validate_Reset_Reprocess_Deterministic()
{
int period = 15;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.2, seed: 13);
var bars = gbm.Fetch(100, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
TSeries source = bars.Close;
var cti = new Cti(period);
double[] first = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
first[i] = cti.Update(source[i]).Value;
}
cti.Reset();
double[] second = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
second[i] = cti.Update(source[i]).Value;
}
for (int i = 0; i < source.Count; i++)
{
Assert.Equal(first[i], second[i], 15);
}
}
}
+340
View File
@@ -0,0 +1,340 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// CTI: Correlation Trend Indicator (Ehlers, TASC 2020)
/// </summary>
/// <remarks>
/// Measures the Pearson correlation coefficient between the price series and a
/// perfect linear time index over a rolling window. Output is bounded [-1, +1]:
/// +1 = perfect uptrend, -1 = perfect downtrend, 0 = no linear trend.
///
/// Uses O(1) incremental running sums: ΣY, ΣY², ΣXY. The X-side sums (ΣX, ΣX²)
/// are analytical closed-form functions of n and never need maintenance.
///
/// Incremental ΣXY trick (same as CFO):
/// When the window slides forward one bar:
/// ΣXY -= ΣY_before_removal (shifts all position indices down by 1)
/// ΣXY += (n-1) × y_new (new value enters at highest position)
///
/// References:
/// Ehlers, J.F. (2001). Rocket Science for Traders. Wiley
/// PineScript reference: cti.pine
/// </remarks>
[SkipLocalsInit]
public sealed class Cti : AbstractBase
{
private readonly int _period;
private readonly RingBuffer _buffer;
// Precomputed X-side constants (full-window)
private readonly double _sx; // period*(period-1)/2
private readonly double _sxx; // period*(period-1)*(2*period-1)/6
private readonly double _denomX; // period*sxx - sx*sx (constant, never changes)
[StructLayout(LayoutKind.Auto)]
private record struct State(
double SumY,
double SumY2,
double SumXY,
int Count,
double LastValid);
private State _s, _ps;
private const int ResyncInterval = 1000;
private int _tickCount;
/// <summary>
/// Creates CTI with the specified lookback period.
/// </summary>
/// <param name="period">Rolling window length (must be ≥ 2)</param>
public Cti(int period = 20)
{
if (period < 2)
{
throw new ArgumentException("Period must be greater than or equal to 2", nameof(period));
}
_period = period;
_buffer = new RingBuffer(period);
Name = $"Cti({period})";
WarmupPeriod = period;
_sx = period * (period - 1) / 2.0;
_sxx = period * (period - 1.0) * (2 * period - 1) / 6.0;
_denomX = Math.FusedMultiplyAdd(period, _sxx, -_sx * _sx);
}
/// <summary>
/// Creates CTI subscribed to an upstream publisher.
/// </summary>
public Cti(ITValuePublisher source, int period = 20) : this(period)
{
source.Pub += Handle;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
/// <inheritdoc/>
public override bool IsHot => _buffer.IsFull;
/// <summary>Period of the indicator.</summary>
public int Period => _period;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
double value = input.Value;
// Sanitize input — substitute last-valid on NaN/Infinity
if (!double.IsFinite(value))
{
value = double.IsFinite(_s.LastValid) ? _s.LastValid : 0.0;
}
else
{
_s.LastValid = value;
}
if (isNew)
{
_ps = _s;
if (_buffer.Count == _buffer.Capacity)
{
// Full window: O(1) incremental update
double oldest = _buffer.Oldest;
_s.SumY -= oldest;
_s.SumY2 -= oldest * oldest;
_s.SumXY -= _s.SumY; // shift all indices down by 1
_s.SumXY += (_period - 1) * value; // new value at position (n-1)
}
else
{
// Growing window during warmup
_s.SumXY += _s.Count * value;
_s.Count++;
}
_s.SumY += value;
_s.SumY2 = Math.FusedMultiplyAdd(value, value, _s.SumY2);
_buffer.Add(value);
_tickCount++;
if (_buffer.IsFull && _tickCount >= ResyncInterval)
{
_tickCount = 0;
Resync();
}
}
else
{
_s = _ps;
_buffer.UpdateNewest(value);
Resync();
}
if (!_buffer.IsFull)
{
Last = new TValue(input.Time, 0.0);
PubEvent(Last, isNew);
return Last;
}
double cti = ComputePearson(_s.SumY, _s.SumY2, _s.SumXY, _period, _sx, _sxx, _denomX);
Last = new TValue(input.Time, cti);
PubEvent(Last, isNew);
return Last;
}
/// <inheritdoc/>
public override 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);
Batch(source.Values, vSpan, _period);
source.Times.CopyTo(tSpan);
// Replay to sync internal state
for (int i = 0; i < len; i++)
{
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
}
return new TSeries(t, v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double ComputePearson(
double sumY, double sumY2, double sumXY,
double n, double sx, double sxx, double denomX)
{
double denomY = Math.FusedMultiplyAdd(n, sumY2, -sumY * sumY);
double denom = denomX * denomY;
if (denom <= 0.0)
{
return 0.0;
}
double numer = Math.FusedMultiplyAdd(n, sumXY, -sx * sumY);
return Math.Clamp(numer / Math.Sqrt(denom), -1.0, 1.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Resync()
{
_s.SumY = 0.0;
_s.SumY2 = 0.0;
_s.SumXY = 0.0;
_s.Count = _buffer.Count;
for (int i = 0; i < _buffer.Count; i++)
{
double v = _buffer[i];
_s.SumY += v;
_s.SumY2 = Math.FusedMultiplyAdd(v, v, _s.SumY2);
_s.SumXY = Math.FusedMultiplyAdd(i, v, _s.SumXY);
}
}
/// <inheritdoc/>
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
for (int i = 0; i < source.Length; i++)
{
Update(new TValue(DateTime.UtcNow, source[i]), isNew: true);
}
}
/// <inheritdoc/>
public override void Reset()
{
_buffer.Clear();
_s = default;
_ps = default;
_tickCount = 0;
Last = default;
}
/// <summary>Calculates CTI for an entire TSeries.</summary>
public static TSeries Batch(TSeries source, int period = 20)
{
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
Batch(source.Values, vSpan, period);
source.Times.CopyTo(tSpan);
return new TSeries(t, v);
}
/// <summary>
/// Batch CTI calculation using O(1) incremental Pearson correlation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 20)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (period < 2)
{
throw new ArgumentException("Period must be greater than or equal to 2", nameof(period));
}
int len = source.Length;
if (len == 0)
{
return;
}
double sx = period * (period - 1) / 2.0;
double sxx = period * (period - 1.0) * (2 * period - 1) / 6.0;
double denomX = Math.FusedMultiplyAdd(period, sxx, -sx * sx);
double sumY = 0.0;
double sumY2 = 0.0;
double sumXY = 0.0;
int count = 0;
double lastValid = 0.0;
var buf = new RingBuffer(period);
for (int i = 0; i < len; i++)
{
double val = source[i];
if (!double.IsFinite(val))
{
val = lastValid;
}
else
{
lastValid = val;
}
if (buf.Count == buf.Capacity)
{
double oldest = buf.Oldest;
sumY -= oldest;
sumY2 -= oldest * oldest;
sumXY -= sumY;
sumXY += (period - 1) * val;
}
else
{
sumXY += count * val;
count++;
}
sumY += val;
sumY2 = Math.FusedMultiplyAdd(val, val, sumY2);
buf.Add(val);
if (count < period)
{
output[i] = 0.0;
continue;
}
double denomY = Math.FusedMultiplyAdd(period, sumY2, -sumY * sumY);
double denom = denomX * denomY;
if (denom <= 0.0)
{
output[i] = 0.0;
continue;
}
double numer = Math.FusedMultiplyAdd(period, sumXY, -sx * sumY);
output[i] = Math.Clamp(numer / Math.Sqrt(denom), -1.0, 1.0);
}
}
/// <summary>Calculates CTI and returns both the series and the live indicator.</summary>
public static (TSeries Results, Cti Indicator) Calculate(TSeries source, int period = 20)
{
var indicator = new Cti(period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
}