from turtle import color
from matplotlib import lines
import numpy as np#数组
import datetime as dt#日期
import matplotlib.dates as md#画图包中的日期
import matplotlib.pyplot as plt#画图
def conver_data(datas):
#把时间转换成字符串类型
s_data=str(datas,encoding="utf-8")
#去除前后多余的空格、回车符 去空
da=dt.datetime.strptime(s_data,'%Y/%m/%d')
#修改日期格式 '%Y/%m/%d'----'%Y-%m-%d'
format_data=da.strftime('%Y-%m-%d')
return format_data
"""
converters={列:函数} 把需要的列放到函数中进行加工
M8[D]:日期格式,D代表整数类型
f8:(flot64)
i1(int8) i2(int16) i4(int32) i8(int64)
"""
#读取数据
def read_csv(filePath):
data,open_price,higth_price,low_price,close_price=np.loadtxt(filePath,\
delimiter=",",usecols =(0,1,3,4,5),converters ={0:conver_data},dtype ='M8[D],f8,f8,f8,f8',unpack=True)
return data,open_price,higth_price,low_price,close_price
#画图
def draw_bar(data,open_price,higth_price,low_price,close_price):
#X轴的数据、日期
#data.astype() 任意数据类型修改成任意数据类型
data_md=data.astype(md.datetime.datetime)
y1=higth_price-low_price
y2=close_price-open_price
#大于零就是上涨,红色
up=close_price-open_price> 1e-2
down=open_price-close_price> 1e-2
#创建一个全部是0的一维数组da
full_color=np.zeros(data_md.size,dtype='3f4')
edge_color=np.zeros(data_md.size,dtype='3f4')
#布尔索引
full_color[up]=(1,0,0)#红色
edge_color[up]=(1,0,0)
full_color[down]=(0,0.5,0)
edge_color[down]=(0,0.5,0)
#条形图,宽度=0,就是一根线
plt.bar(x=data_md,height=y1,width=0,align='center',color=full_color,edgecolor=edge_color,bottom=low_price)
#条形图
plt.bar(data_md,y2,width=0.8,align='center',color=full_color,edgecolor=edge_color,bottom=low_price)
plt.show()
#设置图形的背景
def format_bar(fist_day,end_day):
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False#解决负号不显示乱码问题
#x轴的坐标标签
plt.xlabel("从%s到%s的交易日"%(
fist_day.astype(md.datetime.datetime),
end_day.astype(md.datetime.datetime)
),fontsize=20)
#y轴的坐标标签
plt.ylabel("苹果公司的股票交易价格(美元)",fontsize=20)
#标题
plt.title("股票趋势分析图",fontsize=25)
#背景网格
plt.grid(linestyle=":")
#set_major_loactor()主刻度 代表每周的周一
axes1=plt.gca()#获取当前图形的轴信息,返回一个axes对象
axes1.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
#次刻度 每天
axes1.xaxis.set_minor_locator(md.DayLocator())
#自定义主刻度的日期格式
axes1.xaxis.set_major_formatter(md.DateFormatter("%Y/%m/%d"))
#日期倾斜
#plt.gcf() 获取当前图形
plt.gcf().autofmt_xdate()
#测试
filePath="C:\\Users\\Administrator\\Desktop\\BABA.csv"
data,open_price,higth_price,low_price,close_price=read_csv(filePath)
#设置背景格式
format_bar(data[0],data[-1])
draw_bar(data,open_price,higth_price,low_price,close_price)