Preface
NumPy has many specialized functions for special needs in financial computing or signal processing.
1. Sorting (np. lexsort())
NumPy provides various sorting functions:
The sort() function returns the sorted array
The LexSort() function sorts key values based on their lexicographic order
The argsort() function returns the index of the sorted input array
The sort() method of the ndarray class can sort arrays in place
The msort() function sorts along the first axis
Sort_The complex() function sorts complex numbers in the order of real parts first and then imaginary parts
Among them, the argsort and sort functions can be used to sort NumPy array types.
import numpy as np
import datetime
#conversion function for processing dates
def datestr2num(s):
return datetime.datetime.strptime(s.decode('ascii'), "%d-%m-%Y").toordinal()
dates, closes = np.loadtxt('AAPL.csv', delimiter=',', usecols=(1, 6), converters={1: datestr2num}, unpack=True)
#apply lexsort () function sorting (sorted by closing price)
indices = np.lexsort((dates, closes))
print("Indices", indices)
print(["%s %s" % (datetime.date.fromordinal(int(dates[i])), closes[i]) for i in indices])
2. Plurality sorting (np. sort_complex())
Complex numbers contain both real and imaginary parts, and NumPy has a specialized complex type that uses two floating-point numbers to represent complex numbers. These complex numbers can be sorted using NumPy_Sort using the complex() function in the order of the real part first and then the imaginary part.
import numpy as np
np.random.seed(42)
complex_numbers = np.random.random(5) + 1j * np.random.random(5)
print("Complex numbersn", complex_numbers)
print("Sortedn", np.sort_complex(complex_numbers))
3. Search (np. argmax(), np. argmin(), np. nanargmax(), np. argwhere(), np. searchsort(), np. insert(), np. extract(), np. nonzero())
# NumPy there are multiple functions in the array that can be searched for
# argmax the function returns the index corresponding to the maximum value in the array.
a = np.array([2, 4, 8])
print(np.argmax(a))
print(np.argmin(a))
# nanargmax functions provide the same functionality, but ignore NaN value
b = np.array([np.nan, 2, 4])
print(np.nanargmax(b))
# argmin and nanargmin the function functions similarly, but with a minimum value.
# argwhere the function searches for non-zero elements based on conditions and returns the corresponding index by grouping them.
a = np.array([2, 4, 8])
print(np.argwhere(a <= 4))
The searchsorted() function returns an index position in an ordered array for the specified insertion value, from which insertion can maintain the order of the array.
# searchsorted the () function returns an index position in an ordered array for the specified insertion value, from which insertion can maintain the orderliness of the array
import numpy as np
a = np.arange(5)
print("a",a)
indices = np.searchsorted(a, [-2, 7])
print("Indices", indices)
print("The full array", np.insert(a, indices, [-2, 7]))
The extract() function can extract elements from an array based on a certain condition. The nonzero() function is specifically used to extract non-zero array elements.
import numpy as np
a = np.arange(-5,7)
print(a)
condition = (a % 2) == 0
print("Even numbers", np.extract(condition, a))
print("Non zero", np.nonzero(a))
4. Financial functions
There are many financial functions in NumPy:
The fv function calculates the so-called future value, which is the value of a financial asset at a certain point in the future based on some assumptions
The PV function calculates the present value, which is the current value of financial assets
The npv function returns the net present value, which is the sum of net cash flows calculated at a discount rate
The PMT function calculates the amount to be paid for each period based on the principal and interest rate. θ
The irr function calculates the internal rate of return. The internal rate of return is the effective interest rate when the net present value is 0, without considering inflation factors
The Mirr function calculates the modified internal rate of return, which is an improved version of the internal rate of return
The nper function calculates the number of periodic payment periods
Calculate the rate of interest using the rate function.
#calculate final value
# pip install numpy-financial
import numpy_financial as npf
from matplotlib.pyplot import plot, show
#interest rate 3 % 10 quarterly payments, 5 year deposit period, and a present value of 1000
print("Future value", npf.fv(0.03/4, 5 * 4, -10, -1000))
fvals = []
for i in range(1, 10):
fvals.append(npf.fv(0.03/4, i * 4, -10, -1000))
plot(fvals, 'bo')
show()
#calculate present value
import numpy_financial as npf
from matplotlib.pyplot import plot, show
print("Future value", npf.pv(0.03/4, 5 * 4, -10, 1376.09))
#calculate net present value
import numpy as np
import numpy_financial as npf
cashflows = np.random.randint(100, size=5)
print(cashflows)
cashflows = np.insert(cashflows, 0, -100)
print("Cashflows", cashflows)
print("Net present value", npf.npv(0.03, cashflows))
#calculate internal rate of return
import numpy as np
import numpy_financial as npf
cashflows = np.random.randint(100, size=5)
print(cashflows)
cashflows = np.insert(cashflows, 0, -100)
print("Cashflows", cashflows)
print("Net present value", npf.irr(cashflows))
#calculate installment payments
import numpy_financial as npf
#loan of 1 million yuan with an annual interest rate of 10% % repay the loan for 30 years and pay the funds monthly
print("Payment", npf.pmt(0.10/12, 12 * 30, 1000000))
#calculate the number of payment periods
import numpy_financial as npf
#loan 9000, annual interest rate 10 % fixed monthly repayment of 100, required number of months
print("Number of payments", npf.nper(0.10/12, -100, 9000))
#calculate interest rates
import numpy_financial as npf
print("Interest rate", 12 * npf.rate(167, -100, 9000, 0))
5. Window function
Window function is a commonly used mathematical function in the field of signal processing, with related applications including spectral analysis and filter design. These window functions all take values of 0 except within the given interval. There are many window functions in NumPy, such as Bartlett, Blackman, Hamming, Hanning, and Kaiser.
#draw the bartlett window
import numpy as np
window = np.bartlett(42)
plot(window)
show()
#draw blackman window
import numpy as np
window = np.blackman(30)
plot(window)
show()
#draw the hanming window
import numpy as np
window = np.hamming(30)
plot(window)
show()
#draw kaize window
import numpy as np
window = np.kaiser(30,12)
plot(window)
show()
#the blackman window is formally the sum of three cosine values
import numpy as np
from matplotlib.pyplot import plot, show, legend
from matplotlib.dates import datestr2num
import sys
closes=np.loadtxt('AAPL.csv', delimiter=',', usecols=(6,), converters={1:datestr2num}, unpack=True)
N = 6
window = np.blackman(N)
smoothed = np.convolve(window/window.sum(), closes, mode='same')
plot(smoothed[N:-N], lw=2, label="smoothed")
plot(closes[N:-N], label="closes")
legend(loc='best')
show()
6. Specialized mathematical functions (np.i0(), np. sinc())
The Bessel function is the standard solution function for Bessel differential equations. In NumPy, i0 represents the first type of modified zero order Bessel function
The sinc function in NumPy has the same named function sinc, and there is also a two-dimensional version of this function, sinc is a trigonometric function.
#apply NumPy middle i the 0() function draws the first type of modified zero order bessel function
import numpy as np
x = np.linspace(0, 4, 100)
vals = np.i0(x)
plot(x, vals)
show()
#draw sinc () function
import numpy as np
x = np.linspace(0, 4, 100)
vals = np.sinc(x)
plot(x, vals)
show()
#draw 2d sinc () function
import numpy as np
from matplotlib.pyplot import imshow, show
x = np.linspace(0, 4, 100)
xx = np.outer(x, x)
vals = np.sinc(xx)
imshow(vals)
show()
Summary
Introduced some specialized NumPy features, including sorting and searching, specialized functions, financial functions, and window functions.