style: format code with dotnet-format

This commit fixes the style issues introduced in 1e77eb8 according to the output
from dotnet-format.

Details: None
This commit is contained in:
deepsource-autofix[bot]
2024-10-06 06:59:26 +00:00
committed by GitHub
parent 1e77eb80a4
commit 5fe968754f
116 changed files with 1773 additions and 2748 deletions
+2 -2
View File
@@ -52,13 +52,13 @@ public class Dsma : AbstractBase
// SuperSmoother filter coefficients
double _a1 = Math.Exp(-1.414 * Math.PI / (0.5 * period));
double _b1 = 2 * _a1 * Math.Cos(1.414 * Math.PI / (0.5 * period));
_c2 = _b1;
_c3 = -_a1 * _a1;
_c1 = 1 - _c2 - _c3;
Name = "Dsma";
WarmupPeriod = (int) (period * 1.5); // A conservative estimate
WarmupPeriod = (int)(period * 1.5); // A conservative estimate
Init();
}
+1 -1
View File
@@ -45,7 +45,7 @@ namespace QuanTAlib
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
if (_buffer.Count < _period)
+5 -2
View File
@@ -40,7 +40,9 @@ public class Mgdi : AbstractBase
{
_p_prevMd = _prevMd;
_index++;
} else {
}
else
{
_prevMd = _p_prevMd;
}
}
@@ -50,7 +52,8 @@ public class Mgdi : AbstractBase
ManageState(Input.IsNew);
double value = Input.Value;
if (_index < 2){
if (_index < 2)
{
_prevMd = value;
}
else
+3 -3
View File
@@ -6,9 +6,9 @@ public class Qema : AbstractBase
private readonly Ema _ema1, _ema2, _ema3, _ema4;
private double _lastQema, _p_lastQema;
public Qema(double k1=0.2, double k2=0.2, double k3=0.2, double k4=0.2) : base()
public Qema(double k1 = 0.2, double k2 = 0.2, double k3 = 0.2, double k4 = 0.2) : base()
{
if (k1 <= 0 || k2 <= 0 || k3 <= 0 || k4 <= 0 )
if (k1 <= 0 || k2 <= 0 || k3 <= 0 || k4 <= 0)
{
throw new ArgumentOutOfRangeException("All k values must be in the range (0, 1].");
}
@@ -26,7 +26,7 @@ public class Qema : AbstractBase
Name = $"QEMA ({k1:F2},{k2:F2},{k3:F2},{k4:F2})";
double smK = Math.Min(Math.Min(_k1, _k2), Math.Min(_k3, _k4));
WarmupPeriod = (int) ((2 - smK) / smK);
WarmupPeriod = (int)((2 - smK) / smK);
Init();
}
+71 -55
View File
@@ -1,65 +1,81 @@
using System;
using System.Runtime.CompilerServices;
namespace QuanTAlib {
namespace QuanTAlib
{
public class Rma : AbstractBase {
private readonly int _period;
private double _alpha;
private double _lastRMA;
private double _savedLastRMA;
public class Rma : AbstractBase
{
private readonly int _period;
private double _alpha;
private double _lastRMA;
private double _savedLastRMA;
public Rma(int period) : base() {
if (period < 1) {
throw new ArgumentException("Period must be greater than or equal to 1.", nameof(period));
}
_period = period;
WarmupPeriod = period * 2;
_alpha = 1.0 / _period; // Wilder's smoothing factor
Name = $"Rma({_period})";
Init();
}
public Rma(object source, int period) : this(period) {
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
public override void Init() {
base.Init();
_lastRMA = 0;
_savedLastRMA = 0;
}
protected override void ManageState(bool isNew) {
if (isNew) {
_savedLastRMA = _lastRMA;
_lastValidValue = Input.Value;
_index++;
} else {
_lastRMA = _savedLastRMA;
}
}
protected override double Calculation() {
ManageState(Input.IsNew);
double rma;
if (_index == 1) {
rma = Input.Value;
} else if (_index <= _period) {
// Simple average during initial period
rma = (_lastRMA * (_index - 1) + Input.Value) / _index;
} else {
// Wilder's smoothing method
rma = _alpha * (Input.Value - _lastRMA) + _lastRMA;
public Rma(int period) : base()
{
if (period < 1)
{
throw new ArgumentException("Period must be greater than or equal to 1.", nameof(period));
}
_period = period;
WarmupPeriod = period * 2;
_alpha = 1.0 / _period; // Wilder's smoothing factor
Name = $"Rma({_period})";
Init();
}
_lastRMA = rma;
IsHot = _index >= WarmupPeriod;
public Rma(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
return rma;
public override void Init()
{
base.Init();
_lastRMA = 0;
_savedLastRMA = 0;
}
protected override void ManageState(bool isNew)
{
if (isNew)
{
_savedLastRMA = _lastRMA;
_lastValidValue = Input.Value;
_index++;
}
else
{
_lastRMA = _savedLastRMA;
}
}
protected override double Calculation()
{
ManageState(Input.IsNew);
double rma;
if (_index == 1)
{
rma = Input.Value;
}
else if (_index <= _period)
{
// Simple average during initial period
rma = (_lastRMA * (_index - 1) + Input.Value) / _index;
}
else
{
// Wilder's smoothing method
rma = _alpha * (Input.Value - _lastRMA) + _lastRMA;
}
_lastRMA = rma;
IsHot = _index >= WarmupPeriod;
return rma;
}
}
}
}
+27 -12
View File
@@ -1,6 +1,7 @@
namespace QuanTAlib;
public class T3 : AbstractBase {
public class T3 : AbstractBase
{
private readonly int _period;
private readonly double _vfactor;
private readonly bool _useSma;
@@ -9,8 +10,10 @@ public class T3 : AbstractBase {
private double _lastEma1, _lastEma2, _lastEma3, _lastEma4, _lastEma5, _lastEma6;
private double _p_lastEma1, _p_lastEma2, _p_lastEma3, _p_lastEma4, _p_lastEma5, _p_lastEma6;
public T3(int period, double vfactor = 0.7, bool useSma = true) {
if (period < 1) {
public T3(int period, double vfactor = 0.7, bool useSma = true)
{
if (period < 1)
{
throw new ArgumentException("Period must be greater than or equal to 1.", nameof(period));
}
_period = period;
@@ -37,12 +40,14 @@ public class T3 : AbstractBase {
Init();
}
public T3(object source, int period, double vfactor = 0.7, bool useSma = true) : this(period, vfactor, useSma) {
public T3(object source, int period, double vfactor = 0.7, bool useSma = true) : this(period, vfactor, useSma)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
public override void Init() {
public override void Init()
{
_lastEma1 = _lastEma2 = _lastEma3 = _lastEma4 = _lastEma5 = _lastEma6 = 0;
_buffer1.Clear();
_buffer2.Clear();
@@ -52,8 +57,10 @@ public class T3 : AbstractBase {
_buffer6.Clear();
}
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
_p_lastEma1 = _lastEma1;
@@ -62,7 +69,9 @@ public class T3 : AbstractBase {
_p_lastEma4 = _lastEma4;
_p_lastEma5 = _lastEma5;
_p_lastEma6 = _lastEma6;
} else {
}
else
{
_lastEma1 = _p_lastEma1;
_lastEma2 = _p_lastEma2;
_lastEma3 = _p_lastEma3;
@@ -73,14 +82,18 @@ public class T3 : AbstractBase {
}
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
double ema1, ema2, ema3, ema4, ema5, ema6;
if (_index == 1) {
if (_index == 1)
{
ema1 = ema2 = ema3 = ema4 = ema5 = ema6 = Input.Value;
} else if (_index <= _period && _useSma) {
}
else if (_index <= _period && _useSma)
{
_buffer1.Add(Input.Value, Input.IsNew);
ema1 = _buffer1.Average();
_buffer2.Add(ema1, Input.IsNew);
@@ -93,7 +106,9 @@ public class T3 : AbstractBase {
ema5 = _buffer5.Average();
_buffer6.Add(ema5, Input.IsNew);
ema6 = _buffer6.Average();
} else {
}
else
{
ema1 = _k * (Input.Value - _lastEma1) + _lastEma1;
ema2 = _k * (ema1 - _lastEma2) + _lastEma2;
ema3 = _k * (ema2 - _lastEma3) + _lastEma3;
+1 -1
View File
@@ -58,7 +58,7 @@ public class Tema : AbstractBase
{
double result, _ema1, _ema2, _ema3;
ManageState(Input.IsNew);
_e = (_e > 1e-10) ? (1 - _k) * _e : 0;
double _invE = (_e > 1e-10) ? 1 / (1 - _e) : 1;
+1 -1
View File
@@ -55,7 +55,7 @@ public class Zlema : AbstractBase
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer!.Add(Input.Value, Input.IsNew);
int lag = Math.Max(Math.Min((int)((_period - 1) * 0.5), _buffer.Count - 1), 0) + 1;
+14 -7
View File
@@ -8,7 +8,8 @@ namespace QuanTAlib;
/// and methods used by inheriting indicator types. It handles the basic flow of
/// receiving bar data, performing calculations, and publishing results.
/// </remarks>
public abstract class AbstractBarBase : iTValue {
public abstract class AbstractBarBase : iTValue
{
public DateTime Time { get; set; }
public double Value { get; set; }
public bool IsNew { get; set; }
@@ -20,7 +21,8 @@ public abstract class AbstractBarBase : iTValue {
public event ValueSignal Pub = delegate { };
protected int _index;
protected double _lastValidValue;
protected AbstractBarBase() {
protected AbstractBarBase()
{
// Add parameters into constructor if needed
}
@@ -34,7 +36,8 @@ public abstract class AbstractBarBase : iTValue {
/// <summary>
/// Initializes the indicator's state.
/// </summary>
public virtual void Init() {
public virtual void Init()
{
_index = 0;
_lastValidValue = 0;
}
@@ -44,9 +47,11 @@ public abstract class AbstractBarBase : iTValue {
/// </summary>
/// <param name="input">The input bar data.</param>
/// <returns>A TValue containing the calculated result.</returns>
public virtual TValue Calc(TBar input) {
public virtual TValue Calc(TBar input)
{
Input = input;
if (double.IsNaN(input.Close) || double.IsInfinity(input.Close)) {
if (double.IsNaN(input.Close) || double.IsInfinity(input.Close))
{
return Process(new TValue(Time: input.Time, Value: GetLastValid(), IsNew: input.IsNew, IsHot: true));
}
this.Value = Calculation();
@@ -57,7 +62,8 @@ public abstract class AbstractBarBase : iTValue {
/// Retrieves the last valid calculated value.
/// </summary>
/// <returns>The last valid value of the indicator.</returns>
protected virtual double GetLastValid() {
protected virtual double GetLastValid()
{
return this.Value;
}
@@ -79,7 +85,8 @@ public abstract class AbstractBarBase : iTValue {
/// </summary>
/// <param name="value">The calculated TValue to process.</param>
/// <returns>The processed TValue.</returns>
protected virtual TValue Process(TValue value) {
protected virtual TValue Process(TValue value)
{
this.Time = value.Time;
this.Value = value.Value;
this.IsNew = value.IsNew;
+96 -46
View File
@@ -12,7 +12,8 @@ namespace QuanTAlib;
/// a fixed-size buffer of double values. It uses SIMD operations for improved performance
/// on supported hardware.
/// </remarks>
public class CircularBuffer : IEnumerable<double> {
public class CircularBuffer : IEnumerable<double>
{
private readonly double[] _buffer;
private int _start = 0;
private int _size = 0;
@@ -31,7 +32,8 @@ public class CircularBuffer : IEnumerable<double> {
/// Initializes a new instance of the CircularBuffer class with the specified capacity.
/// </summary>
/// <param name="capacity">The maximum number of elements the buffer can hold.</param>
public CircularBuffer(int capacity) {
public CircularBuffer(int capacity)
{
Capacity = capacity;
_buffer = GC.AllocateArray<double>(capacity, pinned: true);
}
@@ -42,16 +44,23 @@ public class CircularBuffer : IEnumerable<double> {
/// <param name="item">The item to add to the buffer.</param>
/// <param name="isNew">Indicates whether the item is a new value or an update to the last added value.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(double item, bool isNew = true) {
if (_size == 0 || isNew) {
if (_size < Capacity) {
public void Add(double item, bool isNew = true)
{
if (_size == 0 || isNew)
{
if (_size < Capacity)
{
_buffer[(_start + _size) % Capacity] = item;
_size++;
} else {
}
else
{
_buffer[_start] = item;
_start = (_start + 1) % Capacity;
}
} else {
}
else
{
_buffer[(_start + _size - 1) % Capacity] = item;
}
}
@@ -61,15 +70,18 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The element at the specified index.</returns>
public double this[Index index] {
public double this[Index index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get {
get
{
int actualIndex = index.IsFromEnd ? _size - index.Value : index.Value;
actualIndex = Math.Clamp(actualIndex, 0, _size - 1);
return _buffer[(_start + actualIndex) % Capacity];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set {
set
{
int actualIndex = index.IsFromEnd ? _size - index.Value : index.Value;
actualIndex = Math.Clamp(actualIndex, 0, _size - 1);
_buffer[(_start + actualIndex) % Capacity] = value;
@@ -77,7 +89,8 @@ public class CircularBuffer : IEnumerable<double> {
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowArgumentOutOfRangeException() {
private static void ThrowArgumentOutOfRangeException()
{
throw new ArgumentOutOfRangeException("index", "Index is out of range.");
}
@@ -86,7 +99,8 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>The newest element in the buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Newest() {
public double Newest()
{
if (_size == 0)
return 0;
return _buffer[(_start + _size - 1) % Capacity];
@@ -97,14 +111,16 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>The oldest element in the buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Oldest() {
public double Oldest()
{
if (_size == 0)
ThrowInvalidOperationException();
return _buffer[_start];
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidOperationException() {
private static void ThrowInvalidOperationException()
{
throw new InvalidOperationException("Buffer is empty.");
}
@@ -119,13 +135,15 @@ public class CircularBuffer : IEnumerable<double> {
/// <summary>
/// Represents an enumerator for the CircularBuffer.
/// </summary>
public struct Enumerator : IEnumerator<double> {
public struct Enumerator : IEnumerator<double>
{
private readonly CircularBuffer _buffer;
private int _index;
private double _current;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(CircularBuffer buffer) {
internal Enumerator(CircularBuffer buffer)
{
_buffer = buffer;
_index = -1;
_current = default;
@@ -136,7 +154,8 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext() {
public bool MoveNext()
{
if (_index + 1 >= _buffer._size)
return false;
@@ -154,7 +173,8 @@ public class CircularBuffer : IEnumerable<double> {
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the buffer.
/// </summary>
public void Reset() {
public void Reset()
{
_index = -1;
_current = default;
}
@@ -171,13 +191,17 @@ public class CircularBuffer : IEnumerable<double> {
/// <param name="destination">The one-dimensional array that is the destination of the elements copied from the buffer.</param>
/// <param name="destinationIndex">The zero-based index in array at which copying begins.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(double[] destination, int destinationIndex) {
public void CopyTo(double[] destination, int destinationIndex)
{
if (_size == 0)
return;
if (_start + _size <= Capacity) {
if (_start + _size <= Capacity)
{
Array.Copy(_buffer, _start, destination, destinationIndex, _size);
} else {
}
else
{
int firstPartLength = Capacity - _start;
Array.Copy(_buffer, _start, destination, destinationIndex, firstPartLength);
Array.Copy(_buffer, 0, destination, destinationIndex + firstPartLength, _size - firstPartLength);
@@ -189,13 +213,17 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>A read-only span over the buffer contents.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<double> GetSpan() {
public ReadOnlySpan<double> GetSpan()
{
if (_size == 0)
return ReadOnlySpan<double>.Empty;
if (_start + _size <= Capacity) {
if (_start + _size <= Capacity)
{
return new ReadOnlySpan<double>(_buffer, _start, _size);
} else {
}
else
{
return new ReadOnlySpan<double>(ToArray());
}
}
@@ -216,7 +244,8 @@ public class CircularBuffer : IEnumerable<double> {
/// Removes all elements from the buffer.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear() {
public void Clear()
{
Array.Clear(_buffer, 0, _buffer.Length);
_start = 0;
_size = 0;
@@ -227,7 +256,8 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>The maximum value in the buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Max() {
public double Max()
{
if (_size == 0)
ThrowInvalidOperationException();
@@ -239,7 +269,8 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>The minimum value in the buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Min() {
public double Min()
{
if (_size == 0)
ThrowInvalidOperationException();
@@ -251,7 +282,8 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>The sum of all values in the buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Sum() {
public double Sum()
{
return SumSimd();
}
@@ -260,7 +292,8 @@ public class CircularBuffer : IEnumerable<double> {
/// </summary>
/// <returns>The average of all values in the buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Average() {
public double Average()
{
if (_size == 0)
ThrowInvalidOperationException();
@@ -268,22 +301,26 @@ public class CircularBuffer : IEnumerable<double> {
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double MaxSimd() {
private double MaxSimd()
{
var span = GetSpan();
var vectorSize = Vector<double>.Count;
var maxVector = new Vector<double>(double.MinValue);
int i = 0;
for (; i <= span.Length - vectorSize; i += vectorSize) {
for (; i <= span.Length - vectorSize; i += vectorSize)
{
maxVector = Vector.Max(maxVector, new Vector<double>(span.Slice(i, vectorSize)));
}
double max = double.MinValue;
for (int j = 0; j < vectorSize; j++) {
for (int j = 0; j < vectorSize; j++)
{
max = Math.Max(max, maxVector[j]);
}
for (; i < span.Length; i++) {
for (; i < span.Length; i++)
{
max = Math.Max(max, span[i]);
}
@@ -291,22 +328,26 @@ public class CircularBuffer : IEnumerable<double> {
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double MinSimd() {
private double MinSimd()
{
var span = GetSpan();
var vectorSize = Vector<double>.Count;
var minVector = new Vector<double>(double.MaxValue);
int i = 0;
for (; i <= span.Length - vectorSize; i += vectorSize) {
for (; i <= span.Length - vectorSize; i += vectorSize)
{
minVector = Vector.Min(minVector, new Vector<double>(span.Slice(i, vectorSize)));
}
double min = double.MaxValue;
for (int j = 0; j < vectorSize; j++) {
for (int j = 0; j < vectorSize; j++)
{
min = Math.Min(min, minVector[j]);
}
for (; i < span.Length; i++) {
for (; i < span.Length; i++)
{
min = Math.Min(min, span[i]);
}
@@ -314,22 +355,26 @@ public class CircularBuffer : IEnumerable<double> {
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double SumSimd() {
private double SumSimd()
{
var span = GetSpan();
var vectorSize = Vector<double>.Count;
var sumVector = Vector<double>.Zero;
int i = 0;
for (; i <= span.Length - vectorSize; i += vectorSize) {
for (; i <= span.Length - vectorSize; i += vectorSize)
{
sumVector += new Vector<double>(span.Slice(i, vectorSize));
}
double sum = 0;
for (int j = 0; j < vectorSize; j++) {
for (int j = 0; j < vectorSize; j++)
{
sum += sumVector[j];
}
for (; i < span.Length; i++) {
for (; i < span.Length; i++)
{
sum += span[i];
}
@@ -340,7 +385,8 @@ public class CircularBuffer : IEnumerable<double> {
/// Copies the buffer elements to a new array.
/// </summary>
/// <returns>An array containing copies of the buffer elements.</returns>
public double[] ToArray() {
public double[] ToArray()
{
double[] array = new double[_size];
CopyTo(array, 0);
return array;
@@ -350,10 +396,12 @@ public class CircularBuffer : IEnumerable<double> {
/// Performs a parallel operation on the buffer elements.
/// </summary>
/// <param name="operation">The operation to perform on each partition of the buffer.</param>
public void ParallelOperation(Func<double[], int, int, double> operation) {
public void ParallelOperation(Func<double[], int, int, double> operation)
{
const int MinimumPartitionSize = 1024;
if (_size < MinimumPartitionSize) {
if (_size < MinimumPartitionSize)
{
var span = GetSpan();
var array = span.ToArray();
operation(array, 0, array.Length);
@@ -363,7 +411,8 @@ public class CircularBuffer : IEnumerable<double> {
int partitionCount = Environment.ProcessorCount;
int partitionSize = _size / partitionCount;
if (partitionSize < MinimumPartitionSize) {
if (partitionSize < MinimumPartitionSize)
{
partitionCount = Math.Max(1, _size / MinimumPartitionSize);
partitionSize = _size / partitionCount;
}
@@ -371,7 +420,8 @@ public class CircularBuffer : IEnumerable<double> {
var buffer = ToArray();
var results = new double[partitionCount];
Parallel.For(0, partitionCount, i => {
Parallel.For(0, partitionCount, i =>
{
int start = i * partitionSize;
int length = (i == partitionCount - 1) ? _size - start : partitionSize;
results[i] = operation(buffer, start, length);
+19 -19
View File
@@ -14,28 +14,28 @@ public interface iTBar
public readonly record struct TBar(DateTime Time, double Open, double High, double Low, double Close, double Volume, bool IsNew = true) : iTBar
{
public DateTime Time { get; init; } = Time;
public double Open { get; init; } = Open;
public double High { get; init; } = High;
public double Low { get; init; } = Low;
public double Close { get; init; } = Close;
public double Volume { get; init; } = Volume;
public bool IsNew { get; init; } = IsNew;
public double Open { get; init; } = Open;
public double High { get; init; } = High;
public double Low { get; init; } = Low;
public double Close { get; init; } = Close;
public double Volume { get; init; } = Volume;
public bool IsNew { get; init; } = IsNew;
public double HL2 => (High + Low) * 0.5;
public double OC2 => (Open + Close) * 0.5;
public double OHL3 => (Open + High + Low) / 3;
public double HLC3 => (High + Low + Close) / 3;
public double OHLC4 => (Open + High + Low + Close) * 0.25;
public double HLCC4 => (High + Low + Close + Close) * 0.25;
public double HL2 => (High + Low) * 0.5;
public double OC2 => (Open + Close) * 0.5;
public double OHL3 => (Open + High + Low) / 3;
public double HLC3 => (High + Low + Close) / 3;
public double OHLC4 => (Open + High + Low + Close) * 0.25;
public double HLCC4 => (High + Low + Close + Close) * 0.25;
public TBar() : this(DateTime.UtcNow, 0, 0, 0, 0, 0) { }
public TBar(double Open, double High, double Low, double Close, double Volume, bool IsNew = true) : this(DateTime.UtcNow, Open, High, Low, Close, Volume, IsNew) { }
public TBar(double value) : this(Time: DateTime.UtcNow, Open: value, High: value, Low: value, Close: value, Volume: value, IsNew: true) { }
public TBar(TValue value) : this(Time: value.Time, Open: value.Value, High: value.Value, Low: value.Value, Close: value.Value, Volume: value.Value, IsNew: value.IsNew) { }
public TBar() : this(DateTime.UtcNow, 0, 0, 0, 0, 0) { }
public TBar(double Open, double High, double Low, double Close, double Volume, bool IsNew = true) : this(DateTime.UtcNow, Open, High, Low, Close, Volume, IsNew) { }
public TBar(double value) : this(Time: DateTime.UtcNow, Open: value, High: value, Low: value, Close: value, Volume: value, IsNew: true) { }
public TBar(TValue value) : this(Time: value.Time, Open: value.Value, High: value.Value, Low: value.Value, Close: value.Value, Volume: value.Value, IsNew: value.IsNew) { }
public static implicit operator double(TBar bar) => bar.Close;
public static implicit operator DateTime(TBar tv) => tv.Time;
public override string ToString() => $"[{Time:yyyy-MM-dd HH:mm:ss}: O={Open:F2}, H={High:F2}, L={Low:F2}, C={Close:F2}, V={Volume:F2}]";
public static implicit operator double(TBar bar) => bar.Close;
public static implicit operator DateTime(TBar tv) => tv.Time;
public override string ToString() => $"[{Time:yyyy-MM-dd HH:mm:ss}: O={Open:F2}, H={High:F2}, L={Low:F2}, C={Close:F2}, V={Volume:F2}]";
}
public delegate void BarSignal(object source, in TBarEventArgs args);
+12 -12
View File
@@ -11,19 +11,19 @@ public interface iTValue
public readonly record struct TValue(DateTime Time, double Value, bool IsNew = true, bool IsHot = true) : iTValue
{
public DateTime Time { get; init; } = Time;
public double Value { get; init; } = Value;
public bool IsNew { get; init; } = IsNew;
public bool IsHot { get; init; } = IsHot;
public DateTime t => Time;
public double v => Value;
public double Value { get; init; } = Value;
public bool IsNew { get; init; } = IsNew;
public bool IsHot { get; init; } = IsHot;
public DateTime t => Time;
public double v => Value;
public TValue() : this(DateTime.UtcNow, 0) { }
public TValue(double value, bool isNew = true, bool isHot = true) : this(DateTime.UtcNow, value, IsNew: isNew, IsHot: isHot) { }
public static implicit operator double(TValue tv) => tv.Value;
public static implicit operator DateTime(TValue tv) => tv.Time;
public static implicit operator TValue(double value) => new TValue(DateTime.UtcNow, value);
public TValue() : this(DateTime.UtcNow, 0) { }
public TValue(double value, bool isNew = true, bool isHot = true) : this(DateTime.UtcNow, value, IsNew: isNew, IsHot: isHot) { }
public static implicit operator double(TValue tv) => tv.Value;
public static implicit operator DateTime(TValue tv) => tv.Time;
public static implicit operator TValue(double value) => new TValue(DateTime.UtcNow, value);
public override string ToString() => $"[{Time:yyyy-MM-dd HH:mm:ss}, {Value:F2}, IsNew: {IsNew}, IsHot: {IsHot}]";
public override string ToString() => $"[{Time:yyyy-MM-dd HH:mm:ss}, {Value:F2}, IsNew: {IsNew}, IsHot: {IsHot}]";
}
public delegate void ValueSignal(object source, in ValueEventArgs args);
@@ -66,7 +66,7 @@ public class TSeries : List<TValue>
public new virtual void Add(TValue tick)
{
if (tick.IsNew || base.Count==0) { base.Add(tick); }
if (tick.IsNew || base.Count == 0) { base.Add(tick); }
else { this[^1] = tick; }
Pub?.Invoke(this, new ValueEventArgs(tick));
}
+56 -56
View File
@@ -4,67 +4,67 @@ namespace QuanTAlib;
public class GbmFeed : TBarSeries
{
private readonly double _mu, _sigma;
private readonly Random _random;
private double _lastClose, _lastHigh, _lastLow;
private readonly double _mu, _sigma;
private readonly Random _random;
private double _lastClose, _lastHigh, _lastLow;
public GbmFeed(double initialPrice = 100.0, double mu = 0.05, double sigma = 0.2) : base()
{
_lastClose = _lastHigh = _lastLow = initialPrice;
_mu = mu;
_sigma = sigma;
_random = new Random((int)DateTime.Now.Ticks);
this.Name = $"GBM({_sigma:F2})";
}
public GbmFeed(double initialPrice = 100.0, double mu = 0.05, double sigma = 0.2) : base()
{
_lastClose = _lastHigh = _lastLow = initialPrice;
_mu = mu;
_sigma = sigma;
_random = new Random((int)DateTime.Now.Ticks);
this.Name = $"GBM({_sigma:F2})";
}
public void Add(bool isNew = true) => Add(time: DateTime.Now, isNew: isNew);
public void Add(DateTime time, bool isNew = true) => base.Add(Generate(time, isNew));
public void Add(int count)
{
DateTime startTime = DateTime.UtcNow - TimeSpan.FromHours(count);
TBar lastBar = new();
for (int i = 0; i < count; i++)
{
Add(startTime, true);
Add(startTime, false);
Add(startTime, false);
startTime = startTime.AddHours(1);
}
}
public void Add(bool isNew = true) => Add(time: DateTime.Now, isNew: isNew);
public void Add(DateTime time, bool isNew = true) => base.Add(Generate(time, isNew));
public void Add(int count)
{
DateTime startTime = DateTime.UtcNow - TimeSpan.FromHours(count);
TBar lastBar = new();
for (int i = 0; i < count; i++)
{
Add(startTime, true);
Add(startTime, false);
Add(startTime, false);
startTime = startTime.AddHours(1);
}
}
public TBar Generate(DateTime time, bool isNew = true)
{
double dt = 1.0 / 252;
double drift = (_mu - 0.5 * _sigma * _sigma) * dt;
double diffusion = _sigma * Math.Sqrt(dt) * GenerateNormalRandom();
double newClose = _lastClose * Math.Exp(drift + diffusion);
public TBar Generate(DateTime time, bool isNew = true)
{
double dt = 1.0 / 252;
double drift = (_mu - 0.5 * _sigma * _sigma) * dt;
double diffusion = _sigma * Math.Sqrt(dt) * GenerateNormalRandom();
double newClose = _lastClose * Math.Exp(drift + diffusion);
double open = _lastClose;
double high = Math.Max(_lastHigh, Math.Max(open, newClose) * (1 + _random.NextDouble() * 0.01));
double low = Math.Min(_lastLow, Math.Min(open, newClose) * (1 - _random.NextDouble() * 0.01));
double volume = 1000 + _random.NextDouble() * 1000;
double open = _lastClose;
double high = Math.Max(_lastHigh, Math.Max(open, newClose) * (1 + _random.NextDouble() * 0.01));
double low = Math.Min(_lastLow, Math.Min(open, newClose) * (1 - _random.NextDouble() * 0.01));
double volume = 1000 + _random.NextDouble() * 1000;
if (isNew)
{
_lastClose = newClose;
}
else
{
high = Math.Max(_lastHigh, high);
low = Math.Min(_lastLow, low);
}
_lastHigh = high;
_lastLow = low;
if (isNew)
{
_lastClose = newClose;
}
else
{
high = Math.Max(_lastHigh, high);
low = Math.Min(_lastLow, low);
}
_lastHigh = high;
_lastLow = low;
TBar bar = new(time, open, high, low, newClose, volume, isNew);
return bar;
}
TBar bar = new(time, open, high, low, newClose, volume, isNew);
return bar;
}
private double GenerateNormalRandom()
{
// Box-Muller transform to generate standard normal random variable
double u1 = 1.0 - _random.NextDouble(); // Uniform(0,1] random doubles
double u2 = 1.0 - _random.NextDouble();
return Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
}
private double GenerateNormalRandom()
{
// Box-Muller transform to generate standard normal random variable
double u1 = 1.0 - _random.NextDouble(); // Uniform(0,1] random doubles
double u2 = 1.0 - _random.NextDouble();
return Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
}
}
+23 -11
View File
@@ -10,7 +10,8 @@ namespace QuanTAlib;
/// efficiently. It also implements a decay mechanism to adjust the minimum value over
/// time, allowing for a more responsive indicator in changing market conditions.
/// </remarks>
public class Min : AbstractBase {
public class Min : AbstractBase
{
private readonly int Period;
private readonly CircularBuffer _buffer;
private readonly double _halfLife;
@@ -25,11 +26,14 @@ public class Min : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 1 or decay is negative.
/// </exception>
public Min(int period, double decay = 0) : base() {
if (period < 1) {
public Min(int period, double decay = 0) : base()
{
if (period < 1)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 1.");
}
if (decay < 0) {
if (decay < 0)
{
throw new ArgumentOutOfRangeException(nameof(decay), "Half-life must be non-negative.");
}
Period = period;
@@ -46,7 +50,8 @@ public class Min : AbstractBase {
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the minimum value.</param>
/// <param name="decay">The decay factor to apply to older values (default is 0).</param>
public Min(object source, int period, double decay = 0) : this(period, decay) {
public Min(object source, int period, double decay = 0) : this(period, decay)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -54,7 +59,8 @@ public class Min : AbstractBase {
/// <summary>
/// Initializes the Min instance by setting initial values.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_currentMin = double.MaxValue;
_timeSinceNewMin = 0;
@@ -64,14 +70,18 @@ public class Min : AbstractBase {
/// Manages the state of the Min instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_p_currentMin = _currentMin;
_lastValidValue = Input.Value;
_index++;
_timeSinceNewMin++;
_p_timeSinceNewMin = _timeSinceNewMin;
} else {
}
else
{
_currentMin = _p_currentMin;
_timeSinceNewMin = _p_timeSinceNewMin;
}
@@ -87,11 +97,13 @@ public class Min : AbstractBase {
/// The decay rate is calculated using an exponential function based on the time since
/// the last new minimum and the specified half-life.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
if (Input.Value <= _currentMin) {
if (Input.Value <= _currentMin)
{
_currentMin = Input.Value;
_timeSinceNewMin = 0;
}
+19 -9
View File
@@ -9,7 +9,8 @@ namespace QuanTAlib;
/// efficiently. Before the specified period is reached, it returns the average of
/// the available values as an approximation.
/// </remarks>
public class Mode : AbstractBase {
public class Mode : AbstractBase
{
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -20,8 +21,10 @@ public class Mode : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 1.
/// </exception>
public Mode(int period) : base() {
if (period < 1) {
public Mode(int period) : base()
{
if (period < 1)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 1.");
}
Period = period;
@@ -36,7 +39,8 @@ public class Mode : AbstractBase {
/// </summary>
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the mode.</param>
public Mode(object source, int period) : this(period) {
public Mode(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -45,8 +49,10 @@ public class Mode : AbstractBase {
/// Manages the state of the Mode instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -64,12 +70,14 @@ public class Mode : AbstractBase {
/// the available values as an approximation of the mode. Once the period is
/// reached, it calculates the true mode by grouping and counting the values.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double mode;
if (_index >= Period) {
if (_index >= Period)
{
var values = _buffer.GetSpan().ToArray();
var groupedValues = values.GroupBy(v => v)
.OrderByDescending(g => g.Count())
@@ -82,7 +90,9 @@ public class Mode : AbstractBase {
.ToList();
mode = modes.Average(); // If there are multiple modes, we return their average
} else {
}
else
{
mode = _buffer.Average(); // Use average until we have enough data points
}
+28 -13
View File
@@ -10,7 +10,8 @@ namespace QuanTAlib;
/// between two data points. Before the specified period is reached, it returns the
/// average of the available values as an approximation.
/// </remarks>
public class Percentile : AbstractBase {
public class Percentile : AbstractBase
{
private readonly int Period;
private readonly double Percent;
private readonly CircularBuffer _buffer;
@@ -23,11 +24,14 @@ public class Percentile : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2 or percent is not between 0 and 100.
/// </exception>
public Percentile(int period, double percent) : base() {
if (period < 2) {
public Percentile(int period, double percent) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2 for percentile calculation.");
}
if (percent < 0 || percent > 100) {
if (percent < 0 || percent > 100)
{
throw new ArgumentOutOfRangeException(nameof(percent), "Percent must be between 0 and 100.");
}
Period = period;
@@ -44,7 +48,8 @@ public class Percentile : AbstractBase {
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the percentile.</param>
/// <param name="percent">The percentile to calculate (between 0 and 100).</param>
public Percentile(object source, int period, double percent) : this(period, percent) {
public Percentile(object source, int period, double percent) : this(period, percent)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -52,7 +57,8 @@ public class Percentile : AbstractBase {
/// <summary>
/// Initializes the Percentile instance by clearing the buffer.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
}
@@ -61,8 +67,10 @@ public class Percentile : AbstractBase {
/// Manages the state of the Percentile instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -80,12 +88,14 @@ public class Percentile : AbstractBase {
/// as an approximation. Once the period is reached, it calculates the true percentile by
/// sorting the values and interpolating as necessary.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double result;
if (_buffer.Count >= Period) {
if (_buffer.Count >= Period)
{
var values = _buffer.GetSpan().ToArray();
Array.Sort(values);
@@ -93,16 +103,21 @@ public class Percentile : AbstractBase {
int lowerIndex = (int)Math.Floor(position);
int upperIndex = (int)Math.Ceiling(position);
if (lowerIndex == upperIndex) {
if (lowerIndex == upperIndex)
{
result = values[lowerIndex];
} else {
}
else
{
// Interpolate between the two nearest values
double lowerValue = values[lowerIndex];
double upperValue = values[upperIndex];
double fraction = position - lowerIndex;
result = lowerValue + (upperValue - lowerValue) * fraction;
}
} else {
}
else
{
// Use average for insufficient data, like the Median class
result = _buffer.Average();
}
+22 -11
View File
@@ -10,7 +10,8 @@ namespace QuanTAlib;
/// for sample skewness calculation. A minimum of 3 data points is required for the
/// calculation.
/// </remarks>
public class Skew : AbstractBase {
public class Skew : AbstractBase
{
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -21,8 +22,10 @@ public class Skew : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 3.
/// </exception>
public Skew(int period) : base() {
if (period < 3) {
public Skew(int period) : base()
{
if (period < 3)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 3 for skewness calculation.");
}
Period = period;
@@ -37,7 +40,8 @@ public class Skew : AbstractBase {
/// </summary>
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the skewness.</param>
public Skew(object source, int period) : this(period) {
public Skew(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -45,7 +49,8 @@ public class Skew : AbstractBase {
/// <summary>
/// Initializes the Skew instance by clearing the buffer.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
}
@@ -54,8 +59,10 @@ public class Skew : AbstractBase {
/// Manages the state of the Skew instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -73,13 +80,15 @@ public class Skew : AbstractBase {
/// calculation. If there are fewer than 3 data points, or if the standard
/// deviation is zero, the method returns 0.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double skew = 0;
if (_buffer.Count >= 3) { // We need at least 3 data points for skewness
if (_buffer.Count >= 3)
{ // We need at least 3 data points for skewness
var values = _buffer.GetSpan().ToArray();
double mean = values.Average();
double n = values.Length;
@@ -87,7 +96,8 @@ public class Skew : AbstractBase {
double sumCubedDeviations = 0;
double sumSquaredDeviations = 0;
foreach (var value in values) {
foreach (var value in values)
{
double deviation = value - mean;
sumCubedDeviations += Math.Pow(deviation, 3);
sumSquaredDeviations += Math.Pow(deviation, 2);
@@ -98,7 +108,8 @@ public class Skew : AbstractBase {
double m2 = sumSquaredDeviations / n;
double s3 = Math.Pow(m2, 1.5);
if (s3 != 0) { // Avoid division by zero
if (s3 != 0)
{ // Avoid division by zero
skew = (Math.Sqrt(n * (n - 1)) / (n - 2)) * (m3 / s3);
}
}
+29 -14
View File
@@ -8,7 +8,8 @@ namespace QuanTAlib;
/// statistical measures such as intercept, standard deviation, R-squared, and the last
/// point on the regression line. It uses the least squares method for calculation.
/// </remarks>
public class Slope : AbstractBase {
public class Slope : AbstractBase
{
private readonly int _period;
private readonly CircularBuffer _buffer;
private readonly CircularBuffer _timeBuffer;
@@ -24,8 +25,10 @@ public class Slope : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than or equal to 1.
/// </exception>
public Slope(int period) {
if (period <= 1) {
public Slope(int period)
{
if (period <= 1)
{
throw new ArgumentOutOfRangeException(nameof(period), period,
"Period must be greater than 1 for Slope/Linear Regression.");
}
@@ -43,7 +46,8 @@ public class Slope : AbstractBase {
/// </summary>
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the slope.</param>
public Slope(object source, int period) : this(period) {
public Slope(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -51,7 +55,8 @@ public class Slope : AbstractBase {
/// <summary>
/// Initializes the Slope instance by clearing buffers and resetting calculated values.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
_timeBuffer.Clear();
@@ -65,8 +70,10 @@ public class Slope : AbstractBase {
/// Manages the state of the Slope instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -84,7 +91,8 @@ public class Slope : AbstractBase {
/// If there are fewer than 2 data points, or if the sum of squared x deviations is 0,
/// the method returns 0 and sets the additional properties to null.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
@@ -92,7 +100,8 @@ public class Slope : AbstractBase {
double slope = 0;
if (_buffer.Count < 2) {
if (_buffer.Count < 2)
{
return slope; // Return 0 when there are fewer than 2 points
}
@@ -101,7 +110,8 @@ public class Slope : AbstractBase {
// Calculate averages
double sumX = 0, sumY = 0;
for (int i = 0; i < count; i++) {
for (int i = 0; i < count; i++)
{
sumX += i + 1;
sumY += values[i];
}
@@ -110,7 +120,8 @@ public class Slope : AbstractBase {
// Least squares method
double sumSqX = 0, sumSqY = 0, sumSqXY = 0;
for (int i = 0; i < count; i++) {
for (int i = 0; i < count; i++)
{
double devX = (i + 1) - avgX;
double devY = values[i] - avgY;
sumSqX += devX * devX;
@@ -118,7 +129,8 @@ public class Slope : AbstractBase {
sumSqXY += devX * devY;
}
if (sumSqX > 0) {
if (sumSqX > 0)
{
slope = sumSqXY / sumSqX;
Intercept = avgY - (slope * avgX);
@@ -127,14 +139,17 @@ public class Slope : AbstractBase {
double stdDevY = Math.Sqrt(sumSqY / count);
StdDev = stdDevY;
if (stdDevX * stdDevY != 0) {
if (stdDevX * stdDevY != 0)
{
double r = sumSqXY / (stdDevX * stdDevY) / count;
RSquared = r * r;
}
// Calculate last Line value (y = mx + b)
Line = (slope * count) + Intercept;
} else {
}
else
{
Intercept = null;
StdDev = null;
RSquared = null;
+18 -9
View File
@@ -9,7 +9,8 @@ namespace QuanTAlib;
/// standard deviation based on the isPopulation parameter. It uses a circular buffer
/// to efficiently manage the data points within the specified period.
/// </remarks>
public class Stddev : AbstractBase {
public class Stddev : AbstractBase
{
private readonly int Period;
private readonly bool IsPopulation;
private readonly CircularBuffer _buffer;
@@ -25,8 +26,10 @@ public class Stddev : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2.
/// </exception>
public Stddev(int period, bool isPopulation = false) : base() {
if (period < 2) {
public Stddev(int period, bool isPopulation = false) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
}
Period = period;
@@ -46,7 +49,8 @@ public class Stddev : AbstractBase {
/// <param name="isPopulation">
/// A flag indicating whether to calculate population (true) or sample (false) standard deviation.
/// </param>
public Stddev(object source, int period, bool isPopulation = false) : this(period, isPopulation) {
public Stddev(object source, int period, bool isPopulation = false) : this(period, isPopulation)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -54,7 +58,8 @@ public class Stddev : AbstractBase {
/// <summary>
/// Initializes the Stddev instance by clearing the buffer.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
}
@@ -63,8 +68,10 @@ public class Stddev : AbstractBase {
/// Manages the state of the Stddev instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -83,13 +90,15 @@ public class Stddev : AbstractBase {
/// where x is each value, mean is the average of all values, and n is the number of values.
/// If there's only one value in the buffer, the method returns 0.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double stddev = 0;
if (_buffer.Count > 1) {
if (_buffer.Count > 1)
{
var values = _buffer.GetSpan().ToArray();
double mean = values.Average();
double sumOfSquaredDifferences = values.Sum(x => Math.Pow(x - mean, 2));
+18 -9
View File
@@ -9,7 +9,8 @@ namespace QuanTAlib;
/// variance based on the isPopulation parameter. It uses a circular buffer
/// to efficiently manage the data points within the specified period.
/// </remarks>
public class Variance : AbstractBase {
public class Variance : AbstractBase
{
private readonly int Period;
private readonly bool IsPopulation;
private readonly CircularBuffer _buffer;
@@ -25,8 +26,10 @@ public class Variance : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2.
/// </exception>
public Variance(int period, bool isPopulation = false) : base() {
if (period < 2) {
public Variance(int period, bool isPopulation = false) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
}
Period = period;
@@ -46,7 +49,8 @@ public class Variance : AbstractBase {
/// <param name="isPopulation">
/// A flag indicating whether to calculate population (true) or sample (false) variance.
/// </param>
public Variance(object source, int period, bool isPopulation = false) : this(period, isPopulation) {
public Variance(object source, int period, bool isPopulation = false) : this(period, isPopulation)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -54,7 +58,8 @@ public class Variance : AbstractBase {
/// <summary>
/// Initializes the Variance instance by clearing the buffer.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
}
@@ -63,8 +68,10 @@ public class Variance : AbstractBase {
/// Manages the state of the Variance instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -83,13 +90,15 @@ public class Variance : AbstractBase {
/// where x is each value, mean is the average of all values, and n is the number of values.
/// If there's only one value in the buffer, the method returns 0.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double variance = 0;
if (_buffer.Count > 1) {
if (_buffer.Count > 1)
{
var values = _buffer.GetSpan().ToArray();
double mean = values.Average();
double sumOfSquaredDifferences = values.Sum(x => Math.Pow(x - mean, 2));
+20 -10
View File
@@ -9,7 +9,8 @@ namespace QuanTAlib;
/// the most recent value in a given period. It uses a circular buffer to
/// efficiently manage the data points within the specified period.
/// </remarks>
public class Zscore : AbstractBase {
public class Zscore : AbstractBase
{
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -20,8 +21,10 @@ public class Zscore : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2.
/// </exception>
public Zscore(int period) : base() {
if (period < 2) {
public Zscore(int period) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2 for Z-score calculation.");
}
Period = period;
@@ -36,7 +39,8 @@ public class Zscore : AbstractBase {
/// </summary>
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the Z-score.</param>
public Zscore(object source, int period) : this(period) {
public Zscore(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -44,7 +48,8 @@ public class Zscore : AbstractBase {
/// <summary>
/// Initializes the Zscore instance by clearing the buffer.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
}
@@ -53,8 +58,10 @@ public class Zscore : AbstractBase {
/// Manages the state of the Zscore instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -72,13 +79,15 @@ public class Zscore : AbstractBase {
/// where x is the input value, μ is the mean of the period, and σ is the sample standard deviation.
/// If there are fewer than 2 data points or if the standard deviation is 0, the method returns 0.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double zScore = 0;
if (_buffer.Count >= 2) { // We need at least 2 data points for Z-score
if (_buffer.Count >= 2)
{ // We need at least 2 data points for Z-score
var values = _buffer.GetSpan().ToArray();
double mean = values.Average();
double n = values.Length;
@@ -86,7 +95,8 @@ public class Zscore : AbstractBase {
double sumSquaredDeviations = values.Sum(x => Math.Pow(x - mean, 2));
double standardDeviation = Math.Sqrt(sumSquaredDeviations / (n - 1)); // Sample standard deviation
if (standardDeviation != 0) { // Avoid division by zero
if (standardDeviation != 0)
{ // Avoid division by zero
zScore = (Input.Value - mean) / standardDeviation;
}
}
+22 -11
View File
@@ -8,7 +8,8 @@ namespace QuanTAlib;
/// of the true range. The true range is the greatest of: current high - current low,
/// absolute value of current high - previous close, or absolute value of current low - previous close.
/// </remarks>
public class Atr : AbstractBarBase {
public class Atr : AbstractBarBase
{
private readonly Ema _ma;
private double _prevClose, _p_prevClose;
@@ -19,11 +20,13 @@ public class Atr : AbstractBarBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 1.
/// </exception>
public Atr(int period) {
if (period < 1) {
public Atr(int period)
{
if (period < 1)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 1.");
}
_ma = new(1.0/period);
_ma = new(1.0 / period);
WarmupPeriod = _ma.WarmupPeriod;
Name = $"ATR({period})";
}
@@ -33,7 +36,8 @@ public class Atr : AbstractBarBase {
/// </summary>
/// <param name="source">The source object to subscribe to for bar updates.</param>
/// <param name="period">The period over which to calculate the ATR.</param>
public Atr(object source, int period) : this(period) {
public Atr(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
@@ -41,7 +45,8 @@ public class Atr : AbstractBarBase {
/// <summary>
/// Initializes the Atr instance by setting up the initial state.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_ma.Init();
_prevClose = double.NaN;
@@ -51,11 +56,15 @@ public class Atr : AbstractBarBase {
/// Manages the state of the Atr instance based on whether a new bar is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new bar.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_index++;
_p_prevClose = _prevClose;
} else {
}
else
{
_prevClose = _p_prevClose;
}
}
@@ -71,7 +80,8 @@ public class Atr : AbstractBarBase {
/// to smooth the true range values. For the first bar, it uses the high-low range
/// as the true range.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
double trueRange = Math.Max(
@@ -81,7 +91,8 @@ public class Atr : AbstractBarBase {
),
Math.Abs(Input.Low - _prevClose)
);
if (_index < 2) {
if (_index < 2)
{
trueRange = Input.High - Input.Low;
}
+24 -12
View File
@@ -9,7 +9,8 @@ namespace QuanTAlib;
/// both annualized and non-annualized volatility measures. The calculation uses a sample
/// standard deviation formula and assumes 252 trading days in a year for annualization.
/// </remarks>
public class Historical : AbstractBase {
public class Historical : AbstractBase
{
private readonly int Period;
private readonly bool IsAnnualized;
private readonly CircularBuffer _buffer;
@@ -24,8 +25,10 @@ public class Historical : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2.
/// </exception>
public Historical(int period, bool isAnnualized = true) : base() {
if (period < 2) {
public Historical(int period, bool isAnnualized = true) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
}
Period = period;
@@ -43,7 +46,8 @@ public class Historical : AbstractBase {
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate historical volatility.</param>
/// <param name="isAnnualized">Whether to annualize the volatility (default is true).</param>
public Historical(object source, int period, bool isAnnualized = true) : this(period, isAnnualized) {
public Historical(object source, int period, bool isAnnualized = true) : this(period, isAnnualized)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -51,7 +55,8 @@ public class Historical : AbstractBase {
/// <summary>
/// Initializes the Historical instance by clearing buffers and resetting the previous close value.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_buffer.Clear();
_logReturns.Clear();
@@ -62,8 +67,10 @@ public class Historical : AbstractBase {
/// Manages the state of the Historical instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -82,19 +89,23 @@ public class Historical : AbstractBase {
/// 3. If annualized, multiply by the square root of 252 (assumed trading days in a year).
/// The method returns 0 until enough data points are available for the calculation.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double volatility = 0;
if (_buffer.Count > 1) {
if (_previousClose != 0) {
if (_buffer.Count > 1)
{
if (_previousClose != 0)
{
double logReturn = Math.Log(Input.Value / _previousClose);
_logReturns.Add(logReturn, Input.IsNew);
}
if (_logReturns.Count == Period) {
if (_logReturns.Count == Period)
{
var returns = _logReturns.GetSpan().ToArray();
double mean = returns.Average();
double sumOfSquaredDifferences = returns.Sum(x => Math.Pow(x - mean, 2));
@@ -102,7 +113,8 @@ public class Historical : AbstractBase {
double variance = sumOfSquaredDifferences / (Period - 1); // Using sample standard deviation
volatility = Math.Sqrt(variance);
if (IsAnnualized) {
if (IsAnnualized)
{
// Assuming 252 trading days in a year. Adjust as needed.
volatility *= Math.Sqrt(252);
}
+22 -11
View File
@@ -9,7 +9,8 @@ namespace QuanTAlib;
/// both annualized and non-annualized volatility measures. The calculation uses a rolling
/// sum of squared returns for efficiency and assumes 252 trading days in a year for annualization.
/// </remarks>
public class Realized : AbstractBase {
public class Realized : AbstractBase
{
private readonly int Period;
private readonly bool IsAnnualized;
private readonly CircularBuffer _returns;
@@ -24,8 +25,10 @@ public class Realized : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2.
/// </exception>
public Realized(int period, bool isAnnualized = true) : base() {
if (period < 2) {
public Realized(int period, bool isAnnualized = true) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
}
Period = period;
@@ -39,7 +42,8 @@ public class Realized : AbstractBase {
/// <summary>
/// Initializes the Realized instance by clearing buffers and resetting calculation variables.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_returns.Clear();
_previousClose = 0;
@@ -50,8 +54,10 @@ public class Realized : AbstractBase {
/// Manages the state of the Realized instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
@@ -72,14 +78,17 @@ public class Realized : AbstractBase {
/// 5. If annualized, multiply by the square root of 252 (assumed trading days in a year).
/// The method returns 0 until enough data points are available for the calculation.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
double volatility = 0;
if (_previousClose != 0) {
if (_previousClose != 0)
{
double logReturn = Math.Log(Input.Value / _previousClose);
if (_returns.Count == Period) {
if (_returns.Count == Period)
{
// Remove the oldest squared return from the sum
_sumSquaredReturns -= Math.Pow(_returns[0], 2);
}
@@ -87,11 +96,13 @@ public class Realized : AbstractBase {
_returns.Add(logReturn, Input.IsNew);
_sumSquaredReturns += Math.Pow(logReturn, 2);
if (_returns.Count == Period) {
if (_returns.Count == Period)
{
double variance = _sumSquaredReturns / Period;
volatility = Math.Sqrt(variance);
if (IsAnnualized) {
if (IsAnnualized)
{
// Assuming 252 trading days in a year. Adjust as needed.
volatility *= Math.Sqrt(252);
}
+21 -10
View File
@@ -13,7 +13,8 @@ namespace QuanTAlib;
/// This implementation uses a combination of Standard Deviation and Simple Moving Average
/// calculations to compute the RVI.
/// </remarks>
public class Rvi : AbstractBase {
public class Rvi : AbstractBase
{
private readonly int Period;
private Stddev _upStdDev, _downStdDev;
private Sma _upSma, _downSma;
@@ -26,8 +27,10 @@ public class Rvi : AbstractBase {
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 2.
/// </exception>
public Rvi(int period) : base() {
if (period < 2) {
public Rvi(int period) : base()
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
}
Period = period;
@@ -45,7 +48,8 @@ public class Rvi : AbstractBase {
/// </summary>
/// <param name="source">The source object to subscribe to for value updates.</param>
/// <param name="period">The period over which to calculate the RVI.</param>
public Rvi(object source, int period) : this(period) {
public Rvi(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
@@ -53,7 +57,8 @@ public class Rvi : AbstractBase {
/// <summary>
/// Initializes the Rvi instance by setting up the initial state.
/// </summary>
public override void Init() {
public override void Init()
{
base.Init();
_previousClose = 0;
}
@@ -62,8 +67,10 @@ public class Rvi : AbstractBase {
/// Manages the state of the Rvi instance based on whether a new value is being processed.
/// </summary>
/// <param name="isNew">Indicates whether the current input is a new value.</param>
protected override void ManageState(bool isNew) {
if (isNew) {
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Value;
_index++;
}
@@ -84,7 +91,8 @@ public class Rvi : AbstractBase {
/// 5. Compute the RVI as a percentage of up volatility to total volatility.
/// The method returns 0 if the sum of up and down volatility is zero.
/// </remarks>
protected override double Calculation() {
protected override double Calculation()
{
ManageState(Input.IsNew);
double close = Input.Value;
@@ -97,9 +105,12 @@ public class Rvi : AbstractBase {
_downSma.Calc(_downStdDev.Calc(new TValue(Input.Time, downMove, Input.IsNew)));
double rvi;
if (_upSma.Value + _downSma.Value != 0) {
if (_upSma.Value + _downSma.Value != 0)
{
rvi = 100 * _upSma.Value / (_upSma.Value + _downSma.Value);
} else {
}
else
{
rvi = 0;
}