Adr, Ap, Atrp, Atrs, Vp, Vwap, Vwma

This commit is contained in:
Miha Kralj
2024-11-01 18:36:01 -07:00
parent 7c6b698c9a
commit f519594371
14 changed files with 1035 additions and 120 deletions
+83
View File
@@ -0,0 +1,83 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ADR: Average Daily Range
/// A volatility indicator that measures the average range of price movement over
/// a specified period. It helps identify normal trading ranges and potential
/// breakout levels.
/// </summary>
/// <remarks>
/// The ADR calculation process:
/// 1. Calculate daily range (High - Low)
/// 2. Apply SMA to daily ranges
/// 3. Updates with each new price bar
///
/// Key characteristics:
/// - Simple volatility measure
/// - Period-based average
/// - Trend independent
/// - Absolute price measure
/// - Support/resistance aid
///
/// Formula:
/// Daily Range = High - Low
/// ADR = SMA(Daily Range, period)
///
/// Market Applications:
/// - Position sizing
/// - Volatility analysis
/// - Support/resistance levels
/// - Breakout identification
/// - Risk assessment
///
/// Note: Simpler alternative to ATR, doesn't consider gaps
/// </remarks>
[SkipLocalsInit]
public sealed class Adr : AbstractBase
{
private readonly Sma _ma;
private const int DefaultPeriod = 14;
/// <param name="period">The number of periods for ADR calculation (default 14).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Adr(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_ma = new(period);
WarmupPeriod = period;
Name = $"ADR({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for ADR calculation.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Adr(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate daily range
double range = BarInput.High - BarInput.Low;
// Apply SMA smoothing
return _ma.Calc(range, BarInput.IsNew);
}
}
+120
View File
@@ -0,0 +1,120 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// AP: Andrew's Pitchfork
/// A trend channel tool that uses three points to create a channel with a median
/// line and two parallel lines. It helps identify potential support and resistance
/// levels based on market pivots.
/// </summary>
/// <remarks>
/// The AP calculation process:
/// 1. Use three pivot points (P0, P1, P2)
/// 2. Calculate median line from P0 to midpoint of P1-P2
/// 3. Draw parallel lines at P1 and P2
/// 4. Project all lines forward
///
/// Key characteristics:
/// - Trend channel tool
/// - Support/resistance levels
/// - Price projection
/// - Market geometry
/// - Pivot-based analysis
///
/// Formula:
/// Median Line = Line from P0 to (P1 + P2)/2
/// Upper Line = Parallel to median at P1
/// Lower Line = Parallel to median at P2
///
/// Market Applications:
/// - Trend analysis
/// - Support/resistance
/// - Price targets
/// - Channel trading
/// - Market structure
///
/// Sources:
/// Dr. Alan Andrews
/// https://www.investopedia.com/terms/a/andrewspitchfork.asp
///
/// Note: Returns median line value for current price level
/// </remarks>
[SkipLocalsInit]
public sealed class Ap : AbstractBase
{
private readonly CircularBuffer _highs;
private readonly CircularBuffer _lows;
private readonly CircularBuffer _closes;
private const int DefaultPeriod = 20;
/// <param name="period">The lookback period for pivot points (default 20).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 3.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Ap(int period = DefaultPeriod)
{
if (period < 3)
throw new ArgumentOutOfRangeException(nameof(period));
_highs = new(period);
_lows = new(period);
_closes = new(period);
WarmupPeriod = period;
Name = $"AP({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The lookback period for pivot points.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Ap(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static (double x, double y) FindPivot(CircularBuffer highs, CircularBuffer lows, CircularBuffer closes, int offset)
{
double high = highs[offset];
double low = lows[offset];
double close = closes[offset];
return (offset, (high + low + close) / 3.0); // Simple pivot point calculation
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Store price data
_highs.Add(BarInput.High, BarInput.IsNew);
_lows.Add(BarInput.Low, BarInput.IsNew);
_closes.Add(BarInput.Close, BarInput.IsNew);
if (_index < WarmupPeriod)
return BarInput.Close;
// Find three pivot points
var p0 = FindPivot(_highs, _lows, _closes, 2);
var p1 = FindPivot(_highs, _lows, _closes, 1);
var p2 = FindPivot(_highs, _lows, _closes, 0);
// Calculate midpoint of P1-P2
double midX = (p1.x + p2.x) / 2.0;
double midY = (p1.y + p2.y) / 2.0;
// Calculate slope of median line
double slope = (midY - p0.y) / (midX - p0.x);
// Project median line to current bar
double currentX = _index - p0.x;
return p0.y + slope * currentX;
}
}
+85
View File
@@ -0,0 +1,85 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ATRP: Average True Range Percent
/// A volatility indicator that expresses ATR as a percentage of current price.
/// This normalization allows for comparison across different price levels and
/// instruments.
/// </summary>
/// <remarks>
/// The ATRP calculation process:
/// 1. Calculate ATR normally
/// 2. Divide by current price
/// 3. Multiply by 100 for percentage
///
/// Key characteristics:
/// - Normalized volatility measure
/// - Price-independent comparison
/// - Percentage output
/// - Cross-market analysis
/// - Relative volatility measure
///
/// Formula:
/// ATRP = (ATR / Close) * 100
///
/// Market Applications:
/// - Cross-market comparison
/// - Position sizing
/// - Volatility analysis
/// - Risk assessment
/// - Market comparison
///
/// Note: More suitable for comparing different instruments than raw ATR
/// </remarks>
[SkipLocalsInit]
public sealed class Atrp : AbstractBase
{
private readonly Atr _atr;
private const int DefaultPeriod = 14;
private const double ScalingFactor = 100.0;
/// <param name="period">The number of periods for ATR calculation (default 14).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrp(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_atr = new(period);
WarmupPeriod = period;
Name = $"ATRP({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for ATR calculation.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrp(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate ATR
double atr = _atr.Calc(BarInput);
// Convert to percentage of price
return Math.Abs(BarInput.Close) > double.Epsilon
? (atr / BarInput.Close) * ScalingFactor
: 0.0;
}
}
+159
View File
@@ -0,0 +1,159 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ATRS: ATR Trailing Stop
/// A volatility-based trailing stop indicator that uses ATR to dynamically adjust
/// stop levels. It helps maintain position while allowing for normal market
/// fluctuations.
/// </summary>
/// <remarks>
/// The ATRS calculation process:
/// 1. Calculate ATR
/// 2. Multiply ATR by factor
/// 3. Apply trailing logic based on trend
/// 4. Update stop levels
///
/// Key characteristics:
/// - Dynamic stop levels
/// - Trend-following
/// - Volatility-based
/// - Position protection
/// - Risk management
///
/// Formula:
/// Long Stop = High - (ATR * Factor)
/// Short Stop = Low + (ATR * Factor)
/// where Factor is multiplier for ATR (default 2.0)
///
/// Market Applications:
/// - Stop loss placement
/// - Position management
/// - Trend following
/// - Risk control
/// - Exit strategy
///
/// Note: Returns stop level based on current trend
/// </remarks>
[SkipLocalsInit]
public sealed class Atrs : AbstractBase
{
private readonly Atr _atr;
private double _prevStop;
private double _p_prevStop;
private bool _isLong;
private bool _p_isLong;
private const int DefaultPeriod = 14;
private const double DefaultFactor = 2.0;
/// <summary>
/// Gets the current trend direction (true for long, false for short)
/// </summary>
public bool IsLong => _isLong;
/// <param name="period">The number of periods for ATR calculation (default 14).</param>
/// <param name="factor">The multiplier for ATR (default 2.0).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1 or factor is less than or equal to 0.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrs(int period = DefaultPeriod, double factor = DefaultFactor)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
if (factor <= 0)
throw new ArgumentOutOfRangeException(nameof(factor));
_atr = new(period);
Factor = factor;
WarmupPeriod = period;
Name = $"ATRS({period},{factor:F1})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for ATR calculation.</param>
/// <param name="factor">The multiplier for ATR.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrs(object source, int period = DefaultPeriod, double factor = DefaultFactor) : this(period, factor)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
/// <summary>
/// Gets or sets the ATR multiplier factor
/// </summary>
public double Factor { get; set; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Init()
{
base.Init();
_atr.Init();
_prevStop = double.NaN;
_isLong = true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
{
_index++;
_p_prevStop = _prevStop;
_p_isLong = _isLong;
}
else
{
_prevStop = _p_prevStop;
_isLong = _p_isLong;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate ATR
double atr = _atr.Calc(BarInput);
double atrBand = atr * Factor;
if (_index == 1 || double.IsNaN(_prevStop))
{
// Initialize stop level
_isLong = BarInput.Close > BarInput.Open;
_prevStop = _isLong ? BarInput.Low - atrBand : BarInput.High + atrBand;
return _prevStop;
}
// Update stop level based on trend
if (_isLong)
{
double newStop = BarInput.High - atrBand;
if (BarInput.Close < _prevStop)
{
_isLong = false;
_prevStop = BarInput.High + atrBand;
}
else if (newStop > _prevStop)
{
_prevStop = newStop;
}
}
else
{
double newStop = BarInput.Low + atrBand;
if (BarInput.Close > _prevStop)
{
_isLong = true;
_prevStop = BarInput.Low - atrBand;
}
else if (newStop < _prevStop)
{
_prevStop = newStop;
}
}
return _prevStop;
}
}
+5 -5
View File
@@ -1,11 +1,11 @@
# Volatility indicators
Done: 11, Todo: 24
Done: 15, Todo: 20
ADR - Average Daily Range
AP - Andrew's Pitchfork
✔️ ADR - Average Daily Range
✔️ AP - Andrew's Pitchfork
✔️ ATR - Average True Range
ATRP - Average True Range Percent
ATRS - ATR Trailing Stop
✔️ ATRP - Average True Range Percent
✔️ ATRS - ATR Trailing Stop
*BB - Bollinger Bands® (Upper, Middle, Lower)
CCV - Close-to-Close Volatility
CE - Chandelier Exit