docs: remove C# Implementation Considerations sections, clean up temp scripts, reorganize test files

- Remove 'C# Implementation Considerations' sections from 34 indicator .md files
- Delete 29 temp PowerShell scripts (_fix_mojibake.ps1, _hex_scan.ps1, etc.)
- Move test files into tests/ subdirectories for consistent project structure
- Add trader-focused bullet points to indicator documentation
This commit is contained in:
Miha Kralj
2026-03-12 12:34:16 -07:00
parent 8937b0c0fa
commit 060649192f
1149 changed files with 1780 additions and 3316 deletions
@@ -0,0 +1,111 @@
using TradingPlatform.BusinessLayer;
using QuanTAlib;
namespace QuanTAlib.Tests;
public sealed class CfoIndicatorTests
{
[Fact]
public void CfoIndicator_Constructor_SetsDefaults()
{
var indicator = new CfoIndicator();
Assert.Equal(14, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("CFO - Chande Forecast Oscillator", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void CfoIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new CfoIndicator { Period = 14 };
Assert.Equal(0, CfoIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void CfoIndicator_ShortName_IncludesParameters()
{
var indicator = new CfoIndicator { Period = 20 };
indicator.Initialize();
Assert.Contains("CFO", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("20", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void CfoIndicator_SourceCodeLink_IsValid()
{
var indicator = new CfoIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Cfo.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void CfoIndicator_Initialize_CreatesInternalCfo()
{
var indicator = new CfoIndicator { Period = 10 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void CfoIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new CfoIndicator { 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 CfoIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new CfoIndicator { 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 CfoIndicator_Parameters_CanBeChanged()
{
var indicator = new CfoIndicator { Period = 14 };
indicator.Period = 20;
indicator.Source = SourceType.Open;
Assert.Equal(20, indicator.Period);
Assert.Equal(SourceType.Open, indicator.Source);
Assert.Equal(0, CfoIndicator.MinHistoryDepths);
}
}
+384
View File
@@ -0,0 +1,384 @@
using Xunit;
namespace QuanTAlib.Tests;
public sealed class CfoTests
{
private const int DefaultPeriod = 14;
private const double Tolerance = 1e-10;
// ───── A) Constructor validation ─────
[Fact]
public void Constructor_PeriodZero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Cfo(period: 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_NegativePeriod_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Cfo(period: -1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_ValidPeriod_SetsProperties()
{
var cfo = new Cfo(period: 10);
Assert.Equal(10, cfo.Period);
Assert.Equal("Cfo(10)", cfo.Name);
Assert.Equal(10, cfo.WarmupPeriod);
}
// ───── B) Basic calculation ─────
[Fact]
public void Update_ReturnsTValue()
{
var cfo = new Cfo(DefaultPeriod);
var result = cfo.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.IsType<TValue>(result);
}
[Fact]
public void Update_Last_IsAccessible()
{
var cfo = new Cfo(DefaultPeriod);
cfo.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.NotEqual(default, cfo.Last);
Assert.False(cfo.IsHot);
Assert.Equal($"Cfo({DefaultPeriod})", cfo.Name);
}
[Fact]
public void Update_ConstantInput_ZeroCfo()
{
var cfo = new Cfo(period: 5);
for (int i = 0; i < 10; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 50.0));
}
// Constant input => TSF == source => CFO == 0
Assert.Equal(0.0, cfo.Last.Value, Tolerance);
}
// ───── C) State + bar correction ─────
[Fact]
public void Update_IsNew_True_AdvancesState()
{
var cfo = new Cfo(DefaultPeriod);
cfo.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
cfo.Update(new TValue(DateTime.UtcNow, 110.0), isNew: true);
var last = cfo.Last;
// Should have two distinct updates
Assert.NotEqual(default, last);
}
[Fact]
public void Update_IsNew_False_RollsBack()
{
var cfo = new Cfo(period: 5);
for (int i = 0; i < 6; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
}
// Bar correction: rewrite last bar
cfo.Update(new TValue(DateTime.UtcNow, 105.0), isNew: false);
var corrected = cfo.Last;
// Repeat same correction — should produce identical result
cfo.Update(new TValue(DateTime.UtcNow, 105.0), isNew: false);
var corrected2 = cfo.Last;
Assert.Equal(corrected.Value, corrected2.Value, Tolerance);
}
[Fact]
public void Update_IterativeCorrections_Restore()
{
var cfo = new Cfo(period: 5);
double[] data = [100, 102, 104, 106, 108, 110];
for (int i = 0; i < data.Length; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, data[i]), isNew: true);
}
var baseline = cfo.Last.Value;
// Correct last bar 3 times, then restore original
cfo.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
cfo.Update(new TValue(DateTime.UtcNow, 888.0), isNew: false);
cfo.Update(new TValue(DateTime.UtcNow, data[^1]), isNew: false);
Assert.Equal(baseline, cfo.Last.Value, Tolerance);
}
[Fact]
public void Reset_ClearsState()
{
var cfo = new Cfo(DefaultPeriod);
for (int i = 0; i < 20; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
Assert.True(cfo.IsHot);
cfo.Reset();
Assert.False(cfo.IsHot);
Assert.Equal(default, cfo.Last);
}
// ───── D) Warmup / convergence ─────
[Fact]
public void IsHot_FlipsWhenBufferFull()
{
var cfo = new Cfo(period: 5);
for (int i = 0; i < 4; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 100.0 + i));
Assert.False(cfo.IsHot);
}
cfo.Update(new TValue(DateTime.UtcNow, 104.0));
Assert.True(cfo.IsHot);
}
[Fact]
public void WarmupPeriod_MatchesPeriod()
{
var cfo = new Cfo(period: 20);
Assert.Equal(20, cfo.WarmupPeriod);
}
// ───── E) Robustness ─────
[Fact]
public void Update_NaN_UsesLastValid()
{
var cfo = new Cfo(period: 5);
for (int i = 0; i < 6; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
cfo.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(cfo.Last.Value));
}
[Fact]
public void Update_Infinity_UsesLastValid()
{
var cfo = new Cfo(period: 5);
for (int i = 0; i < 6; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
cfo.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(cfo.Last.Value));
cfo.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
Assert.True(double.IsFinite(cfo.Last.Value));
}
[Fact]
public void Update_BatchNaN_Safe()
{
var cfo = new Cfo(period: 5);
for (int i = 0; i < 3; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, double.NaN));
}
// No exception thrown; result should be finite (falls back to 0.0)
Assert.True(double.IsFinite(cfo.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 Cfo(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 = Cfo.Batch(source, period);
// 3. Batch Span
var spanOutput = new double[source.Count];
Cfo.Batch(source.Values, spanOutput, period);
// 4. Event-based
var eventSource = new TSeries();
var eventIndicator = new Cfo(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;
}
// Compare all modes
for (int i = 0; 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>(() => Cfo.Batch(source.AsSpan(), output.AsSpan(), DefaultPeriod));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_ZeroPeriod_ThrowsArgumentException()
{
var source = new double[10];
var output = new double[10];
var ex = Assert.Throws<ArgumentException>(() => Cfo.Batch(source.AsSpan(), output.AsSpan(), 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_Empty_NoException()
{
double[] source = [];
double[] output = [];
var ex = Record.Exception(() => Cfo.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 = Cfo.Batch(source, period);
var spanOutput = new double[source.Count];
Cfo.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(() => Cfo.Batch(src.AsSpan(), output.AsSpan(), 5));
Assert.Null(ex);
}
// ───── H) Chainability ─────
[Fact]
public void PubEvent_FiresOnUpdate()
{
var cfo = new Cfo(DefaultPeriod);
int firedCount = 0;
cfo.Pub += (object? _, in TValueEventArgs _) => firedCount++;
cfo.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(1, firedCount);
}
[Fact]
public void EventChaining_Works()
{
var source = new TSeries();
var cfo = new Cfo(source, period: 5);
var downstream = new TSeries();
cfo.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) = Cfo.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 Cfo(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 Cfo(period);
TSeries batchResults = batch.Update(source);
for (int i = 0; i < source.Count; i++)
{
Assert.Equal(streamResults[i], batchResults.Values[i], Tolerance);
}
}
// ───── Division by zero ─────
[Fact]
public void Update_ZeroSource_ReturnsNaN()
{
var cfo = new Cfo(period: 3);
for (int i = 0; i < 3; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 0.0));
}
Assert.True(double.IsNaN(cfo.Last.Value));
}
}
@@ -0,0 +1,158 @@
using Skender.Stock.Indicators;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public sealed class CfoValidationTests : IDisposable
{
private readonly ValidationTestData _testData;
private readonly ITestOutputHelper _output;
private bool _disposed;
public CfoValidationTests(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 = 14;
// Streaming
var streaming = new Cfo(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 = Cfo.Batch(_testData.Data, period);
// Span
double[] src = _testData.RawData.ToArray();
double[] spanOutput = new double[src.Length];
Cfo.Batch(src.AsSpan(), spanOutput.AsSpan(), period);
// O(1) streaming sumXY maintenance accumulates cancellation drift vs full-recalc batch.
// ResyncInterval=1000 bounds drift, but between resyncs tolerance must be relaxed.
// Batch vs span should match exactly (same code path).
int start = Math.Max(0, src.Length - 200);
for (int i = start; i < src.Length; i++)
{
Assert.Equal(batchSeries[i].Value, spanOutput[i], 12); // batch≡span (same path)
Assert.Equal(batchSeries[i].Value, streamValues[i], 4); // streaming drifts ~1e-5 between resyncs
}
_output.WriteLine("CFO validation: streaming, batch, and span outputs agree within tolerance.");
}
[Fact]
public void Validate_Against_LinReg()
{
// Cross-validate CFO against our own LinReg class.
// LinReg.Last.Value = intercept = regression value at x=0 (current bar) = TSF.
// CFO = 100 * (source - TSF) / source.
int[] periods = [5, 10, 14, 20, 50];
foreach (int period in periods)
{
var cfo = new Cfo(period);
var linreg = new LinReg(period);
int validCount = 0;
foreach (var item in _testData.Data)
{
cfo.Update(item);
linreg.Update(item);
if (!cfo.IsHot || !linreg.IsHot)
{
continue;
}
double src = item.Value;
if (src == 0.0)
{
continue;
}
double tsf = linreg.Last.Value; // intercept = regression at current bar
double expectedCfo = 100.0 * (src - tsf) / src;
double actualCfo = cfo.Last.Value;
// skipcq: CS-R1140 - Absolute tolerance needed: two independent O(1) streaming implementations accumulate floating-point drift
Assert.True(Math.Abs(expectedCfo - actualCfo) < 1e-6,
$"CFO mismatch at period={period}: expected={expectedCfo}, actual={actualCfo}, diff={Math.Abs(expectedCfo - actualCfo)}");
validCount++;
}
Assert.True(validCount > 0, $"No valid comparison points for period {period}");
_output.WriteLine($"CFO period={period}: validated {validCount} points against LinReg.");
}
}
[Fact]
public void Validate_KnownValues_LinearTrend()
{
// For a perfect linear trend y = a + b*x, the regression line exactly fits.
// TSF should equal the source value, so CFO should be 0.
int period = 5;
var cfo = new Cfo(period);
// Feed a perfect linear trend: 10, 11, 12, 13, 14, 15, ...
for (int i = 0; i < 20; i++)
{
cfo.Update(new TValue(DateTime.UtcNow, 10.0 + i));
}
// After warmup, CFO should be ~0 for a perfect linear trend
Assert.Equal(0.0, cfo.Last.Value, 10);
_output.WriteLine("CFO known-values: perfect linear trend produces CFO=0.");
}
[Fact]
public void Validate_MultiPeriod_Consistency()
{
// Different periods should produce different results
int[] periods = [5, 14, 50];
var results = new List<TSeries>();
foreach (int period in periods)
{
results.Add(Cfo.Batch(_testData.Data, period));
}
// After all warmups, values should differ for different periods
int checkIdx = 100;
for (int i = 0; i < results.Count - 1; i++)
{
Assert.NotEqual(results[i][checkIdx].Value, results[i + 1][checkIdx].Value);
}
_output.WriteLine("CFO multi-period: different periods produce different results.");
}
}