import numpy as np
__author__ = 'ZengDong'
""" 1. Sorting NumPy has several data sorting routines, as follows: ‹‹ The 【sort】 function returns a sorted array ‹‹ The 【lexsort】 function performs sorting with a list of keys ‹‹ The 【argsort】 function returns the indices that would sort an array ‹‹ The ndarray class has a 【sort】 method that performs place sorting ‹‹ The 【msort】 function sorts an array along the first axis ‹‹ The 【sort_complex】 function sorts complex numbers by their real part and then their imaginary part function: lexsort函数文档没看懂【未解决】 """
import datetime
def datestr2num(s):
return datetime.datetime.strptime(s, "%d-%m-%Y").toordinal()
dates, closes = np.loadtxt("AAPL.csv", delimiter=",", usecols=(1, 6), converters={1:datestr2num}, unpack=True)
indices = np.lexsort((dates, closes))
print("Indices", indices)
print ["%s %s" % (datetime.date.fromordinal(int(dates[i])), closes[i]) for i in indices]
""" 2. Complex numbers Complex numbers are numbers that have a real and imaginary part. These numbers can be sorted using the NumPy sort_ complex function. This function sorts the real part first and then the imaginary part. function: sort_complex """
np.random.seed(42)
complex_numbers = np.random.random(5) + 1j * np.random.random(5)
print("Complex numbers\n", complex_numbers)
print("Sorted\n", np.sort_complex(complex_numbers))
""" 先比较real part 然后比较 image part ('Sorted\n', array([ 0.15601864+0.70807258j, 0.37454012+0.15599452j, 0.59865848+0.60111501j, 0.73199394+0.86617615j, 0.95071431+0.05808361j])) """
print("33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333")
""" 3. Searching NumPy has several functions that can search through arrays, as follows: function: argmax nanargmax argmin and nanargmin argwhere searchsorted insert """
a = np.array([2, 4, 8])
print(np.argmax(a))
b = np.array([np.nan, 2, 4])
print(np.nanargmax(b))
a = np.array([2, 4, 8])
print(np.argwhere(a <= 4))
a = np.arange(5)
indices = np.searchsorted(a, [-2, 7])
print("Indices", indices)
print("The full array", np.insert(a, indices, [-2, 7]))
print("44444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444")
""" 4. Array elements' extraction The NumPy extract function allows us to extract items from an array based on a condition. This function is similar to the where function we encountered in Chapter 3 The special nonzero function selects non-zero elements. function: extract nonzero """
a = np.arange(7)
conditions = (a % 2) == 0
print(conditions, conditions.dtype)
print("Even numbers", np.extract(conditions, a))
print("Non zero", np.nonzero(a))
print("55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555")
""" 5. Financial functions function: NumPy has a number of financial functions, as follows: ‹‹ The fv function calculates the so-called future value. The future value gives the value of a financial instrument at a future date, based on certain assumptions. ‹‹ The pv function computes the present value. The present value is the value of an asset today. ‹‹ The npv function returns the net present value. The net present value is defined as the sum of all the present value cash flows. ‹‹ The pmt function computes the payment against loan principal plus interest. ‹‹ The irr function calculates the internal rate of return. The internal rate of return is the effective interested rate, which does not take into account inflation. ‹‹ The mirr function calculates the modified internal rate of return. The modified internal rate of return is an improved version of the internal rate of return. ‹‹ The nper function returns the number of periodic payments. ‹‹ The rate function calculates the rate of interest. """
from matplotlib.pyplot import plot, show
print "Future value", np.fv(0.03/4, 5 * 4, -10, -1000)
fvals = []
for i in xrange(1, 10):
fvals.append(np.fv(.03/4, i * 4, -10, -1000))
plot(fvals, 'bo')
""" 中间部分函数没兴趣,跳过........... """
print("66666666666666666666666666666666666666666666666666666666666666666666666666666666666666666")
""" 6. Window functions Window functions are mathematical functions commonly used in signal processing. Applications include spectral analysis and filter design. These functions are defined to be 0 outside a specified domain. NumPy has a number of window functions such as bartlett, blackman, hamming, hanning, and kaiser. function: bartlett blackman hamming """
window = np.bartlett(42)
import matplotlib.pyplot as plt
plt.clf()
plot(window)
plt.clf()
closes = np.loadtxt("AAPL.csv", delimiter=",", usecols=(6,), converters={1:datestr2num}, unpack=True)
N = 5
window = np.blackman(N)
smoothed = np.convolve(window/window.sum(), closes, mode="same")
plt.plot(smoothed[N:-N], lw=2, label="smoothed")
plt.plot(closes[N:-N], label="closes")
plt.legend(loc="best")
plt.clf()
window = np.hamming(42)
plt.plot(window)
plt.clf()
window = np.kaiser(42, 14)
plt.plot(window)
print("777777777777777777777777777777777777777777777777777777777777777777777777777777")
""" 7. sinc The sinc function is widely used in Mathematics and signal processing. NumPy has a function with the same name. function: sinc outer """
x = np.linspace(0, 4, 100)
vals = np.sinc(x)
plt.clf()
plt.plot(x, vals)
xx = np.outer(x, x)
vals = np.sinc(xx)
plt.clf()
plt.imshow(vals)
plt.show()