一、静态2D绘图
首先是导入和绘图定制操作
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.__version__
mpl.rcParams['font.family']='serif' #图表字体设置
plt.style.use('seaborn') #绘图样式设置
np.random.seed(1000)
y=np.random.standard_normal(20)
x=np.arange(len(y))
上述代码设置了x和y随机数,接下来调用plt.plot()函数绘图。如果只提供y值,plot以索引值为x值。接下来介绍2D图表的几项基本设置。
plt.plot(x,y,'b') #蓝色线
plt.plot(y)
plt.figure(figsize=(10,3)) #设置图标大小
plt.plot(y.cumsum())
plt.grid(True) #图表网格线设置
plt.axis('equal') #坐标轴数据设置,以下为其他参数
#empty\off\equal\scaled\tight\iamge\
#\[xmin,xmax,ymin,ymax]
plt.xlim(1,10)
plt.ylim(2,4)
plt.title() #图表标题
plt.xlabel() #坐标轴名称
plt.ylabel()
一般而言,对于包含多个单独的子集,且每个子集的绘制有不同的标准时,可以通过直接绘图(这种情况下plot函数会自动分类数据)或者申明具体数据组来绘图,同时添加其他通用函数以及进一步的注释帮助用户理解。
plt.plot(y[:,0],lw=1.5,label-'1st')
plt.plot(y[:,1],lw=1.5,label='2nd')
plt.legend(loc=0) #将图例放在合适的位置
#1 右上 2 左上
特别地,如果出现两组数据的刻度差别过大时,一个统一的刻度可能导致某个数据组不可视。为此解决方法有:使用左右两种刻度的y轴;使用上下两种视图。以下为两种方法的示例。
fig.ax1=plt.subplots() #定义图和轴对象
plt.plot(y[:,0],'b',label='1st')
ax2=ax1.twinx() #创建第二个轴对象
plt.plot(y[:,1],'y',label='2nd')
plt.subplot(211)
plt.plot(y[:,0],'b',label='1st')
plt.subplot(212)
plt.plot(y[:,1],'y',label='2nd')
子图的定位需要通过plt.subplot()函数中三个整数参数:numrows,numcols,fignum来指定子图的行数、列数和指定子图编号。接下来介绍几种其他集中绘图样式。
#柱状图
plt.bar()
#散点图
plt.scatter(y[:,0],y[:,1])
plt.scatter(y[:,0],y[:,1],y[:,2],cmap='coolwarm')
plt.colorbar()
#柱状图
plt.hist(y,label=['1st','2nd'])
#bins数组数 range数组据上下界 normed规范化整数 weights数组权重 color数组颜色
#箱线图
plt.boxplot(y)
plt.setp(ax,xticklabels=['1st','2nd'])
二、静态3D绘图
这一部分我们会使用一个基于Black-Scholes-Merton模型的欧式看涨期权类的例子来展示如何用代码实现欧式看涨期权价值曲面和Vega值曲面的可视化实例。我们首先看看这个类。
class bsm_call_option(object):
def __init__(self,S0,K,T,r,sigma):
self.S0 =float(S))#标的物当前价格
self.K=K #行权价
self.T=T #年为单位的到期日
self.r=r #连续复利的无风险利率
self.sigma=sigma #标的物价格波动率
def value(self):
d1=((log(self.S)/self.K)+(self.r+0.5*self.sigma **2)*self.T)/(self.sigma*sqrt(self.T)))
d2=((log(self.S0/self.K)+(self.r-0.5*self.sigma**2)*self.T)/(self.sigma*sqrt(self.T)))
value=(self.S0*stats.norm.cdf(d1,0.0,1.0)-self.K*exp(-self.r*self.T)*stats.norm.cdf(d2,0.0,1.0))
return value
def vega(self):
d1=((log(self.S)/self.K)+(self.r+0.5*self.sigma **2)*self.T)/(self.sigma*sqrt(self.T)))
vega=self.S0*stats.norm.pdf(d1,0.0,1.0)*sqrt(self.T)
return vega
def imp_vol(self,C0,sigma_est=0.2,it=100): #计算隐含波动率
option=bsm_call_option(self.S0,self.K,self.T,self.r,sigma_est)
for i in range(it):
option.sigma-=(option.value()-C0)/option.vega()
return option.sigma
那么第一步,就是对类进行实例化
strike=np.linspace(50,150,24)
ttm=np.linspace(0.5,2.5,24)
strike,ttm=np.meshgrid(strike,ttm)
iv=(strike-100)**2/(100*strike)/ttm
#iv为虚拟的隐含波动率
第二步,绘制图表
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure(figsize=(10,6))
ax=fig.gac(projection='3d') #创建画布
surf=ax.plot_surface(strike,ttm,iv,rstride=2,cstride=2,cmap=plt.cm.coolwarm,linewidth=0.5,antialiased=True) #创建3D图表
ax.set_xlabel('strike')
ax.set_ylabel('time-to-maturity')
ax.set_zlabel('implied volatility')
fig.colorbar(surf,shrink=0.5,aspect=5) #创建色卡条
三、交互式2D绘图
前面两个章节主要是讨论静态位图或者PDF格式的图表,在本节中我们希望创建一种可以缩放、通过鼠标悬停检查数据的图表。这种图表被称为交互式绘图,也就是面向对象绘图。与之相对的是非交互式绘图,也就是面向过程绘图。当plotly和pandas的DataFrame对象以及封装器软件包Cufflinks相结合时功能十分强大。简单介绍一下cufflinks的使用。
import pandas as pd
import numpy as np
import cufflinks as cf
import plotly.offline as plyo #导入plotly的离线绘图功能
cf.set_config_file(offline=True) #设置为offline模式可避免次数问题
plyo.init_notebook_mode(connected=True) #笔记本绘图模式
df.iplot(kind,barmode)
df.datagen.histogram().iplot(kind)
cf.datagen.box().iplot(kind)
以上只是对cufflinks函数的简单罗列,对这部分感兴趣的读者可以移步相关博客。接下来展示一段较为完整的交互式图表创建和表示的代码。
a=np.random.standard_normal((250,5)).cumsum(axis=0)
index=pd.date_range('2020-1-1',freq='B',periods=len(a))
df=pd.DataFrame(100+a,columns=list('abcdde'),index=index)
plyo.iplot(df.iplot(asFigure=True),filename='ply_01')
#其他参数 theme title xTitle yTitle mode symbol size colors
plyo.iplot(kind='hist',subplots=True,bins=15)
为了说明几种库组合在处理金融时间序列数据时的强大功能,我们以金融时间序列数据为例。
qf=cf.QuantFig(data,title,legend,name)
plyo.iplot(qf.iplot(asFigure=True),filename)
#添加金融图表元素
qf.add_bollinger_bands(periods,boll_std) #periods布林线周期 boll_std布林线宽度标准差
qf.add_RSI(periods,showbands) #periods RSI周期 showbands是否显示高低线
该实例化过程中,QuantFig对象将DataFrame对象作为输入后使用qf.iplot()方法按照对象中数据来绘制图表。也因此可以通过对象的不同方法,添加各种辅助判断的金融元素。
本文为笔者学习《Python金融大数据分析》所得,若有不妥谬误之处,还望温和批评指正。