通用函数

通用函数

二元通用函数 

1、通用函数

arr = np.arange(10)
np.sqrt(arr) #开平方
np.exp(arr) #指数运算  个元素的e*

x = randn(8) #随机生成数组
y = randn(8)
x
y
np.maximum(x, y) # 元素级最大值

modf 将整数和小数分开分成两

 

2、利用数组进行数据处理

  (1)向量化

meshgrid用于从数组a和b产生网格。生成的网格矩阵A和B大小是相同的。它也可以是更高维的。
[A,B]=Meshgrid(a,b)
生成size(b)Xsize(a)大小的矩阵A和B。它相当于a从一行重复增加到size(b)行,把b转置成一列再重复增加到size(a)列。因此命令等效于:
A=ones(size(b))*a;
B=b'*ones(size(a))
如下所示:
>> a=[1:2]
a =
     1     2
>> b=[3:5]
b =
     3     4     5
>> [A,B]=meshgrid(a,b)
A =
     1     2
     1     2
     1     2

B =
     3     3
     4     4
     5     5
 
>> [B,A]=meshgrid(b,a)
B =
     3     4     5
     3     4     5

A =
     1     1     1
     2     2     2
Meshgrid
points = np.arange(-5, 5, 0.01) # 1000 equally spaced points
xs, ys = np.meshgrid(points, points)
ys

import matplotlib.pyplot as plt #画图包
z = np.sqrt(xs ** 2 + ys ** 2)
z
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")

plt.draw()

  (2)将条件逻辑表达为数组运算

    列表推导式    (1)结果是浮点小数 (2) 大型数组运算速度慢   运用了Python的for循环  (3)没法用于多维数组

xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])

result = [(x if c else y)
          for x, y, c in zip(xarr, yarr, cond)]
result

    where 函数

    第一个参数 条件判断语句或  者逻辑向量 维度要跟后面的一样    他是对元数据进行操作    结果不会产生误差

result = np.where(cond, xarr, yarr)
result

    第一个参数换成表达式

 

# Not to be executed
#python 写法
result = []
for i in range(n):
    if cond1[i] and cond2[i]:
        result.append(0)
    elif cond1[i]:
        result.append(1)
    elif cond2[i]:
        result.append(2)
    else:
        result.append(3)

# Not to be executed
#where写法
np.where(cond1 & cond2, 0,
         np.where(cond1, 1,
                  np.where(cond2, 2, 3)))

# Not to be executed
result = 1 * cond1 + 2 * cond2 + 3 * -(cond1 | cond2)

  (3)数学与统计方法

 

M = mean(A)
返回沿数组中不同维的元素的平均值。
如果A是一个向量,mean(A)返回A中元素的平均值。
如果A是一个矩阵,mean(A)将其中的各列视为向量,把矩阵中的每列看成一个向量,返回一个包含每一列所有元素的平均值的行向量。
如果A是一个多元数组,mean(A)将数组中第一个非单一维的值看成一个向量,返回每个向量的平均值。

M = mean(A,dim)
返回A中沿着标量dim指定的维数上的元素的平均值。对于矩阵,mean(A,2)就是包含每一行的平均值的列向量。
《Simulink与信号处理》
应用举例 编辑本段回目录

A = [1 2 3; 3 3 6; 4 6 8; 4 7 7];
mean(A)
ans =
       3.0000 4.5000 6.0000

mean(A,2)
ans =
       2.0000
       4.0000

       6.0000
       6.0000
mean(A)
当A为向量时,那么返回值为该向量所有元素的均值
当A为矩阵时,那么返回值为该矩阵各列向量的均值
mean(A,2)
返回值为该矩阵的各行向量的均值
mean()

 

  (4)用于布尔型数组的方法

以为布尔值是1 或者0 所以能求取真的数量来

arr = randn(100)
(arr > 0).sum() # 正值的数量

any和all

bools = np.array([False, False, True, False])
bools.any()  #一真则真
bools.all()  #一假则假

  (5)唯一化及其他集合逻辑

#排序 会改变原数组
arr = randn(8)
arr
arr.sort() #从大到小排序
arr

arr = randn(5, 3)
arr
arr.sort(1) #二维数组指定排序方式
arr
设连续随机变量X的分布函数为F(X),密度函数为p(x)。那么,对任意0<p<1的p,称F(X)=p的X为此分布的分位数,或者下侧分位数。简单的说,分位数指的就是连续分布函数中的一个点,这个点的一侧对应概率p。
分位数
large_arr = randn(1000)
large_arr.sort()
large_arr[int(0.05 * len(large_arr))] # 5%分位数

(6)唯一化以及其他的集合逻辑

#唯一化以及其他的集合逻辑
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
np.unique(names)   #去重 然后排序   然后返回数据类型
ints = np.array([3, 3, 3, 2, 2, 1, 1, 4, 4]) #对数字类型的计算
np.unique(ints)

