refactoring

This commit is contained in:
Miha Kralj
2025-12-16 21:16:50 -08:00
parent a67ad65fa5
commit d277e08056
137 changed files with 5074 additions and 3178 deletions
+84
View File
@@ -0,0 +1,84 @@
using System;
using Xunit;
namespace QuanTAlib.Tests;
public class AtrTests
{
[Fact]
public void BasicCalculation_DoesNotCrash()
{
var atr = new Atr(14);
var gbm = new GBM();
var bars = gbm.Fetch(100, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
foreach (var bar in bars)
{
atr.Update(bar);
}
Assert.True(double.IsFinite(atr.Last.Value));
}
[Fact]
public void IsNew_Consistency()
{
var atr = new Atr(14);
var gbm = new GBM();
var bars = gbm.Fetch(100, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Feed first 99
for (int i = 0; i < 99; i++)
{
atr.Update(bars[i]);
}
// Update with 100th point (isNew=true)
atr.Update(bars[99], true);
// Update with modified 100th point (isNew=false)
var modifiedBar = new TBar(bars[99].Time, bars[99].Open, bars[99].High + 10.0, bars[99].Low - 10.0, bars[99].Close, bars[99].Volume);
// This will update the logic: compute new TR based on modifiedBar vs prevBar(98)
double val2 = atr.Update(modifiedBar, false).Value;
// Create new instance and feed up to modified
var atr2 = new Atr(14);
for (int i = 0; i < 99; i++)
{
atr2.Update(bars[i]);
}
double val3 = atr2.Update(modifiedBar, true).Value;
Assert.Equal(val3, val2, 1e-9);
}
[Fact]
public void Reset_Works()
{
var atr = new Atr(14);
var gbm = new GBM();
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
foreach (var bar in bars) atr.Update(bar);
double lastVal = atr.Last.Value;
Assert.NotEqual(0, lastVal);
atr.Reset();
Assert.Equal(0, atr.Last.Value);
Assert.False(atr.IsHot);
}
[Fact]
public void Chainability_Works()
{
var atr = new Atr(14);
var gbm = new GBM();
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var result = atr.Update(bars);
Assert.Equal(50, result.Count);
Assert.Equal(atr.Last.Value, result.Last.Value);
}
}
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Skender.Stock.Indicators;
using TALib;
using Xunit;
using QuanTAlib.Tests;
namespace QuanTAlib;
public sealed class AtrValidationTests : IDisposable
{
private readonly ValidationTestData _data;
public AtrValidationTests()
{
_data = new ValidationTestData();
}
public void Dispose()
{
_data.Dispose();
}
[Fact]
public void MatchesSkender()
{
var atr = new Atr(14);
var results = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
var res = atr.Update(_data.Bars[i]);
results.Add(res.Value);
}
var skenderResults = _data.SkenderQuotes.GetAtr(14).ToList();
// ATR involves smoothing, so early values might differ slightly depending on initialization.
// Skender uses Wilder's initialization method.
ValidationHelper.VerifyData(results, skenderResults, x => x.Atr);
}
[Fact]
public void MatchesTalib()
{
var atr = new Atr(14);
var results = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
var res = atr.Update(_data.Bars[i]);
results.Add(res.Value);
}
double[] hData = _data.Bars.High.Select(x => x.Value).ToArray();
double[] lData = _data.Bars.Low.Select(x => x.Value).ToArray();
double[] cData = _data.Bars.Close.Select(x => x.Value).ToArray();
double[] outReal = new double[_data.Bars.Count];
var retCode = TALib.Functions.Atr(hData, lData, cData, 0..^0, outReal, out var outRange, 14);
Assert.Equal(Core.RetCode.Success, retCode);
int lookback = TALib.Functions.AtrLookback(14);
ValidationHelper.VerifyData(results, outReal, outRange, lookback);
}
}
+199
View File
@@ -0,0 +1,199 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ATR: Average True Range
/// </summary>
/// <remarks>
/// ATR measures the volatility of an asset.
/// It is the moving average (typically RMA/Wilder's) of the True Range.
///
/// Calculation:
/// 1. True Range (TR) = Max(High - Low, |High - PrevClose|, |Low - PrevClose|)
/// - For the first bar, TR = High - Low
/// 2. ATR = RMA(TR)
///
/// Sources:
/// "New Concepts in Technical Trading Systems" by J. Welles Wilder
/// </remarks>
[SkipLocalsInit]
public sealed class Atr : AbstractBase
{
private readonly Rma _rma;
private TBar _prevBar;
private bool _isInitialized;
/// <summary>
/// Creates ATR with specified period.
/// </summary>
/// <param name="period">Period for ATR calculation (must be > 0)</param>
public Atr(int period)
{
if (period <= 0)
throw new ArgumentException("Period must be greater than 0", nameof(period));
_rma = new Rma(period);
Name = $"Atr({period})";
WarmupPeriod = period;
_isInitialized = false;
}
/// <summary>
/// Creates ATR with specified source and period.
/// </summary>
/// <param name="source">Source to subscribe to</param>
/// <param name="period">Period for ATR calculation</param>
public Atr(ITValuePublisher source, int period) : this(period)
{
source.Pub += (item) => Update(item);
}
/// <summary>
/// Creates ATR with specified source and period.
/// </summary>
public Atr(TBarSeries source, int period) : this(period)
{
var tr = CalculateTrueRange(source);
_rma.Prime(tr.Values);
Last = _rma.Last;
// We can't automatically subscribe to TBarSeries updates via this constructor
// because AbstractBase doesn't enforce TBarSeries subscription structure,
// but we can rely on manual updates or the user subscribing.
}
/// <summary>
/// True if the ATR has warmed up and is providing valid results.
/// </summary>
public override bool IsHot => _rma.IsHot;
/// <summary>
/// Initializes the indicator state using the provided history.
/// Note: ATR needs OHLCV data to calculate TR properly.
/// This Prime method expects pre-calculated TR values or handles basic priming
/// if the user erroneously passes non-TR data. Ideally, use Batched TBarSeries.
/// </summary>
public override void Prime(ReadOnlySpan<double> source)
{
_rma.Prime(source);
Last = _rma.Last;
}
/// <summary>
/// Resets the ATR state.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Reset()
{
_rma.Reset();
_prevBar = default;
_isInitialized = false;
Last = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TBar input, bool isNew = true)
{
double tr;
if (!_isInitialized)
{
// For the very first bar, Wilder defines TR as High - Low
tr = input.High - input.Low;
}
else
{
// Calculate TR
double hl = input.High - input.Low;
double hpc = Math.Abs(input.High - _prevBar.Close);
double lpc = Math.Abs(input.Low - _prevBar.Close);
tr = Math.Max(hl, Math.Max(hpc, lpc));
}
if (isNew)
{
_prevBar = input;
_isInitialized = true;
}
// Smooth TR using RMA
TValue result = _rma.Update(new TValue(input.Time, tr), isNew);
Last = result;
PubEvent(Last);
return result;
}
/// <summary>
/// Update for TValue input (not recommended for ATR as it needs OHLC).
/// This treats the input value as the TR itself.
/// </summary>
public override TValue Update(TValue input, bool isNew = true)
{
// If user passes a single value, we assume it IS the True Range
TValue result = _rma.Update(input, isNew);
Last = result;
PubEvent(Last);
return result;
}
public TSeries Update(TBarSeries source)
{
if (source.Count == 0) return [];
// 1. Calculate TR series
TSeries trSeries = CalculateTrueRange(source);
// 2. Run RMA on TR
var result = _rma.Update(trSeries);
Last = _rma.Last;
// 3. Synchronize state for subsequent updates
_prevBar = source.Last;
_isInitialized = true;
return result;
}
// AbstractBase.Update(TSeries)
public override TSeries Update(TSeries source)
{
// Assumes source is already TR
return _rma.Update(source);
}
private static TSeries CalculateTrueRange(TBarSeries source)
{
var t = new List<long>(source.Count);
var v = new List<double>(source.Count);
if (source.Count == 0) return new TSeries(t, v);
// First bar TR = H - L
t.Add(source[0].Time);
v.Add(source[0].High - source[0].Low);
for (int i = 1; i < source.Count; i++)
{
var bar = source[i];
var prevBar = source[i - 1];
double hl = bar.High - bar.Low;
double hpc = Math.Abs(bar.High - prevBar.Close);
double lpc = Math.Abs(bar.Low - prevBar.Close);
double tr = Math.Max(hl, Math.Max(hpc, lpc));
t.Add(bar.Time);
v.Add(tr);
}
return new TSeries(t, v);
}
/// <summary>
/// Calculates ATR for the entire series using a new instance.
/// </summary>
public static TSeries Batch(TBarSeries source, int period)
{
var atr = new Atr(period);
return atr.Update(source);
}
}