This commit is contained in:
Miha Kralj
2024-11-08 10:07:11 -08:00
parent 11fc798517
commit 02c92712a0
5 changed files with 78 additions and 39 deletions
+5 -5
View File
@@ -122,10 +122,10 @@ public class EventingTests
return new TBar( return new TBar(
DateTime.Now, DateTime.Now,
baseValue, baseValue,
baseValue + Math.abs(GetRandomDouble(rng) * 10), baseValue + Math.Abs(GetRandomDouble(rng) * 10),
baseValue - Math.abs(GetRandomDouble(rng) * 10), baseValue - Math.Abs(GetRandomDouble(rng) * 10),
baseValue + (GetRandomDouble(rng) * 5), baseValue + (GetRandomDouble(rng) * 5),
Math.abs(GetRandomDouble(rng) * 1000), Math.Abs(GetRandomDouble(rng) * 1000),
true true
); );
} }
@@ -151,7 +151,7 @@ public class EventingTests
} }
bool areEqual = (double.IsNaN(directIndicator.Value) && double.IsNaN(eventIndicator.Value)) || bool areEqual = (double.IsNaN(directIndicator.Value) && double.IsNaN(eventIndicator.Value)) ||
Math.abs(directIndicator.Value - eventIndicator.Value) < Tolerance; Math.Abs(directIndicator.Value - eventIndicator.Value) < Tolerance;
Assert.True(areEqual, $"Value indicator {indicatorName} failed: Expected {directIndicator.Value}, Actual {eventIndicator.Value}"); Assert.True(areEqual, $"Value indicator {indicatorName} failed: Expected {directIndicator.Value}, Actual {eventIndicator.Value}");
} }
@@ -177,7 +177,7 @@ public class EventingTests
} }
bool areEqual = (double.IsNaN(directIndicator.Value) && double.IsNaN(eventIndicator.Value)) || bool areEqual = (double.IsNaN(directIndicator.Value) && double.IsNaN(eventIndicator.Value)) ||
Math.abs(directIndicator.Value - eventIndicator.Value) < Tolerance; Math.Abs(directIndicator.Value - eventIndicator.Value) < Tolerance;
Assert.True(areEqual, $"Bar indicator {indicatorName} failed: Expected {directIndicator.Value}, Actual {eventIndicator.Value}"); Assert.True(areEqual, $"Bar indicator {indicatorName} failed: Expected {directIndicator.Value}, Actual {eventIndicator.Value}");
} }
+1 -1
View File
@@ -162,7 +162,7 @@ namespace QuanTAlib
[Fact] public void Vortex() => TestIndicatorMultipleFields<momentum::QuanTAlib.VortexIndicator>(new[] { "PlusLine", "MinusLine" }); [Fact] public void Vortex() => TestIndicatorMultipleFields<momentum::QuanTAlib.VortexIndicator>(new[] { "PlusLine", "MinusLine" });
// Oscillators Indicators // Oscillators Indicators
[Fact] public void Cti() => TestIndicator<oscillator::QuanTAlib.CtiIndicator>("Series"); [Fact] public void Cti() => TestIndicator<oscillators::QuanTAlib.CtiIndicator>("Series");
} }
} }
+49 -16
View File
@@ -3,32 +3,37 @@ namespace QuanTAlib;
/// <summary> /// <summary>
/// CTI: Ehler's Correlation Trend Indicator /// CTI: Ehler's Correlation Trend Indicator
/// A momentum oscillator that measures the correlation between the price and a lagged version of the price. /// Measures the correlation between price and an ideal trend line.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The CTI calculation process: /// The CTI calculation process:
/// 1. Calculate the correlation between the price and a lagged version of the price over a specified period. /// 1. Correlates price curve with an ideal trend line (negative count due to backwards data storage)
/// 2. Normalize the correlation values to oscillate between -1 and 1. /// 2. Uses Spearman's correlation algorithm
/// 3. Use the normalized correlation values to calculate the CTI. /// 3. Returns values between -1 and 1
/// ///
/// Key characteristics: /// Key characteristics:
/// - Oscillates between -1 and 1 /// - Oscillates between -1 and 1
/// - Positive values indicate bullish momentum /// - Positive values indicate price follows uptrend
/// - Negative values indicate bearish momentum /// - Negative values indicate price follows downtrend
/// ///
/// Formula: /// Formula:
/// CTI = 2 * (Correlation - 0.5) /// CTI = (n∑xy - ∑x∑y) / sqrt((n∑x² - (∑x)²)(n∑y² - (∑y)²))
/// where:
/// x = price curve
/// y = -count (ideal trend line)
/// n = period length
/// ///
/// Sources: /// Sources:
/// John Ehlers - "Cybernetic Analysis for Stocks and Futures" (2004) /// John Ehlers - "Cybernetic Analysis for Stocks and Futures" (2004)
/// https://www.investopedia.com/terms/c/correlation-trend-indicator.asp /// John Ehlers, Correlation Trend Indicator, Stocks & Commodities May-2020
/// </remarks> /// </remarks>
[SkipLocalsInit] [SkipLocalsInit]
public sealed class Cti : AbstractBase public sealed class Cti : AbstractBase
{ {
private readonly int _period; private readonly int _period;
private readonly CircularBuffer _priceBuffer; private readonly CircularBuffer _priceBuffer;
private readonly Corr _correlation; private readonly double[] _trendLine;
private const int MinimumPoints = 2; // Minimum points needed for correlation
/// <param name="source">The data source object that publishes updates.</param> /// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The calculation period (default: 20)</param> /// <param name="period">The calculation period (default: 20)</param>
@@ -44,7 +49,14 @@ public sealed class Cti : AbstractBase
{ {
_period = period; _period = period;
_priceBuffer = new CircularBuffer(period); _priceBuffer = new CircularBuffer(period);
_correlation = new Corr(period);
// Pre-calculate trend line values since they're static
_trendLine = new double[period];
for (int i = 0; i < period; i++)
{
_trendLine[i] = -i; // negative count for backwards data
}
WarmupPeriod = period; WarmupPeriod = period;
Name = "CTI"; Name = "CTI";
} }
@@ -62,15 +74,36 @@ public sealed class Cti : AbstractBase
protected override double Calculation() protected override double Calculation()
{ {
ManageState(Input.IsNew); ManageState(Input.IsNew);
_priceBuffer.Add(Input.Value, Input.IsNew); _priceBuffer.Add(Input.Value, Input.IsNew);
var laggedPrice = _index >= _period ? _priceBuffer[_index - _period] : double.NaN;
_correlation.Calc(new TValue(Input.Time, Input.Value, Input.IsNew), new TValue(Input.Time, laggedPrice, Input.IsNew)); // Use available points for early calculations
int points = Math.Min(_index + 1, _period);
if (points < MinimumPoints) return 0; // Need at least 2 points for correlation
if (_index < _period - 1) return double.NaN; double sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0;
var correlation = _correlation.Value; // Calculate correlation components using available points
return 2 * (correlation - 0.5); for (int i = 0; i < points; i++)
{
double x = _priceBuffer[i]; // price curve
double y = _trendLine[i]; // pre-calculated trend line
sx += x;
sy += y;
sxx += x * x;
sxy += x * y;
syy += y * y;
}
// Check for numerical stability
double denomX = points * sxx - sx * sx;
double denomY = points * syy - sy * sy;
if (denomX > 0 && denomY > 0)
{
return (points * sxy - sx * sy) / Math.Sqrt(denomX * denomY);
}
return 0;
} }
} }
+1
View File
@@ -59,6 +59,7 @@ public class WmaIndicator : Indicator, IWatchlistIndicator
Series!.SetValue(result.Value); Series!.SetValue(result.Value);
Series!.SetMarker(0, Color.Transparent); //OnPaintChart draws the line, hidden here Series!.SetMarker(0, Color.Transparent); //OnPaintChart draws the line, hidden here
} }
#pragma warning disable CA1416 // Validate platform compatibility
public override void OnPaintChart(PaintChartEventArgs args) public override void OnPaintChart(PaintChartEventArgs args)
{ {
+22 -17
View File
@@ -3,10 +3,10 @@ using System.Drawing;
namespace QuanTAlib namespace QuanTAlib
{ {
public class CtiIndicator : Indicator public class CtiIndicator : Indicator, IWatchlistIndicator
{ {
[InputParameter("Period", 0, 1, 100, 1, 0)] [InputParameter("Period", 0, 1, 100, 1, 0)]
public int Period = 20; public int Period { get; set; } = 20;
[InputParameter("Source Type", 1, variants: new object[] [InputParameter("Source Type", 1, variants: new object[]
{ {
@@ -21,46 +21,51 @@ namespace QuanTAlib
"OHLC4", SourceType.OHLC4, "OHLC4", SourceType.OHLC4,
"HLCC4", SourceType.HLCC4 "HLCC4", SourceType.HLCC4
})] })]
public SourceType SourceType = SourceType.Close; public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show Cold Values", 2)] [InputParameter("Show Cold Values", 2)]
public bool ShowColdValues = false; public bool ShowColdValues { get; set; } = true;
private Cti cti; private Cti? cti;
protected LineSeries? CtiSeries; protected LineSeries? Series;
protected string? SourceName;
public int MinHistoryDepths => Period + 1; public int MinHistoryDepths => Period + 1;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths; int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public CtiIndicator() public CtiIndicator()
{ {
OnBackGround = false;
SeparateWindow = true;
this.Name = "CTI - Ehler's Correlation Trend Indicator"; this.Name = "CTI - Ehler's Correlation Trend Indicator";
SourceName = Source.ToString();
this.Description = "A momentum oscillator that measures the correlation between the price and a lagged version of the price."; this.Description = "A momentum oscillator that measures the correlation between the price and a lagged version of the price.";
CtiSeries = new($"CTI {Period}", Color: IndicatorExtensions.Oscillators, 2, LineStyle.Solid); Series = new($"CTI {Period}", color: IndicatorExtensions.Oscillators, width: 2, LineStyle.Solid);
AddLineSeries(CtiSeries); AddLineSeries(Series);
} }
protected override void OnInit() protected override void OnInit()
{ {
cti = new Cti(this.Period); cti = new Cti(this.Period);
SourceName = Source.ToString();
base.OnInit(); base.OnInit();
} }
protected override void OnUpdate(UpdateArgs args) protected override void OnUpdate(UpdateArgs args)
{ {
TValue input = this.GetInputValue(args, Source); TValue input = this.GetInputValue(args, Source);
cti.Calc(value); TValue result = cti!.Calc(input);
CtiSeries!.SetValue(cti.Value); Series!.SetValue(result);
CtiSeries!.SetMarker(0, Color.Transparent); Series!.SetMarker(0, Color.Transparent);
} }
public override string ShortName => $"CTI ({Period}:{SourceName})"; public override string ShortName => $"CTI ({Period}:{SourceName})";
#pragma warning disable CA1416 // Validate platform compatibility #pragma warning disable CA1416 // Validate platform compatibility
public override void OnPaintChart(PaintChartEventArgs args) public override void OnPaintChart(PaintChartEventArgs args)
{ {
base.OnPaintChart(args); base.OnPaintChart(args);
this.PaintSmoothCurve(args, CtiSeries!, cti!.WarmupPeriod, showColdValues: ShowColdValues, tension: 0.2); this.PaintSmoothCurve(args, Series!, cti!.WarmupPeriod, showColdValues: ShowColdValues, tension: 0.0);
} }
} }
} }