sorted(set(names)) #纯python来实现

values = np.array([6, 0, 0, 3, 2, 5, 6])
np.in1d(values, [2, 3, 6]) #用来测试一个成员是否在另一个成员中   返回布尔值

3、numpy 在线性代数上面的一些函数

矩阵相乘的必要条件就是前面这个矩阵的列数跟后面矩阵的行数一样

###线性代数
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
x
y
x.dot(y)  # 等价numpy模块 np.dot(x, y)
>>> np.ones(5)
array([ 1.,  1.,  1.,  1.,  1.])
>>>
>>> np.ones((5,), dtype=np.int)
array([1, 1, 1, 1, 1])
>>>
>>> np.ones((2, 1))
array([[ 1.],
       [ 1.]])
>>>
>>> s = (2,2)
>>> np.ones(s)
array([[ 1.,  1.],
       [ 1.,  1.]])
np.ones 知识点补充

矩阵相乘

np.dot(x, np.ones(3))

np.random.seed(12345)

from numpy.linalg import inv, qr
X = randn(5, 5)
mat = X.T.dot(X)
inv(mat)
mat.dot(inv(mat))
q, r = qr(mat)
r

两种生成随机数速度的比较

samples = np.random.normal(size=(4, 4))
samples

from random import normalvariate
N = 1000000
get_ipython().magic(u'timeit samples = [normalvariate(0, 1) for _ in xrange(N)]')
get_ipython().magic(u'timeit np.random.normal(size=N)')
随机漫步
# 范例:随机漫步
方法一 python
import random
position = 0
walk = [position]
steps = 1000
for i in xrange(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)

np.random.seed(12345)
方法二
nsteps = 1000
draws = np.random.randint(0, 2, size=nsteps)
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum()

walk.min()
walk.max()

(np.abs(walk) >= 10).argmax()#argmax对于所有结果进行了一次扫描
一次模拟多个随机漫步
nwalks = 5000
nsteps = 1000
draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1
steps = np.where(draws > 0, 1, -1)
walks = steps.cumsum(1)
walks

walks.max()
walks.min()


hits30 = (np.abs(walks) >= 30).any(1)
hits30
hits30.sum() # 到达30或-30的数量

crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
crossing_times.mean()

steps = np.random.normal(loc=0, scale=0.25,
                         size=(nwalks, nsteps))

 5、利用NumPy进行历史股价分析

c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True)#(文件名称,分割符,下标为6和7的字段,分开赋值给c,v)

#计算成交量加权平均价格

#计算成交量加权平均价格
vwap = np.average(c, weights=v)
print "VWAP =", vwap

#算术平均值函数
print "mean =", np.mean(c)

#时间加权平均价格
t = np.arange(len(c))
print "twap =", np.average(c, weights=t)

#寻找最大值和最小值
h,l=np.loadtxt('data.csv', delimiter=',', usecols=(4,5), unpack=True)
print "highest =", np.max(h)
print "lowest =", np.min(l)
print (np.max(h) + np.min(l)) /2

极值  取值范围  最大值减去最小值

print "Spread high price", np.ptp(h)
print "Spread low price", np.ptp(l)

就是一排数据从小到大排列后,中间那个数。
举例说,1,3,6,9,11。中间那个数是6,这就是中位数。1,3,6,9,11,13。这是有六个数,中间是两个数了,那么中位数就是6和9
中位数

中位数

c=np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
print "median =", np.median(c) #中位数  如果是偶数  取得是平均值
sorted = np.msort(c)
print "sorted =", sorted

 

N = len(c)
print "middle =", sorted[(N - 1)/2]
print "average middle =", (sorted[N /2] + sorted[(N - 1) / 2]) / 2

 

方差

print "variance =", np.var(c)
print "variance from definition =", np.mean((c - c.mean())**2)

 

股票收益率
c=np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

普通收益率,就是简单收益率,两个相邻之间的差的变化率

returns = np.diff( c ) / c[ : -1]
print "Standard deviation =", np.std(returns)

对数收益率

    检查数组,以确保里面没有0或者负数,因为0和负数没有对数

logreturns = np.diff( np.log(c) )

收益率大于0的日期找出来

posretindices = np.where(returns > 0)
print "Indices with positive returns", posretindices

价格的波动率

(1)对数波动 = 对数收益率的标准差/均值

annual_volatility = np.std(logreturns)/np.mean(logreturns)

(2)年化波动率

annual_volatility = annual_volatility / np.sqrt(1./252.)
print "Annual volatility", annual_volatility

(3)月度波动率

print "Monthly volatility", annual_volatility * np.sqrt(1./12.)

#日期分析
from datetime import datetime

# Monday 0
# Tuesday 1
# Wednesday 2
# Thursday 3
# Friday 4
# Saturday 5
# Sunday 6

 把数据转换成时间格式(Python会默认转换成浮点数)

