Time for action – avoiding loops with vectorize()
The vectorize()
function is a yet another trick to reduce the number of loops in your programs. Calculate the profit of a single trading day following these steps:
- First, load the data:
o, h, l, c = np.loadtxt('BHP.csv', delimiter=',', usecols=(3, 4, 5, 6), unpack=True)
- The
vectorize()
function is the NumPy equivalent of the Pythonmap()
function. Call thevectorize()
function, giving it as an argument thecalc_profit()
function:func = np.vectorize(calc_profit)
- We can now apply
func()
as if it is a function. Apply thefunc()
function result that we got to the price arrays:profits = func(o, h, l, c)
- The
calc_profit()
function is pretty simple. First, we try to buy slightly below the open price. If this ...
Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.