Click here to Skip to main content
Click here to Skip to main content
Go to top

Volume Weighted Average Price (VWAP) Algorithm

, 11 Jan 2006
Rate this:
Please Sign up or sign in to vote.
Calculates Volume Weighted Average Price for Financial Time series.

Introduction

Volume Weighted Average Price is, as defined by the Handbook of World Stock, Derivative & Commodity Exchanges:

Represents the total value of shares traded in a particular stock on a given day, divided by the total volume of shares traded in that stock on that day. Calculation techniques vary: some will use data from all markets or just the primary market, and may or may not adjust for resubmits and other error corrections. VWAP is a method of pricing transactions and also a benchmark to measure the efficiency of institutional trading or the performance of traders themselves.

Background

VWAP is primarily used by institutional traders. Many broker dealers offer VWAP orders so that a basket of orders' fill price will average out to the VWAP. This increases risk to the broker dealer or ECN, so there are often higher spreads or fees for this type of orders, or they are only offered to high-volume traders. VWAP orders are intended to balance time versus market impact, and often traders will use VWAP orders to send a packet of a few hundred shares every few seconds over the course of an entire day. Index funds also use VWAP to track an index as they are particularly sensitive to impacting the index they are tracking.

While many electronic broker dealers now offer VWAP orders, it is often difficult for traders to calculate VWAP real time (and audit this calculation). This simple VWAP class automates the algorithm for a financial time series.

Using the code

Before calculating the volume weighted average price, we first need to construct a TimeSeries class that holds our data. We will implement the IEnumerable interface and use an internal SortedList to hold our values. We make the class Serializable so that it can be sent across remoting channels.

[SerializableAttribute()]
public class TimeSeries: IEnumerable
{

Because a time series will be indexed by both DateTime and an integer indexer, we will provide multiple ways of accessing our data.

public virtual object this [int Index]
{
    get
    {
        return fArray.GetByIndex(Index);
    }
}

public virtual double this [int Index, int Row]
{
    get
    {
        return (double)fArray.GetByIndex(Index);
    }
}    

public object this [DateTime DateTime]
{
    get
    {
        int i = GetIndex(DateTime);
        if (i != -1)
        {
            return fArray.GetByIndex(i);
        }
        else
        {
            return null;
        }
    }
    set
    {
        Add(DateTime, value);
    }
}

The TimeSeries class has a few more features, but let's get to the meat of the VWAP algorithm calculation. The VWAP class is intentionally kept very simple, and I therefore chose to make all of its methods and properties static. Pass in the column you want to use for price, the column you use for the output, and the volume column. The algorithm iterates from the end of the array and calculates VWAP. Note: some ticks in the time series will be set to double.NaN because it is impossible to calculate VWAP if the algorithm does not have past data to calculate on. The client code should handle this situation accordingly.

/// <summary>
/// Volume Weighted Average Price
/// </summary>
public class VWAP
{
    private static TimeSeries _timeSeries;
    private static int _length = 1;

    private VWAP()
    {
    }

    /// <summary>
    /// Calculate VWAP for a timeseries
    /// </summary>
    /// <param name="timeSeries"></param>
    /// <param name="length"></param>
    /// <param name="calcColumn"></param>
    /// <param name="outputColumn"></param>
    /// <param name="volumeColumn"></param>
    public static TimeSeries Calculate(TimeSeries timeSeries, int length, 
                  int calcColumn, int outputColumn, int volumeColumn)
    {
        _length = length;
        _timeSeries = timeSeries;
        for (int i = 0; i < timeSeries.Count; i++)
        {
            ((object[])timeSeries[i])[outputColumn] = 
                       Value(i, calcColumn, volumeColumn);
        }
        return timeSeries;
    }

    /// <summary>
    /// Calculate VWAP for each value in the timeseries
    /// </summary>
    /// <param name="outputColumn"></param>
    /// <param name="volumeColumn"></param>
    /// <returns></returns>
    private static double Value(int index, 
                   int calcColumn, int volumeColumn)
    {
        if (index < _length - 1)
        {
            return double.NaN;
        }
        double d1 = 0.0;
        double d2 = 0.0;
        for (int i = index; i >= index - _length + 1; i--)
        {
            object[] series = (object[])_timeSeries[i];

            d1 += (double)series[calcColumn] * 
                  (double)series[volumeColumn];
            d2 += (double)series[volumeColumn];
        }
        d1 /= d2;
        return d1;
    }

To graph price vs. VWAP, I used StockChartX, a third-party component from ModulusFE. I have used this extensively in some of my other work, such as my automated trading system. The screenshot blow shows VWAP as a lagging derivative indicator of price.

Points of Interest

Let me know if this sort of financial indicator/algorithm is interesting to you. I may post some more as I am building a C# financial library called QFramework. It will contain other technical analysis methods, quantitative finance (option pricing, Monte Carlo, etc.), and other useful algorithms.

Further reading:

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

AndrewPeters
Web Developer
United States United States
Andrew Peters is a systems developer interested in non-trivial trading systems and financial systems architecture. He is currently focused on realtime, high performance multi-threaded applications running on the server and the desktop.
 
After a 4 year stint in China learning Mandarin and Tibetan, Andrew returned to the US to learn more about enterprise development and financial markets. While in China, he translated meetings between demure Communist officials and angry American businessmen, served coffee and fetid tofu in his 'BaiSuiFang' Coffee Shop, started Fabrefactum Software and was generally laughed at for his stupid jokes in Chinese.
 
He currently helps the pricing/analytics team hack on code at Chatham Financial, an interest rate and foreign exchange derivative consulting company.

Comments and Discussions

 
QuestionNeed direction Pinmemberlew2614-Oct-13 8:09 
General.NET 2+ Version PinmemberGChannon5-Feb-08 23:49 
GeneralRe: .NET 2+ Version Pinmemberagelospanagiotakis28-Jan-10 5:36 
is there a .net 2 version ?
Questioninteresting stuff, but no sourcecode? Pinmemberhahnl10-Jan-06 1:34 
AnswerRe: interesting stuff, but no sourcecode? PinmemberAndrewPeters10-Jan-06 2:34 
AnswerRe: interesting stuff, but no sourcecode? PinmemberAndrewPeters11-Jan-06 4:25 
QuestionIs this right? PinmemberDaniel Turini4-Jan-06 22:51 
AnswerRe: Is this right? PinmemberAndrewPeters5-Jan-06 4:53 
Generalinteresting article Pinmemberschmulen4-Jan-06 14:53 
GeneralRe: interesting article PinmemberAndrewPeters4-Jan-06 15:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 11 Jan 2006
Article Copyright 2006 by AndrewPeters
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid