利用numpy加载文件
numpy提供了函数用于加载逻辑上可被解释为二维数组的文本文件,格式如下:
数据项1 <分隔符> 数据项2 <分隔符> ... <分隔符> 数据项n
例如:
AA,AA,AA,AA,AA
BB,BB,BB,BB,BB
或:
AA:AA:AA:AA:AA
BB:BB:BB:BB:BB
调用numpy.loadtxt()函数可以直接读取该文件并且获取ndarray数组对象:
import numpy as np
np.loadtxt(
'../aapl.csv',
delimiter=',',
usecols=(1, 3),
unpack=False,
dtype='U10, f8',
converters={1:func}
)
csv源文件信息: 第0列: 股票名称 第1列: 日期 第3列: 开盘价 第4列: 当日最高价 第5列: 当日最低价 第6列: 收盘价 第7列: 成交量 案例:读取aapl.csv文件,得到文件中的信息:
import numpy as np
import datetime as dt
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, lowest_prices, closeing_prices = np.loadtxt(
'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv',
delimiter=',',
usecols=(1, 3, 4, 5, 6),
unpack=True,
dtype='M8[D], f8, f8, f8, f8',
converters={1:dmy2ymd})
print(dates, opening_prices, highest_prices, lowest_prices, closeing_prices)
运行结果:
['2011-01-28' '2011-01-31' '2011-02-01' '2011-02-02' '2011-02-03'
'2011-02-04' '2011-02-07' '2011-02-08' '2011-02-09' '2011-02-10'
'2011-02-11' '2011-02-14' '2011-02-15' '2011-02-16' '2011-02-17'
'2011-02-18' '2011-02-22' '2011-02-23' '2011-02-24' '2011-02-25'
'2011-02-28' '2011-03-01' '2011-03-02' '2011-03-03' '2011-03-04'
'2011-03-07' '2011-03-08' '2011-03-09' '2011-03-10' '2011-03-11']
[344.17 335.8 341.3 344.45 343.8 343.61 347.89 353.68 355.19 357.39
354.75 356.79 359.19 360.8 357.1 358.21 342.05 338.77 344.02 345.29
351.21 355.47 349.96 357.2 360.07 361.11 354.91 354.69 349.69 345.4 ]
[344.4 340.04 345.65 345.25 344.24 346.7 353.25 355.52 359. 360.
357.8 359.48 359.97 364.9 360.27 359.5 345.4 344.64 345.15 348.43
355.05 355.72 354.35 359.79 360.29 361.67 357.4 354.76 349.77 352.32]
[333.53 334.3 340.98 343.55 338.55 343.51 347.64 352.15 354.87 348.
353.54 356.71 357.55 360.5 356.52 349.52 337.72 338.61 338.37 344.8
351.12 347.68 348.4 355.92 357.75 351.31 352.25 350.6 344.9 345. ]
[336.1 339.32 345.03 344.32 343.44 346.5 351.88 355.2 358.16 354.54
356.85 359.18 359.9 363.13 358.3 350.56 338.61 342.62 342.88 348.16
353.21 349.31 352.12 359.56 360. 355.36 355.76 352.47 346.67 351.99]
从已读的日期和收盘价,使用matplotlib绘制K线图:
import numpy as np
import datetime as dt
import matplotlib.pyplot as mp
import matplotlib.dates as md
mp.figure('APPL K', facecolor='lightgray')
mp.title('APPL K')
mp.xlabel('Day', fontsize=12)
mp.ylabel('Price', fontsize=12)
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())
mp.tick_params(labelsize=8)
dates = dates.astype(md.datetime.datetime)
mp.plot(dates, closeing_prices, color='dodgerblue', linestyle='-')
mp.gcf().autofmt_xdate()
mp.show()
运行结果:
k线图(蜡烛图)的基本形态指标: 1、收盘价高于开盘价时,则开盘价在下收盘价在上,二者之间的长方柱用红色或空心绘出,称之为阳线;其上影线的最高点为最高价,下影线的最低点为最低价。
2、收盘价低于开盘价时,则开盘价在上收盘价在下,二者之间的长方柱用黑色或实心绘出,称之为阴线,其上影线的最高点为最高价,下影线的最低点为最低价。 在上述已得到的折线图的基础上,绘制蜡烛图:
rise = closeing_prices >= opening_prices
color = np.array([('white' if x else 'limegreen') for x in rise])
ecolor = np.zeros(closing_prices.size, dtype='U5')
ecolor[:] = 'limegreen'
ecolor[rise] = 'red'
mp.bar(dates, highest_prices - lowest_prices, 0.1, lowest_prices, color=edgecolor)
mp.bar(dates, closeing_prices - opening_prices, 0.8, opening_prices, color=color, edgecolor=edgecolor)
运行结果:
平均值
算术平均值
算术平均值: m = (s1 + s2 + … + sn) / n 算术平均值表示对真值的无偏估计。
m = np.mean(array)
m = array.mean()
案例:计算收盘价的算术平均值。
import numpy as np
closing_prices = np.loadtxt(
'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv', delimiter=',',
usecols=(6), unpack=True)
mean = 0
for closing_price in closing_prices:
mean += closing_price
mean /= closing_prices.size
print(mean)
加权平均值
样本:
S
=
[
s
1
,
s
2
,
s
3
.
.
.
s
n
]
S = [s_1, s_2, s_3 ... s_n]
S=[s1?,s2?,s3?...sn?]
权重:
W
=
[
w
1
,
w
2
,
w
3
.
.
.
w
n
]
W =[w_1, w_2, w_3 ... w_n]
W=[w1?,w2?,w3?...wn?]
加权平均值:
a
=
s
1
w
1
+
s
2
w
2
+
.
.
.
+
s
n
w
n
w
1
+
w
2
+
.
.
.
+
w
n
a = \frac{s_1w_1 + s_2w_2 + ... + s_nw_n}{w_1+w_2+...+w_n}
a=w1?+w2?+...+wn?s1?w1?+s2?w2?+...+sn?wn??
a = np.average(closing_prices, weights=volumes)
VWAP - 成交量加权平均价格
成交量体现了市场对当前交易价格的认可度,成交量加权平均价格将会更接近这支股票的真实价值。
import numpy as np
closing_prices, volumes = np.loadtxt(
'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv', delimiter=',',
usecols=(6, 7), unpack=True)
vwap, wsum = 0, 0
for closing_price, volume in zip(
closing_prices, volumes):
vwap += closing_price * volume
wsum += volume
vwap /= wsum
print(vwap)
TWAP - 时间加权平均价格
时间越晚权重越高,参考意义越大。
import datetime as dt
import numpy as np
def dmy2days(dmy):
dmy = str(dmy, encoding='utf-8')
date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
days = (date - dt.date.min).days
return days
days, closing_prices = np.loadtxt(
'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv', delimiter=',',
usecols=(1, 6), unpack=True,
converters={1: dmy2days})
twap = np.average(closing_prices, weights=days)
print(twap)
综合三个平均值绘制图像:
import numpy as np
import matplotlib.pyplot as mp
import datetime as dt
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, lowest_prices, closing_prices, volumes = np.loadtxt('C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv',
delimiter=',', usecols=(1,3,4,5,6,7),
unpack=True, dtype='M8[D],f8,f8,f8,f8,f8',
converters={1:dmy2ymd})
mp.figure('AAPL', facecolor='lightgray')
mp.title('AAPL', fontsize=18)
mp.xlabel('Date', fontsize=14)
mp.ylabel('Price', fontsize=14)
mp.grid(linestyle=':')
import matplotlib.dates as md
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_prices, color='dodgerblue',
label='Closing Price', linewidth=2,
linestyle='--')
m = np.mean(closing_prices)
mp.hlines(m, dates[0], dates[-1], color='orangered', label='Mean(cp)')
vwap = np.average(closing_prices, weights=volumes)
mp.hlines(vwap, dates[0], dates[-1], color='blue', label='VWAP')
w = np.linspace(1, 7, closing_prices.size)
twap = np.average(closing_prices, weights=w)
mp.hlines(twap, dates[0], dates[-1], color='red', label='TWAP')
mp.legend()
mp.gcf().autofmt_xdate()
mp.show()
运行结果:
最值
np.max() / np.min() / np.ptp(): 返回一个数组中最大值/最小值/极差
import numpy as np
a = np.random.randint(10, 100, 9)
print(a)
print(np.max(a), np.min(a), np.ptp(a))
np.argmax() / np.argmin(): 返回一个数组中最大/最小元素的下标
print(np.argmax(a), np.argmin(a))
np.maximum() / np.minimum(): 将两个同维数组中对应元素中最大/最小元素构成一个新的数组
b = np.random.randint(10, 100, 9)
print(np.maximum(a, b), np.minimum(a, b), sep='\n')
综合案例求最值:
import numpy as np
import matplotlib.pyplot as mp
import datetime as dt
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, lowest_prices, closing_prices, volumes = np.loadtxt('C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv',
delimiter=',', usecols=(1,3,4,5,6,7),
unpack=True, dtype='M8[D],f8,f8,f8,f8,f8',
converters={1:dmy2ymd})
max_val = np.max(highest_prices)
min_val = np.min(lowest_prices)
print(max_val, '~', min_val)
max_ind = np.argmax(highest_prices)
min_ind = np.argmin(lowest_prices)
print('max:', dates[max_ind])
print('min:', dates[min_ind])
highest_ptp = np.ptp(highest_prices)
lowest_ptp = np.ptp(lowest_prices)
print(lowest_ptp, highest_ptp)
中位数
将多个样本按照大小排序,取中间位置的元素。
若样本数量为奇数,中位数为最中间的元素
[
1
,
2000
,
3000
,
4000
,
10000000
]
[1, 2000, 3000, 4000, 10000000]
[1,2000,3000,4000,10000000]
若样本数量为偶数,中位数为最中间的两个元素的平均值
[
1
,
2000
,
3000
,
4000
,
5000
,
10000000
]
[1,2000,3000,4000,5000,10000000]
[1,2000,3000,4000,5000,10000000]
案例:计算收盘价的中位数
import numpy as np
closing_prices = np.loadtxt( 'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv',
delimiter=',', usecols=(6), unpack=True)
size = closing_prices.size
sorted_prices = np.msort(closing_prices)
median = (sorted_prices[int((size - 1) / 2)] + sorted_prices[int(size / 2)]) / 2
print(median)
把代表中位数的水平线加入到折线图中:
median = np.median(closing_prices)
mp.hlines(median, dates[0], dates[-1], color='violet', label='median')
标准差
样本:
S
=
[
s
1
,
s
2
,
s
3
,
.
.
.
,
s
n
]
S = [s_1, s_2, s_3, ..., s_n]
S=[s1?,s2?,s3?,...,sn?]
平均值:
m
=
s
1
+
s
2
+
s
3
+
.
.
.
+
s
n
n
m = \frac{s_1 + s_2 + s_3 + ... + s_n}{n}
m=ns1?+s2?+s3?+...+sn??
离差:
D
=
[
d
1
,
d
2
,
d
3
,
.
.
.
,
d
n
]
;
d
i
=
S
i
?
m
D = [d_1, d_2, d_3, ..., d_n]; d_i = S_i-m
D=[d1?,d2?,d3?,...,dn?];di?=Si??m
离差方:
Q
=
[
q
1
,
q
2
,
q
3
,
.
.
.
,
q
n
]
;
q
i
=
d
i
2
Q = [q_1, q_2, q_3, ..., q_n]; q_i=d_i^2
Q=[q1?,q2?,q3?,...,qn?];qi?=di2?
总体方差:
v
=
(
q
1
+
q
2
+
q
3
+
.
.
.
+
q
n
)
n
v = \frac{(q_1+q_2+q_3 + ... + q_n)}{n}
v=n(q1?+q2?+q3?+...+qn?)?
总体标准差:
s
=
v
s = \sqrt{v}
s=v
?
样本方差:
v
′
=
(
q
1
+
q
2
+
q
3
+
.
.
.
+
q
n
)
n
?
1
v' = \frac{(q_1+q_2+q_3 + ... + q_n)}{n-1}
v′=n?1(q1?+q2?+q3?+...+qn?)?
样本标准差:
s
′
=
v
′
s' = \sqrt{v'}
s′=v′
?
import numpy as np
closing_prices = np.loadtxt(
'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv',
delimiter=',', usecols=(6), unpack=True)
mean = np.mean(closing_prices)
devs = closing_prices - mean
dsqs = devs ** 2
pvar = np.sum(dsqs) / dsqs.size
pstd = np.sqrt(pvar)
svar = np.sum(dsqs) / (dsqs.size - 1)
sstd = np.sqrt(svar)
print(pstd, sstd)
时间数据处理
案例:统计每个周一、周二、…、周五的收盘价的平均值,并放入一个数组。
import datetime as dt
import numpy as np
def dmy2wday(dmy):
dmy = str(dmy, encoding='utf-8')
date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
wday = date.weekday()
return wday
wdays, closing_prices = np.loadtxt('C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv', delimiter=',', usecols=(1, 6), unpack=True, converters={1: dmy2wday})
print(wdays)
ave_closing_prices = np.zeros(5)
for wday in range(ave_closing_prices.size):
ave_closing_prices[wday] = np.mean(closing_prices[wdays == wday])
print(ave_closing_prices)
数组的轴向汇总
案例:汇总每周的最高价,最低价,开盘价,收盘价。
def func(data):
pass
np.apply_along_axis(func, axis, array)
举个例子(统计每个学生成绩中的最高分及最高分的下标):
import numpy as np
data = np.array([[80, 81, 92],
[71, 81, 82],
[92, 61, 22],
[83, 73, 42],
[74, 85, 52],
[95, 89, 62],
[96, 91, 72]])
def func(data):
return data.max(), data.argmax()
r = np.apply_along_axis(func, 1, data)
print(r)
沿着数组中所指定的轴向,调用处理函数,并将每次调用的返回值重新组织成数组返回。
import numpy as np
import matplotlib.pyplot as mp
import datetime as dt
wdays, opening_prices, highest_prices, \
lowest_prices, closing_prices = np.loadtxt(
'C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/aapl.csv',
delimiter=',', usecols=(1, 3, 4, 5, 6),
unpack=True, converters={1: dmy2wday})
first_mon = np.where(wdays==0)[0][0]
last_fri = np.where(wdays==4)[0][-1]
wdays = wdays[first_mon:last_fri+1]
indices = np.arange(first_mon, last_fri+1)
mon_indices = indices[wdays==0]
tue_indices = indices[wdays==1]
wen_indices = indices[wdays==2]
thu_indices = indices[wdays==3]
fri_indices = indices[wdays==4]
max_len = np.max((mon_indices.size, tue_indices.size, wen_indices.size, thu_indices.size, fri_indices.size))
mon_indices = np.pad(mon_indices, pad_width=(0, max_len-mon_indices.size), mode='constant', constant_values=-1)
indices = np.vstack((mon_indices,tue_indices,wen_indices,thu_indices,fri_indices))
def summary(indices):
indices = indices[indices!=-1]
opening_price = opening_prices[indices[0]]
highest_price = highest_prices[indices].max()
lowest_price = lowest_prices[indices].min()
closing_price = closing_prices[indices[-1]]
return opening_price, highest_price, lowest_price, closing_price
r = np.apply_along_axis(summary, 1, indices)
print(r)
移动均线
收盘价5日均线:从第五天开始,每天计算最近五天的收盘价的平均值所构成的一条线。
移动均线算法:
(a+b+c+d+e)/5
(b+c+d+e+f)/5
(c+d+e+f+g)/5
...
(f+g+h+i+j)/5
在K线图中绘制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('C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_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()
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()
卷积
先理解卷积运算的过程:
a = [1, 2, 3, 4, 5] 源数组
b = [8, 7, 6] 卷积核 kernel
使用b作为卷积核,对a数组执行卷积运算的过程如下:
44 65 86 有效卷积 (valid)
23 44 65 86 59 同维卷积 (same)
(即中间元素有参与运算开始)
8 23 44 65 86 59 30 完全卷积 (full)
0 0 1 2 3 4 5 0 0
6 7 8
6 7 8
6 7 8
6 7 8
6 7 8
6 7 8
6 7 8
c = numpy.convolve(a, b, 卷积类型)
5日移动均线序列也可以直接使用卷积实现
a = [a, b, c, d, e, f, g, h, i, j]
b = [1/5, 1/5, 1/5, 1/5, 1/5]
使用卷积函数numpy.convolve(a, b, 卷积类型)实现5日均线
sma52 = np.convolve( closing_prices, np.ones(5) / 5, 'valid')
mp.plot(dates[4:], sma52, c='limegreen', alpha=0.5,
linewidth=6, label='SMA-5(2)')
使用卷积函数numpy.convolve(a, b, 卷积类型)实现10日均线
sma10 = np.convolve(closing_prices, np.ones(10) / 10, 'valid')
mp.plot(dates[9:], sma10, c='dodgerblue', label='SMA-10')
使用卷积函数numpy.convolve(a, b, 卷积类型)实现加权5日均线
weights = np.exp(np.linspace(-1, 0, 5))
weights /= weights.sum()
ema5 = np.convolve(closing_prices, weights[::-1], 'valid')
mp.plot(dates[4:], sma52, c='limegreen', alpha=0.5,
linewidth=6, label='SMA-5')
在折线图中显示多条均线:
import numpy as np
import matplotlib.pyplot as mp
import datetime as dt
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, \
lowest_prices, closing_prices = \
np.loadtxt('C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/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=18)
mp.xlabel('Date', fontsize=14)
mp.ylabel('Price', fontsize=14)
mp.grid(linestyle=':')
import matplotlib.dates as md
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_prices, color='dodgerblue',
label='Closing Price', linewidth=2,
linestyle='--', alpha=0.6)
ma5 = np.zeros(closing_prices.size - 4)
for i in range(ma5.size):
ma5[i] = closing_prices[i:i+5].mean()
mp.plot(dates[4:], ma5, color='orangered',
label='MA5')
kernel = np.ones(5) / 5
ma52 = np.convolve(closing_prices, kernel, 'valid')
mp.plot(dates[4:], ma52, color='orangered',
label='MA52', linewidth=7, alpha=0.3)
kernel = np.ones(10) / 10
ma10 = np.convolve(closing_prices, kernel, 'valid')
mp.plot(dates[9:], ma10, color='green',
label='MA10', linewidth=2)
kernel = np.exp(np.linspace(-1, 0, 5))
kernel = kernel[::-1] / kernel.sum()
ma53 = np.convolve(closing_prices, kernel, 'valid')
mp.plot(dates[4:], ma53, color='red',
label='MA53', linewidth=2)
mp.legend()
mp.gcf().autofmt_xdate()
mp.show()
布林带
布林带由三条线组成:
中轨:移动平均线
上轨:中轨+2x5日收盘价标准差 (顶部的压力)
下轨:中轨-2x5日收盘价标准差 (底部的支撑力)
布林带收窄代表稳定的趋势,布林带张开代表有较大的波动空间的趋势。
布林线指标
⑴ 股价由下向上穿越下轨线(Down)时,可视为买进信号。 ⑵ 股价由下向上穿越中轨时,股价将加速上扬,是加仓买进的信号。 ⑶ 股价在中轨与上轨(UPER)之间波动运行时为多头市场,可持股观望。 ⑷ 股价长时间在中轨与上轨(UPER)间运行后,由上向下跌破中轨为卖出信号。 ⑸ 股价在中轨与下轨(Down)之间向下波动运行时为空头市场,此时投资者应持币观望。 ⑹ 布林中轨经长期大幅下跌后转平,出现向上的拐点,且股价在2~3日内均在中轨之上。此时,若股价回调,其回档低点往往是适量低吸的中短线切入点。 ⑺ 对于在布林中轨与上轨之间运作的强势股,不妨以回抽中轨作为低吸买点,并以中轨作为其重要的止盈、止损线。 ⑻ 飚升股往往股价会短期冲出布林线上轨运行,一旦冲出上轨过多,而成交量又无法持续放出,注意短线高抛了结,如果由上轨外回落跌破上轨,此时也是一个卖点。
基本应用方法
1.价格向上穿越布林带中轨,为买入时机。 2.价格向下穿越布林带中轨,为卖出时机。 3.布林带的带宽非常狭窄时,是行情即将选择突破方向的信号。在使用这一方法时务必谨慎,因为这时价格往往会出现假突破,投资者要等突破方向明确,布林带的带宽放大时再介入。
绘制5日均线的布林带
kernel = np.exp(np.linspace(-1, 0, 5))
kernel = kernel[::-1] / kernel.sum()
ma53 = np.convolve(closing_prices, kernel, 'valid')
mp.plot(dates[4:], ma53, color='blue', label='MA53', linewidth=2)
std53 = np.zeros(ma53.size)
for i in range(std53.size):
std53[i] = closing_prices[i:i+5].std()
upper = ma53 + 2 * std53
lower = ma53 - 2 * std53
mp.plot(dates[4:], upper, color='red', label='upper', linewidth=2)
mp.plot(dates[4:], lower, color='green', label='lower', linewidth=2)
mp.fill_between(dates[4:], upper, lower, upper > lower, color='orangered', alpha=0.2)
综合收盘价折线图绘制布林带:
import numpy as np
import matplotlib.pyplot as mp
import datetime as dt
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, \
lowest_prices, closing_prices = \
np.loadtxt('C:/Users/ADMIN/Desktop/DATASCIENCE/day03/da_data/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=18)
mp.xlabel('Date', fontsize=14)
mp.ylabel('Price', fontsize=14)
mp.grid(linestyle=':')
import matplotlib.dates as md
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_prices, color='dodgerblue',
label='Closing Price', linewidth=2,
linestyle='--', alpha=0.6)
kernel = np.exp(np.linspace(-1, 0, 5))
kernel = kernel[::-1] / kernel.sum()
ma53 = np.convolve(closing_prices, kernel, 'valid')
mp.plot(dates[4:], ma53, color='blue',
label='MA53', linewidth=2)
std53 = np.zeros(ma53.size)
for i in range(std53.size):
std53[i] = closing_prices[i:i+5].std()
upper = ma53 + 2 * std53
lower = ma53 - 2 * std53
mp.plot(dates[4:], upper, color='red', label='upper', linewidth=2)
mp.plot(dates[4:], lower, color='green', label='lower', linewidth=2)
mp.fill_between(dates[4:], upper, lower, upper > lower, color='orangered', alpha=0.2)
mp.legend()
mp.gcf().autofmt_xdate()
mp.show()
|