mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-23 04:58:08 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using QuanTAlib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class CrsiIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void CrsiIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new CrsiIndicator();
|
||||
|
||||
Assert.Equal(3, indicator.RsiPeriod);
|
||||
Assert.Equal(2, indicator.StreakPeriod);
|
||||
Assert.Equal(100, indicator.RankPeriod);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("CRSI - Connors RSI", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new CrsiIndicator { RsiPeriod = 3 };
|
||||
|
||||
Assert.Equal(0, CrsiIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_ShortName_IncludesParameters()
|
||||
{
|
||||
var indicator = new CrsiIndicator { RsiPeriod = 5, StreakPeriod = 3, RankPeriod = 50 };
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Contains("CRSI", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("5", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("3", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("50", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new CrsiIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Crsi.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_Initialize_CreatesLineSeries()
|
||||
{
|
||||
var indicator = new CrsiIndicator { RsiPeriod = 3, StreakPeriod = 2, RankPeriod = 10 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new CrsiIndicator { RsiPeriod = 3, StreakPeriod = 2, RankPeriod = 10 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
Assert.True(value >= 0.0 && value <= 100.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new CrsiIndicator { RsiPeriod = 3, StreakPeriod = 2, RankPeriod = 10 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
}
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(20), 120, 130, 110, 125);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries[0].Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_Parameters_CanBeChanged()
|
||||
{
|
||||
var indicator = new CrsiIndicator();
|
||||
|
||||
indicator.RsiPeriod = 5;
|
||||
indicator.StreakPeriod = 3;
|
||||
indicator.RankPeriod = 50;
|
||||
indicator.Source = SourceType.Open;
|
||||
|
||||
Assert.Equal(5, indicator.RsiPeriod);
|
||||
Assert.Equal(3, indicator.StreakPeriod);
|
||||
Assert.Equal(50, indicator.RankPeriod);
|
||||
Assert.Equal(SourceType.Open, indicator.Source);
|
||||
Assert.Equal(0, CrsiIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CrsiIndicator_DifferentSources_Work()
|
||||
{
|
||||
foreach (var source in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
|
||||
{
|
||||
var indicator = new CrsiIndicator { RsiPeriod = 3, StreakPeriod = 2, RankPeriod = 5, Source = source };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class CrsiIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("RSI Period", sortIndex: 1, 1, 500, 1, 0)]
|
||||
public int RsiPeriod { get; set; } = 3;
|
||||
|
||||
[InputParameter("Streak RSI Period", sortIndex: 2, 1, 500, 1, 0)]
|
||||
public int StreakPeriod { get; set; } = 2;
|
||||
|
||||
[InputParameter("Percent Rank Period", sortIndex: 3, 1, 1000, 1, 0)]
|
||||
public int RankPeriod { get; set; } = 100;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput(sortIndex: 4)]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Crsi _crsi = null!;
|
||||
private readonly LineSeries _series;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"CRSI ({RsiPeriod},{StreakPeriod},{RankPeriod})";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/crsi/Crsi.Quantower.cs";
|
||||
|
||||
public CrsiIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = true;
|
||||
Name = "CRSI - Connors RSI";
|
||||
Description = "Composite momentum oscillator combining price RSI, streak RSI, and percent rank of ROC";
|
||||
|
||||
_series = new LineSeries("CRSI", Color.Yellow, 2, LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_crsi = new Crsi(RsiPeriod, StreakPeriod, RankPeriod);
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var priceSelector = Source.GetPriceSelector();
|
||||
var item = HistoricalData[0, SeekOriginHistory.End];
|
||||
double price = priceSelector(item);
|
||||
|
||||
TValue input = new(item.TimeLeft, price);
|
||||
TValue result = _crsi.Update(input, args.IsNewBar());
|
||||
|
||||
if (!_crsi.IsHot && !ShowColdValues)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_series.SetValue(result.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class CrsiTests
|
||||
{
|
||||
private const double Tolerance = 1e-10;
|
||||
|
||||
// ───── A) Constructor validation ─────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_RsiPeriodZero_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Crsi(rsiPeriod: 0));
|
||||
Assert.Equal("rsiPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_RsiPeriodNegative_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Crsi(rsiPeriod: -1));
|
||||
Assert.Equal("rsiPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_StreakPeriodZero_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Crsi(streakPeriod: 0));
|
||||
Assert.Equal("streakPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_StreakPeriodNegative_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Crsi(streakPeriod: -5));
|
||||
Assert.Equal("streakPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_RankPeriodZero_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Crsi(rankPeriod: 0));
|
||||
Assert.Equal("rankPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_RankPeriodNegative_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Crsi(rankPeriod: -10));
|
||||
Assert.Equal("rankPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidDefaults_SetsProperties()
|
||||
{
|
||||
var crsi = new Crsi();
|
||||
Assert.Equal(3, crsi.RsiPeriod);
|
||||
Assert.Equal(2, crsi.StreakPeriod);
|
||||
Assert.Equal(100, crsi.RankPeriod);
|
||||
Assert.Equal("Crsi(3,2,100)", crsi.Name);
|
||||
Assert.False(crsi.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomPeriods_SetsProperties()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 5, streakPeriod: 3, rankPeriod: 50);
|
||||
Assert.Equal(5, crsi.RsiPeriod);
|
||||
Assert.Equal(3, crsi.StreakPeriod);
|
||||
Assert.Equal(50, crsi.RankPeriod);
|
||||
Assert.Equal("Crsi(5,3,50)", crsi.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_RsiPeriodZero_ThrowsArgumentException()
|
||||
{
|
||||
var src = new double[] { 1, 2, 3 };
|
||||
var out1 = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() => Crsi.Batch(src, out1, rsiPeriod: 0));
|
||||
Assert.Equal("rsiPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_StreakPeriodZero_ThrowsArgumentException()
|
||||
{
|
||||
var src = new double[] { 1, 2, 3 };
|
||||
var out1 = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() => Crsi.Batch(src, out1, streakPeriod: 0));
|
||||
Assert.Equal("streakPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_RankPeriodZero_ThrowsArgumentException()
|
||||
{
|
||||
var src = new double[] { 1, 2, 3 };
|
||||
var out1 = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() => Crsi.Batch(src, out1, rankPeriod: 0));
|
||||
Assert.Equal("rankPeriod", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_MismatchedLength_ThrowsArgumentException()
|
||||
{
|
||||
var src = new double[] { 1, 2, 3 };
|
||||
var out1 = new double[4];
|
||||
var ex = Assert.Throws<ArgumentException>(() => Crsi.Batch(src, out1));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
// ───── B) Basic calculation ─────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
var result = crsi.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.IsType<TValue>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_OutputInRange0To100()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 10);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.3, seed: 99);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
foreach (var bar in bars.Close)
|
||||
{
|
||||
var v = crsi.Update(bar).Value;
|
||||
Assert.True(v >= 0.0 && v <= 100.0, $"CRSI={v} out of [0,100]");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_NameAccessible()
|
||||
{
|
||||
var crsi = new Crsi(3, 2, 100);
|
||||
crsi.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.Equal("Crsi(3,2,100)", crsi.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_IsHotFalseBeforeWarmup()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
crsi.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
Assert.False(crsi.IsHot);
|
||||
}
|
||||
}
|
||||
|
||||
// ───── C) State + bar correction ─────
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNew_True_AdvancesState()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
var t = DateTime.UtcNow;
|
||||
crsi.Update(new TValue(t, 100.0), isNew: true);
|
||||
var v1 = crsi.Last;
|
||||
crsi.Update(new TValue(t.AddMinutes(1), 105.0), isNew: true);
|
||||
var v2 = crsi.Last;
|
||||
|
||||
// Two distinct bars — Last values can differ
|
||||
Assert.NotEqual(default, v1);
|
||||
Assert.NotEqual(default, v2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNew_False_RollsBack()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
double[] prices = [100, 102, 104, 103, 105, 107];
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < prices.Length; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), prices[i]), isNew: true);
|
||||
}
|
||||
|
||||
// Correction — produce different value
|
||||
crsi.Update(new TValue(t.AddMinutes(prices.Length), 150.0), isNew: false);
|
||||
var corrected1 = crsi.Last.Value;
|
||||
|
||||
// Same correction again must produce same result (idempotent)
|
||||
crsi.Update(new TValue(t.AddMinutes(prices.Length), 150.0), isNew: false);
|
||||
var corrected2 = crsi.Last.Value;
|
||||
|
||||
Assert.Equal(corrected1, corrected2, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_IterativeCorrections_Restore()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
double[] prices = [100, 102, 98, 105, 103, 107];
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < prices.Length; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), prices[i]), isNew: true);
|
||||
}
|
||||
|
||||
double baseline = crsi.Last.Value;
|
||||
|
||||
// Two bad corrections, then restore original
|
||||
crsi.Update(new TValue(t.AddMinutes(prices.Length), 999.0), isNew: false);
|
||||
crsi.Update(new TValue(t.AddMinutes(prices.Length), 888.0), isNew: false);
|
||||
crsi.Update(new TValue(t.AddMinutes(prices.Length), prices[^1]), isNew: false);
|
||||
|
||||
Assert.Equal(baseline, crsi.Last.Value, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), 100.0 + i));
|
||||
}
|
||||
|
||||
Assert.True(crsi.IsHot);
|
||||
crsi.Reset();
|
||||
Assert.False(crsi.IsHot);
|
||||
Assert.Equal(default, crsi.Last);
|
||||
}
|
||||
|
||||
// ───── D) Warmup / convergence ─────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAfterRankPeriodBars()
|
||||
{
|
||||
int rankPeriod = 5;
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: rankPeriod);
|
||||
var t = DateTime.UtcNow;
|
||||
|
||||
// rankPeriod-1 bars: still cold
|
||||
for (int i = 0; i < rankPeriod - 1; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), 100.0 + i));
|
||||
Assert.False(crsi.IsHot);
|
||||
}
|
||||
|
||||
// rankPeriod bar: hot
|
||||
crsi.Update(new TValue(t.AddMinutes(rankPeriod - 1), 100.0 + rankPeriod - 1));
|
||||
Assert.True(crsi.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_IsAccessible()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 100);
|
||||
Assert.True(crsi.WarmupPeriod > 0);
|
||||
}
|
||||
|
||||
// ───── E) Robustness ─────
|
||||
|
||||
[Fact]
|
||||
public void Update_NaN_UsesLastValid()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), 100.0 + i));
|
||||
}
|
||||
|
||||
crsi.Update(new TValue(t.AddMinutes(8), double.NaN));
|
||||
Assert.True(double.IsFinite(crsi.Last.Value));
|
||||
Assert.True(crsi.Last.Value >= 0.0 && crsi.Last.Value <= 100.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Infinity_UsesLastValid()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), 100.0 + i));
|
||||
}
|
||||
|
||||
crsi.Update(new TValue(t.AddMinutes(8), double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(crsi.Last.Value));
|
||||
|
||||
crsi.Update(new TValue(t.AddMinutes(9), double.NegativeInfinity));
|
||||
Assert.True(double.IsFinite(crsi.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_BatchNaN_Safe()
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod: 3, streakPeriod: 2, rankPeriod: 5);
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
crsi.Update(new TValue(t.AddMinutes(i), double.NaN));
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(crsi.Last.Value));
|
||||
}
|
||||
|
||||
// ───── F) Consistency (4 modes match) ─────
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ProduceSameResults()
|
||||
{
|
||||
int rsiPeriod = 3;
|
||||
int streakPeriod = 2;
|
||||
int rankPeriod = 20;
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.2, seed: 77);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
// 1. Streaming
|
||||
var streaming = new Crsi(rsiPeriod, streakPeriod, rankPeriod);
|
||||
var streamResults = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
streamResults[i] = streaming.Update(source[i]).Value;
|
||||
}
|
||||
|
||||
// 2. Batch TSeries
|
||||
TSeries batchSeries = Crsi.Batch(source, rsiPeriod, streakPeriod, rankPeriod);
|
||||
|
||||
// 3. Batch Span
|
||||
var spanOutput = new double[source.Count];
|
||||
Crsi.Batch(source.Values, spanOutput, rsiPeriod, streakPeriod, rankPeriod);
|
||||
|
||||
// 4. Event-based
|
||||
var eventSource = new TSeries();
|
||||
var eventIndicator = new Crsi(eventSource, rsiPeriod, streakPeriod, rankPeriod);
|
||||
var eventResults = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
eventSource.Add(source[i]);
|
||||
eventResults[i] = eventIndicator.Last.Value;
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], batchSeries.Values[i], Tolerance);
|
||||
Assert.Equal(streamResults[i], spanOutput[i], Tolerance);
|
||||
Assert.Equal(streamResults[i], eventResults[i], Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
// ───── G) Span API tests ─────
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_EmptySource_DoesNotThrow()
|
||||
{
|
||||
var src = Array.Empty<double>();
|
||||
var out1 = Array.Empty<double>();
|
||||
// Should not throw and output remains empty
|
||||
Crsi.Batch(src, out1);
|
||||
Assert.Empty(out1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_OutputInRange0to100()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.2, seed: 55);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var src = bars.Close.Values;
|
||||
var out1 = new double[src.Length];
|
||||
|
||||
Crsi.Batch(src, out1, rsiPeriod: 3, streakPeriod: 2, rankPeriod: 20);
|
||||
|
||||
for (int i = 0; i < out1.Length; i++)
|
||||
{
|
||||
Assert.True(out1[i] >= 0.0 && out1[i] <= 100.0, $"Span output[{i}]={out1[i]} out of range");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchSpan_LargeData_NoStackOverflow()
|
||||
{
|
||||
int n = 10_000;
|
||||
var src = new double[n];
|
||||
var out1 = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
src[i] = 100.0 + i * 0.01;
|
||||
}
|
||||
|
||||
// rankPeriod > 256 to exercise ArrayPool path
|
||||
Crsi.Batch(src, out1, rsiPeriod: 3, streakPeriod: 2, rankPeriod: 500);
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Assert.True(out1[i] >= 0.0 && out1[i] <= 100.0);
|
||||
}
|
||||
}
|
||||
|
||||
// ───── H) Chainability ─────
|
||||
|
||||
[Fact]
|
||||
public void EventChaining_PubFires()
|
||||
{
|
||||
int rsiPeriod = 3;
|
||||
int streakPeriod = 2;
|
||||
int rankPeriod = 5;
|
||||
var sourceTs = new TSeries();
|
||||
var crsi = new Crsi(sourceTs, rsiPeriod, streakPeriod, rankPeriod);
|
||||
|
||||
int count = 0;
|
||||
crsi.Pub += (_, in _) => count++;
|
||||
|
||||
var t = DateTime.UtcNow;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
sourceTs.Add(new TValue(t.AddMinutes(i), 100.0 + i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Self-consistency validation: batch == streaming, span == TSeries batch.
|
||||
/// </summary>
|
||||
public sealed class CrsiValidationTests
|
||||
{
|
||||
private const double Tolerance = 1e-10;
|
||||
|
||||
[Fact]
|
||||
public void Streaming_MatchesBatch_DefaultParams()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.2, seed: 1001);
|
||||
var bars = gbm.Fetch(300, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
// Streaming
|
||||
var streaming = new Crsi(3, 2, 100);
|
||||
var streamVals = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
streamVals[i] = streaming.Update(source[i]).Value;
|
||||
}
|
||||
|
||||
// Batch TSeries
|
||||
TSeries batchTs = Crsi.Batch(source, 3, 2, 100);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamVals[i], batchTs.Values[i], Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Span_MatchesBatch_DefaultParams()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.2, seed: 1002);
|
||||
var bars = gbm.Fetch(300, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
// Batch TSeries
|
||||
TSeries batchTs = Crsi.Batch(source, 3, 2, 100);
|
||||
|
||||
// Batch Span
|
||||
var spanOut = new double[source.Count];
|
||||
Crsi.Batch(source.Values, spanOut, 3, 2, 100);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchTs.Values[i], spanOut[i], Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Eventing_MatchesStreaming()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.2, seed: 1003);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
// Streaming
|
||||
var streaming = new Crsi(3, 2, 50);
|
||||
var streamVals = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
streamVals[i] = streaming.Update(source[i]).Value;
|
||||
}
|
||||
|
||||
// Event-based
|
||||
var eventTs = new TSeries();
|
||||
var eventCrsi = new Crsi(eventTs, 3, 2, 50);
|
||||
var eventVals = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
eventTs.Add(source[i]);
|
||||
eventVals[i] = eventCrsi.Last.Value;
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamVals[i], eventVals[i], Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Output_AlwaysInRange0To100()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 50.0, mu: 0.05, sigma: 0.5, seed: 1004);
|
||||
var bars = gbm.Fetch(500, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
var crsi = new Crsi(3, 2, 100);
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
double v = crsi.Update(source[i]).Value;
|
||||
Assert.True(v >= 0.0 && v <= 100.0, $"CRSI={v} at i={i}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ThenReplay_MatchesFreshRun()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 1005);
|
||||
var bars = gbm.Fetch(150, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
var crsi1 = new Crsi(3, 2, 30);
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
crsi1.Update(source[i]);
|
||||
}
|
||||
|
||||
double finalVal1 = crsi1.Last.Value;
|
||||
|
||||
// Reset and replay
|
||||
crsi1.Reset();
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
crsi1.Update(source[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(finalVal1, crsi1.Last.Value, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentPeriods_ProduceDistinctResults()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.01, sigma: 0.2, seed: 1006);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
TSeries r1 = Crsi.Batch(source, 3, 2, 50);
|
||||
TSeries r2 = Crsi.Batch(source, 5, 3, 50);
|
||||
|
||||
// With different RSI/streak parameters and same data, results should differ
|
||||
bool anyDiff = false;
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
if (Math.Abs(r1.Values[i] - r2.Values[i]) > 1e-6)
|
||||
{
|
||||
anyDiff = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(anyDiff, "Different periods should produce different results");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// CRSI: Connors RSI
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Composite momentum oscillator combining three independent measurements:
|
||||
/// 1. Price RSI (Wilder smoothing, default period 3)
|
||||
/// 2. RSI of consecutive up/down streak length (default period 2)
|
||||
/// 3. Percent rank of 1-bar ROC over a lookback window (default period 100)
|
||||
///
|
||||
/// CRSI = (PriceRSI + StreakRSI + PercentRank) / 3, clamped to [0, 100].
|
||||
///
|
||||
/// References:
|
||||
/// Connors, L. & Alvarez, C. (2012). An Introduction to ConnorsRSI. TradingMarkets.
|
||||
/// PineScript reference: crsi.pine
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Crsi : AbstractBase
|
||||
{
|
||||
private readonly int _rsiPeriod;
|
||||
private readonly int _streakPeriod;
|
||||
private readonly int _rankPeriod;
|
||||
|
||||
// Sub-indicators
|
||||
private readonly Rsi _priceRsi;
|
||||
private readonly Rsi _streakRsi;
|
||||
|
||||
// Circular buffer for ROC percent-rank (stores close prices, size = rankPeriod + 1)
|
||||
// We store the last rankPeriod+1 closing prices so we can compute 1-bar ROC for each slot
|
||||
// and then do the percent-rank scan.
|
||||
// Actually: store the ROC values directly (rankPeriod slots).
|
||||
private readonly double[] _rocBuf;
|
||||
private readonly double[] _rocBufSnap;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(
|
||||
int Streak,
|
||||
double PrevClose,
|
||||
int RocHead,
|
||||
int RocCount,
|
||||
double PrevRocSlot,
|
||||
double LastValid);
|
||||
|
||||
private State _s, _ps;
|
||||
|
||||
/// <summary>
|
||||
/// Creates CRSI with specified periods.
|
||||
/// </summary>
|
||||
/// <param name="rsiPeriod">Price RSI period (must be > 0)</param>
|
||||
/// <param name="streakPeriod">Streak RSI period (must be > 0)</param>
|
||||
/// <param name="rankPeriod">Percent rank lookback period (must be > 0)</param>
|
||||
public Crsi(int rsiPeriod = 3, int streakPeriod = 2, int rankPeriod = 100)
|
||||
{
|
||||
if (rsiPeriod <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(rsiPeriod));
|
||||
}
|
||||
|
||||
if (streakPeriod <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(streakPeriod));
|
||||
}
|
||||
|
||||
if (rankPeriod <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(rankPeriod));
|
||||
}
|
||||
|
||||
_rsiPeriod = rsiPeriod;
|
||||
_streakPeriod = streakPeriod;
|
||||
_rankPeriod = rankPeriod;
|
||||
|
||||
_priceRsi = new Rsi(rsiPeriod);
|
||||
_streakRsi = new Rsi(streakPeriod);
|
||||
|
||||
_rocBuf = new double[rankPeriod];
|
||||
_rocBufSnap = new double[rankPeriod];
|
||||
|
||||
_s = new State(0, double.NaN, 0, 0, double.NaN, double.NaN);
|
||||
_ps = _s;
|
||||
|
||||
Name = $"Crsi({rsiPeriod},{streakPeriod},{rankPeriod})";
|
||||
WarmupPeriod = rankPeriod + rsiPeriod + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates CRSI with event-based source chaining.
|
||||
/// </summary>
|
||||
public Crsi(ITValuePublisher source, int rsiPeriod = 3, int streakPeriod = 2, int rankPeriod = 100)
|
||||
: this(rsiPeriod, streakPeriod, rankPeriod)
|
||||
{
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
/// <summary>
|
||||
/// True once the percent-rank buffer is full (dominant warmup component).
|
||||
/// </summary>
|
||||
public override bool IsHot => _s.RocCount >= _rankPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// Price RSI period.
|
||||
/// </summary>
|
||||
public int RsiPeriod => _rsiPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// Streak RSI period.
|
||||
/// </summary>
|
||||
public int StreakPeriod => _streakPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// Percent rank lookback period.
|
||||
/// </summary>
|
||||
public int RankPeriod => _rankPeriod;
|
||||
|
||||
/// <inheritdoc/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
double value = input.Value;
|
||||
|
||||
// Sanitize input
|
||||
if (!double.IsFinite(value))
|
||||
{
|
||||
value = double.IsFinite(_s.LastValid) ? _s.LastValid : 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
_s.LastValid = value;
|
||||
}
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
// Snapshot state + ROC buffer before advancing
|
||||
_ps = _s;
|
||||
Array.Copy(_rocBuf, _rocBufSnap, _rankPeriod);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Rollback: restore state and ROC buffer
|
||||
// Save the value in the slot we're about to restore (PrevRocSlot was set on last isNew=true)
|
||||
_s = _ps;
|
||||
Array.Copy(_rocBufSnap, _rocBuf, _rankPeriod);
|
||||
}
|
||||
|
||||
var s = _s;
|
||||
|
||||
// ── Component 1: Price RSI ──
|
||||
double priceRsiVal = _priceRsi.Update(new TValue(input.Time, value), isNew).Value;
|
||||
|
||||
// ── Component 2: Streak ──
|
||||
int streak = s.Streak;
|
||||
if (!double.IsNaN(s.PrevClose))
|
||||
{
|
||||
if (value > s.PrevClose)
|
||||
{
|
||||
streak = streak >= 0 ? streak + 1 : 1;
|
||||
}
|
||||
else if (value < s.PrevClose)
|
||||
{
|
||||
streak = streak <= 0 ? streak - 1 : -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
streak = 0;
|
||||
}
|
||||
}
|
||||
|
||||
double streakRsiVal = _streakRsi.Update(new TValue(input.Time, (double)streak), isNew).Value;
|
||||
|
||||
// ── Component 3: Percent rank of 1-bar ROC ──
|
||||
double roc = 0.0;
|
||||
if (!double.IsNaN(s.PrevClose) && s.PrevClose != 0.0)
|
||||
{
|
||||
roc = (value - s.PrevClose) / s.PrevClose * 100.0;
|
||||
}
|
||||
|
||||
// Circular buffer: slot at RocHead holds the current (overwritten) ROC
|
||||
// PrevRocSlot saved the old value at RocHead before this bar wrote it (on isNew=true path)
|
||||
int head = s.RocHead;
|
||||
int count = s.RocCount;
|
||||
bool slotWasEmpty = (count < _rankPeriod);
|
||||
|
||||
// Save old slot content (used by next rollback)
|
||||
s.PrevRocSlot = _rocBuf[head];
|
||||
|
||||
_rocBuf[head] = roc;
|
||||
s.RocHead = (head + 1) % _rankPeriod;
|
||||
if (slotWasEmpty)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
|
||||
s.RocCount = count;
|
||||
|
||||
// Percent rank: count how many entries in buffer are <= current roc
|
||||
int lessOrEqual = 0;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (_rocBuf[i] <= roc)
|
||||
{
|
||||
lessOrEqual++;
|
||||
}
|
||||
}
|
||||
|
||||
double pctRank = count > 0 ? (double)lessOrEqual / count * 100.0 : 50.0;
|
||||
|
||||
// Update prev close and streak in state
|
||||
s.PrevClose = value;
|
||||
s.Streak = streak;
|
||||
_s = s;
|
||||
|
||||
// ── Compose ──
|
||||
double crsi = (priceRsiVal + streakRsiVal + pctRank) / 3.0;
|
||||
crsi = Math.Max(0.0, Math.Min(100.0, crsi));
|
||||
|
||||
Last = new TValue(input.Time, crsi);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
int len = source.Count;
|
||||
var t = new List<long>(len);
|
||||
var v = new List<double>(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
|
||||
Batch(source.Values, vSpan, _rsiPeriod, _streakPeriod, _rankPeriod);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
// Rebuild streaming state to match end of series
|
||||
Reset();
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
|
||||
}
|
||||
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
Update(new TValue(DateTime.UtcNow, source[i]), isNew: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Reset()
|
||||
{
|
||||
_priceRsi.Reset();
|
||||
_streakRsi.Reset();
|
||||
_s = new State(0, double.NaN, 0, 0, double.NaN, double.NaN);
|
||||
_ps = _s;
|
||||
Array.Clear(_rocBuf, 0, _rankPeriod);
|
||||
Array.Clear(_rocBufSnap, 0, _rankPeriod);
|
||||
Last = default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch static: TSeries → TSeries.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int rsiPeriod = 3, int streakPeriod = 2, int rankPeriod = 100)
|
||||
{
|
||||
var crsi = new Crsi(rsiPeriod, streakPeriod, rankPeriod);
|
||||
return crsi.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch static: span → span.
|
||||
/// </summary>
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output,
|
||||
int rsiPeriod = 3, int streakPeriod = 2, int rankPeriod = 100)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (rsiPeriod <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(rsiPeriod));
|
||||
}
|
||||
|
||||
if (streakPeriod <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(streakPeriod));
|
||||
}
|
||||
|
||||
if (rankPeriod <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(rankPeriod));
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Allocate streak series
|
||||
double[]? rentedStreak = null;
|
||||
scoped Span<double> streakBuf;
|
||||
const int StackallocThreshold = 256;
|
||||
if (len <= StackallocThreshold)
|
||||
{
|
||||
streakBuf = stackalloc double[len];
|
||||
}
|
||||
else
|
||||
{
|
||||
rentedStreak = System.Buffers.ArrayPool<double>.Shared.Rent(len);
|
||||
streakBuf = rentedStreak.AsSpan(0, len);
|
||||
}
|
||||
|
||||
// Allocate ROC percent rank scratch (rankPeriod circular buffer)
|
||||
double[]? rentedRoc = null;
|
||||
scoped Span<double> rocBuf;
|
||||
if (rankPeriod <= StackallocThreshold)
|
||||
{
|
||||
rocBuf = stackalloc double[rankPeriod];
|
||||
}
|
||||
else
|
||||
{
|
||||
rentedRoc = System.Buffers.ArrayPool<double>.Shared.Rent(rankPeriod);
|
||||
rocBuf = rentedRoc.AsSpan(0, rankPeriod);
|
||||
}
|
||||
|
||||
// Allocate priceRsi output and streakRsi output
|
||||
double[]? rentedPriceRsi = null;
|
||||
double[]? rentedStreakRsi = null;
|
||||
scoped Span<double> priceRsiOut;
|
||||
scoped Span<double> streakRsiOut;
|
||||
if (len <= StackallocThreshold)
|
||||
{
|
||||
priceRsiOut = stackalloc double[len];
|
||||
streakRsiOut = stackalloc double[len];
|
||||
}
|
||||
else
|
||||
{
|
||||
rentedPriceRsi = System.Buffers.ArrayPool<double>.Shared.Rent(len);
|
||||
rentedStreakRsi = System.Buffers.ArrayPool<double>.Shared.Rent(len);
|
||||
priceRsiOut = rentedPriceRsi.AsSpan(0, len);
|
||||
streakRsiOut = rentedStreakRsi.AsSpan(0, len);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Compute streak values
|
||||
int streak = 0;
|
||||
double prevClose = double.NaN;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double v = source[i];
|
||||
if (!double.IsFinite(v))
|
||||
{
|
||||
v = double.IsFinite(prevClose) ? prevClose : 0.0;
|
||||
}
|
||||
|
||||
if (!double.IsNaN(prevClose))
|
||||
{
|
||||
if (v > prevClose)
|
||||
{
|
||||
streak = streak >= 0 ? streak + 1 : 1;
|
||||
}
|
||||
else if (v < prevClose)
|
||||
{
|
||||
streak = streak <= 0 ? streak - 1 : -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
streak = 0;
|
||||
}
|
||||
}
|
||||
|
||||
streakBuf[i] = (double)streak;
|
||||
prevClose = v;
|
||||
}
|
||||
|
||||
// Compute price RSI and streak RSI
|
||||
Rsi.Batch(source, priceRsiOut, rsiPeriod);
|
||||
Rsi.Batch(streakBuf, streakRsiOut, streakPeriod);
|
||||
|
||||
// Compute percent rank of 1-bar ROC
|
||||
rocBuf.Clear();
|
||||
int rocHead = 0;
|
||||
int rocCount = 0;
|
||||
prevClose = double.NaN;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double v = source[i];
|
||||
if (!double.IsFinite(v))
|
||||
{
|
||||
v = double.IsFinite(prevClose) ? prevClose : 0.0;
|
||||
}
|
||||
|
||||
double roc = 0.0;
|
||||
if (!double.IsNaN(prevClose) && prevClose != 0.0)
|
||||
{
|
||||
roc = (v - prevClose) / prevClose * 100.0;
|
||||
}
|
||||
|
||||
prevClose = v;
|
||||
|
||||
bool wasEmpty = rocCount < rankPeriod;
|
||||
rocBuf[rocHead] = roc;
|
||||
rocHead = (rocHead + 1) % rankPeriod;
|
||||
if (wasEmpty)
|
||||
{
|
||||
rocCount++;
|
||||
}
|
||||
|
||||
int lessOrEqual = 0;
|
||||
for (int j = 0; j < rocCount; j++)
|
||||
{
|
||||
if (rocBuf[j] <= roc)
|
||||
{
|
||||
lessOrEqual++;
|
||||
}
|
||||
}
|
||||
|
||||
double pctRank = rocCount > 0 ? (double)lessOrEqual / rocCount * 100.0 : 50.0;
|
||||
double crsi = (priceRsiOut[i] + streakRsiOut[i] + pctRank) / 3.0;
|
||||
output[i] = Math.Max(0.0, Math.Min(100.0, crsi));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rentedStreak != null)
|
||||
{
|
||||
System.Buffers.ArrayPool<double>.Shared.Return(rentedStreak);
|
||||
}
|
||||
|
||||
if (rentedRoc != null)
|
||||
{
|
||||
System.Buffers.ArrayPool<double>.Shared.Return(rentedRoc);
|
||||
}
|
||||
|
||||
if (rentedPriceRsi != null)
|
||||
{
|
||||
System.Buffers.ArrayPool<double>.Shared.Return(rentedPriceRsi);
|
||||
}
|
||||
|
||||
if (rentedStreakRsi != null)
|
||||
{
|
||||
System.Buffers.ArrayPool<double>.Shared.Return(rentedStreakRsi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user