Time for action – calculating volume-weighted average price
The following are the actions that we will take:
Read the data into arrays.
Calculate VWAP.
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 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.
The mean function
The mean
function is quite friendly and not so mean. This function calculates the arithmetic mean of an array. Let's see it in action:
print "mean =", np.mean(c) mean = 351.037666667
Time-weighted average price
In finance, TWAP is another "average" price measure. Now that we are at it, let's compute the time-weighted average price, too. It is just a variation on a theme really. The idea is that recent price quotes are more important, so...