"""
文件加载--绘制股票K线图
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dts
import time
def dmy2ymd(dmy):
"""
与numpy.loadtxt中converters转换器配合使用
变换日期格式:字符串-->解析为日期-->格式化为字符串
:param dmy:
:return: 新的时间字符串
"""
time1 = time.strptime(dmy.decode(), '%d-%m-%Y')
t = time.strftime('%Y-%m-%d', time1)
return t
pass
date, opening_price, highest_price, lowest_price, closing_price = \
np.loadtxt(r'E:\Python达内\数据分析学习素材\da_data\aapl.csv',
dtype='M8[D],f8,f8,f8,f8',
delimiter=',',
usecols=(1, 3, 4, 5, 6),
unpack=True,
converters={1: dmy2ymd})
plt.figure('K line Chart', facecolor='lightgray')
plt.grid(linestyle='-.')
plt.tick_params(labelsize='10')
plt.title('APPL', fontdict={'fontsize': 18, 'color': 'black'})
plt.xlabel('Date', fontdict={'fontsize': 15})
plt.ylabel('Price', fontdict={'fontsize': 15})
ax = plt.gca()
ax.xaxis.set_major_locator(dts.WeekdayLocator(byweekday=dts.MO))
ax.xaxis.set_major_formatter(dts.DateFormatter('%d %m %Y'))
ax.xaxis.set_minor_locator(dts.DayLocator())
plt.plot(date, opening_price, color='yellow', label='opening price', alpha=0.3)
plt.plot(date, closing_price, color='blue', label='closing_price', alpha=0.3)
rise = opening_price > closing_price
color_arr1 = np.array(['green' for i in range(1, 31)], dtype='U5')
color_arr1[rise] = 'white'
color_arr2 = np.array(['green' for j in range(1, 31)], dtype='U5')
color_arr2[rise] = 'r'
plt.bar(date, closing_price - opening_price, 0.8,
bottom=opening_price, color=color_arr1,
edgecolor=color_arr2, zorder=3)
plt.vlines(date, lowest_price, highest_price, colors='black')
plt.legend()
plt.gcf().autofmt_xdate()
plt.show()