Numpy科学计算库基础知识2

一、 库的读写

1.1读取

import  numpy as np
#np.localtxt(filepath,delemiter="",usecols="",unpack="")
#filepath:加载文件的路径
#delemiter=:分隔符
#usecols=:加载文件中的索引
#unpack=:是否将文件中的数据赋值给不同的变量

result=np.loadtxt("data.csv",delimiter=",",usecols=(6,7))
print(result)
#从result中切片分别取出收盘价和成交量
close=result[:,0]
print("收盘价:\n",close)
# 当加载csv文件的多列数据时候,可讲数据列用unpack解藕到不用数据中
arr1,arr2=np.loadtxt("data.csv",delimiter=",",usecols=(6,7),unpack=True)
print("收盘价:\n",arr1)
print("成交量:\n",arr2)
'''
收盘价:
 [336.1  339.32 345.03 344.32 343.44 346.5  351.88 355.2  358.16 354.54
 356.85 359.18 359.9  363.13 358.3  350.56 338.61 342.62 342.88 348.16
 353.21 349.31 352.12 359.56 360.   355.36 355.76 352.47 346.67 351.99]
成交量:
 [21144800. 13473000. 15236800.  9242600. 14064100. 11494200. 17322100.
 13608500. 17240800. 33162400. 13127500. 11086200. 10149000. 17184100.
 18949000. 29144500. 31162200. 23994700. 17853500. 13572000. 14395400.
 16290300. 21521000. 17885200. 16188000. 19504300. 12718000. 16192700.
 18138800. 16824200.]
'''

1.2写入

import numpy as np
example=np.arange(24).reshape(3,8)
#numpy的ndarray数组保存在txt文件中
#savetxt(fileName,data)
#fileName:保存的路径和,名称
#data:需要保存的数据
np.savetxt("example.txt",example)
print("保存完成")

二 、Numpy基础函数的定义运用

2.1极差— ptp(ndarray)

import numpy as np
#计算数据的极差,(最大小的,之差)
high=np.loadtxt("data.csv",delimiter=",",usecols=(4,))
#计算最高价的极差
ptp=np.ptp(high)
print("股票的极差:",ptp)  #股票的极差: 24.859999999999957
max=np.max(high)
min=np.min(high)
ptp2=max-min
print("相减法:",ptp2)  #相减法: 24.859999999999957

2.2中位数– median(ndarray)

#求中位数  np.median(ndarray)
close=np.loadtxt("data.csv",delimiter=",",usecols=(6,))
#对收盘价排序
# close.sort
# print(close)
median=np.median(close)
print("中位数",median)
#验证中位数是否正确
def Median(ndarray):
    ndarray.sort()
    k=len(ndarray)
    if k%2==1:
        print("中位数:",ndarray[(k-1)/2])
    else:
        print("中位数:",(ndarray[int(k/2)]+ndarray[int((k/2)-1)])/2)
    return Median
Median(close)

2.3方差— var(ndarray)

close=np.loadtxt("data.csv",delimiter=",",usecols=(6,))
open=np.loadtxt("data.csv",delimiter=",",usecols=(3,))
print("收盘价的方差",np.var(close))
print("开盘价的方差",np.var(open))

方差是各个数和平均数的差的平方之和.

2.4加权平均价— average(arr1,weight=arr2)

#成交量加权平均价  np.average(arr1,weight=arr2)
average=np.average(close,weights=amount)  #weights权重,就是多次运算用到的数据
print("成交量加权平均价:",average)

就是我们通常说的平均值

2.5算术平均值— mean(ndarray)

np.mean(ndarray)
#计算收盘价的算术平均值
mean=np.mean(close)
print("收盘价的平均价格:",mean)

2.6最大/小值— np.max(ndarray) np.min(ndarray)

#求最大和最小值  np.max(ndarray)   np.min(ndarray)
maxAmount=np.max(amount)
minAmount=np.min(amount)
print("最大成交量:",maxAmount)
print("最小成交量:",minAmount)


#多维数组取最大/小
example=np.arange(24).reshape(2,3,4)
max=np.max(example)
print("example最大值为:",max)
print("----------------------------------------")
def getMaxandMin(ndarray):
    max,min=None,None
    d1=ndarray.flatten()   #展平
    for i in range(len(d1)):# 排序
        for j in range(len(d1)):
            if d1[i]<d1[j]:
                d1[i],d1[j]=d1[j],d1[i]
                max=d1[i]
                min = d1[0]
    print(d1)
    print(max)
    print(min)
    return getMaxandMin
