mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-25 13:58:04 +00:00
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:
@@ -0,0 +1,159 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class TsfIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void TsfIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new TsfIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("TSF - Time Series Forecast", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_MinHistoryDepths_IsZero()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, TsfIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 15 };
|
||||
|
||||
Assert.Contains("TSF", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new TsfIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Tsf.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_Initialize_CreatesInternalTsf()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 10 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
|
||||
Assert.Equal(1, indicator.LinesSeries[0].Count);
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries[0].Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
double firstValue = indicator.LinesSeries[0].GetValue(0);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
|
||||
double secondValue = indicator.LinesSeries[0].GetValue(0);
|
||||
|
||||
Assert.True(double.IsFinite(firstValue));
|
||||
Assert.True(double.IsFinite(secondValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_MultipleUpdates_ProducesCorrectSequence()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
double[] closes = { 100, 102, 104, 103, 105 };
|
||||
|
||||
foreach (var close in closes)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now, close, close + 2, close - 2, close);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
now = now.AddMinutes(1);
|
||||
}
|
||||
|
||||
for (int i = 0; i < closes.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(closes.Length - 1 - i)));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_DifferentSourceTypes_Work()
|
||||
{
|
||||
var sources = new[] { SourceType.Open, SourceType.High, SourceType.Low, SourceType.Close, SourceType.HL2, SourceType.HLC3 };
|
||||
|
||||
foreach (var source in sources)
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 3, Source = source };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 110, 90, 105);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)),
|
||||
$"Source {source} should produce finite value");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TsfIndicator_Period_CanBeChanged()
|
||||
{
|
||||
var indicator = new TsfIndicator { Period = 5 };
|
||||
Assert.Equal(5, indicator.Period);
|
||||
|
||||
indicator.Period = 20;
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(0, TsfIndicator.MinHistoryDepths);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class TsfTests
|
||||
{
|
||||
private static TSeries MakeSeries(int count = 500)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
|
||||
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1)).Close;
|
||||
}
|
||||
|
||||
// ── A) Constructor validation ──────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidPeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex0 = Assert.Throws<ArgumentException>(() => new Tsf(0));
|
||||
Assert.Equal("period", ex0.ParamName);
|
||||
|
||||
var exNeg = Assert.Throws<ArgumentException>(() => new Tsf(-1));
|
||||
Assert.Equal("period", exNeg.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidParameters_SetsProperties()
|
||||
{
|
||||
var tsf = new Tsf(14);
|
||||
Assert.Equal("Tsf(14)", tsf.Name);
|
||||
Assert.False(tsf.IsHot);
|
||||
Assert.Equal(14, tsf.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NullSource_ThrowsArgumentNullException()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() => new Tsf(null!, 14));
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ───────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_SingleValue_ReturnsSameValue()
|
||||
{
|
||||
var tsf = new Tsf(14);
|
||||
var result = tsf.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(100, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Last_IsAccessible()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
var series = MakeSeries(20);
|
||||
foreach (var item in series)
|
||||
{
|
||||
tsf.Update(item);
|
||||
}
|
||||
Assert.True(double.IsFinite(tsf.Last.Value));
|
||||
Assert.True(tsf.IsHot);
|
||||
Assert.Contains("Tsf", tsf.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_LinearTrend_ReturnsNextValue()
|
||||
{
|
||||
// For a perfect linear trend y = x,
|
||||
// TSF should return x+1 (one step forecast) after warmup
|
||||
const int period = 10;
|
||||
var tsf = new Tsf(period);
|
||||
|
||||
for (int i = 0; i < period * 2; i++)
|
||||
{
|
||||
var result = tsf.Update(new TValue(DateTime.UtcNow, i));
|
||||
if (i >= period)
|
||||
{
|
||||
// TSF forecasts one step ahead: should be i+1
|
||||
Assert.Equal(i + 1, result.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_ConstantValue_ReturnsSameValue()
|
||||
{
|
||||
const int period = 10;
|
||||
var tsf = new Tsf(period);
|
||||
const double value = 123.45;
|
||||
|
||||
for (int i = 0; i < period * 2; i++)
|
||||
{
|
||||
var result = tsf.Update(new TValue(DateTime.UtcNow, value));
|
||||
Assert.Equal(value, result.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_LinearSlope_ForecastsCorrectly()
|
||||
{
|
||||
// y = 2x + 5
|
||||
// At bar i, the next bar's value should be 2*(i+1) + 5
|
||||
const int period = 8;
|
||||
var tsf = new Tsf(period);
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
double y = 2.0 * i + 5.0;
|
||||
var result = tsf.Update(new TValue(DateTime.UtcNow, y));
|
||||
|
||||
if (i >= period)
|
||||
{
|
||||
double expected = 2.0 * (i + 1) + 5.0;
|
||||
Assert.Equal(expected, result.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ──────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Calc_IsNew_AcceptsParameter()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
var result = tsf.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calc_IsNew_False_UpdatesValue()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
var series = MakeSeries(20);
|
||||
|
||||
foreach (var item in series)
|
||||
{
|
||||
tsf.Update(item, isNew: true);
|
||||
}
|
||||
|
||||
double valueBefore = tsf.Last.Value;
|
||||
tsf.Update(new TValue(DateTime.UtcNow, series[^1].Value * 1.1), isNew: false);
|
||||
double valueAfter = tsf.Last.Value;
|
||||
|
||||
Assert.NotEqual(valueBefore, valueAfter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_RestoreToOriginalState()
|
||||
{
|
||||
var tsf = new Tsf(10);
|
||||
var series = MakeSeries(50);
|
||||
|
||||
// Feed N values
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
tsf.Update(series[i], isNew: true);
|
||||
}
|
||||
double expectedValue = tsf.Last.Value;
|
||||
|
||||
// Feed M corrections with isNew: false
|
||||
for (int j = 0; j < 5; j++)
|
||||
{
|
||||
tsf.Update(new TValue(DateTime.UtcNow, 999.0 + j), isNew: false);
|
||||
}
|
||||
|
||||
// Restore original value
|
||||
tsf.Update(series[29], isNew: false);
|
||||
Assert.Equal(expectedValue, tsf.Last.Value, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var tsf = new Tsf(10);
|
||||
var series = MakeSeries(50);
|
||||
foreach (var item in series)
|
||||
{
|
||||
tsf.Update(item);
|
||||
}
|
||||
|
||||
Assert.True(tsf.IsHot);
|
||||
tsf.Reset();
|
||||
Assert.False(tsf.IsHot);
|
||||
|
||||
// Re-feed same data should produce identical results
|
||||
var tsf2 = new Tsf(10);
|
||||
foreach (var item in series)
|
||||
{
|
||||
tsf.Update(item);
|
||||
tsf2.Update(item);
|
||||
}
|
||||
Assert.Equal(tsf2.Last.Value, tsf.Last.Value, 1e-12);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ──────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_BecomesTrueWhenBufferFull()
|
||||
{
|
||||
var tsf = new Tsf(10);
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
tsf.Update(new TValue(DateTime.UtcNow, i));
|
||||
Assert.False(tsf.IsHot);
|
||||
}
|
||||
tsf.Update(new TValue(DateTime.UtcNow, 9));
|
||||
Assert.True(tsf.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_IsPeriodDependent()
|
||||
{
|
||||
foreach (int period in new[] { 5, 10, 20, 50 })
|
||||
{
|
||||
var tsf = new Tsf(period);
|
||||
for (int i = 0; i < period - 1; i++)
|
||||
{
|
||||
tsf.Update(new TValue(DateTime.UtcNow, i));
|
||||
Assert.False(tsf.IsHot);
|
||||
}
|
||||
tsf.Update(new TValue(DateTime.UtcNow, period - 1));
|
||||
Assert.True(tsf.IsHot);
|
||||
}
|
||||
}
|
||||
|
||||
// ── E) Robustness (NaN/Infinity) ───────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
var series = MakeSeries(20);
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
tsf.Update(series[i]);
|
||||
}
|
||||
|
||||
_ = tsf.Last.Value;
|
||||
tsf.Update(new TValue(DateTime.UtcNow, double.NaN), isNew: true);
|
||||
Assert.True(double.IsFinite(tsf.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_Input_UsesLastValidValue()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
var series = MakeSeries(20);
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
tsf.Update(series[i]);
|
||||
}
|
||||
|
||||
tsf.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity), isNew: true);
|
||||
Assert.True(double.IsFinite(tsf.Last.Value));
|
||||
|
||||
tsf.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity), isNew: true);
|
||||
Assert.True(double.IsFinite(tsf.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MultipleNaN_ContinuesWithLastValid()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
var series = MakeSeries(20);
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
tsf.Update(series[i]);
|
||||
}
|
||||
|
||||
for (int j = 0; j < 5; j++)
|
||||
{
|
||||
tsf.Update(new TValue(DateTime.UtcNow, double.NaN), isNew: true);
|
||||
Assert.True(double.IsFinite(tsf.Last.Value));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchCalc_HandlesNaN()
|
||||
{
|
||||
double[] input = { 1, 2, 3, double.NaN, 5, 6, 7, 8, 9, 10 };
|
||||
double[] output = new double[input.Length];
|
||||
Tsf.Batch(input.AsSpan(), output.AsSpan(), 5);
|
||||
|
||||
for (int i = 0; i < output.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(output[i]));
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency (all 4 modes match) ─────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ProduceSameResult()
|
||||
{
|
||||
int period = 14;
|
||||
var series = MakeSeries(500);
|
||||
|
||||
// 1. Batch (TSeries)
|
||||
var batchResult = Tsf.Batch(series, period);
|
||||
|
||||
// 2. Span
|
||||
double[] spanOutput = new double[series.Count];
|
||||
Tsf.Batch(series.Values, spanOutput.AsSpan(), period);
|
||||
|
||||
// 3. Streaming
|
||||
var streamTsf = new Tsf(period);
|
||||
var streamResults = new List<double>();
|
||||
foreach (var item in series)
|
||||
{
|
||||
streamResults.Add(streamTsf.Update(item).Value);
|
||||
}
|
||||
|
||||
// 4. Eventing
|
||||
var pubSource = new TSeries();
|
||||
var eventTsf = new Tsf(pubSource, period);
|
||||
foreach (var item in series)
|
||||
{
|
||||
pubSource.Add(item);
|
||||
}
|
||||
|
||||
// Compare last values
|
||||
double batchLast = batchResult.Values[^1];
|
||||
double spanLast = spanOutput[^1];
|
||||
double streamLast = streamResults[^1];
|
||||
double eventLast = eventTsf.Last.Value;
|
||||
|
||||
Assert.Equal(batchLast, spanLast, 1e-9);
|
||||
Assert.Equal(batchLast, streamLast, 1e-9);
|
||||
Assert.Equal(batchLast, eventLast, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchCalc_MatchesIterativeCalc()
|
||||
{
|
||||
int period = 10;
|
||||
var series = MakeSeries(200);
|
||||
|
||||
// Batch
|
||||
var batchResult = Tsf.Batch(series, period);
|
||||
|
||||
// Iterative
|
||||
var tsf = new Tsf(period);
|
||||
TSeries streamResult = tsf.Update(series);
|
||||
|
||||
int compareCount = Math.Min(100, series.Count);
|
||||
int start = series.Count - compareCount;
|
||||
|
||||
for (int i = start; i < series.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchResult.Values[i], streamResult.Values[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
// ── G) Span API tests ──────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void SpanCalc_ValidatesInput_LengthMismatch()
|
||||
{
|
||||
double[] input = { 1, 2, 3, 4, 5 };
|
||||
double[] output = new double[3];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Tsf.Batch(input.AsSpan(), output.AsSpan(), 3));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanCalc_ValidatesInput_InvalidPeriod()
|
||||
{
|
||||
double[] input = { 1, 2, 3, 4, 5 };
|
||||
double[] output = new double[5];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Tsf.Batch(input.AsSpan(), output.AsSpan(), 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanCalc_MatchesTSeriesCalc()
|
||||
{
|
||||
int period = 20;
|
||||
var series = MakeSeries(500);
|
||||
|
||||
var batchResult = Tsf.Batch(series, period);
|
||||
double[] spanOutput = new double[series.Count];
|
||||
Tsf.Batch(series.Values, spanOutput.AsSpan(), period);
|
||||
|
||||
int compareCount = 100;
|
||||
int start = series.Count - compareCount;
|
||||
for (int i = start; i < series.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchResult.Values[i], spanOutput[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanCalc_EmptyInput_NoException()
|
||||
{
|
||||
double[] input = Array.Empty<double>();
|
||||
double[] output = Array.Empty<double>();
|
||||
Tsf.Batch(input.AsSpan(), output.AsSpan(), 5);
|
||||
Assert.Empty(output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanCalc_LargeDataset_NoStackOverflow()
|
||||
{
|
||||
int size = 10_000;
|
||||
double[] input = new double[size];
|
||||
double[] output = new double[size];
|
||||
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 99);
|
||||
var series = gbm.Fetch(size, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1)).Close;
|
||||
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
input[i] = series.Values[i];
|
||||
}
|
||||
|
||||
Tsf.Batch(input.AsSpan(), output.AsSpan(), 300);
|
||||
|
||||
Assert.True(double.IsFinite(output[^1]));
|
||||
}
|
||||
|
||||
// ── H) Chainability ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var tsf = new Tsf(5);
|
||||
int fireCount = 0;
|
||||
tsf.Pub += (object? _, in TValueEventArgs _) => fireCount++;
|
||||
|
||||
var series = MakeSeries(20);
|
||||
foreach (var item in series)
|
||||
{
|
||||
tsf.Update(item);
|
||||
}
|
||||
|
||||
Assert.Equal(series.Count, fireCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventChaining_Works()
|
||||
{
|
||||
int period = 5;
|
||||
var source = new TSeries();
|
||||
var tsf = new Tsf(source, period);
|
||||
|
||||
var series = MakeSeries(50);
|
||||
foreach (var item in series)
|
||||
{
|
||||
source.Add(item);
|
||||
}
|
||||
|
||||
Assert.True(tsf.IsHot);
|
||||
Assert.True(double.IsFinite(tsf.Last.Value));
|
||||
}
|
||||
|
||||
// ── TSF-specific tests ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void TSF_EqualsLSMA_PlusSlope()
|
||||
{
|
||||
// TSF = LSMA(offset=0) + slope
|
||||
// Which is the same as LSMA(offset=1)?
|
||||
// Yes: LSMA uses result = b - m * offset
|
||||
// LSMA(offset=1) = b - m*1 = b - m = TSF
|
||||
const int period = 14;
|
||||
var series = MakeSeries(500);
|
||||
|
||||
var lsma = new Lsma(period, offset: 1);
|
||||
var tsf = new Tsf(period);
|
||||
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
var lsmaResult = lsma.Update(series[i]);
|
||||
var tsfResult = tsf.Update(series[i]);
|
||||
|
||||
Assert.Equal(lsmaResult.Value, tsfResult.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsBothResultsAndIndicator()
|
||||
{
|
||||
var series = MakeSeries(100);
|
||||
var (results, indicator) = Tsf.Calculate(series, 10);
|
||||
|
||||
Assert.True(results.Count > 0);
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.Equal(results[^1].Value, indicator.Last.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
using OoplesFinance.StockIndicators;
|
||||
using OoplesFinance.StockIndicators.Models;
|
||||
using Tulip;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class TsfValidationTests : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData;
|
||||
private readonly ITestOutputHelper _output;
|
||||
private bool _disposed;
|
||||
|
||||
public TsfValidationTests(ITestOutputHelper output)
|
||||
{
|
||||
_output = output;
|
||||
_testData = new ValidationTestData();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed && disposing)
|
||||
{
|
||||
_testData.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cross-validate against LSMA(offset=1) ─────────────────────────
|
||||
// TSF = LSMA with offset=1. This is a mathematical identity.
|
||||
|
||||
[Fact]
|
||||
public void Validate_LSMA_Batch()
|
||||
{
|
||||
int[] periods = { 5, 10, 14, 20, 50 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var tsf = new global::QuanTAlib.Tsf(period);
|
||||
var tsfResult = tsf.Update(_testData.Data);
|
||||
|
||||
var lsma = new global::QuanTAlib.Lsma(period, offset: 1);
|
||||
var lsmaResult = lsma.Update(_testData.Data);
|
||||
|
||||
int compareCount = 100;
|
||||
int start = tsfResult.Count - compareCount;
|
||||
|
||||
for (int i = start; i < tsfResult.Count; i++)
|
||||
{
|
||||
Assert.Equal(lsmaResult.Values[i], tsfResult.Values[i], 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("TSF Batch validated successfully against LSMA(offset=1)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_LSMA_Streaming()
|
||||
{
|
||||
int[] periods = { 5, 10, 14, 20, 50 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var tsf = new global::QuanTAlib.Tsf(period);
|
||||
var lsma = new global::QuanTAlib.Lsma(period, offset: 1);
|
||||
|
||||
var tsfResults = new List<double>();
|
||||
var lsmaResults = new List<double>();
|
||||
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
tsfResults.Add(tsf.Update(item).Value);
|
||||
lsmaResults.Add(lsma.Update(item).Value);
|
||||
}
|
||||
|
||||
int compareCount = 100;
|
||||
int start = tsfResults.Count - compareCount;
|
||||
|
||||
for (int i = start; i < tsfResults.Count; i++)
|
||||
{
|
||||
Assert.Equal(lsmaResults[i], tsfResults[i], 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("TSF Streaming validated successfully against LSMA(offset=1)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_LSMA_Span()
|
||||
{
|
||||
int[] periods = { 5, 10, 14, 20, 50 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
double[] tsfOutput = new double[_testData.RawData.Length];
|
||||
double[] lsmaOutput = new double[_testData.RawData.Length];
|
||||
|
||||
global::QuanTAlib.Tsf.Batch(_testData.RawData.Span, tsfOutput.AsSpan(), period);
|
||||
global::QuanTAlib.Lsma.Batch(_testData.RawData.Span, lsmaOutput.AsSpan(), period, offset: 1);
|
||||
|
||||
int compareCount = 100;
|
||||
int start = tsfOutput.Length - compareCount;
|
||||
|
||||
for (int i = start; i < tsfOutput.Length; i++)
|
||||
{
|
||||
Assert.Equal(lsmaOutput[i], tsfOutput[i], 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("TSF Span validated successfully against LSMA(offset=1)");
|
||||
}
|
||||
|
||||
// ── Self-consistency checks ────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Validate_Batch_Streaming_Consistency()
|
||||
{
|
||||
const int period = 14;
|
||||
|
||||
// Batch
|
||||
var batchResult = global::QuanTAlib.Tsf.Batch(_testData.Data, period);
|
||||
|
||||
// Streaming
|
||||
var tsf = new global::QuanTAlib.Tsf(period);
|
||||
var streamResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
streamResults.Add(tsf.Update(item).Value);
|
||||
}
|
||||
|
||||
int compareCount = 100;
|
||||
int start = batchResult.Count - compareCount;
|
||||
for (int i = start; i < batchResult.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchResult.Values[i], streamResults[i], 1e-6);
|
||||
}
|
||||
_output.WriteLine("TSF Batch vs Streaming consistency verified");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_DifferentPeriods()
|
||||
{
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var result = global::QuanTAlib.Tsf.Batch(_testData.Data, period);
|
||||
Assert.True(result.Count == _testData.Data.Count);
|
||||
Assert.True(double.IsFinite(result.Values[^1]));
|
||||
}
|
||||
_output.WriteLine("TSF different periods validated");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
const int period = 14;
|
||||
var (results, indicator) = global::QuanTAlib.Tsf.Calculate(_testData.Data, period);
|
||||
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.True(results.Count == _testData.Data.Count);
|
||||
Assert.Equal(results.Values[^1], indicator.Last.Value);
|
||||
_output.WriteLine("TSF Calculate returns hot indicator verified");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_BarCorrection_Consistency()
|
||||
{
|
||||
const int period = 14;
|
||||
|
||||
// Feed initial data
|
||||
var tsf = new global::QuanTAlib.Tsf(period);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
tsf.Update(_testData.Data[i], isNew: true);
|
||||
}
|
||||
double expectedLast = tsf.Last.Value;
|
||||
|
||||
// Apply multiple corrections, then restore
|
||||
for (int j = 0; j < 5; j++)
|
||||
{
|
||||
tsf.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
|
||||
}
|
||||
tsf.Update(_testData.Data[99], isNew: false);
|
||||
|
||||
Assert.Equal(expectedLast, tsf.Last.Value, 1e-6);
|
||||
_output.WriteLine("TSF bar correction consistency verified");
|
||||
}
|
||||
|
||||
// ── Tulip Cross-Validation ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Validates TSF against Tulip <c>tsf</c> (Time Series Forecast).
|
||||
/// Tulip formula: linear regression value projected one period forward —
|
||||
/// identical to QuanTAlib TSF = slope*(n-1+1) + intercept = Lsma(offset=1).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Tsf_Matches_Tulip_Batch()
|
||||
{
|
||||
const int period = 14;
|
||||
double[] data = _testData.RawData.ToArray();
|
||||
|
||||
var qResult = global::QuanTAlib.Tsf.Batch(_testData.Data, period);
|
||||
|
||||
var tulipIndicator = Tulip.Indicators.tsf;
|
||||
double[][] inputs = { data };
|
||||
double[] options = { period };
|
||||
int lookback = tulipIndicator.Start(options);
|
||||
double[][] outputs = { new double[data.Length - lookback] };
|
||||
tulipIndicator.Run(inputs, options, outputs);
|
||||
double[] tResult = outputs[0];
|
||||
|
||||
ValidationHelper.VerifyData(qResult, tResult, lookback, tolerance: 1e-9);
|
||||
_output.WriteLine("TSF Batch validated against Tulip tsf");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tsf_Matches_Tulip_Streaming()
|
||||
{
|
||||
const int period = 20;
|
||||
double[] data = _testData.RawData.ToArray();
|
||||
|
||||
var tsf = new global::QuanTAlib.Tsf(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(tsf.Update(item).Value);
|
||||
}
|
||||
|
||||
var tulipIndicator = Tulip.Indicators.tsf;
|
||||
double[][] inputs = { data };
|
||||
double[] options = { period };
|
||||
int lookback = tulipIndicator.Start(options);
|
||||
double[][] outputs = { new double[data.Length - lookback] };
|
||||
tulipIndicator.Run(inputs, options, outputs);
|
||||
double[] tResult = outputs[0];
|
||||
|
||||
// Tolerance relaxed to 2e-8: floating-point accumulation over long runs can produce
|
||||
// low-1e-8 drift between streaming (incremental) and batch (single-pass) paths.
|
||||
ValidationHelper.VerifyData(qResults, tResult, lookback, tolerance: 2e-8);
|
||||
_output.WriteLine("TSF Streaming validated against Tulip tsf");
|
||||
}
|
||||
|
||||
// ── Cross-library: OoplesFinance ────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Structural validation against Ooples <c>CalculateTimeSeriesForecast</c>.
|
||||
/// Ooples TSF uses the same linear-regression-forecast-one-bar-ahead definition.
|
||||
/// Numeric equality is not asserted: Ooples default period is 500 (batch-oriented),
|
||||
/// so at period=14 results may differ due to seeding strategy.
|
||||
/// Both must produce finite output after warmup on the same close series.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Tsf_MatchesOoples_Structural()
|
||||
{
|
||||
const int period = 14;
|
||||
|
||||
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 oResult = stockData.CalculateTimeSeriesForecast(length: period);
|
||||
var oValues = oResult.OutputValues.Values.First();
|
||||
|
||||
var tsf = new Tsf(period);
|
||||
var qValues = new System.Collections.Generic.List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qValues.Add(tsf.Update(item).Value);
|
||||
}
|
||||
|
||||
Assert.True(oValues.Count > 0, "Ooples TSF must produce output");
|
||||
|
||||
int finiteCount = 0;
|
||||
for (int i = period; i < Math.Min(oValues.Count, qValues.Count); i++)
|
||||
{
|
||||
if (double.IsFinite(oValues[i]) && double.IsFinite(qValues[i]))
|
||||
{
|
||||
finiteCount++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(finiteCount > 100, $"Expected >100 finite TSF pairs, got {finiteCount}");
|
||||
_output.WriteLine($"TSF Ooples structural: {finiteCount} finite pairs verified.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user