目录
Numpy数据分析API总结
numpy常见函数
加载文件
import numpy as np
np.loadtxt(
'path',delimiter = ',',usecols = (0,2),unpack = False,
dtype = 'U10 f8',converters = {
1:func} # 转换器函数字典
)
案例,绘制K线图
绘制收盘价格折线图
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')
t = time.date().strftime('%Y-%m-%d')
return t
dates,opening_prices,highest_prices,lowest_prices,closing_prices =
np.loadtxt('aapl.csv',delimiter = ',',usecols = (1,3,4,5,6),
unpack = True,dtype = 'M8[D],f8,f8,f8,f8',
converters = {
1,dmy2ymd})
# 折线图
mp.figure('AAPL', facecolor='lightgray')
mp.title('AAPL', fontsize=16)
mp.xlabel('Date', fontsize=14)
mp.ylabel('Price', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
# 设置x轴刻度定位器
ax = mp.gca()
ax.xaxis.set_major_locator(
md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.set_major_formatter(
md.DateFormatter('%d %b %Y'))
ax.xaxis.set_minor_locator(md.DayLocator())
# 为了日期显示合理,修改dates的dtype
dates = dates.astype(md.datetime.datetime)
mp.plot(dates, closing_prices, alpha=0.3,
color='dodgerblue', linewidth=2,
linestyle='--', label='AAPL CP')
mp.legend()
mp.show()
在上图基础上添加蜡烛图,即包含实体(开盘价、收盘价)和影线(最高价、最低价)的bar
# 控制实体与影线的颜色
rise = closing_prices >= opening_prices
color = np.array(
['white' if x else 'green' for x in rise])
ecolor = np.array(
['red' if x else 'green' for x in rise])
# 绘制实体
mp.bar(dates, closing_prices - opening_prices,
0.8, opening_prices, color=color,
edgecolor=ecolor, zorder=3)
# 绘制影线
mp.vlines(dates, lowest_prices, highest_prices,
color=ecolor)
算数平局值
np.mean(array)
加权平均值
np.average(array,weights = array2)
最大值、最小值、极差
np.max()
np.min()
np.ptp()
# 返回下标
np.argmax()
np.argmin()
# 将满足条件的同维数组组合成新的数组
np.maximun(a_array,b_array)
np.minimum(a_array,b_array)
中位数
np.median(array)
标准差
np.std(array,[ddof=1]) 总体[样本]标准差
移动平均
案例:绘制5日均线
import datetime as dt
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.dates as md
def dmy2ymd(dmy):
dmy = str(dmy, encoding='utf-8')
date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
ymd = date.strftime('%Y-%m-%d')
return ymd
dates, closing_prices = np.loadtxt('../data/aapl.csv', delimiter=',',
usecols=(1, 6), unpack=True, dtype='M8[D], f8', converters={
1: dmy2ymd})
# 处理数据
sma51 = np.zeros(closing_prices.size - 4)
for i in range(sma51.size):
sma51[i] = closing_prices[i:i + 5].mean()
# 开始绘制5日均线
mp.figure('Simple Moving Average', facecolor='lightgray')
mp.title('Simple Moving Average', fontsize=20)
mp.xlabel('Date', fontsize=14)
mp.ylabel('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('%d %b %Y'))
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
dates = dates.astype(md.datetime.datetime)
mp.plot(dates, closing_prices, c='lightgray', label='Closing Price')
mp.plot(dates[4:], sma51, c='orangered', label='SMA-5(1)')
mp.legend()
mp.gcf().autofmt_xdate()
mp.show()
卷积实现移动平均
sma5 = np.convolve(array,np.ones(5)/5,'valid') # 'valid'==有效,same == 同维,full = 完全卷积
mp.plot(x[4:],sma5,color = 'green',alpha = 0.5,linewidth = 6, label ='sma5')
布林带
布林带的组成:中轨:移动平均线;上轨:中轨+2×标准差;下轨:中轨-2×标准差
API:
weights = np.exp(np.linspace(-1, 0, 5))
weights /= weights.sum()
em5 = np.convolve(closing_prices, weights[::-1], 'valid')
stds = np.zeros(em5.size)
for i in range(stds.size):
stds[i] = closing_prices[i:i + 5].std()
stds *= 2
lowers = medios - stds
uppers = medios