getMaxandMin(example)

2.7阶乘— np.prod(ndarray)

arr1=np.array([5,2,4,7])
prod=np.prod(arr1)
print("阶乘",prod)  #所有的数相乘,得到的是一个数

2.8累积乘积— cumprod

#2累积乘积  np.cumprod()
cumArr=np.array([2,3,4,5])
cumprod=np.cumprod(cumArr)
print(cumprod)  #[  2   6  24 120]

2.9数组的属性

2.9.1维度 ndim
import numpy as np
#1维度  ndim
example=np.arange(24).reshape(3,4,2)
print("len方法维度:",len(example))
#因为len()能获取一次,所以和维度ndim相等,除了一维数组
print("维度:",example.ndim)
# len方法维度: 3
# 维度: 3
2.9.2获取元素个数 size

print("size元素个数:",example.size)
# size元素个数: 24
2.9.3 数组中每个元素的所占字节数itemsize
#默认是int32位
print("每个元素所占的字节数:",example.itemsize)
# 每个元素所占的字节数: 4
2.9.4整个数组所占的字节数nbytes
print("整个数组所占的字节数:",example.nbytes)
# 整个数组所占的字节数: 96
2.9.5数组的转置结果 T

print("原数组:\n",example)
print("转置结果:\n",example.T)  #(2,4,3)
2.9.6复数数组的实部 real
comp=np.array([2+5j,6+3j,4+2j])
real=comp.real
print("复数数组的实部:\n",real)
#复数数组的虚部 real
imag=comp.imag
print("复数数组的虚部:\n",imag)
2.9.7求comp的复数数组的每个元素的摸 sqrt=开根
print(np.sqrt(real**2+imag**2))
#得出来的还是数组[5.38516481 6.70820393 4.47213595]

2.10标准差— std

std_price=np.std(close)     #计算收盘价的标准差

三 、Numpy进阶函数的定义运用

3.1修剪— np.clip(num1,num2)

#显示在【num1~num2】(包含),其他的都替换掉
clip1=np.array([152,7,97,43,6777,99])
clip2=clip1.clip(90,200)
print(clip2)    #[152  90  97  90 200  99]
clip3=clip1.clip(200,90)
print(clip3)    #[200 200 200 200  90 200]

num1和num2没有num2 > num1的要求,依据给定的顺序修剪

3.2分割— split()

3.2.1分割— np.split()
import numpy as np
full=np.arange(9).reshape(3,3)
print(full)
'''
[[0 1 2]
 [3 4 5]
 [6 7 8]]
'''
# 按列分割
#np.split()    axis=0按行分割
axis0=np.split(full,3,axis=0)
print(axis0)
# [array([[0, 1, 2]]), 
#   array([[3, 4, 5]]), 
#   array([[6, 7, 8]])]
print(axis0[0])#[[0 1 2]]
print(axis0[1])#[[3 4 5]]
print(axis0[2])#[[6 7 8]]
#.split()      axis=1按列分割
axis1=np.split(full,3,axis=1)  #分割数一定要是列的公因数
'''
[array([[0],[3],[6]]), 
 array([[1],[4],[7]]),
 array([[2],[5],[8]])]
'''
print(axis1)
print(axis1[0])
print(axis1[1])
print(axis1[2])
print("**********************")
#水平分割hsplit(arg,num)====.split(,,axis=1)
hsplit=np.hsplit(full,3)
print(hsplit)
3.2.2深度分割— np.dsplit()
import numpy as np
d3=np.arange(8).reshape(2,2,2)
# [[[0 1]
#   [2 3]]

#  [[4 5]
#   [6 7]]]
print("d3:\n",d3)
print("---------------------------------")
dsplit=np.dsplit(d3,2)
print(dsplit)
'''
[array([[[0],
        [2]],

       [[4],
        [6]]]), array([[[1],
        [3]],

       [[5],
        [7]]])]
'''
#类似于田字格分割

3.3筛选— np.where/compress(条件)

#1筛选出大于0 的所有元素的索引
indices=np.where(Log>0)
print("收益率大于0的索引:\n",indices))

3.4获取

