Numpy的基本数据函数
1.蜡烛图
import matplotlib.pyplot as mp
import numpy as np
import datetime as dt
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
dates,opening_prices,highest_prices,lowerst_prices,closing_pirce =np.loadtxt('/home/tarena/aid1907/data/day03/aapl.csv',
delimiter=',',
usecols=(1,3,4,5,6),
dtype='M8[D],f8,f8,f8,f8',
unpack=True,
converters={1:dmy2ymd})
# print(dates)
# 画图
mp.figure('AAPL',facecolor='lightgray')
mp.title('AAPL',fontsize=18)
mp.grid(linestyle=':')
mp.xlabel('Date',fontsize=14)
mp.ylabel('Closing Price',fontsize=14)
# 设置刻度定位器
ax = mp.gca()
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
# ax.xaxis.set_minor_locator(md.DayLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('%Y/%m/%d'))
dates = dates.astype(md.datetime.datetime)
mp.plot(dates,closing_pirce,color='pink',
linewidth=2,
linestyle='--',
label='closing',
alpha=0.8)
# 判断涨跌
rise_ = closing_pirce>opening_prices
# 填充色
color = ['white' if x else 'green' for x in rise_]
# 边缘色
ecolor = np.zeros(rise_.size,dtype='U5')
ecolor[:]='green'
ecolor[rise_] = 'red'
# print(color)
# 绘制k线
# 绘制实体
mp.bar(dates,closing_pirce-opening_prices,0.8,opening_prices,color=color,
edgecolor=ecolor,zorder=3)
# 绘制影线
mp.vlines(dates,lowerst_prices,highest_prices,color=ecolor)
mp.legend()
mp.gcf().autofmt_xdate() # 刻度为斜线
mp.show()
算术平均数
import matplotlib.pyplot as mp
import numpy as np
import datetime as dt
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
dates,opening_prices,highest_prices,lowerst_prices,closing_pirce =np.loadtxt('/home/tarena/aid1907/data/day03/aapl.csv',
delimiter=',',
usecols=(1,3,4,5,6),
dtype='M8[D],f8,f8,f8,f8',
unpack=True,
converters={1:dmy2ymd})
# print(dates)
# 画图
mp.figure('AAPL',facecolor='lightgray')
mp.title('AAPL',fontsize=18)
mp.grid(linestyle=':')
mp.xlabel('Date',fontsize=14)
mp.ylabel('Closing Price',fontsize=14)
# 设置刻度定位器
ax = mp.gca()
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
# ax.xaxis.set_minor_locator(md.DayLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('%Y/%m/%d'))
dates = dates.astype(md.datetime.datetime)
mp.plot(dates,closing_pirce,color='pink',
linewidth=2,
linestyle='--',
label='closing')
# 求算术平均数
mean = np.mean(closing_pirce)
mp.hlines(mean,dates[0],dates[-1],color='pink',label='Mean(CP)')
mp.legend()
mp.gcf().autofmt_xdate() # 刻度为斜线
mp.show()
加权平均数--成交量