An Implementation of the ZigZag Algorithm for Technical Analysis of Stock Price Data

kaecan

Newbie
Messages
1
Likes
1
The ZigZag algorithm is used in technical analysis of stock price data to filter out minor movements, thereby identifying major swing lows and highs. Also known as the ZigZag indicator. This particular implementation is written in the C# programming language.

Input

1. quotes: Array of stock price objects.
2. obsStart, obsEnd: Observation indexes limiting evaluation to a specific array range.
3. minSwingPct: Minimum price swing, in percent.

Output

1. Returns a list of indexes pointing to the input array's major swing low and high elements.
2. obsLow, obsHigh: Indexes pointing to input array elements, for the last major swing in progress.

Code:
using System.Collections.Generic;

internal class Quote
{
    internal DateTime Time;
    internal float Open = 0F;
    internal float High = float.MinValue;
    internal float Low = float.MaxValue;
    internal float Close = 0F;
}

internal static class Indicator
{
    internal static List<int> ZigZag(Quote[] quotes, int obsStart, int obsEnd, float minSwingPct, out int obsLow, out int obsHigh)
    {
        bool swingHigh = false, swingLow = false;
        obsLow = obsHigh = obsStart;
        List<int> zigZag = new List<int>();
        for (int obs = obsStart; obs <= obsEnd; obs++)
        {
            if (quotes[obs].High > quotes[obsHigh].High)
            {
                obsHigh = obs;
                if (!swingLow &&
                     ((quotes[obsHigh].High - quotes[obsLow].Low) / quotes[obsLow].Low) * 100F >= minSwingPct)
                {
                    zigZag.Add(obsLow);  // new swinglow
                    swingHigh = false; swingLow = true;
                }
                if (swingLow) obsLow = obsHigh;
            }
            else if (quotes[obs].Low < quotes[obsLow].Low)
            {
                obsLow = obs;
                if (!swingHigh &&
                     ((quotes[obsHigh].High - quotes[obsLow].Low) / quotes[obsLow].Low) * 100F >= minSwingPct)
                {
                    zigZag.Add(obsHigh);  // new swinghigh
                    swingHigh = true; swingLow = false;
                }
                if (swingHigh) obsHigh = obsLow;
            }
        }
        return zigZag;
    }
}
 
Top