Data analysis (x) moving average

5 day moving average closing price: from the fifth day, calculate an average of the closing price of the latest line constituted daily five days.

Moving average algorithm:

(a+b+c+d+e)/5
(b+c+d+e+f)/5
(c+d+e+f+g)/5
...
(f+g+h+i+j)/5

Drawing 5. 10 MA K line graph in FIG.

# Moving Average 
Import numpy AS NP
 Import matplotlib.pyplot AS MP
 Import datetime dt AS
 Import matplotlib.dates AS md 


DEF dmy2ymd (dmy):
   "" " 
  The sun and the moon in turn date 
  : param Day: 
  : return: 
  " " " 
  DMY = STR (DMY, encoding = ' UTF-. 8 ' ) 
  T = dt.datetime.strptime (DMY, ' %% D- M-% the Y ' ) 
  S = t.date (). the strftime ( ' % Y- M-% D% ' )
   return S 


a dates, opening_prices, \
highest_prices, lowest_prices, \
closing_prices = \ 
  Np.loadtxt ( ' aapl.csv ' , 
             DELIMITER = ' , ' , 
             usecols = (. 1,. 3,. 4,. 5,. 6 ), 
             the unpack = True, 
             DTYPE = ' M8 [D], F8, F8, F8, F8 ' , 
             Converters = {. 1: dmy2ymd})   # DMY transfer date 
Print (a dates)
 # drawn closing price discount FIG 
mp.figure ( ' APPL ' , facecolor = ' LightGray ') 
Mp.title ( ' APPL ' , 18 is fontSize = ) 
mp.xlabel ( ' a Date ' , fontSize = 14 ) 
mp.ylabel ( ' Price ' , fontSize = 14 ) 
mp.grid (lineStyle = " : " ) 

# Set Scale Locator 
# weekly main scale a day, a time scale 

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()

 

Guess you like

Origin www.cnblogs.com/maplethefox/p/11459180.html