4.NumPy文件读写
4.1 NumPy 读写文件
4.1.1 参数详解
- 该命令除了读取文本文件,还可以读取生成器
delimiter要注意不要遗漏,否则会进行一次错误的读取usecols,如果分析仅仅是想取出其中的一些列,那么就指定indexunpack可以根据需要和偏好决定
python
loadtxt(fname, dtype=<class 'float'>, comments='#',
delimiter=None, converters=None, skiprows=0,
usecols=None, unpack=False, ndmin=0)
# fname 要读取的文件、文件名、或生成器
# dtype 数据类型,默认 float
# comments 注释
# delimiter 分隔符,默认是空格
# skiprows 跳过前几行读取,默认是 0,必须是 int 型
# usecols 要读取哪些列,例如 usecols=(1,4,5) 将提取第2、第5和第6列
# unpack 如果为 True,将分列读取4.1.2 np.loadtxt
- 可以读取 csv、txt 等文本数据
unpack读取可以一次性生成多个array方便计算- 注意
np.mean与np.average - 注意加权平均的计算可以通过
np.average配合weights参数来完成
python
# numpy文件io
### 利用NumPy进行历史股价分析
import sys
# 读入文件
c,v = np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True)
# unpack如果为True 将分别读取
# c表示第6列 v表示第7列
# 计算成交量加权平均价格
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))4.2 NumPy 读取文件案例
案例 1:
np.max计算最大值np.min计算最小值np.ptp计算极差(最大值 - 最小值)np.sort可以实现排序
python
# 寻找最大值和最小值
h, l = np.loadtxt(file_path, delimiter=',', usecols=(4,5), unpack=True)
print("highest =", np.max(h)) # 打印最大值
print("lowest =", np.min(l)) # 打印最小值
print((np.max(h) + np.min(l)) / 2)
# np.ptp 极差计算
print("Spread high price", np.ptp(h)) # 高价极差
print("Spread low price", np.ptp(l)) # 低价极差
# 统计分析
c = np.loadtxt(file_path, delimiter=',', usecols=(6,), unpack=True)
print("median =", np.median(c)) # 中位数
# np.msort(a) 等价于 np.sort(a, axis=0)
sorted_c = np.sort(c, axis=0) # 排序
print("sorted =", sorted_c)案例 2:
np.diff计算差分np.log计算对数np.where条件判断np.std计算标准差np.sqrt计算平方根
python
# 数组差分
# 股票收益率计算
# 读取收益率数据
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
# 计算简单收益率:差分 / 前一日价格
returns = np.diff(c) / c[:-1]
print("Standard deviation =", np.std(returns)) # 计算标准差
# 计算对数收益率
logreturns = np.diff(np.log(c))
# 查找正收益率的位置
posretindices = np.where(returns > 0)
print("Indices with positive returns", posretindices)
# 年化波动率 = 日对数收益率标准差 / 日均值
annual_volatility = np.std(logreturns) / np.mean(logreturns)
# 年化波动率除以 sqrt(1/252),转换为交易日标准
annual_volatility = annual_volatility / np.sqrt(1. / 252.)
print("Annual volatility", annual_volatility) # 年化波动率
print("Monthly volatility", annual_volatility * np.sqrt(1. / 12.)) # 月波动率4.3 NumPy 保存文件
np.savetxt 函数
- 指定输出对象,文本以及文本的类型
fmt为数据类型delimiter默认是逗号- 可以针对特定的数组写入文本,更换参数对比结果
python
savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n',
header='', footer='', comments='# ')
# fname 指定输出对象,文本以及文本的类型
# X 存入文件的数组
# fmt 数据类型(写入文件的格式)
# delimiter 默认是逗号
# newline 换行符
# header 写在文件开头的字符串
# footer 写在文件结尾的字符串
# comments 注释字符,header 和 footer 前会自动加上它4.4 NumPy 读写文件案例
- fmt 是指数据的类型
- 可以首先执行保存命令
- 然后观察 3 个文本文件的异同,尝试总结参数对于输出文本的影响
python
# 保存 array
# 保存logreturns到res.txt,数据格式为整数,逗号分隔
np.savetxt('res.txt', logreturns, fmt="%d", delimiter=",")
# 保存logreturns到res1.txt,默认数据格式,逗号分隔
np.savetxt('res1.txt', logreturns, delimiter=",")
# 保存logreturns到res2.txt,数据格式为浮点数,逗号分隔
np.savetxt('res2.txt', logreturns, fmt="%f", delimiter=",")4.5 NumPy 专用文件 IO
4.5.1 np.save /savez 函数
np.save(file 为文件位置, arr 为数组)np.savez(file 为文件位置, args, 多个数组, 就连续写数组)
python
# 单个数组:一次写 1 个数组
np.save('array_test.npy', logreturns) # 保存 logreturns 到 .npy 文件
# 多个数组:一次写 2 个数组
np.savez('array_test_full.npz', # 输出 .npz 文件(压缩包)
logreturns, # 第 1 个数组
logreturns) # 第 2 个数组4.5.2 np.load 函数
np.load(file 文件位置)
- 如果是 npy 格式,则直接返回数组
- 如果是 npz 格式,则返回一个 NpzFile 数据结构,可以像字典一样,使用提示的 key 去取得对应的数组
python
np.load('array_test.npy') # 读取 npy 文件 返回数组
# 判断读取的内容是否等于 logreturns
np.load('array_test.npy') == logreturns # 返回逐元素比较结果4.5.3 读取压缩文件验证
npz 文件读入后,每一个 key 对应的数组都与写入的数组相同
python
# 读取压缩文件中的数组
np.load('array_test.npz')['arr_0']
# 检查 'arr_0' 是否与 logreturns 相同
np.load('array_test_full.npz')['arr_0'] == logreturns
# 检查 'arr_1' 是否与 logreturns 相同
np.load('array_test_full.npz')['arr_1'] == logreturns