同花顺Supermind量化交易 财务分析建模 Matplotlib绘图实现数据可视化

67 阅读10分钟

数据分析能力是一项非常重要的能力,尤其是在分析股票数据时,挖掘其中的有用信息是成功的必要因素。而数据可视化可谓是秀数据分析能力的最好方式,本章内容主要介绍python的matplotlib模块,让你的数据分析结果,show出来!

第一篇:Matplotlib绘图实现数据可视化

导语:数据分析能力是一项非常重要的能力,尤其是在分析股票数据时,挖掘其中的有用信息是成功的必要因素。而数据可视化可谓是秀数据分析能力的最好方式,本章内容主要介绍python的matplotlib模块,让你的数据分析结果,show出来!

matplotlib绘图

  开始之前,还是学习一个模块导入操作

In [3]:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

  让我们先搬上小白板

In [4]:

fig = plt.figure()
axes = fig.add_axes([0.2, 0.2, 1, 1]) # 左侧间距,底部间距,宽度,高度 (从0到1)
axes

Out[4]:

<matplotlib.axes._axes.Axes at 0x7f3262446dd8>

  先画个y=x2曲线:

In [7]:

fig = plt.figure()
axes = fig.add_axes([0.2, 0.2, 1, 1]) # 左侧间距,底部间距,宽度,高度 (从0到1)
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('微笑') #设置标题

Out[7]:

<matplotlib.text.Text at 0x7f32603b66d8>

  小白板上再插入一个小白板

In [8]:

fig = plt.figure()
axes = fig.add_axes([0.2, 0.2, 1, 1]) # 左侧间距,底部间距,宽度,高度 (从0到1)
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('微笑中微笑')

Out[8]:

<matplotlib.text.Text at 0x7f3260288550>

  plt.figure()函数内部有figsize和dpi参数,用于设置图像的大小和精度。
我们将上述代码中fig = plt.figure()改成fig = plt.figure(figsize=(8,4), dpi=100),结果如下:

In [10]:

fig = plt.figure(figsize=(8,4), dpi=100)
axes = fig.add_axes([0.2, 0.2, 1, 1]) # 左侧间距,底部间距,宽度,高度 (从0到1)
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('微笑中微笑')

Out[10]:

<matplotlib.text.Text at 0x7f3260115978>

  让我们尝试画一个沪深300指数收盘价走势图:

In [11]:

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日走势图')

Out[11]:

<matplotlib.text.Text at 0x7f3248561b38>

  同时在小白板上绘制沪深300指数和创业板指数(净值数据)

In [12]:

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指数','创业板指数'])

Out[12]:

<matplotlib.legend.Legend at 0x7f324851c748>

  是不是觉得小白板上的标题和X,Y轴字体太小了,我们需要设置字体大小。

In [13]:

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('日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300与创业板净值走势',fontsize=20)
axes.legend(['沪深300指数','创业板指数'],fontsize=20)

Out[13]:

<matplotlib.legend.Legend at 0x7f3248237a58>

  当然,我们可以通过全局操作,一条语句控制字体和大小

In [15]:

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指数','创业板指数'])
matplotlib.rcParams.update({'font.size': 20, 'font.family': 'serif'})

  如何改变线条宽度、类型、颜色呢?axes.plot()函数内,color代表颜色参数,linewidth是宽度参数,linestyle是样式参数,将上述代码的axes.plot()内置参数进行如下修改。

In [16]:

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)))
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(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
axes.set_xlabel('日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300与创业板净值走势',fontsize=20)
axes.legend(['沪深300指数','创业板指数'],fontsize=20)
axes.plot(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')

Out[16]:

[<matplotlib.lines.Line2D at 0x7f3246807b70>]

  除此之外,我们还能在曲线上做标记,并设置标的形状,大小,颜色。axes.plot()函数内 marker代表标记形状,markersize代表标记大小,markerfacecolor代表标记颜色。将上述代码的axes.plot()内置参数进行如下修改。

In [17]:

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)))
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(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
axes.set_xlabel('日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300与创业板净值走势',fontsize=20)
axes.legend(['沪深300指数','创业板指数'],fontsize=20)
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')

Out[17]:

[<matplotlib.lines.Line2D at 0x7f32483d17b8>]

  设置坐标轴范围

In [18]:

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)))
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(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
axes.set_xlabel('日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300与创业板净值走势',fontsize=20)
axes.legend(['沪深300指数','创业板指数'],fontsize=20)
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])

Out[18]:

(0, 100)

  你也可以自定义坐标轴。

In [19]:

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)))
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(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
axes.set_xlabel('日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300与创业板净值走势',fontsize=20)
axes.legend(['沪深300指数','创业板指数'],fontsize=20)
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')
#设置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)

Out[19]:

[<matplotlib.text.Text at 0x7f3248427ef0>,
 <matplotlib.text.Text at 0x7f32467a1128>,
 <matplotlib.text.Text at 0x7f32483cb6d8>]

  加入文字注释和自定义网格

In [20]:

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)))
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(x, y, color='r',linewidth=1,linestyle='-.')
axes.plot(x2, y2, color='y',linewidth=2,linestyle=':')
axes.set_xlabel('日期',fontsize=20)
axes.set_ylabel('指数值',fontsize=20)
axes.set_title('沪深300与创业板净值走势',fontsize=20)
axes.legend(['沪深300指数','创业板指数'],fontsize=20)
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')
#设置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')

Out[20]:

<matplotlib.text.Text at 0x7f32489c6da0>

  接下来介绍其他二维绘图样式

  1.axes.scatter()

In [21]:

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

Out[21]:

<matplotlib.text.Text at 0x7f3248dd75f8>

  2.axes.step()

In [23]:

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

Out[23]:

<matplotlib.text.Text at 0x7f3248af05f8>

  3.axes.bar()

In [24]:

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

Out[24]:

<matplotlib.text.Text at 0x7f3248c60828>

  4.axes.fill_between()

In [25]:

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

Out[25]:

<matplotlib.text.Text at 0x7f3248ce4c88>

  学习绘制沪深300指数K线图走势,希望同学们结合上面的知识点,学习更多绘图技巧。

  绘制代码:

In [22]:

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'])
#画图
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)
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走势图分析')
沪深300走势图分析

image.png

查看以上策略详情请到supermind量化交易官网查看:同花顺Supermind量化交易 财务分析建模 Matplotlib绘图实现数据可视化