Time for action – calculating Volume Weighted Average Price

The following are the actions that we will take:

  1. Read the data into arrays.
  2. Calculate VWAP:
    from __future__ import print_function
    import numpy as np
    c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True)
    vwap = np.average(c, weights=v)
    print("VWAP =", vwap)

    The output is as follows:

    VWAP = 350.589549353
    

What just happened?

That wasn't very hard, was it? We just called the average() function and set its weights parameter to use the v array for weights. By the way, NumPy also has a function to calculate the arithmetic mean. This is an unweighted average with all the weights equal to 1.

The mean() function

The mean() function is quite friendly and not so mean. This function calculates the arithmetic mean of an array.

Note

The arithmetic mean is given by the following formula:

The mean() function

It sums the values in an array a and divides the sum by the number of elements n (see https://www.khanacademy.org/math/probability/descriptive-statistics/central_tendency/e/mean_median_and_mode).

Let's see it in action:

print("mean =", np.mean(c))

As a result, we get the following printout:

mean = 351.037666667

Time-weighted average price

In finance, time-weighted average price (TWAP) is another average price measure. Now that we are at it, let's compute the TWAP too. It is just a variation on a theme really. The idea is that recent price quotes are more important, so we should give recent prices higher weights. The easiest way is to create an array with the arange() function of increasing values from zero to the number of elements in the close price array. This is not necessarily the correct way. In fact, most of the examples concerning stock price analysis in this book are only illustrative. The following is the TWAP code:

t = np.arange(len(c))
print("twap =", np.average(c, weights=t))

It produces the following output:

twap = 352.428321839

The TWAP is even higher than the mean.

Pop quiz – computing the weighted average

Q1. Which function returns the weighted average of an array?

  1. weighted average
  2. waverage
  3. average
  4. avg

Have a go hero – calculating other averages

Try doing the same calculation using the open price. Calculate the mean for the volume and the other prices.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset