mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-24 21:48:03 +00:00
Refactor tests and implementations for various indicators
- Updated RsiIndicatorTests to ensure proper initialization and state checks. - Added new tests for Rsx, Vel, and Adosc indicators to validate behavior under iterative corrections and edge cases (NaN, Infinity). - Enhanced Bessel indicator tests and implementation with consistent formatting. - Improved Ema and Pwma implementations by ensuring proper handling of values. - Introduced mock classes for charting to facilitate testing without dependencies. - Ensured all indicators produce consistent results across different modes of operation. - Cleaned up code formatting and added missing commas for better readability.
This commit is contained in:
+673
-40
@@ -1,15 +1,42 @@
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class CsvFeedTests
|
||||
public sealed class CsvFeedTests : IDisposable
|
||||
{
|
||||
private const string TestCsvPath = "daily_IBM.csv";
|
||||
private readonly List<string> _tempFiles = new();
|
||||
private bool _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
foreach (var file in _tempFiles)
|
||||
{
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try { File.Delete(file); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string CreateTempCsv(string[] lines)
|
||||
{
|
||||
string tempPath = Path.GetTempFileName() + ".csv";
|
||||
File.WriteAllLines(tempPath, lines);
|
||||
_tempFiles.Add(tempPath);
|
||||
return tempPath;
|
||||
}
|
||||
|
||||
#region Constructor Tests
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidFile_LoadsData()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
Assert.NotNull(feed);
|
||||
Assert.True(feed.Count > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -21,15 +48,185 @@ public class CsvFeedTests
|
||||
[Fact]
|
||||
public void Constructor_NullPath_ThrowsArgumentException()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new CsvFeed(null!));
|
||||
var ex = Assert.Throws<ArgumentException>(() => new CsvFeed(null!));
|
||||
Assert.Equal("filePath", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_EmptyPath_ThrowsArgumentException()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new CsvFeed(""));
|
||||
var ex = Assert.Throws<ArgumentException>(() => new CsvFeed(""));
|
||||
Assert.Equal("filePath", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhitespacePath_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new CsvFeed(" "));
|
||||
Assert.Equal("filePath", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_EmptyCsv_ThrowsInvalidDataException()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(Array.Empty<string>());
|
||||
Assert.Throws<InvalidDataException>(() => new CsvFeed(tempCsv));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_HeaderOnlyCsv_ThrowsInvalidDataException()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[] { "timestamp,open,high,low,close,volume" });
|
||||
Assert.Throws<InvalidDataException>(() => new CsvFeed(tempCsv));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_MalformedDate_ThrowsFormatException()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"not-a-date,100,101,99,100,1000"
|
||||
});
|
||||
Assert.Throws<FormatException>(() => new CsvFeed(tempCsv));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_MalformedPrice_ThrowsFormatException()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,not-a-number,101,99,100,1000"
|
||||
});
|
||||
Assert.Throws<FormatException>(() => new CsvFeed(tempCsv));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_MissingColumns_ThrowsFormatException()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,100,101,99,100" // Missing volume
|
||||
});
|
||||
Assert.Throws<FormatException>(() => new CsvFeed(tempCsv));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ExtraColumns_ThrowsFormatException()
|
||||
{
|
||||
// Extra columns should throw format exception (strict 6-column format)
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume,extra",
|
||||
"2023-01-01,100,101,99,100,1000,extra_data"
|
||||
});
|
||||
Assert.Throws<FormatException>(() => new CsvFeed(tempCsv));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Property Tests
|
||||
|
||||
[Fact]
|
||||
public void Count_ReturnsCorrectNumber()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
Assert.True(feed.Count > 0);
|
||||
// IBM CSV has 100 rows of data
|
||||
Assert.Equal(100, feed.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilePath_ReturnsLoadedPath()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
Assert.Equal(TestCsvPath, feed.FilePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasMore_TrueAtStart()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
Assert.True(feed.HasMore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasMore_FalseWhenExhausted()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,100,101,99,100,1000"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
|
||||
Assert.True(feed.HasMore);
|
||||
feed.Next(isNew: true);
|
||||
Assert.False(feed.HasMore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CurrentIndex_StartsAtZero()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
Assert.Equal(0, feed.CurrentIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CurrentIndex_IncrementsOnNext()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
Assert.Equal(0, feed.CurrentIndex);
|
||||
feed.Next(isNew: true);
|
||||
Assert.Equal(1, feed.CurrentIndex);
|
||||
feed.Next(isNew: true);
|
||||
Assert.Equal(2, feed.CurrentIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CurrentIndex_DoesNotIncrementOnUpdate()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
feed.Next(isNew: true);
|
||||
int indexAfterFirst = feed.CurrentIndex;
|
||||
|
||||
feed.Next(isNew: false);
|
||||
Assert.Equal(indexAfterFirst, feed.CurrentIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasCurrentBar_FalseAtStart()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
Assert.False(feed.HasCurrentBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasCurrentBar_TrueAfterNext()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
feed.Next(isNew: true);
|
||||
Assert.True(feed.HasCurrentBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Data_ReturnsUnderlyingSeries()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
var data = feed.Data;
|
||||
|
||||
Assert.NotNull(data);
|
||||
Assert.Equal(feed.Count, data.Count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Next Method Tests
|
||||
|
||||
[Fact]
|
||||
public void Next_StreamsDataChronologically()
|
||||
{
|
||||
@@ -109,6 +306,43 @@ public class CsvFeedTests
|
||||
Assert.Equal(lastBar.Time, finalBar.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Next_EmptyData_ReturnsDefaultAndSignalsNoMore()
|
||||
{
|
||||
// Create a mock scenario - but since constructor throws on empty,
|
||||
// we test the behavior when all data is consumed
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,100,101,99,100,1000"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
|
||||
// Consume all data
|
||||
bool isNew = true;
|
||||
feed.Next(ref isNew);
|
||||
|
||||
// Now at end
|
||||
isNew = true;
|
||||
var bar = feed.Next(ref isNew);
|
||||
Assert.False(isNew);
|
||||
Assert.Equal(100.0, bar.Close); // Returns last bar
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Next_DefaultParameter_IsNewTrue()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
var bar1 = feed.Next(); // Default isNew = true
|
||||
var bar2 = feed.Next(); // Default isNew = true
|
||||
Assert.True(bar2.Time > bar1.Time);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Fetch Method Tests
|
||||
|
||||
[Fact]
|
||||
public void Fetch_ReturnsCorrectNumberOfBars()
|
||||
{
|
||||
@@ -124,15 +358,25 @@ public class CsvFeedTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_InvalidCount_ThrowsArgumentException()
|
||||
public void Fetch_ZeroCount_ThrowsArgumentException()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
var startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromDays(1);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => feed.Fetch(0, startTime, interval));
|
||||
Assert.Throws<ArgumentException>(() => feed.Fetch(-1, startTime, interval));
|
||||
var ex = Assert.Throws<ArgumentException>(() => feed.Fetch(0, startTime, interval));
|
||||
Assert.Equal("count", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_NegativeCount_ThrowsArgumentException()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
var startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromDays(1);
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => feed.Fetch(-1, startTime, interval));
|
||||
Assert.Equal("count", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -154,6 +398,174 @@ public class CsvFeedTests
|
||||
Assert.True(bar.Time >= startTime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_ResetsHasCurrentBar()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
feed.Next(isNew: true);
|
||||
Assert.True(feed.HasCurrentBar);
|
||||
|
||||
var startTime = new DateTime(2025, 7, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
|
||||
feed.Fetch(5, startTime, TimeSpan.FromDays(1));
|
||||
|
||||
Assert.False(feed.HasCurrentBar);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Reset Method Tests
|
||||
|
||||
[Fact]
|
||||
public void Reset_ReturnsToStart()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
// Advance several bars
|
||||
var firstBar = feed.Next(isNew: true);
|
||||
feed.Next(isNew: true);
|
||||
feed.Next(isNew: true);
|
||||
Assert.Equal(3, feed.CurrentIndex);
|
||||
|
||||
// Reset
|
||||
feed.Reset();
|
||||
|
||||
Assert.Equal(0, feed.CurrentIndex);
|
||||
Assert.True(feed.HasMore);
|
||||
Assert.False(feed.HasCurrentBar);
|
||||
|
||||
// Next bar should be first bar again
|
||||
var afterReset = feed.Next(isNew: true);
|
||||
Assert.Equal(firstBar.Time, afterReset.Time);
|
||||
Assert.Equal(firstBar.Close, afterReset.Close);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WithIndex_SetsCorrectPosition()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
// Reset to middle
|
||||
int targetIndex = 50;
|
||||
feed.Reset(targetIndex);
|
||||
|
||||
Assert.Equal(targetIndex, feed.CurrentIndex);
|
||||
Assert.False(feed.HasCurrentBar);
|
||||
|
||||
// Next bar should be at that index
|
||||
var bar = feed.Next(isNew: true);
|
||||
var expectedBar = feed.GetBar(targetIndex);
|
||||
Assert.Equal(expectedBar.Time, bar.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WithNegativeIndex_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => feed.Reset(-1));
|
||||
Assert.Equal("index", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WithIndexBeyondCount_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => feed.Reset(feed.Count + 1));
|
||||
Assert.Equal("index", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WithIndexAtCount_IsValid()
|
||||
{
|
||||
// Resetting to exactly Count means "at end" - valid but no more data
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
feed.Reset(feed.Count);
|
||||
|
||||
Assert.Equal(feed.Count, feed.CurrentIndex);
|
||||
Assert.False(feed.HasMore);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetBar Method Tests
|
||||
|
||||
[Fact]
|
||||
public void GetBar_ReturnsCorrectBar()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
// Get bar without affecting streaming
|
||||
var bar0 = feed.GetBar(0);
|
||||
var bar1 = feed.GetBar(1);
|
||||
|
||||
// Streaming position unchanged
|
||||
Assert.Equal(0, feed.CurrentIndex);
|
||||
|
||||
// Bars should be in chronological order
|
||||
Assert.True(bar1.Time > bar0.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetBar_NegativeIndex_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => feed.GetBar(-1));
|
||||
Assert.Equal("index", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetBar_IndexAtCount_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => feed.GetBar(feed.Count));
|
||||
Assert.Equal("index", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetBar_DoesNotAffectStreaming()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
// Stream first bar
|
||||
var streamed = feed.Next(isNew: true);
|
||||
int indexAfter = feed.CurrentIndex;
|
||||
|
||||
// Random access
|
||||
var bar50 = feed.GetBar(50);
|
||||
Assert.True(bar50.Time > 0);
|
||||
|
||||
// Streaming position unchanged
|
||||
Assert.Equal(indexAfter, feed.CurrentIndex);
|
||||
|
||||
// Continue streaming
|
||||
var next = feed.Next(isNew: true);
|
||||
Assert.True(next.Time > streamed.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetBar_ConsistentWithNext()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
// Get bars via random access
|
||||
var bar0 = feed.GetBar(0);
|
||||
var bar1 = feed.GetBar(1);
|
||||
var bar2 = feed.GetBar(2);
|
||||
|
||||
// Get same bars via streaming
|
||||
var streamed0 = feed.Next(isNew: true);
|
||||
var streamed1 = feed.Next(isNew: true);
|
||||
var streamed2 = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(bar0.Time, streamed0.Time);
|
||||
Assert.Equal(bar1.Time, streamed1.Time);
|
||||
Assert.Equal(bar2.Time, streamed2.Time);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region OHLCV Validation Tests
|
||||
|
||||
[Fact]
|
||||
public void LoadFromCsv_ParsesValuesCorrectly()
|
||||
{
|
||||
@@ -190,10 +602,91 @@ public class CsvFeedTests
|
||||
for (int i = 1; i < bars.Count; i++)
|
||||
{
|
||||
Assert.True(bars[i].Time > bars[i - 1].Time,
|
||||
$"Bar {i} time ({bars[i].AsDateTime}) should be after bar {i-1} time ({bars[i-1].AsDateTime})");
|
||||
$"Bar {i} time ({bars[i].AsDateTime}) should be after bar {i - 1} time ({bars[i - 1].AsDateTime})");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromCsv_AllBarsHaveValidOHLCV()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
for (int i = 0; i < feed.Count; i++)
|
||||
{
|
||||
var bar = feed.GetBar(i);
|
||||
|
||||
Assert.True(double.IsFinite(bar.Open), $"Bar {i} has non-finite Open");
|
||||
Assert.True(double.IsFinite(bar.High), $"Bar {i} has non-finite High");
|
||||
Assert.True(double.IsFinite(bar.Low), $"Bar {i} has non-finite Low");
|
||||
Assert.True(double.IsFinite(bar.Close), $"Bar {i} has non-finite Close");
|
||||
Assert.True(double.IsFinite(bar.Volume), $"Bar {i} has non-finite Volume");
|
||||
|
||||
Assert.True(bar.High >= bar.Low, $"Bar {i}: High ({bar.High}) < Low ({bar.Low})");
|
||||
Assert.True(bar.High >= bar.Open, $"Bar {i}: High ({bar.High}) < Open ({bar.Open})");
|
||||
Assert.True(bar.High >= bar.Close, $"Bar {i}: High ({bar.High}) < Close ({bar.Close})");
|
||||
Assert.True(bar.Low <= bar.Open, $"Bar {i}: Low ({bar.Low}) > Open ({bar.Open})");
|
||||
Assert.True(bar.Low <= bar.Close, $"Bar {i}: Low ({bar.Low}) > Close ({bar.Close})");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromCsv_ParsesDecimalsCorrectly()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,100.1234,101.5678,99.9999,100.0001,1234567.89"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var bar = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(100.1234, bar.Open, precision: 4);
|
||||
Assert.Equal(101.5678, bar.High, precision: 4);
|
||||
Assert.Equal(99.9999, bar.Low, precision: 4);
|
||||
Assert.Equal(100.0001, bar.Close, precision: 4);
|
||||
Assert.Equal(1234567.89, bar.Volume, precision: 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromCsv_ParsesNegativeValues()
|
||||
{
|
||||
// While negative prices are unusual, the parser should handle them
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,-100,50,-150,-50,1000"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var bar = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(-100, bar.Open);
|
||||
Assert.Equal(50, bar.High);
|
||||
Assert.Equal(-150, bar.Low);
|
||||
Assert.Equal(-50, bar.Close);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromCsv_ParsesScientificNotation()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,1.5e2,2e2,1e2,1.75e2,1e6"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var bar = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(150, bar.Open);
|
||||
Assert.Equal(200, bar.High);
|
||||
Assert.Equal(100, bar.Low);
|
||||
Assert.Equal(175, bar.Close);
|
||||
Assert.Equal(1000000, bar.Volume);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IFeed Interface Tests
|
||||
|
||||
[Fact]
|
||||
public void CsvFeed_WorksWithIFeedInterface()
|
||||
{
|
||||
@@ -206,6 +699,35 @@ public class CsvFeedTests
|
||||
Assert.True(bar2.Time > bar1.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CsvFeed_IFeedRefOverload()
|
||||
{
|
||||
IFeed feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
bool isNew = true;
|
||||
var bar1 = feed.Next(ref isNew);
|
||||
Assert.True(bar1.Time > 0);
|
||||
|
||||
isNew = false;
|
||||
var bar1Update = feed.Next(ref isNew);
|
||||
Assert.Equal(bar1.Time, bar1Update.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CsvFeed_IFeedFetch()
|
||||
{
|
||||
IFeed feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
var startTime = new DateTime(2025, 7, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
|
||||
var series = feed.Fetch(5, startTime, TimeSpan.FromDays(1));
|
||||
|
||||
Assert.True(series.Count > 0);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Edge Case Tests
|
||||
|
||||
[Fact]
|
||||
public void Next_MixedNewAndUpdate_WorksCorrectly()
|
||||
{
|
||||
@@ -248,49 +770,160 @@ public class CsvFeedTests
|
||||
var series = feed.Fetch(5, startTime, TimeSpan.FromDays(1));
|
||||
|
||||
// Should return empty or minimal data
|
||||
Assert.True(series.Count == 0);
|
||||
Assert.Empty(series);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_HandlesGapsCorrectly()
|
||||
{
|
||||
string tempCsv = Path.GetTempFileName() + ".csv";
|
||||
try
|
||||
// Create CSV with gaps using helper
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
// Create CSV with gaps
|
||||
// Date, Open, High, Low, Close, Volume
|
||||
// 2023-01-01 (Sunday)
|
||||
// 2023-01-02 (Monday)
|
||||
// 2023-01-04 (Wednesday) - Gap of Tuesday
|
||||
// 2023-01-05 (Thursday)
|
||||
var lines = new[]
|
||||
{
|
||||
"Date,Open,High,Low,Close,Volume",
|
||||
"2023-01-05,103,104,102,103,1000",
|
||||
"2023-01-04,102,103,101,102,1000",
|
||||
"2023-01-02,101,102,100,101,1000",
|
||||
"2023-01-01,100,101,99,100,1000"
|
||||
};
|
||||
File.WriteAllLines(tempCsv, lines);
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-05,103,104,102,103,1000",
|
||||
"2023-01-04,102,103,101,102,1000",
|
||||
"2023-01-02,101,102,100,101,1000",
|
||||
"2023-01-01,100,101,99,100,1000"
|
||||
});
|
||||
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var startTime = new DateTime(2023, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
|
||||
var interval = TimeSpan.FromDays(1);
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var startTime = new DateTime(2023, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
|
||||
var interval = TimeSpan.FromDays(1);
|
||||
|
||||
// Fetch 5 bars. Should get 4 bars (Jan 1, 2, 4, 5).
|
||||
var series = feed.Fetch(10, startTime, interval);
|
||||
// Fetch bars. Should get 4 bars (Jan 1, 2, 4, 5).
|
||||
var series = feed.Fetch(10, startTime, interval);
|
||||
|
||||
Assert.Equal(4, series.Count);
|
||||
Assert.Equal(startTime, series[0].Time); // Jan 1
|
||||
Assert.Equal(startTime + interval.Ticks, series[1].Time); // Jan 2
|
||||
// Gap here
|
||||
Assert.Equal(startTime + 3 * interval.Ticks, series[2].Time); // Jan 4
|
||||
Assert.Equal(startTime + 4 * interval.Ticks, series[3].Time); // Jan 5
|
||||
Assert.Equal(4, series.Count);
|
||||
Assert.Equal(startTime, series[0].Time); // Jan 1
|
||||
Assert.Equal(startTime + interval.Ticks, series[1].Time); // Jan 2
|
||||
// Gap here (Jan 3 missing)
|
||||
Assert.Equal(startTime + 3 * interval.Ticks, series[2].Time); // Jan 4
|
||||
Assert.Equal(startTime + 4 * interval.Ticks, series[3].Time); // Jan 5
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SingleBar_StreamsAndEnds()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,100,101,99,100,1000"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
|
||||
Assert.Equal(1, feed.Count);
|
||||
Assert.True(feed.HasMore);
|
||||
|
||||
bool isNew = true;
|
||||
var bar = feed.Next(ref isNew);
|
||||
Assert.True(isNew);
|
||||
Assert.Equal(100.0, bar.Close);
|
||||
Assert.False(feed.HasMore);
|
||||
|
||||
// Try to get next
|
||||
isNew = true;
|
||||
var noMore = feed.Next(ref isNew);
|
||||
Assert.False(isNew); // Signals end
|
||||
Assert.Equal(bar.Time, noMore.Time); // Returns last bar
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WhitespaceInValues_Trimmed()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
" 2023-01-01 , 100 , 101 , 99 , 100 , 1000 "
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var bar = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(100.0, bar.Open);
|
||||
Assert.Equal(101.0, bar.High);
|
||||
Assert.Equal(99.0, bar.Low);
|
||||
Assert.Equal(100.0, bar.Close);
|
||||
Assert.Equal(1000.0, bar.Volume);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroValues_Accepted()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,0,0,0,0,0"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var bar = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(0.0, bar.Open);
|
||||
Assert.Equal(0.0, bar.High);
|
||||
Assert.Equal(0.0, bar.Low);
|
||||
Assert.Equal(0.0, bar.Close);
|
||||
Assert.Equal(0.0, bar.Volume);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VeryLargeValues_Parsed()
|
||||
{
|
||||
string tempCsv = CreateTempCsv(new[]
|
||||
{
|
||||
"timestamp,open,high,low,close,volume",
|
||||
"2023-01-01,999999999.99,1000000000.01,999999999.00,999999999.50,9999999999999"
|
||||
});
|
||||
var feed = new CsvFeed(tempCsv);
|
||||
var bar = feed.Next(isNew: true);
|
||||
|
||||
Assert.Equal(999999999.99, bar.Open, precision: 2);
|
||||
Assert.Equal(1000000000.01, bar.High, precision: 2);
|
||||
Assert.Equal(999999999.00, bar.Low, precision: 2);
|
||||
Assert.Equal(999999999.50, bar.Close, precision: 2);
|
||||
Assert.Equal(9999999999999.0, bar.Volume, precision: 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConsecutiveResets_WorkCorrectly()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
feed.Next(isNew: true);
|
||||
feed.Next(isNew: true);
|
||||
feed.Reset();
|
||||
feed.Reset();
|
||||
feed.Reset();
|
||||
|
||||
Assert.Equal(0, feed.CurrentIndex);
|
||||
Assert.False(feed.HasCurrentBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StreamThenResetThenStream_Consistent()
|
||||
{
|
||||
var feed = new CsvFeed(TestCsvPath);
|
||||
|
||||
// First pass
|
||||
var firstPass = new List<double>();
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
firstPass.Add(feed.Next(isNew: true).Close);
|
||||
}
|
||||
finally
|
||||
|
||||
// Reset
|
||||
feed.Reset();
|
||||
|
||||
// Second pass
|
||||
var secondPass = new List<double>();
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
if (File.Exists(tempCsv))
|
||||
File.Delete(tempCsv);
|
||||
secondPass.Add(feed.Next(isNew: true).Close);
|
||||
}
|
||||
|
||||
// Should be identical
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
Assert.Equal(firstPass[i], secondPass[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
+258
-38
@@ -1,28 +1,80 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// Parsed OHLCV data from a CSV line.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
internal readonly record struct ParsedOhlcv(long Time, double Open, double High, double Low, double Close, double Volume);
|
||||
|
||||
/// <summary>
|
||||
/// Mutable state for parsing OHLCV columns. Used as ref parameter to reduce method signature size.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
internal ref struct OhlcvParseState
|
||||
{
|
||||
public long Time;
|
||||
public double Open;
|
||||
public double High;
|
||||
public double Low;
|
||||
public double Close;
|
||||
public double Volume;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CSV file feed for loading historical OHLCV data.
|
||||
/// Loads data in constructor and streams through it with Next() or returns batches with Fetch().
|
||||
/// CSV format: timestamp,open,high,low,close,volume (header required)
|
||||
/// Timestamp format: YYYY-MM-DD (UTC midnight assumed)
|
||||
/// </summary>
|
||||
public class CsvFeed : IFeed
|
||||
[SkipLocalsInit]
|
||||
public sealed class CsvFeed : IFeed
|
||||
{
|
||||
private readonly TBarSeries _data;
|
||||
private readonly string _filePath;
|
||||
|
||||
// Streaming state
|
||||
private int _currentIndex;
|
||||
private TBar _currentBar;
|
||||
private bool _hasCurrentBar;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the total number of bars available in the CSV file.
|
||||
/// </summary>
|
||||
public int Count => _data.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file path of the loaded CSV.
|
||||
/// </summary>
|
||||
public string FilePath => _filePath;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether there are more bars to stream.
|
||||
/// </summary>
|
||||
public bool HasMore => _currentIndex < _data.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current streaming position (0-based index).
|
||||
/// </summary>
|
||||
public int CurrentIndex => _currentIndex;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the feed has a current bar in progress.
|
||||
/// </summary>
|
||||
public bool HasCurrentBar => _hasCurrentBar;
|
||||
|
||||
/// <summary>
|
||||
/// Loads CSV file and prepares data for streaming.
|
||||
/// Data is reversed to chronological order (oldest first).
|
||||
/// </summary>
|
||||
/// <param name="filePath">Path to CSV file</param>
|
||||
/// <exception cref="ArgumentException">Thrown when filePath is null or empty</exception>
|
||||
/// <exception cref="FileNotFoundException">Thrown when the specified file does not exist</exception>
|
||||
/// <exception cref="InvalidDataException">Thrown when CSV file is empty or contains only header</exception>
|
||||
/// <exception cref="FormatException">Thrown when CSV format is invalid</exception>
|
||||
public CsvFeed(string filePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath))
|
||||
@@ -31,6 +83,7 @@ public class CsvFeed : IFeed
|
||||
if (!File.Exists(filePath))
|
||||
throw new FileNotFoundException($"CSV file not found: {filePath}", filePath);
|
||||
|
||||
_filePath = filePath;
|
||||
_data = LoadFromCsv(filePath);
|
||||
_currentIndex = 0;
|
||||
}
|
||||
@@ -65,37 +118,131 @@ public class CsvFeed : IFeed
|
||||
|
||||
var series = new TBarSeries(dataLines.Count);
|
||||
|
||||
// Pre-allocate arrays for bulk loading (SoA layout)
|
||||
long[] t = new long[dataLines.Count];
|
||||
double[] o = new double[dataLines.Count];
|
||||
double[] h = new double[dataLines.Count];
|
||||
double[] l = new double[dataLines.Count];
|
||||
double[] c = new double[dataLines.Count];
|
||||
double[] v = new double[dataLines.Count];
|
||||
|
||||
for (int i = 0; i < dataLines.Count; i++)
|
||||
{
|
||||
var line = dataLines[i];
|
||||
|
||||
var parts = line.Split(',');
|
||||
int originalLineNumber = dataLines.Count - i + 1;
|
||||
if (parts.Length != 6)
|
||||
throw new FormatException($"Invalid CSV format at line {originalLineNumber}. Expected 6 columns, found {parts.Length}");
|
||||
|
||||
// Parse timestamp (YYYY-MM-DD format, assume UTC midnight)
|
||||
if (!DateTime.TryParseExact(parts[0].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var timestamp))
|
||||
{
|
||||
throw new FormatException($"Failed to parse timestamp at line {originalLineNumber}: {line}");
|
||||
}
|
||||
|
||||
// Parse OHLCV values
|
||||
if (!double.TryParse(parts[1].Trim(), CultureInfo.InvariantCulture, out double open) ||
|
||||
!double.TryParse(parts[2].Trim(), CultureInfo.InvariantCulture, out double high) ||
|
||||
!double.TryParse(parts[3].Trim(), CultureInfo.InvariantCulture, out double low) ||
|
||||
!double.TryParse(parts[4].Trim(), CultureInfo.InvariantCulture, out double close) ||
|
||||
!double.TryParse(parts[5].Trim(), CultureInfo.InvariantCulture, out double volume))
|
||||
{
|
||||
throw new FormatException($"Failed to parse CSV line {originalLineNumber}: {line}");
|
||||
}
|
||||
|
||||
series.Add(timestamp, open, high, low, close, volume, isNew: true);
|
||||
var parsed = ParseCsvLine(line, originalLineNumber);
|
||||
t[i] = parsed.Time;
|
||||
o[i] = parsed.Open;
|
||||
h[i] = parsed.High;
|
||||
l[i] = parsed.Low;
|
||||
c[i] = parsed.Close;
|
||||
v[i] = parsed.Volume;
|
||||
}
|
||||
|
||||
// Bulk add to series
|
||||
series.Add(t, o, h, l, c, v);
|
||||
|
||||
return series;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a single CSV line into OHLCV components.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static ParsedOhlcv ParseCsvLine(string line, int lineNumber)
|
||||
{
|
||||
// Use Span-based splitting for reduced allocations
|
||||
ReadOnlySpan<char> lineSpan = line.AsSpan();
|
||||
|
||||
int col = 0;
|
||||
int start = 0;
|
||||
OhlcvParseState state = default;
|
||||
|
||||
for (int i = 0; i < lineSpan.Length; i++)
|
||||
{
|
||||
if (lineSpan[i] == ',')
|
||||
{
|
||||
var segment = lineSpan[start..i].Trim();
|
||||
ParseColumn(segment, col, lineNumber, line, ref state);
|
||||
col++;
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Process the last segment after the final comma
|
||||
if (start <= lineSpan.Length)
|
||||
{
|
||||
var segment = lineSpan[start..].Trim();
|
||||
ParseColumn(segment, col, lineNumber, line, ref state);
|
||||
col++;
|
||||
}
|
||||
|
||||
if (col != 6)
|
||||
{
|
||||
throw new FormatException($"Invalid CSV format at line {lineNumber}. Expected 6 columns, found {col}");
|
||||
}
|
||||
|
||||
return new ParsedOhlcv(state.Time, state.Open, state.High, state.Low, state.Close, state.Volume);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a single column value into the appropriate OHLCV field.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void ParseColumn(
|
||||
ReadOnlySpan<char> segment,
|
||||
int col,
|
||||
int lineNumber,
|
||||
string line,
|
||||
ref OhlcvParseState state)
|
||||
{
|
||||
switch (col)
|
||||
{
|
||||
case 0: // Timestamp
|
||||
if (!DateTime.TryParseExact(segment, "yyyy-MM-dd", CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var timestamp))
|
||||
{
|
||||
throw new FormatException($"Failed to parse timestamp at line {lineNumber}: {line}");
|
||||
}
|
||||
state.Time = timestamp.Ticks;
|
||||
break;
|
||||
case 1: // Open
|
||||
if (!double.TryParse(segment, NumberStyles.Float, CultureInfo.InvariantCulture, out state.Open))
|
||||
{
|
||||
throw new FormatException($"Failed to parse open price at line {lineNumber}: {line}");
|
||||
}
|
||||
break;
|
||||
case 2: // High
|
||||
if (!double.TryParse(segment, NumberStyles.Float, CultureInfo.InvariantCulture, out state.High))
|
||||
{
|
||||
throw new FormatException($"Failed to parse high price at line {lineNumber}: {line}");
|
||||
}
|
||||
break;
|
||||
case 3: // Low
|
||||
if (!double.TryParse(segment, NumberStyles.Float, CultureInfo.InvariantCulture, out state.Low))
|
||||
{
|
||||
throw new FormatException($"Failed to parse low price at line {lineNumber}: {line}");
|
||||
}
|
||||
break;
|
||||
case 4: // Close
|
||||
if (!double.TryParse(segment, NumberStyles.Float, CultureInfo.InvariantCulture, out state.Close))
|
||||
{
|
||||
throw new FormatException($"Failed to parse close price at line {lineNumber}: {line}");
|
||||
}
|
||||
break;
|
||||
case 5: // Volume
|
||||
if (!double.TryParse(segment, NumberStyles.Float, CultureInfo.InvariantCulture, out state.Volume))
|
||||
{
|
||||
throw new FormatException($"Failed to parse volume at line {lineNumber}: {line}");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// Extra columns are ignored - this handles the default case requirement
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the next bar with full bidirectional control.
|
||||
/// When end of data reached, returns last bar and sets isNew=false.
|
||||
@@ -123,11 +270,8 @@ public class CsvFeed : IFeed
|
||||
_currentIndex++;
|
||||
_hasCurrentBar = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Update current bar - CSV has no intra-bar updates, return same bar
|
||||
// No change to _currentBar or _currentIndex
|
||||
}
|
||||
// else: Update current bar - CSV has no intra-bar updates, return same bar
|
||||
// No change to _currentBar or _currentIndex
|
||||
|
||||
return _currentBar;
|
||||
}
|
||||
@@ -140,10 +284,16 @@ public class CsvFeed : IFeed
|
||||
{
|
||||
return Next(ref isNew);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a filtered subset of data matching the criteria.
|
||||
/// Resets streaming position to start of returned data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of bars to retrieve (must be positive)</param>
|
||||
/// <param name="startTime">Starting timestamp in ticks</param>
|
||||
/// <param name="interval">Time interval between bars</param>
|
||||
/// <returns>A TBarSeries containing the matched bars</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when count is not positive</exception>
|
||||
public TBarSeries Fetch(int count, long startTime, TimeSpan interval)
|
||||
{
|
||||
if (count <= 0)
|
||||
@@ -151,16 +301,8 @@ public class CsvFeed : IFeed
|
||||
|
||||
var result = new TBarSeries(count);
|
||||
|
||||
// Find starting index
|
||||
int startIndex = -1;
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
if (_data[i].Time >= startTime)
|
||||
{
|
||||
startIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Find starting index using binary search for better performance
|
||||
int startIndex = FindStartIndex(startTime);
|
||||
|
||||
if (startIndex == -1)
|
||||
return result;
|
||||
@@ -168,6 +310,7 @@ public class CsvFeed : IFeed
|
||||
// Collect bars matching interval
|
||||
long expectedTime = startTime;
|
||||
int collected = 0;
|
||||
long tolerance = interval.Ticks / 2; // Allow 50% tolerance
|
||||
|
||||
for (int i = startIndex; i < _data.Count && collected < count; i++)
|
||||
{
|
||||
@@ -175,7 +318,6 @@ public class CsvFeed : IFeed
|
||||
|
||||
// Check if bar time matches expected time (within tolerance)
|
||||
long timeDiff = Math.Abs(bar.Time - expectedTime);
|
||||
long tolerance = interval.Ticks / 2; // Allow 50% tolerance
|
||||
|
||||
if (timeDiff <= tolerance)
|
||||
{
|
||||
@@ -204,4 +346,82 @@ public class CsvFeed : IFeed
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the starting index for the given start time using binary search.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private int FindStartIndex(long startTime)
|
||||
{
|
||||
if (_data.Count == 0)
|
||||
return -1;
|
||||
|
||||
// If startTime is before first bar, return 0
|
||||
if (_data[0].Time >= startTime)
|
||||
return 0;
|
||||
|
||||
// If startTime is after last bar, return -1
|
||||
if (_data[_data.Count - 1].Time < startTime)
|
||||
return -1;
|
||||
|
||||
// Binary search for the first bar >= startTime
|
||||
int left = 0;
|
||||
int right = _data.Count - 1;
|
||||
|
||||
while (left < right)
|
||||
{
|
||||
int mid = left + (right - left) / 2;
|
||||
|
||||
if (_data[mid].Time < startTime)
|
||||
left = mid + 1;
|
||||
else
|
||||
right = mid;
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the streaming position to the beginning.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_currentIndex = 0;
|
||||
_hasCurrentBar = false;
|
||||
_currentBar = default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the streaming position to a specific index.
|
||||
/// </summary>
|
||||
/// <param name="index">The index to reset to (must be valid)</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown when index is out of range</exception>
|
||||
public void Reset(int index)
|
||||
{
|
||||
if (index < 0 || index > _data.Count)
|
||||
throw new ArgumentOutOfRangeException(nameof(index), index, $"Index must be between 0 and {_data.Count}");
|
||||
|
||||
_currentIndex = index;
|
||||
_hasCurrentBar = false;
|
||||
_currentBar = default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bar at the specified index without affecting streaming position.
|
||||
/// </summary>
|
||||
/// <param name="index">The index of the bar to retrieve</param>
|
||||
/// <returns>The bar at the specified index</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown when index is out of range</exception>
|
||||
public TBar GetBar(int index)
|
||||
{
|
||||
if (index < 0 || index >= _data.Count)
|
||||
throw new ArgumentOutOfRangeException(nameof(index), index, $"Index must be between 0 and {_data.Count - 1}");
|
||||
|
||||
return _data[index];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying data series (read-only access).
|
||||
/// </summary>
|
||||
public TBarSeries Data => _data;
|
||||
}
|
||||
|
||||
+476
-56
@@ -1,12 +1,121 @@
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class GBMTests
|
||||
{
|
||||
#region Constructor Tests
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultParameters_CreatesValidInstance()
|
||||
{
|
||||
var gbm = new GBM();
|
||||
|
||||
Assert.Equal(100.0, gbm.StartPrice);
|
||||
Assert.Equal(0.05, gbm.Mu);
|
||||
Assert.Equal(0.2, gbm.Sigma);
|
||||
Assert.Equal(100.0, gbm.CurrentPrice);
|
||||
Assert.False(gbm.HasCurrentBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomParameters_SetsCorrectly()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 50.0, mu: 0.1, sigma: 0.3, seed: 42);
|
||||
|
||||
Assert.Equal(50.0, gbm.StartPrice);
|
||||
Assert.Equal(0.1, gbm.Mu);
|
||||
Assert.Equal(0.3, gbm.Sigma);
|
||||
Assert.Equal(50.0, gbm.CurrentPrice);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
[InlineData(-100)]
|
||||
public void Constructor_InvalidStartPrice_ThrowsArgumentOutOfRangeException(double startPrice)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(startPrice: startPrice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NaNStartPrice_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(startPrice: double.NaN));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InfinityStartPrice_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(startPrice: double.PositiveInfinity));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(startPrice: double.NegativeInfinity));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.01)]
|
||||
[InlineData(-1)]
|
||||
public void Constructor_NegativeSigma_ThrowsArgumentOutOfRangeException(double sigma)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(sigma: sigma));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NaNSigma_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(sigma: double.NaN));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InfinitySigma_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(sigma: double.PositiveInfinity));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NaNMu_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(mu: double.NaN));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InfinityMu_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(mu: double.PositiveInfinity));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(mu: double.NegativeInfinity));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroTimeframe_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(defaultTimeframe: TimeSpan.Zero));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeTimeframe_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new GBM(defaultTimeframe: TimeSpan.FromMinutes(-1)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroSigma_IsValid()
|
||||
{
|
||||
var gbm = new GBM(sigma: 0);
|
||||
Assert.Equal(0, gbm.Sigma);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeMu_IsValid()
|
||||
{
|
||||
var gbm = new GBM(mu: -0.1);
|
||||
Assert.Equal(-0.1, gbm.Mu);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Next Method Tests
|
||||
|
||||
[Fact]
|
||||
public void Next_DefaultParameter_GeneratesNewBar()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var bar1 = gbm.Next();
|
||||
var bar2 = gbm.Next();
|
||||
@@ -18,7 +127,7 @@ public class GBMTests
|
||||
[Fact]
|
||||
public void Next_IsNewTrue_AdvancesToNewBar()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var bar1 = gbm.Next(isNew: true);
|
||||
var bar2 = gbm.Next(isNew: true);
|
||||
@@ -30,7 +139,7 @@ public class GBMTests
|
||||
[Fact]
|
||||
public void Next_IsNewFalse_UpdatesCurrentBar()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var bar1 = gbm.Next(isNew: true);
|
||||
long initialTime = bar1.Time;
|
||||
@@ -38,16 +147,15 @@ public class GBMTests
|
||||
var bar2 = gbm.Next(isNew: false);
|
||||
|
||||
Assert.Equal(initialTime, bar2.Time);
|
||||
// Price likely changed (GBM random walk)
|
||||
Assert.NotEqual(bar1.Close, bar2.Close);
|
||||
Assert.Equal(bar1.Open, bar2.Open);
|
||||
// High/Low/Close/Volume may change
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Next_RefBool_HonorsRequest()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
// GBM always honors isNew - parameter should remain unchanged
|
||||
bool isNew1 = true;
|
||||
var bar1 = gbm.Next(ref isNew1);
|
||||
Assert.True(isNew1, "GBM should honor isNew=true request");
|
||||
@@ -64,10 +172,58 @@ public class GBMTests
|
||||
Assert.NotEqual(time1, bar3.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Next_FirstCallWithIsNewFalse_GeneratesBar()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
// First call with isNew=false should still generate a bar
|
||||
var bar = gbm.Next(isNew: false);
|
||||
|
||||
Assert.True(bar.Time > 0);
|
||||
Assert.True(bar.Open > 0);
|
||||
Assert.True(gbm.HasCurrentBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Next_MultipleUpdates_AccumulatesVolume()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var bar1 = gbm.Next(isNew: true);
|
||||
double initialVolume = bar1.Volume;
|
||||
|
||||
var bar2 = gbm.Next(isNew: false);
|
||||
|
||||
Assert.True(bar2.Volume > initialVolume, "Volume should accumulate on intra-bar updates");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Next_IntraBarUpdates_ExpandsHighLow()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, sigma: 0.5, seed: 42);
|
||||
|
||||
var bar1 = gbm.Next(isNew: true);
|
||||
double initialHigh = bar1.High;
|
||||
double initialLow = bar1.Low;
|
||||
|
||||
// Multiple updates should potentially expand the range
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: false);
|
||||
Assert.True(bar.High >= initialHigh || bar.Low <= initialLow || i > 50,
|
||||
"High-Low range should expand or stay same with updates");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Fetch Method Tests
|
||||
|
||||
[Fact]
|
||||
public void Fetch_GeneratesCorrectCount()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
int count = 10;
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
@@ -80,13 +236,12 @@ public class GBMTests
|
||||
[Fact]
|
||||
public void Fetch_GeneratesSequentialBars()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
var series = gbm.Fetch(5, startTime, interval);
|
||||
|
||||
// Verify time sequence
|
||||
for (int i = 1; i < series.Count; i++)
|
||||
{
|
||||
Assert.True(series[i].Time > series[i - 1].Time);
|
||||
@@ -96,13 +251,12 @@ public class GBMTests
|
||||
[Fact]
|
||||
public void Fetch_RespectsInterval()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
var interval = TimeSpan.FromHours(1);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
|
||||
var series = gbm.Fetch(5, startTime, interval);
|
||||
|
||||
// Verify interval spacing
|
||||
for (int i = 1; i < series.Count; i++)
|
||||
{
|
||||
long expectedDiff = interval.Ticks;
|
||||
@@ -114,7 +268,7 @@ public class GBMTests
|
||||
[Fact]
|
||||
public void Fetch_StartsAtSpecifiedTime()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
var startTime = new DateTime(2024, 1, 1, 9, 30, 0, DateTimeKind.Utc).Ticks;
|
||||
var interval = TimeSpan.FromMinutes(5);
|
||||
|
||||
@@ -125,13 +279,43 @@ public class GBMTests
|
||||
Assert.Equal(startTime + 2 * interval.Ticks, series[2].Time);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
[InlineData(-100)]
|
||||
public void Fetch_InvalidCount_ThrowsArgumentException(int count)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => gbm.Fetch(count, startTime, interval));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_WithDifferentIntervals_WorksCorrectly()
|
||||
public void Fetch_ZeroInterval_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
|
||||
// Test different intervals
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => gbm.Fetch(10, startTime, TimeSpan.Zero));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_NegativeInterval_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => gbm.Fetch(10, startTime, TimeSpan.FromMinutes(-1)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_WithDifferentIntervals_WorksCorrectly()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
|
||||
var intervals = new[] {
|
||||
TimeSpan.FromMinutes(1),
|
||||
TimeSpan.FromMinutes(5),
|
||||
@@ -142,7 +326,6 @@ public class GBMTests
|
||||
{
|
||||
var series = gbm.Fetch(3, startTime, interval);
|
||||
|
||||
// Verify spacing
|
||||
for (int i = 1; i < series.Count; i++)
|
||||
{
|
||||
long expectedDiff = interval.Ticks;
|
||||
@@ -153,44 +336,276 @@ public class GBMTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GeneratesRealisticOHLCV()
|
||||
public void Fetch_LargeCount_WorksCorrectly()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
var series = gbm.Fetch(10, startTime, interval);
|
||||
|
||||
var series = gbm.Fetch(10000, startTime, interval);
|
||||
|
||||
Assert.Equal(10000, series.Count);
|
||||
Assert.All(Enumerable.Range(0, series.Count), i =>
|
||||
{
|
||||
Assert.True(series[i].Open > 0);
|
||||
Assert.True(series[i].High > 0);
|
||||
Assert.True(series[i].Low > 0);
|
||||
Assert.True(series[i].Close > 0);
|
||||
Assert.True(series[i].Volume > 0);
|
||||
});
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region OHLCV Validity Tests
|
||||
|
||||
[Fact]
|
||||
public void GeneratesRealisticOHLCV()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
var series = gbm.Fetch(100, startTime, interval);
|
||||
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
var bar = series[i];
|
||||
|
||||
// High should be >= max(Open, Close)
|
||||
Assert.True(bar.High >= Math.Max(bar.Open, bar.Close));
|
||||
Assert.True(bar.High >= Math.Max(bar.Open, bar.Close),
|
||||
$"Bar {i}: High ({bar.High}) should be >= max(Open, Close) ({Math.Max(bar.Open, bar.Close)})");
|
||||
|
||||
// Low should be <= min(Open, Close)
|
||||
Assert.True(bar.Low <= Math.Min(bar.Open, bar.Close));
|
||||
Assert.True(bar.Low <= Math.Min(bar.Open, bar.Close),
|
||||
$"Bar {i}: Low ({bar.Low}) should be <= min(Open, Close) ({Math.Min(bar.Open, bar.Close)})");
|
||||
|
||||
// High should be >= Low
|
||||
Assert.True(bar.High >= bar.Low,
|
||||
$"Bar {i}: High ({bar.High}) should be >= Low ({bar.Low})");
|
||||
|
||||
// Volume should be positive
|
||||
Assert.True(bar.Volume > 0);
|
||||
Assert.True(bar.Volume > 0, $"Bar {i}: Volume should be positive");
|
||||
|
||||
// All prices should be positive
|
||||
Assert.True(bar.Open > 0);
|
||||
Assert.True(bar.High > 0);
|
||||
Assert.True(bar.Low > 0);
|
||||
Assert.True(bar.Close > 0);
|
||||
// All prices should be positive and finite
|
||||
Assert.True(double.IsFinite(bar.Open) && bar.Open > 0, $"Bar {i}: Open should be positive and finite");
|
||||
Assert.True(double.IsFinite(bar.High) && bar.High > 0, $"Bar {i}: High should be positive and finite");
|
||||
Assert.True(double.IsFinite(bar.Low) && bar.Low > 0, $"Bar {i}: Low should be positive and finite");
|
||||
Assert.True(double.IsFinite(bar.Close) && bar.Close > 0, $"Bar {i}: Close should be positive and finite");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConsecutiveCalls_MaintainContinuity()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var previousBar = gbm.Next();
|
||||
var currentBar = gbm.Next();
|
||||
|
||||
// currentBar.Open should equal previousBar.Close (continuity)
|
||||
Assert.Equal(previousBar.Close, currentBar.Open);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fetch_MaintainsContinuity()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
var series = gbm.Fetch(10, startTime, interval);
|
||||
|
||||
for (int i = 1; i < series.Count; i++)
|
||||
{
|
||||
Assert.True(Math.Abs(series[i - 1].Close - series[i].Open) < 1e-10,
|
||||
$"Bar {i}: Open should equal previous bar's Close for continuity");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Reset Tests
|
||||
|
||||
[Fact]
|
||||
public void Reset_RestoresInitialState()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
// Generate some bars
|
||||
gbm.Next();
|
||||
gbm.Next();
|
||||
gbm.Next();
|
||||
|
||||
Assert.NotEqual(100.0, gbm.CurrentPrice);
|
||||
Assert.True(gbm.HasCurrentBar);
|
||||
|
||||
// Reset
|
||||
gbm.Reset();
|
||||
|
||||
Assert.Equal(100.0, gbm.CurrentPrice);
|
||||
Assert.False(gbm.HasCurrentBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WithStartTime_SetsSpecificTime()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
long specificTime = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
|
||||
|
||||
gbm.Next();
|
||||
gbm.Reset(specificTime);
|
||||
|
||||
var bar = gbm.Next();
|
||||
|
||||
// The bar time should be based on the reset time
|
||||
Assert.True(bar.Time > specificTime);
|
||||
Assert.Equal(100.0, bar.Open); // Should start from initial price
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Seeded Reproducibility Tests
|
||||
|
||||
[Fact]
|
||||
public void SeededGenerator_ProducesReproducibleResults()
|
||||
{
|
||||
var gbm1 = new GBM(startPrice: 100.0, seed: 42);
|
||||
var gbm2 = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
var series1 = gbm1.Fetch(10, startTime, interval);
|
||||
var series2 = gbm2.Fetch(10, startTime, interval);
|
||||
|
||||
for (int i = 0; i < series1.Count; i++)
|
||||
{
|
||||
Assert.Equal(series1[i].Open, series2[i].Open);
|
||||
Assert.Equal(series1[i].High, series2[i].High);
|
||||
Assert.Equal(series1[i].Low, series2[i].Low);
|
||||
Assert.Equal(series1[i].Close, series2[i].Close);
|
||||
Assert.Equal(series1[i].Volume, series2[i].Volume);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentSeeds_ProduceDifferentResults()
|
||||
{
|
||||
var gbm1 = new GBM(startPrice: 100.0, seed: 42);
|
||||
var gbm2 = new GBM(startPrice: 100.0, seed: 123);
|
||||
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
var series1 = gbm1.Fetch(10, startTime, interval);
|
||||
var series2 = gbm2.Fetch(10, startTime, interval);
|
||||
|
||||
bool anyDifferent = false;
|
||||
for (int i = 0; i < series1.Count; i++)
|
||||
{
|
||||
if (series1[i].Close != series2[i].Close)
|
||||
{
|
||||
anyDifferent = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(anyDifferent, "Different seeds should produce different results");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnseededGenerator_ProducesVariableResults()
|
||||
{
|
||||
var gbm1 = new GBM(startPrice: 100.0);
|
||||
var gbm2 = new GBM(startPrice: 100.0);
|
||||
|
||||
// Note: This test may occasionally fail due to randomness, but is extremely unlikely
|
||||
var bar1 = gbm1.Next();
|
||||
var bar2 = gbm2.Next();
|
||||
|
||||
// At least one value should be different
|
||||
bool anyDifferent = bar1.Close != bar2.Close ||
|
||||
bar1.High != bar2.High ||
|
||||
bar1.Low != bar2.Low ||
|
||||
bar1.Volume != bar2.Volume;
|
||||
|
||||
Assert.True(anyDifferent, "Unseeded generators should produce different results");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Drift and Volatility Tests
|
||||
|
||||
[Fact]
|
||||
public void DriftAndVolatility_AffectPriceMovement()
|
||||
{
|
||||
var gbmLowVol = new GBM(startPrice: 100.0, mu: 0.0, sigma: 0.01, seed: 42);
|
||||
var gbmHighVol = new GBM(startPrice: 100.0, mu: 0.0, sigma: 0.5, seed: 42);
|
||||
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
var seriesLow = gbmLowVol.Fetch(100, startTime, interval);
|
||||
var seriesHigh = gbmHighVol.Fetch(100, startTime, interval);
|
||||
|
||||
// Calculate standard deviation of returns
|
||||
double[] returnsLow = new double[99];
|
||||
double[] returnsHigh = new double[99];
|
||||
|
||||
for (int i = 1; i < 100; i++)
|
||||
{
|
||||
returnsLow[i - 1] = Math.Log(seriesLow[i].Close / seriesLow[i - 1].Close);
|
||||
returnsHigh[i - 1] = Math.Log(seriesHigh[i].Close / seriesHigh[i - 1].Close);
|
||||
}
|
||||
|
||||
double stdLow = CalculateStdDev(returnsLow);
|
||||
double stdHigh = CalculateStdDev(returnsHigh);
|
||||
|
||||
Assert.True(stdHigh > stdLow, "High volatility should produce larger return dispersion");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroVolatility_ProducesConstantPrices()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.0, sigma: 0.0, seed: 42);
|
||||
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
var series = gbm.Fetch(10, startTime, interval);
|
||||
|
||||
// With zero volatility and zero drift, price should stay constant
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
Assert.Equal(100.0, series[i].Close, 10);
|
||||
}
|
||||
}
|
||||
|
||||
private static double CalculateStdDev(double[] values)
|
||||
{
|
||||
double mean = 0;
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
mean += values[i];
|
||||
mean /= values.Length;
|
||||
|
||||
double sumSquares = 0;
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
sumSquares += (values[i] - mean) * (values[i] - mean);
|
||||
|
||||
return Math.Sqrt(sumSquares / values.Length);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region State Management Tests
|
||||
|
||||
[Fact]
|
||||
public void IntraBarUpdates_ModifyCurrentBar()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var bar1 = gbm.Next(isNew: true);
|
||||
long initialTime = bar1.Time;
|
||||
double initialClose = bar1.Close;
|
||||
|
||||
// Loop until price changes (random walk might stay same but unlikely)
|
||||
bool changed = false;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
@@ -209,13 +624,11 @@ public class GBMTests
|
||||
[Fact]
|
||||
public void MixedStreamingAndBatch_WorksCorrectly()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
// Start with streaming
|
||||
_ = gbm.Next();
|
||||
var bar2 = gbm.Next();
|
||||
|
||||
// Batch generation with explicit time
|
||||
long startTime = bar2.Time + TimeSpan.FromMinutes(1).Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
var series = gbm.Fetch(3, startTime, interval);
|
||||
@@ -223,59 +636,66 @@ public class GBMTests
|
||||
Assert.True(series[0].Time > bar2.Time);
|
||||
Assert.Equal(3, series.Count);
|
||||
|
||||
// Continue streaming after batch (uses internal state)
|
||||
var bar3 = gbm.Next();
|
||||
Assert.True(bar3.Time > series[2].Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DriftAndVolatility_AffectPriceMovement()
|
||||
public void Fetch_ResetsStreamingState()
|
||||
{
|
||||
// High volatility should produce more price variation
|
||||
var gbmLowVol = new GBM(startPrice: 100.0, mu: 0.0, sigma: 0.01);
|
||||
var gbmHighVol = new GBM(startPrice: 100.0, mu: 0.0, sigma: 0.5);
|
||||
var gbm = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
// Create a bar with intra-bar updates
|
||||
gbm.Next(isNew: true);
|
||||
gbm.Next(isNew: false);
|
||||
Assert.True(gbm.HasCurrentBar);
|
||||
|
||||
// Fetch should reset streaming state
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var interval = TimeSpan.FromMinutes(1);
|
||||
var seriesLow = gbmLowVol.Fetch(100, startTime, interval);
|
||||
var seriesHigh = gbmHighVol.Fetch(100, startTime, interval);
|
||||
gbm.Fetch(5, startTime, TimeSpan.FromMinutes(1));
|
||||
|
||||
// Calculate price ranges
|
||||
double rangeLow = seriesLow[99].Close - seriesLow[0].Open;
|
||||
double rangeHigh = seriesHigh[99].Close - seriesHigh[0].Open;
|
||||
|
||||
// High volatility should generally produce larger absolute movements
|
||||
Assert.True(Math.Abs(rangeHigh) > Math.Abs(rangeLow) * 0.5);
|
||||
Assert.False(gbm.HasCurrentBar);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IFeed Interface Tests
|
||||
|
||||
[Fact]
|
||||
public void ConsecutiveCalls_MaintainContinuity()
|
||||
public void ImplementsIFeed()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
IFeed feed = new GBM(startPrice: 100.0, seed: 42);
|
||||
|
||||
var previousBar = gbm.Next();
|
||||
var currentBar = gbm.Next();
|
||||
var bar1 = feed.Next(isNew: true);
|
||||
Assert.True(bar1.Time > 0);
|
||||
|
||||
// currentBar.Open should equal previousBar.Close (continuity)
|
||||
Assert.Equal(previousBar.Close, currentBar.Open);
|
||||
var bar2 = feed.Next(isNew: true);
|
||||
Assert.True(bar2.Time > bar1.Time);
|
||||
|
||||
long startTime = DateTime.UtcNow.Ticks;
|
||||
var series = feed.Fetch(5, startTime, TimeSpan.FromMinutes(1));
|
||||
Assert.Equal(5, series.Count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Statelessness Tests
|
||||
|
||||
[Fact]
|
||||
public void Stateless_NoHistoryStorage()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0);
|
||||
|
||||
// Generate multiple bars
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
_ = gbm.Next();
|
||||
}
|
||||
|
||||
// GBM should not expose any history storage
|
||||
// Use typeof() instead of GetType() to satisfy trimming analyzer
|
||||
var type = typeof(GBM);
|
||||
var barsProperty = type.GetProperty("Bars");
|
||||
|
||||
Assert.Null(barsProperty);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -1,19 +1,75 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Provides validation utilities for comparing indicator results against external libraries.
|
||||
/// Contains tolerance constants and verification methods for cross-library validation.
|
||||
/// </summary>
|
||||
public static class ValidationHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Default tolerance for floating-point comparisons (1e-7).
|
||||
/// Suitable for most indicator comparisons.
|
||||
/// </summary>
|
||||
public const double DefaultTolerance = 1e-7;
|
||||
|
||||
/// <summary>
|
||||
/// Tolerance for Ooples Finance library comparisons (1e-7).
|
||||
/// May need adjustment for specific indicators with different internal precision.
|
||||
/// </summary>
|
||||
public const double OoplesTolerance = 1e-7;
|
||||
|
||||
/// <summary>
|
||||
/// Tolerance for Skender.Stock.Indicators library comparisons (1e-7).
|
||||
/// Skender uses decimal internally, so some precision loss is expected.
|
||||
/// </summary>
|
||||
public const double SkenderTolerance = 1e-7;
|
||||
|
||||
/// <summary>
|
||||
/// Tolerance for TA-Lib (TALib.NETCore) library comparisons (1e-7).
|
||||
/// TA-Lib uses double precision throughout.
|
||||
/// </summary>
|
||||
public const double TalibTolerance = 1e-7;
|
||||
|
||||
/// <summary>
|
||||
/// Tolerance for Tulip library comparisons (1e-7).
|
||||
/// Note: Tulip may have 1-bar shifts due to different initialization strategies.
|
||||
/// </summary>
|
||||
public const double TulipTolerance = 1e-7;
|
||||
|
||||
/// <summary>
|
||||
/// Relative tolerance for percentage-based comparisons (0.5%).
|
||||
/// Use when absolute tolerance is not appropriate.
|
||||
/// </summary>
|
||||
public const double RelativeTolerance = 0.005;
|
||||
|
||||
public static void VerifyData<TResult>(TSeries qSeries, IReadOnlyList<TResult> sSeries, Func<TResult, double?> selector, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Default number of bars to verify from the end of the series.
|
||||
/// Using 100 bars ensures we're comparing converged values.
|
||||
/// </summary>
|
||||
public const int DefaultVerificationCount = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Verifies TSeries results against an external library's results.
|
||||
/// Compares the last 'skip' values by default.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">The type of results from the external library</typeparam>
|
||||
/// <param name="qSeries">QuanTAlib TSeries results</param>
|
||||
/// <param name="sSeries">External library results</param>
|
||||
/// <param name="selector">Function to extract the comparable value from external results</param>
|
||||
/// <param name="skip">Number of values to verify from the end (default: 100)</param>
|
||||
/// <param name="tolerance">Tolerance for floating-point comparison</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData<TResult>(
|
||||
TSeries qSeries,
|
||||
IReadOnlyList<TResult> sSeries,
|
||||
Func<TResult, double?> selector,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
Assert.Equal(qSeries.Count, sSeries.Count);
|
||||
|
||||
@@ -27,11 +83,22 @@ public static class ValidationHelper
|
||||
|
||||
if (!sValue.HasValue) continue;
|
||||
|
||||
Assert.Equal(sValue.Value, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - sValue.Value) <= tolerance,
|
||||
$"Mismatch at index {i}: QuanTAlib={qValue:G17}, External={sValue.Value:G17}, Diff={Math.Abs(qValue - sValue.Value):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData<TResult>(IReadOnlyList<double> qResults, IReadOnlyList<TResult> sSeries, Func<TResult, double?> selector, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies IReadOnlyList results against an external library's results.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData<TResult>(
|
||||
IReadOnlyList<double> qResults,
|
||||
IReadOnlyList<TResult> sSeries,
|
||||
Func<TResult, double?> selector,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
Assert.Equal(qResults.Count, sSeries.Count);
|
||||
|
||||
@@ -45,11 +112,22 @@ public static class ValidationHelper
|
||||
|
||||
if (!sValue.HasValue) continue;
|
||||
|
||||
Assert.Equal(sValue.Value, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - sValue.Value) <= tolerance,
|
||||
$"Mismatch at index {i}: QuanTAlib={qValue:G17}, External={sValue.Value:G17}, Diff={Math.Abs(qValue - sValue.Value):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData<TResult>(double[] qOutput, IReadOnlyList<TResult> sSeries, Func<TResult, double?> selector, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies double array results against an external library's results.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData<TResult>(
|
||||
double[] qOutput,
|
||||
IReadOnlyList<TResult> sSeries,
|
||||
Func<TResult, double?> selector,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
Assert.Equal(qOutput.Length, sSeries.Count);
|
||||
|
||||
@@ -63,11 +141,27 @@ public static class ValidationHelper
|
||||
|
||||
if (!sValue.HasValue) continue;
|
||||
|
||||
Assert.Equal(sValue.Value, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - sValue.Value) <= tolerance,
|
||||
$"Mismatch at index {i}: QuanTAlib={qValue:G17}, External={sValue.Value:G17}, Diff={Math.Abs(qValue - sValue.Value):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData(TSeries qSeries, double[] tOutput, int lookback, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies TSeries results against TA-Lib style output with lookback offset.
|
||||
/// </summary>
|
||||
/// <param name="qSeries">QuanTAlib TSeries results</param>
|
||||
/// <param name="tOutput">TA-Lib output array</param>
|
||||
/// <param name="lookback">TA-Lib lookback period (output is shifted by this amount)</param>
|
||||
/// <param name="skip">Number of values to verify from the end</param>
|
||||
/// <param name="tolerance">Tolerance for floating-point comparison</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData(
|
||||
TSeries qSeries,
|
||||
double[] tOutput,
|
||||
int lookback,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
int count = qSeries.Count;
|
||||
int start = Math.Max(0, count - skip);
|
||||
@@ -83,11 +177,22 @@ public static class ValidationHelper
|
||||
|
||||
double tValue = tOutput[tIndex];
|
||||
|
||||
Assert.Equal(tValue, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - tValue) <= tolerance,
|
||||
$"Mismatch at index {i} (TA-Lib index {tIndex}): QuanTAlib={qValue:G17}, TA-Lib={tValue:G17}, Diff={Math.Abs(qValue - tValue):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData(IReadOnlyList<double> qResults, double[] tOutput, int lookback, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies IReadOnlyList results against TA-Lib style output with lookback offset.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData(
|
||||
IReadOnlyList<double> qResults,
|
||||
double[] tOutput,
|
||||
int lookback,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
int count = qResults.Count;
|
||||
int start = Math.Max(0, count - skip);
|
||||
@@ -103,11 +208,22 @@ public static class ValidationHelper
|
||||
|
||||
double tValue = tOutput[tIndex];
|
||||
|
||||
Assert.Equal(tValue, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - tValue) <= tolerance,
|
||||
$"Mismatch at index {i} (TA-Lib index {tIndex}): QuanTAlib={qValue:G17}, TA-Lib={tValue:G17}, Diff={Math.Abs(qValue - tValue):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData(double[] qOutput, double[] tOutput, int lookback, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies double array results against TA-Lib style output with lookback offset.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData(
|
||||
double[] qOutput,
|
||||
double[] tOutput,
|
||||
int lookback,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
int count = qOutput.Length;
|
||||
int start = Math.Max(0, count - skip);
|
||||
@@ -123,11 +239,23 @@ public static class ValidationHelper
|
||||
|
||||
double tValue = tOutput[tIndex];
|
||||
|
||||
Assert.Equal(tValue, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - tValue) <= tolerance,
|
||||
$"Mismatch at index {i} (TA-Lib index {tIndex}): QuanTAlib={qValue:G17}, TA-Lib={tValue:G17}, Diff={Math.Abs(qValue - tValue):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData(TSeries qSeries, double[] tOutput, Range outRange, int lookback, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies TSeries results against TA-Lib style output with range and lookback.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData(
|
||||
TSeries qSeries,
|
||||
double[] tOutput,
|
||||
Range outRange,
|
||||
int lookback,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
int count = qSeries.Count;
|
||||
int start = Math.Max(0, count - skip);
|
||||
@@ -144,11 +272,23 @@ public static class ValidationHelper
|
||||
|
||||
double tValue = tOutput[tIndex];
|
||||
|
||||
Assert.Equal(tValue, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - tValue) <= tolerance,
|
||||
$"Mismatch at index {i} (TA-Lib index {tIndex}): QuanTAlib={qValue:G17}, TA-Lib={tValue:G17}, Diff={Math.Abs(qValue - tValue):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData(IReadOnlyList<double> qResults, double[] tOutput, Range outRange, int lookback, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies IReadOnlyList results against TA-Lib style output with range and lookback.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData(
|
||||
IReadOnlyList<double> qResults,
|
||||
double[] tOutput,
|
||||
Range outRange,
|
||||
int lookback,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
int count = qResults.Count;
|
||||
int start = Math.Max(0, count - skip);
|
||||
@@ -165,11 +305,23 @@ public static class ValidationHelper
|
||||
|
||||
double tValue = tOutput[tIndex];
|
||||
|
||||
Assert.Equal(tValue, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - tValue) <= tolerance,
|
||||
$"Mismatch at index {i} (TA-Lib index {tIndex}): QuanTAlib={qValue:G17}, TA-Lib={tValue:G17}, Diff={Math.Abs(qValue - tValue):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void VerifyData(double[] qOutput, double[] tOutput, Range outRange, int lookback, int skip = 100, double tolerance = DefaultTolerance)
|
||||
/// <summary>
|
||||
/// Verifies double array results against TA-Lib style output with range and lookback.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void VerifyData(
|
||||
double[] qOutput,
|
||||
double[] tOutput,
|
||||
Range outRange,
|
||||
int lookback,
|
||||
int skip = DefaultVerificationCount,
|
||||
double tolerance = DefaultTolerance)
|
||||
{
|
||||
int count = qOutput.Length;
|
||||
int start = Math.Max(0, count - skip);
|
||||
@@ -186,7 +338,111 @@ public static class ValidationHelper
|
||||
|
||||
double tValue = tOutput[tIndex];
|
||||
|
||||
Assert.Equal(tValue, qValue, tolerance);
|
||||
Assert.True(
|
||||
Math.Abs(qValue - tValue) <= tolerance,
|
||||
$"Mismatch at index {i} (TA-Lib index {tIndex}): QuanTAlib={qValue:G17}, TA-Lib={tValue:G17}, Diff={Math.Abs(qValue - tValue):G17}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that all values in the series are finite (not NaN or Infinity).
|
||||
/// </summary>
|
||||
/// <param name="series">The series to verify</param>
|
||||
/// <param name="startIndex">Starting index for verification (default: 0)</param>
|
||||
public static void VerifyAllFinite(TSeries series, int startIndex = 0)
|
||||
{
|
||||
for (int i = startIndex; i < series.Count; i++)
|
||||
{
|
||||
Assert.True(
|
||||
double.IsFinite(series[i].Value),
|
||||
$"Non-finite value at index {i}: {series[i].Value}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that all values in the array are finite (not NaN or Infinity).
|
||||
/// </summary>
|
||||
/// <param name="values">The array to verify</param>
|
||||
/// <param name="startIndex">Starting index for verification (default: 0)</param>
|
||||
public static void VerifyAllFinite(double[] values, int startIndex = 0)
|
||||
{
|
||||
for (int i = startIndex; i < values.Length; i++)
|
||||
{
|
||||
Assert.True(
|
||||
double.IsFinite(values[i]),
|
||||
$"Non-finite value at index {i}: {values[i]}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that two series produce the same results (for consistency testing).
|
||||
/// </summary>
|
||||
/// <param name="series1">First series</param>
|
||||
/// <param name="series2">Second series</param>
|
||||
/// <param name="tolerance">Tolerance for floating-point comparison</param>
|
||||
public static void VerifySeriesEqual(TSeries series1, TSeries series2, double tolerance = DefaultTolerance)
|
||||
{
|
||||
Assert.Equal(series1.Count, series2.Count);
|
||||
|
||||
for (int i = 0; i < series1.Count; i++)
|
||||
{
|
||||
Assert.True(
|
||||
Math.Abs(series1[i].Value - series2[i].Value) <= tolerance,
|
||||
$"Mismatch at index {i}: Series1={series1[i].Value:G17}, Series2={series2[i].Value:G17}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the maximum absolute difference between two series.
|
||||
/// Useful for debugging tolerance issues.
|
||||
/// </summary>
|
||||
public static double MaxAbsoluteDifference<TResult>(
|
||||
TSeries qSeries,
|
||||
IReadOnlyList<TResult> sSeries,
|
||||
Func<TResult, double?> selector)
|
||||
{
|
||||
if (qSeries.Count != sSeries.Count)
|
||||
throw new ArgumentException("Series must have the same count", nameof(sSeries));
|
||||
|
||||
double maxDiff = 0;
|
||||
|
||||
for (int i = 0; i < qSeries.Count; i++)
|
||||
{
|
||||
double? sValue = selector(sSeries[i]);
|
||||
if (!sValue.HasValue) continue;
|
||||
|
||||
double diff = Math.Abs(qSeries[i].Value - sValue.Value);
|
||||
if (diff > maxDiff)
|
||||
maxDiff = diff;
|
||||
}
|
||||
|
||||
return maxDiff;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the maximum relative difference between two series.
|
||||
/// Useful for percentage-based tolerance testing.
|
||||
/// </summary>
|
||||
public static double MaxRelativeDifference<TResult>(
|
||||
TSeries qSeries,
|
||||
IReadOnlyList<TResult> sSeries,
|
||||
Func<TResult, double?> selector)
|
||||
{
|
||||
if (qSeries.Count != sSeries.Count)
|
||||
throw new ArgumentException("Series must have the same count", nameof(sSeries));
|
||||
|
||||
double maxDiff = 0;
|
||||
|
||||
for (int i = 0; i < qSeries.Count; i++)
|
||||
{
|
||||
double? sValue = selector(sSeries[i]);
|
||||
if (!sValue.HasValue || sValue.Value == 0) continue;
|
||||
|
||||
double relDiff = Math.Abs((qSeries[i].Value - sValue.Value) / sValue.Value);
|
||||
if (relDiff > maxDiff)
|
||||
maxDiff = relDiff;
|
||||
}
|
||||
|
||||
return maxDiff;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,219 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Skender.Stock.Indicators;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Provides standardized test data for validation tests.
|
||||
/// Uses GBM (Geometric Brownian Motion) to generate realistic price data
|
||||
/// and converts it to formats required by external validation libraries.
|
||||
/// </summary>
|
||||
public sealed class ValidationTestData : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Default number of bars for validation tests.
|
||||
/// 5000 bars ensures sufficient convergence for most indicators.
|
||||
/// </summary>
|
||||
public const int DefaultCount = 5000;
|
||||
|
||||
/// <summary>
|
||||
/// Default starting price for generated data.
|
||||
/// </summary>
|
||||
public const double DefaultStartPrice = 1000.0;
|
||||
|
||||
/// <summary>
|
||||
/// Default annual drift for GBM (5%).
|
||||
/// </summary>
|
||||
public const double DefaultMu = 0.05;
|
||||
|
||||
/// <summary>
|
||||
/// Default annual volatility for GBM (200%).
|
||||
/// High volatility ensures diverse price scenarios.
|
||||
/// </summary>
|
||||
public const double DefaultSigma = 2.0;
|
||||
|
||||
/// <summary>
|
||||
/// Default random seed for reproducibility.
|
||||
/// </summary>
|
||||
public const int DefaultSeed = 123;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the generated bar series.
|
||||
/// </summary>
|
||||
public TBarSeries Bars { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the close price series.
|
||||
/// </summary>
|
||||
public TSeries Data { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the quotes in Skender.Stock.Indicators format.
|
||||
/// </summary>
|
||||
public IReadOnlyList<Quote> SkenderQuotes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw close price data as a ReadOnlyMemory for span-based APIs.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<double> RawData { get; }
|
||||
|
||||
public ValidationTestData(int count = 5000, double startPrice = 1000.0, double mu = 0.05, double sigma = 2.0, int seed = 123)
|
||||
/// <summary>
|
||||
/// Gets the raw open prices as read-only memory.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<double> OpenPrices { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw high prices as read-only memory.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<double> HighPrices { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw low prices as read-only memory.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<double> LowPrices { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw close prices as read-only memory.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<double> ClosePrices { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw volume data as read-only memory.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<double> VolumeData { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the timestamps as read-only memory.
|
||||
/// </summary>
|
||||
public ReadOnlyMemory<long> Timestamps { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of bars in the dataset.
|
||||
/// </summary>
|
||||
public int Count => Bars.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Creates validation test data with default parameters.
|
||||
/// </summary>
|
||||
public ValidationTestData()
|
||||
: this(DefaultCount, DefaultStartPrice, DefaultMu, DefaultSigma, DefaultSeed)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates validation test data with specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of bars to generate</param>
|
||||
/// <param name="startPrice">Starting price</param>
|
||||
/// <param name="mu">Annual drift rate</param>
|
||||
/// <param name="sigma">Annual volatility</param>
|
||||
/// <param name="seed">Random seed for reproducibility</param>
|
||||
public ValidationTestData(
|
||||
int count,
|
||||
double startPrice = DefaultStartPrice,
|
||||
double mu = DefaultMu,
|
||||
double sigma = DefaultSigma,
|
||||
int seed = DefaultSeed)
|
||||
{
|
||||
var gbm = new GBM(startPrice, mu, sigma, seed: seed);
|
||||
Bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
Data = Bars.Close;
|
||||
RawData = Data.Select(x => x.Value).ToArray();
|
||||
|
||||
var quotes = new List<Quote>();
|
||||
for (int i = 0; i < Bars.Count; i++)
|
||||
// Extract raw arrays efficiently (avoid LINQ in hot path)
|
||||
int barCount = Bars.Count;
|
||||
var openPrices = new double[barCount];
|
||||
var highPrices = new double[barCount];
|
||||
var lowPrices = new double[barCount];
|
||||
var closePrices = new double[barCount];
|
||||
var volumeData = new double[barCount];
|
||||
var timestamps = new long[barCount];
|
||||
|
||||
// Use span-based access for efficiency
|
||||
var openSpan = Bars.OpenValues;
|
||||
var highSpan = Bars.HighValues;
|
||||
var lowSpan = Bars.LowValues;
|
||||
var closeSpan = Bars.CloseValues;
|
||||
var volumeSpan = Bars.VolumeValues;
|
||||
var timeSpan = Bars.Times;
|
||||
|
||||
openSpan.CopyTo(openPrices);
|
||||
highSpan.CopyTo(highPrices);
|
||||
lowSpan.CopyTo(lowPrices);
|
||||
closeSpan.CopyTo(closePrices);
|
||||
volumeSpan.CopyTo(volumeData);
|
||||
timeSpan.CopyTo(timestamps);
|
||||
|
||||
// Expose as ReadOnlyMemory to prevent external modification
|
||||
OpenPrices = openPrices;
|
||||
HighPrices = highPrices;
|
||||
LowPrices = lowPrices;
|
||||
ClosePrices = closePrices;
|
||||
VolumeData = volumeData;
|
||||
Timestamps = timestamps;
|
||||
RawData = closePrices;
|
||||
|
||||
// Build Skender quotes without LINQ
|
||||
var quotes = new Quote[barCount];
|
||||
for (int i = 0; i < barCount; i++)
|
||||
{
|
||||
quotes.Add(new Quote
|
||||
quotes[i] = new Quote
|
||||
{
|
||||
Date = new DateTime(Bars.Open.Times[i], DateTimeKind.Utc),
|
||||
Open = (decimal)Bars.Open[i].Value,
|
||||
High = (decimal)Bars.High[i].Value,
|
||||
Low = (decimal)Bars.Low[i].Value,
|
||||
Close = (decimal)Bars.Close[i].Value,
|
||||
Volume = (decimal)Bars.Volume[i].Value
|
||||
});
|
||||
Date = new DateTime(timestamps[i], DateTimeKind.Utc),
|
||||
Open = (decimal)openPrices[i],
|
||||
High = (decimal)highPrices[i],
|
||||
Low = (decimal)lowPrices[i],
|
||||
Close = (decimal)closePrices[i],
|
||||
Volume = (decimal)volumeData[i],
|
||||
};
|
||||
}
|
||||
SkenderQuotes = quotes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a subset of the data for smaller tests.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of bars to include</param>
|
||||
/// <returns>A new ValidationTestData instance with the subset</returns>
|
||||
public ValidationTestData CreateSubset(int count)
|
||||
{
|
||||
if (count <= 0 || count > Count)
|
||||
throw new ArgumentOutOfRangeException(nameof(count), count, $"Count must be between 1 and {Count}");
|
||||
|
||||
return new ValidationTestData(count, DefaultStartPrice, DefaultMu, DefaultSigma, DefaultSeed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the close price span for SIMD operations.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<double> GetCloseSpan() => ClosePrices.Span;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the high price span for SIMD operations.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<double> GetHighSpan() => HighPrices.Span;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the low price span for SIMD operations.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<double> GetLowSpan() => LowPrices.Span;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the open price span for SIMD operations.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<double> GetOpenSpan() => OpenPrices.Span;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the volume span for SIMD operations.
|
||||
/// </summary>
|
||||
public ReadOnlySpan<double> GetVolumeSpan() => VolumeData.Span;
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of resources (no-op, but implements pattern for test fixtures).
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
// No resources to dispose
|
||||
// No unmanaged resources to dispose
|
||||
// Implemented for IDisposable pattern compatibility with test fixtures
|
||||
}
|
||||
}
|
||||
|
||||
+121
-18
@@ -11,10 +11,11 @@ namespace QuanTAlib;
|
||||
[SkipLocalsInit]
|
||||
#pragma warning disable S101 // Rename class 'GBM' to match pascal case naming rules
|
||||
#pragma warning disable S2245 // Random is acceptable for simulation/testing purposes
|
||||
public class GBM : IFeed
|
||||
public sealed class GBM : IFeed
|
||||
#pragma warning restore S101
|
||||
{
|
||||
private readonly Random? _rnd;
|
||||
private readonly double _startPrice;
|
||||
|
||||
private double _lastPrice;
|
||||
private long _lastTime;
|
||||
@@ -35,14 +36,43 @@ public class GBM : IFeed
|
||||
private double _cachedZ;
|
||||
private bool _hasCachedZ;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the annual drift/return rate.
|
||||
/// </summary>
|
||||
public double Mu => _mu;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the annual volatility.
|
||||
/// </summary>
|
||||
public double Sigma => _sigma;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the starting price.
|
||||
/// </summary>
|
||||
public double StartPrice => _startPrice;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current price state.
|
||||
/// </summary>
|
||||
public double CurrentPrice => _lastPrice;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the generator has a current bar in progress.
|
||||
/// </summary>
|
||||
public bool HasCurrentBar => _hasCurrentBar;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new GBM generator.
|
||||
/// </summary>
|
||||
/// <param name="startPrice">Initial price (default: 100.0, must be positive)</param>
|
||||
/// <param name="mu">Annual drift/return rate (default: 0.05 = 5%)</param>
|
||||
/// <param name="sigma">Annual volatility (default: 0.2 = 20%, must be non-negative)</param>
|
||||
/// <param name="defaultTimeframe">Default timeframe for bars (default: 1 minute)</param>
|
||||
/// <param name="startPrice">Initial price (default: 100.0, must be positive and finite)</param>
|
||||
/// <param name="mu">Annual drift/return rate (default: 0.05 = 5%, must be finite)</param>
|
||||
/// <param name="sigma">Annual volatility (default: 0.2 = 20%, must be non-negative and finite)</param>
|
||||
/// <param name="defaultTimeframe">Default timeframe for bars (default: 1 minute, must be positive)</param>
|
||||
/// <param name="seed">Optional random seed for reproducibility (default: null for non-deterministic)</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">
|
||||
/// Thrown when startPrice is not positive/finite, sigma is negative/non-finite,
|
||||
/// mu is non-finite, or defaultTimeframe is non-positive.
|
||||
/// </exception>
|
||||
public GBM(
|
||||
double startPrice = 100.0,
|
||||
double mu = 0.05,
|
||||
@@ -50,18 +80,33 @@ public class GBM : IFeed
|
||||
TimeSpan? defaultTimeframe = null,
|
||||
int? seed = null)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(startPrice);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(sigma);
|
||||
// Validate startPrice
|
||||
if (startPrice <= 0 || !double.IsFinite(startPrice))
|
||||
throw new ArgumentOutOfRangeException(nameof(startPrice), startPrice, "Start price must be positive and finite");
|
||||
|
||||
// Validate mu
|
||||
if (!double.IsFinite(mu))
|
||||
throw new ArgumentOutOfRangeException(nameof(mu), mu, "Drift (mu) must be finite");
|
||||
|
||||
// Validate sigma
|
||||
if (sigma < 0 || !double.IsFinite(sigma))
|
||||
throw new ArgumentOutOfRangeException(nameof(sigma), sigma, "Volatility (sigma) must be non-negative and finite");
|
||||
|
||||
// Use provided timeframe or default to 1 minute
|
||||
var timeframe = defaultTimeframe ?? TimeSpan.FromMinutes(1);
|
||||
|
||||
// Validate timeframe
|
||||
if (timeframe <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(defaultTimeframe), defaultTimeframe, "Timeframe must be positive");
|
||||
|
||||
_rnd = seed.HasValue ? new Random(seed.Value) : null;
|
||||
_startPrice = startPrice;
|
||||
_lastPrice = startPrice;
|
||||
_lastTime = DateTime.UtcNow.Ticks;
|
||||
|
||||
_mu = mu;
|
||||
_sigma = sigma;
|
||||
|
||||
// Use provided timeframe or default to 1 minute
|
||||
var timeframe = defaultTimeframe ?? TimeSpan.FromMinutes(1);
|
||||
_defaultTimeStep = timeframe.Ticks;
|
||||
|
||||
// Calculate dt based on timeframe (assuming 252 trading days/year, 6.5 hours/day)
|
||||
@@ -72,6 +117,33 @@ public class GBM : IFeed
|
||||
_vol = sigma * Math.Sqrt(dt);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the generator to its initial state.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_lastPrice = _startPrice;
|
||||
_lastTime = DateTime.UtcNow.Ticks;
|
||||
_currentBar = default;
|
||||
_hasCurrentBar = false;
|
||||
_cachedZ = 0;
|
||||
_hasCachedZ = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the generator to its initial state with a specific start time.
|
||||
/// </summary>
|
||||
/// <param name="startTime">The start time in ticks.</param>
|
||||
public void Reset(long startTime)
|
||||
{
|
||||
_lastPrice = _startPrice;
|
||||
_lastTime = startTime;
|
||||
_currentBar = default;
|
||||
_hasCurrentBar = false;
|
||||
_cachedZ = 0;
|
||||
_hasCachedZ = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random double in [0, 1) using either the seeded Random or RandomNumberGenerator.
|
||||
/// </summary>
|
||||
@@ -103,6 +175,11 @@ public class GBM : IFeed
|
||||
|
||||
double u1 = 1.0 - NextDouble();
|
||||
double u2 = 1.0 - NextDouble();
|
||||
|
||||
// Guard against log(0) which produces -Infinity
|
||||
if (u1 <= double.Epsilon)
|
||||
u1 = double.Epsilon;
|
||||
|
||||
double mag = Math.Sqrt(-2.0 * Math.Log(u1));
|
||||
double angle = 2.0 * Math.PI * u2;
|
||||
|
||||
@@ -128,17 +205,26 @@ public class GBM : IFeed
|
||||
|
||||
double z = NextNormal();
|
||||
double price = _lastPrice * Math.Exp(_drift + _vol * z);
|
||||
|
||||
// Ensure price stays positive and finite
|
||||
if (!double.IsFinite(price) || price <= 0)
|
||||
price = _lastPrice;
|
||||
|
||||
double volume = 1000 + NextDouble() * 1000;
|
||||
|
||||
double open = _lastPrice;
|
||||
double close = price;
|
||||
double high = Math.Max(open, close) * (1.0 + Math.Abs(NextDouble()) * 0.01);
|
||||
double low = Math.Min(open, close) * (1.0 - Math.Abs(NextDouble()) * 0.01);
|
||||
|
||||
// Ensure valid OHLC
|
||||
double rnd1 = NextDouble();
|
||||
double rnd2 = NextDouble();
|
||||
|
||||
double high = Math.Max(open, close) * (1.0 + rnd1 * 0.01);
|
||||
double low = Math.Min(open, close) * (1.0 - rnd2 * 0.01);
|
||||
|
||||
// Ensure valid OHLC constraints
|
||||
high = Math.Max(high, Math.Max(open, close));
|
||||
low = Math.Min(low, Math.Min(open, close));
|
||||
low = Math.Max(0.0, low);
|
||||
low = Math.Max(double.Epsilon, low); // Ensure positive
|
||||
|
||||
_currentBar = new TBar(currentTime, open, high, low, close, volume);
|
||||
_hasCurrentBar = true;
|
||||
@@ -151,12 +237,18 @@ public class GBM : IFeed
|
||||
// Update current bar (intra-bar tick)
|
||||
double z = NextNormal();
|
||||
double price = _lastPrice * Math.Exp(_drift + _vol * z);
|
||||
|
||||
// Ensure price stays positive and finite
|
||||
if (!double.IsFinite(price) || price <= 0)
|
||||
price = _lastPrice;
|
||||
|
||||
double additionalVolume = 1000 + NextDouble() * 1000;
|
||||
|
||||
var bar = _currentBar;
|
||||
double newClose = price;
|
||||
double newHigh = Math.Max(bar.High, newClose);
|
||||
double newLow = Math.Min(bar.Low, newClose);
|
||||
newLow = Math.Max(double.Epsilon, newLow); // Ensure positive
|
||||
double newVolume = bar.Volume + additionalVolume;
|
||||
|
||||
_currentBar = new TBar(bar.Time, bar.Open, newHigh, newLow, newClose, newVolume);
|
||||
@@ -179,13 +271,19 @@ public class GBM : IFeed
|
||||
/// <summary>
|
||||
/// Generates a batch of bars using optimized batch processing with explicit time parameters.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of bars to generate (must be positive)</param>
|
||||
/// <param name="startTime">Starting timestamp in ticks</param>
|
||||
/// <param name="interval">Time interval between bars (must be positive)</param>
|
||||
/// <returns>A TBarSeries containing the generated bars</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when count is not positive</exception>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown when interval is not positive</exception>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public TBarSeries Fetch(int count, long startTime, TimeSpan interval)
|
||||
{
|
||||
if (count <= 0)
|
||||
throw new ArgumentException("Count must be positive", nameof(count));
|
||||
if (interval <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(interval), "Interval must be positive");
|
||||
throw new ArgumentOutOfRangeException(nameof(interval), interval, "Interval must be positive");
|
||||
|
||||
var series = new TBarSeries(count);
|
||||
|
||||
@@ -212,6 +310,10 @@ public class GBM : IFeed
|
||||
double z = NextNormal();
|
||||
double price = currentPrice * Math.Exp(drift + vol * z);
|
||||
|
||||
// Ensure price stays positive and finite
|
||||
if (!double.IsFinite(price) || price <= 0)
|
||||
price = currentPrice;
|
||||
|
||||
double open = currentPrice;
|
||||
double close = price;
|
||||
|
||||
@@ -223,13 +325,13 @@ public class GBM : IFeed
|
||||
o[i] = open;
|
||||
c[i] = close;
|
||||
|
||||
double high = Math.Max(open, close) * (1.0 + Math.Abs(rnd1) * 0.01);
|
||||
double low = Math.Min(open, close) * (1.0 - Math.Abs(rnd2) * 0.01);
|
||||
double high = Math.Max(open, close) * (1.0 + rnd1 * 0.01);
|
||||
double low = Math.Min(open, close) * (1.0 - rnd2 * 0.01);
|
||||
|
||||
// Ensure valid OHLC
|
||||
// Ensure valid OHLC constraints
|
||||
high = Math.Max(high, Math.Max(open, close));
|
||||
low = Math.Min(low, Math.Min(open, close));
|
||||
low = Math.Max(0.0, low);
|
||||
low = Math.Max(double.Epsilon, low); // Ensure positive
|
||||
|
||||
h[i] = high;
|
||||
l[i] = low;
|
||||
@@ -252,3 +354,4 @@ public class GBM : IFeed
|
||||
return series;
|
||||
}
|
||||
}
|
||||
#pragma warning restore S2245
|
||||
|
||||
Reference in New Issue
Block a user