#1根据索引值,获取相应的数组的元素
result=np.take(Log,indices)
print("收益率大于0的值有:",result)

3.5索引 — np.compress()

arr1=np.arange(8)
mask=arr1 >= 3  
    #Mask索引,将符合条件的设为True不符合的设置为False
    #compress()根据mask索引将True的位置从数组中提取出来
arr2=arr1.compress(arr1>=3) #将元素大于等于3的部分筛选出来
print(arr2)
#[3 4 5 6 7]

3.6拓展—np.repeat(ndarray,次数)

close1=np.array([[100000,10000,7500],[20000,11000,9000]])
a=np.repeat(close1[0],[1,15,20]) #拓展
#答案如下:
[100000  10000  10000  10000  10000  10000  10000  10000  10000  10000
  10000  10000  10000  10000  10000  10000   7500   7500   7500   7500
   7500   7500   7500   7500   7500   7500   7500   7500   7500   7500
   7500   7500   7500   7500   7500   7500]

四、利率基础知识

4.2简单收益率— diff

returns=np.diff(close) / close[:-1]     #计算收盘价的简单收益率
# np.diff() 后一天与前一天的差值(最后一天的不计算)
# close[:-1]  除去最后一天的数组

4.2对数收益率— np.diff(np.log(ndarray))

close=np.loadtxt("data.csv",delimiter=",",usecols=(6,))
#计算对数收益率
logReturns=np.diff(np.log(close))
print("对数收益率:",logReturns)

4.3年波动率

#年波动率等于对数收益率的标准差除以其均值,再除以交易日倒数的平方根,通常交易日取252天。
annual_volatility = (np.std(logreturns) / np.mean(logreturns)) / np.sqrt(1/252)

4.4月波动率

#月波动率等于对数收益率的标准差除以其均值,再除以交易月倒数的平方根,交易月为12月
mon_volatility=(np.std(logreturns) / np.mean(logreturns)) / np.sqrt(1/12)

4.5事例

文件中的数据为给定时间范围内某股票的数据,现要求:获取该时间范围内交易日周一、周二、周三、周四、周五分别对应的平均收盘价及哪天的平均收盘价最高,哪天的平均收盘价最低

import numpy as np
from datetime import datetime
# 将日期转化为星期
def date2num(s):
     return  datetime.strptime(s.decode("utf8"),"%d-%m-%Y").date().weekday()   
                 #返回的是星期weekday()

dates,close=np.loadtxt("data.csv",delimiter=",",
                       usecols=(1,6),
                       converters={1:date2num},   
                        #用来处理字符串转换出来   #用date2num来转换
                       unpack=True)
print("日期:",dates)
print("收盘价:",close)
#分开每星期的数据
average=[]
for i in range(5):
    mask=dates==i
    #根据mask数组从中筛选出星期数是i的收盘价
    weekday=close.compress(mask)
    dayAverage=np.mean(weekday)    #计算出星期数是i的收盘价的均值
    average.append(dayAverage)     #将出来的星期数是i的数添加到average中
print(average)
#获取数组中最大 的索引
maxindex=np.argmax(average)
minindex=np.argmin(average)
print("星期{}的俊平收盘价最高的".format(maxindex+1))
print("星期{}的俊平收盘价最低的".format(minindex+1))

1loadtxt()只能读取数字类型的数据,所以在读取字符串类型的数据(一般为日期)时会报错:could not convert string to float:’28-01-2011’;
2此时需要loadtxt()函数中converters={1:datestr2num}对相应的列进行格式转换,converters是一个数据列和转换函数之间进行映射的字典
3在Python3.x中,经过converters转换后的数据为bytes类型在使用datetime.strptime()函数进行格式转换时会报错:strptime() argument 1 must be str, not bytes
4此时需要对converters转换后的bytes类型数据进行s.decode(“utf8”)解码

五、日期

from datetime import  datetime
dateStr="2018-5-28"
newDate=datetime.strptime(dateStr,"%Y-%m-%d")
print(newDate)
#获取dateStr类型
weekday=newDate.date().weekday()   #date()得到的是类型
print("{}是星期{}".format(dateStr,weekday+1))
#结果如下:
#2018-05-28 00:00:00
#2018-5-28是星期1

猜你喜欢

转载自blog.csdn.net/Sakura55/article/details/80487805