In other words we need to multiply the sign of the close price with the volume. In this tutorial, we will go over two approaches to this problem, one using the NumPy sign
function, and the other using the NumPy piecewise
function.
c, v=np.loadtxt('BHP.csv', delimiter=',', usecols=(6, 7), unpack=True)
Compute the absolute value changes. Calculate the change of the close price with the diff
function. The diff
function computes the difference between two sequential array elements and returns an array containing these differences:
change = np.diff(c) print "Change", change
The changes of the close price are shown as follows:
Change [ 1.92 -1.08 -1.26 0.63 -1.54 -0.28 0.25 -0.6 2.15 0.69 -1.33 1.16 1.59 -0.26 -1.29 -0.13 -2.12 -3.91 1.28 -0.57 -2.07 -2.07 2.5 1.18 -0.88 1.31 1.24 -0.59]
sign
function returns the signs for each element in an array. -1
is returned for a negative number, 1
for a positive number, and 0
, otherwise. Apply the sign
function to the change
array:signs = np.sign(change) print "Signs", signs
The signs of the change array are as follows:
Signs [ 1. -1. -1. 1. -1. -1. 1. -1. 1. 1. -1. 1. 1. -1. -1. -1. -1. -1. -1. -1. -1. 1. 1. 1. -1. 1. 1. -1.]
Alternatively, we can calculate the signs with the piecewise
function. The piecewise
function, as its name suggests, evaluates a function piece-by-piece. Call the function with the appropriate return values and conditions:
pieces = np.piecewise(change, [change < 0, change > 0], [-1, 1]) print "Pieces", pieces
The signs are shown again, as follows:
Pieces [ 1. -1. -1. 1. -1. -1. 1. -1. 1. 1. -1. 1. 1. -1. -1. -1. -1. -1. -1. -1. -1. 1. 1. 1. -1. 1. 1. -1.]
Check that the outcome is the same:
print "Arrays equal?", np.array_equal(signs, pieces)
And the outcome is as follows:
Arrays equal? True
print "On balance volume", v[1:] * signs
The on-balance volume is as follows:
[ 2620800. -2461300. -3270900. 2650200. -4667300. -5359800. 7768400. -4799100. 3448300. 4719800. -3898900. 3727700. 3379400. -2463900. -3590900. -3805000. -3271700. -5507800. 2996800. -3434800. -5008300. -7809799. 3947100. 3809700. 3098200. -3500200. 4285600. 3918800. -3632200.]
We computed the on-balance volume that depends on the change of the closing price. Using the NumPy sign
and piecewise
functions, we went over two different methods to determine the sign of the change (see obv.py
):
import numpy as np c, v=np.loadtxt('BHP.csv', delimiter=',', usecols=(6, 7), unpack=True) change = np.diff(c) print "Change", change signs = np.sign(change) print "Signs", signs pieces = np.piecewise(change, [change < 0, change > 0], [-1, 1]) print "Pieces", pieces print "Arrays equal?", np.array_equal(signs, pieces) print "On balance volume", v[1:] * signs