导语:数据分析能力是一项非常重要的能力,尤其是在分析股票数据时,挖掘其中的有用信
息是成功的必要因素。而数据可视化可谓是秀数据分析能力的最好方式,本章内容主要介绍
python 的matplotlib 模块,让你的数据分析结果,show 出来!
matplotlib 绘图
开始之前,还是学习一个模块导入操作
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
让我们先搬上小白板
fig = plt.figure()
axes = fig.add_axes([0.2, 0.2, 1, 1]) # 左侧间距,底部间距,宽度,高度 (从 0 到1)
axes
----------------------- Page 134-----------------------
先画个 y=x2 曲线:
x = np.linspace(-10, 10)
y = x ** 2
axes.plot(x, y, 'r')
axes.set_xlabel('x') #设置X 轴
axes.set_ylabel('y') #设置Y 轴
axes.set_title('微笑') #设置标题
小白板上再插入一个小白板
axes2 = fig.add_axes([0.5, 0.5, 0.3, 0.3]) #插入面板2
axes2.plot(x, y, 'y')
axes2.set_xlabel('x')
axes2.set_ylabel('y')
axes2.set_title('微笑中微笑')
----------------------- Page 135-----------------------
plt.figure() 函数内部有figsize 和 dpi 参数,用于设置图像的大小和精度。
我们将上述代码中fig = plt.figure()改成fig = plt.figure(figsize=(8,4), dpi=100),结果如下:
----------------------- Page 136-----------------------
让我们尝试画一个沪深300 指数收盘价走势图:
x1_list=get_price('000300.SH', None, '20180125', '1d', ['close'], False, 'pre', 100, is_panel=1)
['close']
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2]) #插入面板2
y=np.array(x1_list)
x=np.array(range(0,len(x1_list)))
axes.plot(x, y, 'r')
axes.set_xlabel(' 日期')
axes.set_ylabel('沪深300 指数值')
axes.set_title('沪深300 近10 日走势图')
----------------------- Page 137-----------------------
同时在小白板上绘制沪深300 指数和创业板指数 (净值数据)
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2]) #插入面板
x1_list=get_price('000300.SH', None, '20180125', '1d', ['close'], False, 'pre', 100, is_panel=1)
['close']
x1_list=list((x1_list-x1_list.iloc[0])/x1_list)
y=np.array(x1_list)
x=np.array(range(0,len(x1_list)))
axes.plot(x, y, 'r')
x2_list=get_price('399006.SZ', None, '20180125', '1d', ['close'], False, 'pre', 100, is_panel=1)['close']
x2_list=list((x2_list-x2_list.iloc[0])/x2_list)
y2=np.array(x2_list)
x2=np.array(range(0,len(x2_list)))
axes.plot(x2, y2, 'y')
axes.set_xlabel(' 日期')
axes.set_ylabel('指数值')
axes.set_title('沪深300 与创业板净值走势')
axes.legend(['沪深300 指数','创业板指数'])
----------------------- Page 138-----------------------
是不是觉得小白板上的标题和X,Y 轴字体太小了,我们需要设置字体大小。
axes.set_xlabel(' 日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300 与创业板净值走势',fontsize=20)
axes.legend(['沪深300 指数','创业板指数'],fontsize=20)
----------------------- Page 139-----------------------
当然,我们可以通过全局操作,一条语句控制字体和大小
matplotlib.rcParams.update({'font.size': 10, 'font.family': 'serif'})
如何改变线条宽度、类型、颜色呢?axes.plot()函数内,color 代表颜色参数,linewidth 是宽
度参数,linestyle 是样式参数,将上述代码的axes.plot() 内置参数进行如下修改。
axes.plot(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
----------------------- Page 140-----------------------
除此之外,我们还能在曲线上做标记,并设置标的形状,大小,颜色。axes.plot()函数
内 marker 代表标记形状,markersize 代表标记大小,markerfacecolor 代表标记颜色。将上述
代码的axes.plot() 内置参数进行如下修改。
axes.plot(x, y, color='r',linewidth=1,linestyle='-',marker='+', markersize=8, markerfacecolor='r')
axes.plot(x2, y2, color='y',linewidth=2,linestyle='-',marker='o', markersize=8, markerfacecolor='y')
设置坐标轴范围
#设置范围
axes.set_ylim([-0.1,0.2 ])
axes.set_xlim([0, 100])
----------------------- Page 141-----------------------
你也可以自定义坐标轴。
#设置X 轴
axes.set_xticks([0,50,100])
axes.set_xticklabels(['开始','一半','收尾'], fontsize=18)
#设置Y 轴
axes.set_yticks([-0.1,0,0.1])
axes.set_yticklabels(['亏损10%','净值基点','盈利 10%'], fontsize=18)
加入文字注释和自定义网格
# 网格
axes.grid(color='b', alpha=1, linestyle='-.', linewidth=1)
#文字注释
axes.text(60, -0.06, r'创业板', fontsize=20, color='blue')
axes.text(60, 0.08, r'沪深300', fontsize=20, color='green')
----------------------- Page 142-----------------------
接下来介绍其他二维绘图样式
1.axes.scatter()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=np.random.randn(100)
y=np.random.randn(100)
axes.scatter(x,y)
axes.set_title('scatter')
2.axes.step()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=[1,2,3,4,5,6,7,]
y=[2,3,4,5,6,7,8,]
axes.step(x, y)
axes.set_title('step')
----------------------- Page 143-----------------------
3.axes.bar()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=[1,2,3,4,5,6,7,]
y=[2,3,4,5,6,7,8,]
axes.bar(x,y)
axes.set_title('bar')
4.axes.fill_between()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=[1,2,3,4,5,6,7,]
y=[2,3,4,5,6,7,8,]
axes.fill_between(x, y);
axes.set_title('fill_between')
----------------------- Page 144-----------------------
学习绘制沪深300 指数K 线图走势,希望同学们结合上面的知识点,学习更多绘图技巧。
绘制结果:
绘制代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
import datetime
data=get_price(['000300.SH'], None, '20171110', '1d', ['open','high','low','close'], True, None, 200,
is_panel=0)
data=data['000300.SH']
#时间转化格式
time=data.index
t=[]
for x in time:
x=str(x).split()[0]
x=x.split('-')
x=x[0]+x[1]+x[2]
x=int(x)
t.append(x)
#画图数据
time=t
open1=list(data['open'])
high1=list(data['high'])
low1=list(data['low'])
close1=list(data['close'])
----------------------- Page 145-----------------------
#画图
fig,ax = plt.subplots(figsize = (20,8),facecolor='pink')
fig.subplots_adjust()
plt.xticks()
plt.yticks()
plt.title("沪深300K 线走势图")
plt.ylabel("股指")
ticks = ax.set_xticks(range(1,200,40))
labels = ax.set_xticklabels([time[0],time[40],time[80],time[120],time[160]])
candlestick2_ohlc(ax,open1,high1,low1,close1,width=0.6,colorup='red',colordown='green')
#支撑线
plt.plot([75,200],[3316,3954],'g',linewidth=10)
# 红星:回踩1
plt.plot(75, 3316, 'r*', markersize = 40.0,label='趋势线')
plt.annotate(r'二次低位', xy=(75, 3316),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=26,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
# 红星:回踩2
plt.plot(140, 3650, 'r*', markersize = 40.0)
plt.annotate(r'止跌,形成趋势线', xy=(140, 3650),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=26,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
# 红星:回踩3
plt.plot(172, 3800, 'r*', markersize = 40.0)
plt.annotate(r' 回踩趋势线', xy=(172, 3800),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=26,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
#MA5
data['ma5']=pd.rolling_mean(data['close'],5)
plt.plot(list(data['ma5']),label='五日均线')
#MA10
data['ma10']=pd.rolling_mean(data['close'],10)
----------------------- Page 146-----------------------
plt.plot(list(data['ma10']),label='十 日均线')
#MA20
data['ma20']=pd.rolling_mean(data['close'],20)
plt.plot(list(data['ma20']),label='二十日均线')
#MA30
data['ma30']=pd.rolling_mean(data['close'],30)
plt.plot(list(data['ma30']),label='三十 日均线')
#MA60
data['ma60']=pd.rolling_mean(data['close'],60)
plt.plot(list(data['ma60']),label='六十日均线')
plt.legend()
print('沪深300 走势图分析')
----------------------- Page 147-----------------------
息是成功的必要因素。而数据可视化可谓是秀数据分析能力的最好方式,本章内容主要介绍
python 的matplotlib 模块,让你的数据分析结果,show 出来!
matplotlib 绘图
开始之前,还是学习一个模块导入操作
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
让我们先搬上小白板
fig = plt.figure()
axes = fig.add_axes([0.2, 0.2, 1, 1]) # 左侧间距,底部间距,宽度,高度 (从 0 到1)
axes
----------------------- Page 134-----------------------
先画个 y=x2 曲线:
x = np.linspace(-10, 10)
y = x ** 2
axes.plot(x, y, 'r')
axes.set_xlabel('x') #设置X 轴
axes.set_ylabel('y') #设置Y 轴
axes.set_title('微笑') #设置标题
小白板上再插入一个小白板
axes2 = fig.add_axes([0.5, 0.5, 0.3, 0.3]) #插入面板2
axes2.plot(x, y, 'y')
axes2.set_xlabel('x')
axes2.set_ylabel('y')
axes2.set_title('微笑中微笑')
----------------------- Page 135-----------------------
plt.figure() 函数内部有figsize 和 dpi 参数,用于设置图像的大小和精度。
我们将上述代码中fig = plt.figure()改成fig = plt.figure(figsize=(8,4), dpi=100),结果如下:
----------------------- Page 136-----------------------
让我们尝试画一个沪深300 指数收盘价走势图:
x1_list=get_price('000300.SH', None, '20180125', '1d', ['close'], False, 'pre', 100, is_panel=1)
['close']
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2]) #插入面板2
y=np.array(x1_list)
x=np.array(range(0,len(x1_list)))
axes.plot(x, y, 'r')
axes.set_xlabel(' 日期')
axes.set_ylabel('沪深300 指数值')
axes.set_title('沪深300 近10 日走势图')
----------------------- Page 137-----------------------
同时在小白板上绘制沪深300 指数和创业板指数 (净值数据)
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2]) #插入面板
x1_list=get_price('000300.SH', None, '20180125', '1d', ['close'], False, 'pre', 100, is_panel=1)
['close']
x1_list=list((x1_list-x1_list.iloc[0])/x1_list)
y=np.array(x1_list)
x=np.array(range(0,len(x1_list)))
axes.plot(x, y, 'r')
x2_list=get_price('399006.SZ', None, '20180125', '1d', ['close'], False, 'pre', 100, is_panel=1)['close']
x2_list=list((x2_list-x2_list.iloc[0])/x2_list)
y2=np.array(x2_list)
x2=np.array(range(0,len(x2_list)))
axes.plot(x2, y2, 'y')
axes.set_xlabel(' 日期')
axes.set_ylabel('指数值')
axes.set_title('沪深300 与创业板净值走势')
axes.legend(['沪深300 指数','创业板指数'])
----------------------- Page 138-----------------------
是不是觉得小白板上的标题和X,Y 轴字体太小了,我们需要设置字体大小。
axes.set_xlabel(' 日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300 与创业板净值走势',fontsize=20)
axes.legend(['沪深300 指数','创业板指数'],fontsize=20)
----------------------- Page 139-----------------------
当然,我们可以通过全局操作,一条语句控制字体和大小
matplotlib.rcParams.update({'font.size': 10, 'font.family': 'serif'})
如何改变线条宽度、类型、颜色呢?axes.plot()函数内,color 代表颜色参数,linewidth 是宽
度参数,linestyle 是样式参数,将上述代码的axes.plot() 内置参数进行如下修改。
axes.plot(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
----------------------- Page 140-----------------------
除此之外,我们还能在曲线上做标记,并设置标的形状,大小,颜色。axes.plot()函数
内 marker 代表标记形状,markersize 代表标记大小,markerfacecolor 代表标记颜色。将上述
代码的axes.plot() 内置参数进行如下修改。
axes.plot(x, y, color='r',linewidth=1,linestyle='-',marker='+', markersize=8, markerfacecolor='r')
axes.plot(x2, y2, color='y',linewidth=2,linestyle='-',marker='o', markersize=8, markerfacecolor='y')
设置坐标轴范围
#设置范围
axes.set_ylim([-0.1,0.2 ])
axes.set_xlim([0, 100])
----------------------- Page 141-----------------------
你也可以自定义坐标轴。
#设置X 轴
axes.set_xticks([0,50,100])
axes.set_xticklabels(['开始','一半','收尾'], fontsize=18)
#设置Y 轴
axes.set_yticks([-0.1,0,0.1])
axes.set_yticklabels(['亏损10%','净值基点','盈利 10%'], fontsize=18)
加入文字注释和自定义网格
# 网格
axes.grid(color='b', alpha=1, linestyle='-.', linewidth=1)
#文字注释
axes.text(60, -0.06, r'创业板', fontsize=20, color='blue')
axes.text(60, 0.08, r'沪深300', fontsize=20, color='green')
----------------------- Page 142-----------------------
接下来介绍其他二维绘图样式
1.axes.scatter()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=np.random.randn(100)
y=np.random.randn(100)
axes.scatter(x,y)
axes.set_title('scatter')
2.axes.step()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=[1,2,3,4,5,6,7,]
y=[2,3,4,5,6,7,8,]
axes.step(x, y)
axes.set_title('step')
----------------------- Page 143-----------------------
3.axes.bar()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=[1,2,3,4,5,6,7,]
y=[2,3,4,5,6,7,8,]
axes.bar(x,y)
axes.set_title('bar')
4.axes.fill_between()
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 2, 2])
x=[1,2,3,4,5,6,7,]
y=[2,3,4,5,6,7,8,]
axes.fill_between(x, y);
axes.set_title('fill_between')
----------------------- Page 144-----------------------
学习绘制沪深300 指数K 线图走势,希望同学们结合上面的知识点,学习更多绘图技巧。
绘制结果:
绘制代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
import datetime
data=get_price(['000300.SH'], None, '20171110', '1d', ['open','high','low','close'], True, None, 200,
is_panel=0)
data=data['000300.SH']
#时间转化格式
time=data.index
t=[]
for x in time:
x=str(x).split()[0]
x=x.split('-')
x=x[0]+x[1]+x[2]
x=int(x)
t.append(x)
#画图数据
time=t
open1=list(data['open'])
high1=list(data['high'])
low1=list(data['low'])
close1=list(data['close'])
----------------------- Page 145-----------------------
#画图
fig,ax = plt.subplots(figsize = (20,8),facecolor='pink')
fig.subplots_adjust()
plt.xticks()
plt.yticks()
plt.title("沪深300K 线走势图")
plt.ylabel("股指")
ticks = ax.set_xticks(range(1,200,40))
labels = ax.set_xticklabels([time[0],time[40],time[80],time[120],time[160]])
candlestick2_ohlc(ax,open1,high1,low1,close1,width=0.6,colorup='red',colordown='green')
#支撑线
plt.plot([75,200],[3316,3954],'g',linewidth=10)
# 红星:回踩1
plt.plot(75, 3316, 'r*', markersize = 40.0,label='趋势线')
plt.annotate(r'二次低位', xy=(75, 3316),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=26,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
# 红星:回踩2
plt.plot(140, 3650, 'r*', markersize = 40.0)
plt.annotate(r'止跌,形成趋势线', xy=(140, 3650),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=26,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
# 红星:回踩3
plt.plot(172, 3800, 'r*', markersize = 40.0)
plt.annotate(r' 回踩趋势线', xy=(172, 3800),
xycoords='data', xytext=(-90, -50),
textcoords='offset points', fontsize=26,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
#MA5
data['ma5']=pd.rolling_mean(data['close'],5)
plt.plot(list(data['ma5']),label='五日均线')
#MA10
data['ma10']=pd.rolling_mean(data['close'],10)
----------------------- Page 146-----------------------
plt.plot(list(data['ma10']),label='十 日均线')
#MA20
data['ma20']=pd.rolling_mean(data['close'],20)
plt.plot(list(data['ma20']),label='二十日均线')
#MA30
data['ma30']=pd.rolling_mean(data['close'],30)
plt.plot(list(data['ma30']),label='三十 日均线')
#MA60
data['ma60']=pd.rolling_mean(data['close'],60)
plt.plot(list(data['ma60']),label='六十日均线')
plt.legend()
print('沪深300 走势图分析')
----------------------- Page 147-----------------------