python 计算标准差
csv文件下载地址:
链接: https://pan.baidu.com/s/1Jm4Z8wlskkloGYeeVNkOXg 提取码: p25v
"""
使用numpy 计算标准差
"""
import numpy as np
import datetime as dt
import matplotlib.pyplot as mp
import matplotlib.dates as md
# 方法-日期转换函数
def dmy2ymd(dmy):
dmy = str(dmy, encoding='utf-8')
time = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
t = time.strftime('%Y-%m-%d')
return t
# 读取csv文件数据
dates, open_price, max_price, min_price, close_price, volumes = np.loadtxt(
r".\aapl.csv",
delimiter=",",
usecols=(1, 3, 4, 5, 6, 7),
unpack=True,
dtype="M8[D], f8, f8, f8, f8, f8",
converters={1: dmy2ymd})
# 计算标准差
std = np.std(close_price)
print(std, "--> 标准差")
s_std = np.std(close_price, ddof=1)
print(s_std, "--> 样本标准差")
# 手动计算标准差
mean = np.mean(close_price) # 算数平均值
devs = close_price - mean # 离差
dsqs = devs ** 2 # 离差方
pvar = np.sum(dsqs) / dsqs.size # 总体方差
p_std = np.sqrt(pvar) # 总体标准差
s_var = np.sum(dsqs) / (dsqs.size - 1) # 样本方差
s_std = np.sqrt(s_var) # 样本标准差
print(p_std, "--> 标准差")
print(s_std, "--> 样本标准差")