Class optimization

This commit is contained in:
Miha
2024-10-27 16:11:08 -07:00
parent b2fcdda785
commit 6c67a0cf31
77 changed files with 2634 additions and 1455 deletions
+29 -19
View File
@@ -1,4 +1,4 @@
using System;
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
@@ -29,6 +29,9 @@ public class Mma : AbstractBase
{
private readonly int _period;
private readonly CircularBuffer _buffer;
private readonly double _periodRecip; // 1/period
private readonly double _combinedRecip; // 6/((period+1)*period)
private readonly double[] _weights; // Precalculated weights
private double _lastMma;
/// <param name="period">The number of periods used in the MMA calculation. Must be at least 2.</param>
@@ -37,10 +40,20 @@ public class Mma : AbstractBase
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
throw new System.ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 2.");
}
_period = period;
_buffer = new CircularBuffer(period);
_periodRecip = 1.0 / period;
_combinedRecip = 6.0 / ((period + 1) * period);
// Precalculate weights
_weights = new double[period];
for (int i = 0; i < period; i++)
{
_weights[i] = (period - (2 * i + 1)) * 0.5;
}
Name = "Mma";
WarmupPeriod = period;
Init();
@@ -54,6 +67,7 @@ public class Mma : AbstractBase
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Init()
{
base.Init();
@@ -61,6 +75,7 @@ public class Mma : AbstractBase
_buffer.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
@@ -69,6 +84,17 @@ public class Mma : AbstractBase
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double CalculateWeightedSum()
{
double sum = 0;
for (int i = 0; i < _period; i++)
{
sum += _weights[i] * _buffer[^(i + 1)];
}
return sum;
}
protected override double Calculation()
{
ManageState(Input.IsNew);
@@ -78,7 +104,7 @@ public class Mma : AbstractBase
{
double T = _buffer.Sum();
double S = CalculateWeightedSum();
_lastMma = (T / _period) + (6 * S) / ((_period + 1) * _period);
_lastMma = (T * _periodRecip) + (S * _combinedRecip);
}
else
{
@@ -89,20 +115,4 @@ public class Mma : AbstractBase
IsHot = _index >= _period;
return _lastMma;
}
/// <summary>
/// Calculates the weighted sum component of the MMA.
/// The weights are symmetric around the center, decreasing linearly from the center outward.
/// </summary>
/// <returns>The weighted sum of the data points.</returns>
private double CalculateWeightedSum()
{
double sum = 0;
for (int i = 0; i < _period; i++)
{
double weight = (_period - (2 * i + 1)) / 2.0;
sum += weight * _buffer[^(i + 1)];
}
return sum;
}
}