-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

NumPy Beginner's Guide
By :

The vectorize
function is a yet another trick to reduce the number of loops in your programs. We will let it calculate the profit of a single trading day:
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 Python map
function. Call the vectorize
function, giving it as an argument the calc_profit
function that we still have to write:
func = np.vectorize(calc_profit)
We can now apply func
as if it is a function. Apply the func
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 is outside of the daily range, then, obviously our attempt failed and no profit was made, or we incurred a loss, therefore, we will return 0
. Otherwise, we sell at the close price and the profit is just the difference between the buy price and the close...
Change the font size
Change margin width
Change background colour