《NumPy Beginner's Guide》笔记Chapter7

时间:2023-02-09 14:34:24
# -*- coding: utf-8 -*-
import numpy as np
__author__ = 'ZengDong'
#日期 = 18:33


""" 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函数文档没看懂【未解决】 """
#The NumPy lexsort function returns an array of indices of the input array elements
#corresponding to lexically sorting an array. We need to give the function an array or tuple of sort keys.

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 """
#generate five random numbers for the real part of the complex numbers and five numbers
#for the imaginary part.
np.random.seed(42)
complex_numbers = np.random.random(5) + 1j * np.random.random(5)
print("Complex numbers\n", complex_numbers)   #('Complex numbers\n', array([ 0.37454012+0.15599452j, 0.95071431+0.05808361j, 0.73199394+0.86617615j, 0.59865848+0.60111501j, 0.15601864+0.70807258j]))

#call the sort_complex function to sort the 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 """
#the argmax function gives the indices of the maximum values of an array
a = np.array([2, 4, 8])
print(np.argmax(a))  #输出 2


#the nanargmax function does the same but ignores NaN values
b = np.array([np.nan, 2, 4])
print(np.nanargmax(b))   #输出 2

#The argmin and nanargmin functions provide similar functionality but pertaining to minimum values.



#the argwhere function searches for non-zero values and returns the corresponding indices grouped by element
a = np.array([2, 4, 8])
print(np.argwhere(a <= 4))   #输出; [[0] [1]]


#The searchsorted function tells you the index in an array where a specified
#value could be inserted to maintain the sort order. It uses binary search, which is
#a O(log n) algorithm. We will see this function in action shortly.

#The extract function retrieves values from an array based on a condition.



#create an array
a = np.arange(5)

#It's time to call the searchsorted function
indices = np.searchsorted(a, [-2, 7])
print("Indices", indices)   #输出;('Indices', array([0, 5], dtype=int64))


#Let's construct the full array with the insert function
print("The full array", np.insert(a, indices, [-2, 7]))   #输出('The full array', array([-2, 0, 1, 2, 3, 4, 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 """
#create the array with the arange function
a = np.arange(7)

#create the condition that selects the even elements
conditions = (a % 2) == 0
print(conditions, conditions.dtype)   #类型是:bool

#extract the even elements based on our condition with the extract function
print("Even numbers", np.extract(conditions, a))  #输出:('Even numbers', array([0, 2, 4, 6]))

#select non-zero values with the nonzero function
print("Non zero", np.nonzero(a))   #输出:('Non zero', (array([1, 2, 3, 4, 5, 6], dtype=int64),))





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
#Call the fv function with the appropriate values to calculate the future value.
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')
#show()












""" 中间部分函数没兴趣,跳过........... """













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 """
#The Bartlett window is a triangular smoothing window. Perform the following steps to plot the Bartlett window:
#call the Numpy bartlett function to calculate the Bartlett window
window = np.bartlett(42)

import matplotlib.pyplot as plt
#plot the Bartlett window
plt.clf()
plot(window)
#show()


#The Blackman window is formed by summing the first three terms of cosines
#Load the data into Numpy array. Call the Numpy backman function to form a window and then
#use this window to smooth the price signal
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")

#plot
plt.plot(smoothed[N:-N], lw=2, label="smoothed")
plt.plot(closes[N:-N], label="closes")
plt.legend(loc="best")
#plt.show()





#The Hamming window is formed by a weighted cosine
#The NumPy hamming function returns the Hamming window. The only parameter is the number of points in the output window
plt.clf()


window = np.hamming(42)
plt.plot(window)
#plt.show()



#The Kaiser window is formed by the Bessel function
#callthe Numpy kaiser function to calculate the Kaiser window
plt.clf()
window = np.kaiser(42, 14)
plt.plot(window)
#plt.show()







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 """
#compute evenly spaced values with the linspace function
x = np.linspace(0, 4, 100)

#call the NumPy sinc function
vals = np.sinc(x)

#plot
plt.clf()
plt.plot(x, vals)
#plt.show()




#We did the same for two dimensions
xx = np.outer(x, x)   #Compute the outer product of two vectors. dot( X.T * X) 得到M*N矩阵
vals = np.sinc(xx)
plt.clf()
plt.imshow(vals)
plt.show()