python matplotlib 计算并显示均值
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
# 1.读取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})
print(open_price)
# 2.设置绘图窗口
mp.figure("Apple K Line", facecolor="lightgray")
mp.title("Apple K Line", fontsize=16)
mp.xlabel("Data", fontsize=14)
mp.ylabel("Price", fontsize=14)
# 3.x坐标(时间轴)轴修改
ax = mp.gca()
# 设置主刻度定位器为周定位器(每周一显示主刻度文本)
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(md.DayLocator())
mp.tick_params(labelsize=8)
mp.grid(linestyle=":")
# 4.时间类型修改 绘制收盘价折线图
dates = dates.astype(md.datetime.datetime)
mp.plot(dates, close_price, color="b", linestyle="--", linewidth=2, label="close")
# 5.计算 平均值
mean_price = np.mean(close_price)
mp.hlines(mean_price, dates[0], dates[-1], colors="g", label="mean")
# 6.计算 加权平均值
print(volumes)
v_wap = np.average(close_price, weights=volumes)
mp.hlines(v_wap, dates[0], dates[-1], colors="r", label="average")
# 7.计算 时间加权平均值
time_wap = np.linspace(10, 100, dates.size)
t_wap = np.average(close_price, weights=time_wap)
mp.hlines(t_wap, dates[0], dates[-1], colors="b", label="Time average")
# 8.中位数
median_val = np.median(close_price)mp.hlines(median_val, dates[0], dates[-1], colors="violet", label="median")
mp.legend()
mp.gcf().autofmt_xdate() # X轴标签自动显示
mp.show()