def datestr2num(s):
return datetime.strptime(s, "%d-%m-%Y").date().weekday()

dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6),
converters={1: datestr2num}, unpack=True)
print "Dates =", dates

averages = np.zeros(5)

周几的均值

for i in range(5):
indices = np.where(dates == i)
prices = np.take(close, indices)
avg = np.mean(prices)
print "Day", i, "prices", prices, "Average", avg
averages[i] = avg

最高

top = np.max(averages)
print "Highest average", top
print "Top day of the week", np.argmax(averages)

最低

bottom = np.min(averages)
print "Lowest average", bottom
print "Bottom day of the week", np.argmin(averages)

 

#周汇总  (会剔除一些随机因素的影响)

def datestr2num(s):
   return datetime.strptime(s, "%d-%m-%Y").date().weekday()

dates, open, high, low, close=np.loadtxt('data.csv', delimiter=',', 
         usecols=(1, 3, 4, 5, 6), converters={1: datestr2num}, unpack=True)
close = close[:16] #前三周的数据
dates = dates[:16]

# get first Monday
first_monday = np.ravel(np.where(dates == 0))[0]
print "The first Monday index is", first_monday

# get last Friday
last_friday = np.ravel(np.where(dates == 4))[-1]
print "The last Friday index is", last_friday

weeks_indices = np.arange(first_monday, last_friday + 1)
print "Weeks indices initial", weeks_indices

weeks_indices = np.split(weeks_indices, 3)
print "Weeks indices after split", weeks_indices

def summarize(a, o, h, l, c):
    monday_open = o[a[0]]
    week_high = np.max( np.take(h, a) )
    week_low = np.min( np.take(l, a) )
    friday_close = c[a[-1]]

    return("APPL", monday_open, week_high, week_low, friday_close)

weeksummary = np.apply_along_axis(summarize, 1, weeks_indices, open, high, low, close)
print "Week summary", weeksummary

np.savetxt("weeksummary.csv", weeksummary, delimiter=",", fmt="%s")
View Code

#真实波动幅度均值

h, l, c = np.loadtxt('data.csv', delimiter=',', usecols=(4, 5, 6), unpack=True)

N =20
h = h[-N:]
l = l[-N:]

print "len(h)", len(h), "len(l)", len(l)
print "Close", c
previousclose = c[-N -1: -1]

print "len(previousclose)", len(previousclose)
print "Previous close", previousclose
truerange = np.maximum(h - l, h - previousclose, previousclose - l) 

print "True range", truerange

atr = np.zeros(N)

atr[0] = np.mean(truerange)

for i in range(1, N):
   atr[i] = (N - 1) * atr[i - 1] + truerange[i]
   atr[i] /= N

print "ATR", atr
View Code

#简单移动平均线

from matplotlib.pyplot import plot #画图
from matplotlib.pyplot import show

N = 5

weights = np.ones(N) / N
print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
sma = np.convolve(weights, c)[N-1:-N+1] #
t = np.arange(N - 1, len(c))
plot(t, c[N-1:], lw=1.0)
plot(t, sma, lw=2.0)
show()
View Code

#指数移动平均线

x = np.arange(5)
print "Exp", np.exp(x)
print "Linspace", np.linspace(-1, 0, 5)

N = 5


weights = np.exp(np.linspace(-1., 0., N))
weights /= weights.sum()
print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
ema = np.convolve(weights, c)[N-1:-N+1]
t = np.arange(N - 1, len(c))
plot(t, c[N-1:], lw=1.0)
plot(t, ema, lw=2.0)
show()
View Code

#布林带

N = 5

weights = np.ones(N) / N
print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
sma = np.convolve(weights, c)[N-1:-N+1]
deviation = []
C = len(c)

for i in range(N - 1, C):
   if i + N < C:
      dev = c[i: i + N]
   else:
      dev = c[-N:]
   
   averages = np.zeros(N)
   averages.fill(sma[i - N - 1])
   dev = dev - averages 
   dev = dev ** 2
   dev = np.sqrt(np.mean(dev))
   deviation.append(dev)

deviation = 2 * np.array(deviation)
print len(deviation), len(sma)
upperBB = sma + deviation
lowerBB = sma - deviation

c_slice = c[N-1:]
between_bands = np.where((c_slice < upperBB) & (c_slice > lowerBB))

print lowerBB[between_bands]
print c[between_bands]
print upperBB[between_bands]
between_bands = len(np.ravel(between_bands))
print "Ratio between bands", float(between_bands)/len(c_slice)

t = np.arange(N - 1, C)
plot(t, c_slice, lw=1.0)
plot(t, sma, lw=2.0)
plot(t, upperBB, lw=3.0)
plot(t, lowerBB, lw=4.0)
show()
View Code

 

posted @ 2016-07-26 23:55  若时光搁浅  阅读(255)  评论(0)    收藏  举报