tests and cleanup

This commit is contained in:
Miha Kralj
2024-10-11 18:02:09 -07:00
parent 839313c9f2
commit cc45cebeb4
96 changed files with 3640 additions and 327 deletions
+22 -1
View File
@@ -4,15 +4,36 @@ namespace QuanTAlib;
/// Calculates the rate of change of the slope over a specified period.
/// Provides insights into trend acceleration or deceleration.
/// </summary>
/// <remarks>
/// Curvature is a second-order derivative that measures how quickly the slope (first-order derivative) is changing.
/// Positive curvature indicates accelerating uptrends or decelerating downtrends.
/// Negative curvature indicates decelerating uptrends or accelerating downtrends.
/// This indicator can be useful for identifying potential trend reversals or confirming trend strength.
/// </remarks>
public class Curvature : AbstractBase
{
private readonly int _period;
private readonly Slope _slopeCalculator;
private readonly CircularBuffer _slopeBuffer;
/// <summary>
/// Gets the y-intercept of the curvature line.
/// </summary>
public double? Intercept { get; private set; }
/// <summary>
/// Gets the standard deviation of the slope values used in the curvature calculation.
/// </summary>
public double? StdDev { get; private set; }
/// <summary>
/// Gets the R-squared value, indicating the goodness of fit of the curvature line.
/// </summary>
public double? RSquared { get; private set; }
/// <summary>
/// Gets the last calculated point on the curvature line.
/// </summary>
public double? Line { get; private set; }
/// <summary>
@@ -153,4 +174,4 @@ public class Curvature : AbstractBase
IsHot = _slopeBuffer.Count == _period;
return curvature;
}
}
}
+14 -2
View File
@@ -4,8 +4,20 @@ namespace QuanTAlib;
/// Measures the unpredictability of data using Shannon's Entropy.
/// Provides insights into the randomness or information content of the time series.
/// </summary>
/// <remarks>
/// Shannon's Entropy quantifies the average amount of information contained in a message.
/// In the context of time series analysis, it can be used to:
/// - Detect regime changes or structural breaks in the data.
/// - Assess the complexity or predictability of price movements.
/// - Identify periods of high uncertainty or information flow in the market.
/// The entropy value is normalized between 0 and 1, where 1 indicates maximum randomness
/// and 0 indicates perfect predictability.
/// </remarks>
public class Entropy : AbstractBase
{
/// <summary>
/// The number of data points to consider for the entropy calculation.
/// </summary>
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -24,7 +36,7 @@ public class Entropy : AbstractBase
"Period must be greater than or equal to 2 for entropy calculation.");
}
Period = period;
WarmupPeriod = 2;
WarmupPeriod = 2; // Minimum number of points needed for entropy calculation
_buffer = new CircularBuffer(period);
Name = $"Entropy(period={period})";
Init();
@@ -110,4 +122,4 @@ public class Entropy : AbstractBase
IsHot = _buffer.Count >= Period;
return entropy;
}
}
}
+22
View File
@@ -4,8 +4,25 @@ namespace QuanTAlib;
/// Calculates excess kurtosis using the Sheskin Algorithm.
/// Measures the "tailedness" of the probability distribution of a real-valued random variable.
/// </summary>
/// <remarks>
/// Kurtosis is a measure of the combined weight of a distribution's tails relative to the center of the distribution.
/// In financial time series analysis, kurtosis can provide insights into:
/// - The frequency and magnitude of extreme returns.
/// - The potential for outliers or "black swan" events.
/// - The shape of the return distribution compared to a normal distribution.
///
/// Interpretation:
/// - Excess kurtosis > 0: Heavy-tailed distribution (more extreme values than a normal distribution)
/// - Excess kurtosis = 0: Normal distribution
/// - Excess kurtosis < 0: Light-tailed distribution (fewer extreme values than a normal distribution)
///
/// High kurtosis in financial returns may indicate a higher risk of extreme events.
/// </remarks>
public class Kurtosis : AbstractBase
{
/// <summary>
/// The number of data points to consider for the kurtosis calculation.
/// </summary>
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -73,6 +90,11 @@ public class Kurtosis : AbstractBase
/// <remarks>
/// Uses the Sheskin Algorithm for kurtosis calculation.
/// Requires at least 4 data points for a valid calculation.
///
/// Interpretation of results:
/// - Positive values indicate a distribution with heavier tails and a higher peak compared to a normal distribution.
/// - Negative values indicate a distribution with lighter tails and a lower peak compared to a normal distribution.
/// - A value close to 0 suggests a distribution similar to a normal distribution in terms of tailedness.
/// </remarks>
protected override double Calculation()
{
+41 -3
View File
@@ -4,19 +4,57 @@ namespace QuanTAlib;
/// Calculates the maximum value over a specified period, with an optional decay factor.
/// Useful for tracking the highest point in a time series with the ability to gradually forget old peaks.
/// </summary>
/// <remarks>
/// The Max indicator is particularly useful in financial analysis for:
/// - Identifying resistance levels in price charts.
/// - Tracking the highest price over a given period.
/// - Implementing trailing stop-loss strategies.
///
/// The decay factor allows the indicator to adapt to changing market conditions by
/// gradually reducing the influence of older maximum values.
/// </remarks>
public class Max : AbstractBase
{
/// <summary>
/// The number of data points to consider for the maximum calculation.
/// </summary>
private readonly int Period;
/// <summary>
/// Circular buffer to store the most recent data points.
/// </summary>
private readonly CircularBuffer _buffer;
/// <summary>
/// The half-life decay factor used to gradually forget old peaks.
/// </summary>
private readonly double _halfLife;
private double _currentMax, _p_currentMax;
private int _timeSinceNewMax, _p_timeSinceNewMax;
/// <summary>
/// The current maximum value.
/// </summary>
private double _currentMax;
/// <summary>
/// The previous maximum value.
/// </summary>
private double _p_currentMax;
/// <summary>
/// The number of periods since a new maximum was set.
/// </summary>
private int _timeSinceNewMax;
/// <summary>
/// The previous value of _timeSinceNewMax.
/// </summary>
private int _p_timeSinceNewMax;
/// <summary>
/// Initializes a new instance of the Max class.
/// </summary>
/// <param name="period">The number of data points to consider. Must be at least 1.</param>
/// <param name="decay">Half-life decay factor. Set to 0 for no decay, higher for faster forgetting. Default is 0.</param>
/// <param name="decay">Half-life decay factor. Set to 0 for no decay, higher for faster forgetting of old peaks. Default is 0.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the period is less than 1 or decay is negative.
/// </exception>
+21
View File
@@ -4,8 +4,20 @@ namespace QuanTAlib;
/// Calculates the median value over a specified period.
/// Provides a measure of central tendency that is robust to outliers.
/// </summary>
/// <remarks>
/// The Median indicator is particularly useful in financial analysis for:
/// - Providing a robust measure of central tendency that is less affected by extreme values than the mean.
/// - Identifying the middle value in a dataset, which can be helpful in understanding price distributions.
/// - Serving as a basis for other indicators or trading strategies that require a stable reference point.
///
/// Unlike the mean, the median is not influenced by extreme outliers, making it valuable
/// in markets with occasional large price swings or in the presence of data anomalies.
/// </remarks>
public class Median : AbstractBase
{
/// <summary>
/// The number of data points to consider for the median calculation.
/// </summary>
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -41,6 +53,15 @@ public class Median : AbstractBase
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
/// <summary>
/// Resets the Median indicator to its initial state.
/// </summary>
public override void Init()
{
base.Init();
_buffer.Clear();
}
/// <summary>
/// Manages the state of the indicator.
/// </summary>
+36 -4
View File
@@ -9,20 +9,52 @@ namespace QuanTAlib;
/// The Min class uses a circular buffer to store values and calculates the minimum
/// efficiently. It also implements a decay mechanism to adjust the minimum value over
/// time, allowing for a more responsive indicator in changing market conditions.
///
/// The decay factor allows the indicator to "forget" old minimum values gradually,
/// which can be useful in adapting to new price trends or market regimes.
/// </remarks>
public class Min : AbstractBase
{
/// <summary>
/// The number of data points to consider for the minimum calculation.
/// </summary>
private readonly int Period;
/// <summary>
/// Circular buffer to store the most recent data points.
/// </summary>
private readonly CircularBuffer _buffer;
/// <summary>
/// The half-life decay factor used to gradually forget old minimums.
/// </summary>
private readonly double _halfLife;
private double _currentMin, _p_currentMin;
private int _timeSinceNewMin, _p_timeSinceNewMin;
/// <summary>
/// The current minimum value.
/// </summary>
private double _currentMin;
/// <summary>
/// The previous minimum value.
/// </summary>
private double _p_currentMin;
/// <summary>
/// The number of periods since a new minimum was set.
/// </summary>
private int _timeSinceNewMin;
/// <summary>
/// The previous value of _timeSinceNewMin.
/// </summary>
private int _p_timeSinceNewMin;
/// <summary>
/// Initializes a new instance of the Min class with the specified period and decay.
/// </summary>
/// <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>
/// <param name="decay">The decay factor to apply to older values. Higher values cause faster forgetting of old minimums. Default is 0 (no decay).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when period is less than 1 or decay is negative.
/// </exception>
@@ -49,7 +81,7 @@ public class Min : 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 minimum value.</param>
/// <param name="decay">The decay factor to apply to older values (default is 0).</param>
/// <param name="decay">The decay factor to apply to older values. Higher values cause faster forgetting of old minimums. Default is 0 (no decay).</param>
public Min(object source, int period, double decay = 0) : this(period, decay)
{
var pubEvent = source.GetType().GetEvent("Pub");
+17
View File
@@ -8,9 +8,17 @@ namespace QuanTAlib;
/// The Mode class uses a circular buffer to store values and calculates the mode
/// efficiently. Before the specified period is reached, it returns the average of
/// the available values as an approximation.
///
/// In financial analysis, the mode can be useful for:
/// - Identifying the most common price levels, which could indicate support or resistance.
/// - Analyzing the distribution of returns or other financial metrics.
/// - Detecting patterns in trading volume or other discrete financial data.
/// </remarks>
public class Mode : AbstractBase
{
/// <summary>
/// The number of data points to consider for the mode calculation.
/// </summary>
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -45,6 +53,15 @@ public class Mode : AbstractBase
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
/// <summary>
/// Resets the Mode indicator to its initial state.
/// </summary>
public override void Init()
{
base.Init();
_buffer.Clear();
}
/// <summary>
/// Manages the state of the Mode instance based on whether a new value is being processed.
/// </summary>
+16 -2
View File
@@ -9,11 +9,25 @@ namespace QuanTAlib;
/// percentile efficiently. It uses linear interpolation when the percentile falls
/// between two data points. Before the specified period is reached, it returns the
/// average of the available values as an approximation.
///
/// In financial analysis, percentiles are useful for:
/// - Assessing the relative standing of a value within a distribution.
/// - Identifying outliers or extreme values in financial data.
/// - Creating risk measures, such as Value at Risk (VaR) calculations.
/// - Analyzing the distribution of returns, trading volumes, or other financial metrics.
/// </remarks>
public class Percentile : AbstractBase
{
/// <summary>
/// The number of data points to consider for the percentile calculation.
/// </summary>
private readonly int Period;
/// <summary>
/// The percentile to calculate (between 0 and 100).
/// </summary>
private readonly double Percent;
private readonly CircularBuffer _buffer;
/// <summary>
@@ -36,7 +50,7 @@ public class Percentile : AbstractBase
}
Period = period;
Percent = percent;
WarmupPeriod = 2;
WarmupPeriod = 2; // Minimum number of points needed for percentile calculation
_buffer = new CircularBuffer(period);
Name = $"Percentile(period={period}, percent={percent})";
Init();
@@ -125,4 +139,4 @@ public class Percentile : AbstractBase
IsHot = _buffer.Count >= Period;
return result;
}
}
}
+18 -1
View File
@@ -9,9 +9,21 @@ namespace QuanTAlib;
/// efficiently. It uses the adjusted Fisher-Pearson standardized moment coefficient
/// for sample skewness calculation. A minimum of 3 data points is required for the
/// calculation.
///
/// In financial analysis, skewness is important for:
/// - Assessing the asymmetry of returns distribution.
/// - Evaluating the risk of extreme events in either direction.
/// - Complementing other risk measures like standard deviation.
/// - Informing investment decisions and risk management strategies.
///
/// Positive skewness indicates a longer tail on the right side of the distribution,
/// while negative skewness indicates a longer tail on the left side.
/// </remarks>
public class Skew : AbstractBase
{
/// <summary>
/// The number of data points to consider for the skewness calculation.
/// </summary>
private readonly int Period;
private readonly CircularBuffer _buffer;
@@ -79,6 +91,11 @@ public class Skew : AbstractBase
/// to calculate the sample skewness. It requires at least 3 data points for the
/// calculation. If there are fewer than 3 data points, or if the standard
/// deviation is zero, the method returns 0.
///
/// Interpretation of results:
/// - Positive values indicate right-skewed distribution (longer tail on the right side).
/// - Negative values indicate left-skewed distribution (longer tail on the left side).
/// - Values close to 0 suggest a relatively symmetric distribution.
/// </remarks>
protected override double Calculation()
{
@@ -117,4 +134,4 @@ public class Skew : AbstractBase
IsHot = _buffer.Count >= Period;
return skew;
}
}
}
+29
View File
@@ -7,15 +7,37 @@ namespace QuanTAlib;
/// The Slope class calculates the slope of a linear regression line, along with other
/// 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.
///
/// In financial analysis, slope is important for:
/// - Identifying trends in price movements or other financial metrics.
/// - Measuring the rate of change in a financial time series.
/// - Assessing the strength and direction of relationships between variables.
/// - Supporting technical analysis indicators and trading strategies.
/// </remarks>
public class Slope : AbstractBase
{
private readonly int _period;
private readonly CircularBuffer _buffer;
private readonly CircularBuffer _timeBuffer;
/// <summary>
/// Gets the y-intercept of the regression line.
/// </summary>
public double? Intercept { get; private set; }
/// <summary>
/// Gets the standard deviation of the y-values.
/// </summary>
public double? StdDev { get; private set; }
/// <summary>
/// Gets the R-squared value, indicating the goodness of fit of the regression line.
/// </summary>
public double? RSquared { get; private set; }
/// <summary>
/// Gets the y-value of the last point on the regression line.
/// </summary>
public double? Line { get; private set; }
/// <summary>
@@ -90,6 +112,13 @@ public class Slope : AbstractBase
/// It also calculates and updates the Intercept, StdDev, RSquared, and Line properties.
/// 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.
///
/// Interpretation of results:
/// - Positive slope: Indicates an upward trend in the data.
/// - Negative slope: Indicates a downward trend in the data.
/// - Slope close to 0: Indicates a relatively flat or no clear trend in the data.
/// The magnitude of the slope represents the rate of change in the dependent variable
/// (y) for each unit change in the independent variable (x).
/// </remarks>
protected override double Calculation()
{
+18
View File
@@ -8,10 +8,23 @@ namespace QuanTAlib;
/// The Stddev class calculates either the population standard deviation or the sample
/// standard deviation based on the isPopulation parameter. It uses a circular buffer
/// to efficiently manage the data points within the specified period.
///
/// In financial analysis, standard deviation is important for:
/// - Measuring volatility of financial instruments or portfolios.
/// - Assessing risk in investments.
/// - Calculating Sharpe ratios and other risk-adjusted performance measures.
/// - Identifying potential outliers or unusual market behavior.
/// </remarks>
public class Stddev : AbstractBase
{
/// <summary>
/// Indicates whether to calculate population (true) or sample (false) standard deviation.
/// </summary>
private readonly bool IsPopulation;
/// <summary>
/// Circular buffer to store the most recent data points.
/// </summary>
private readonly CircularBuffer _buffer;
/// <summary>
@@ -87,6 +100,11 @@ public class Stddev : AbstractBase
/// sqrt(sum((x - mean)^2) / (n - 1)) for sample,
/// 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.
///
/// Interpretation of results:
/// - A low standard deviation indicates that the values tend to be close to the mean.
/// - A high standard deviation indicates that the values are spread out over a wider range.
/// - In financial contexts, higher standard deviation often implies higher volatility or risk.
/// </remarks>
protected override double Calculation()
{
+19
View File
@@ -8,10 +8,23 @@ namespace QuanTAlib;
/// The Variance class calculates either the population variance or the sample
/// variance based on the isPopulation parameter. It uses a circular buffer
/// to efficiently manage the data points within the specified period.
///
/// In financial analysis, variance is important for:
/// - Measuring the dispersion of returns around the mean.
/// - Assessing risk and volatility in financial instruments or portfolios.
/// - Serving as a basis for other risk measures like standard deviation and beta.
/// - Contributing to portfolio optimization techniques, such as Modern Portfolio Theory.
/// </remarks>
public class Variance : AbstractBase
{
/// <summary>
/// Indicates whether to calculate population (true) or sample (false) variance.
/// </summary>
private readonly bool IsPopulation;
/// <summary>
/// Circular buffer to store the most recent data points.
/// </summary>
private readonly CircularBuffer _buffer;
/// <summary>
@@ -87,6 +100,12 @@ public class Variance : AbstractBase
/// sum((x - mean)^2) / (n - 1) for sample,
/// 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.
///
/// Interpretation of results:
/// - A low variance indicates that the values tend to be close to the mean and to each other.
/// - A high variance indicates that the values are spread out over a wider range.
/// - In financial contexts, higher variance often implies higher volatility or risk.
/// - Variance is always non-negative, and its units are squared units of the original data.
/// </remarks>
protected override double Calculation()
{
+22 -1
View File
@@ -8,10 +8,23 @@ namespace QuanTAlib;
/// The Zscore class calculates the Z-score (also known as standard score) for
/// the most recent value in a given period. It uses a circular buffer to
/// efficiently manage the data points within the specified period.
///
/// In financial analysis, Z-score is important for:
/// - Identifying outliers or unusual price movements.
/// - Normalizing data across different scales or time periods.
/// - Assessing the relative position of a value within its historical distribution.
/// - Supporting trading strategies based on mean reversion or momentum.
/// </remarks>
public class Zscore : AbstractBase
{
/// <summary>
/// The number of data points to consider for the Z-score calculation.
/// </summary>
private readonly int Period;
/// <summary>
/// Circular buffer to store the most recent data points.
/// </summary>
private readonly CircularBuffer _buffer;
/// <summary>
@@ -78,6 +91,14 @@ public class Zscore : AbstractBase
/// Z = (x - μ) / σ
/// 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.
///
/// Interpretation of results:
/// - A Z-score of 0 indicates that the data point is exactly on the mean.
/// - A positive Z-score indicates the data point is above the mean.
/// - A negative Z-score indicates the data point is below the mean.
/// - The magnitude of the Z-score represents how many standard deviations away from the mean the data point is.
/// - In a normal distribution, about 68% of the values have a Z-score between -1 and 1,
/// 95% between -2 and 2, and 99.7% between -3 and 3.
/// </remarks>
protected override double Calculation()
{
@@ -104,4 +125,4 @@ public class Zscore : AbstractBase
IsHot = _buffer.Count >= Period;
return zScore;
}
}
}