Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

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:

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...