移动均线
收盘价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日.10日均线图
# 移动平均线 import numpy as np import matplotlib.pyplot as mp import datetime as dt import matplotlib.dates as md def dmy2ymd(dmy): """ 把日月年转年月日 :param day: :return: """ dmy = str(dmy, encoding='utf-8') t = dt.datetime.strptime(dmy, '%d-%m-%Y') s = t.date().strftime('%Y-%m-%d') return s 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}) # 日月年转年月日 print(dates) # 绘制收盘价的折现图 mp.figure('APPL', facecolor='lightgray') mp.title('APPL', fontsize=18) mp.xlabel('Date', fontsize=14) mp.ylabel('Price', fontsize=14) mp.grid(linestyle=":") # 设置刻度定位器 # 每周一一个主刻度,一天一个次刻度 ax = mp.gca() ma_loc = md.WeekdayLocator(byweekday=md.MO) ax.xaxis.set_major_locator(ma_loc) ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d')) ax.xaxis.set_minor_locator(md.DayLocator()) # 修改dates的dtype为md.datetime.datetiem dates = dates.astype(md.datetime.datetime) mp.plot(dates, closing_prices, color='dodgerblue', linewidth=2, linestyle='--', alpha=0.8, label='APPL Closing Price') #绘制5日移动平均线 ma5 = np.zeros(closing_prices.size-4) for i in range(ma5.size): ma5[i] =np.mean(closing_prices[i:i+5]) mp.plot(dates[4:],ma5,color='orangered',label='MA5') #绘制10日移动平均线 ma10 = np.zeros(closing_prices.size-9) for i in range(ma10.size): ma10[i] =np.mean(closing_prices[i:i+10]) mp.plot(dates[9:],ma10,color='green',label='MA10') mp.legend() mp.gcf().autofmt_xdate() mp.show()