python 读写+画图

一、读取/写入文件

1.1 python文件操作的一般步骤是:

  1. 打开文件
  2. 读取文件/写入文件
  3. 关闭文件三部分
  • python打开文件使用open函数,open函数可以接受两个参数,第一个参数是文件的路径,第二个参数是文件打开的模式
  • open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
  • file: 必需,文件路径(相对或者绝对路径)。mode: 可选,文件打开模式。buffering: 设置缓冲。encoding: 一般使用utf8。errors: 报错级别。newline: 区分换行符。closefd: 传入的file参数类型

  • 只读r  写入w  追加a  读写r+w+a+  二进制b  rb wb  ab ab+wb+  ab+f.read(size) 读取size的字符
  • f.readline(size)读取size行的字符
  • f.readlines()读取所有的字符

1.2 读写示例

直接读取f,此时f为迭代器,可用于大内容的文件读取打开和关闭一个只读文件

f = open("./hello/hello.txt" , 'r')
f.close()

//----------------------------

with  open(r'C:\Users\HBX\Documents\新建文件夹\baixi.txt' , 'r') as f:
    print (f.read())
 
    f.close()
    if f.close()==1:
        print ('sucess')
    else:
        print ('filue')

//----------------------------

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数:

  • file.close()  关闭文件。关闭后文件不能再进行读写操作。
  • file.flush()   刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
  • file.next()   返回文件下一行。
  • file.read([size])  从文件读取指定的字节数,如果未给定或为负则读取所有。
  • file.readline([size])  读取整行,包括 "\n" 字符。
  • file.readlines([sizeint])  读取所有行并返回列表,若给定sizeint>0,则是设置一次读多少字节,这是为了减轻读取压力。
  • file.seek(offset[, whence])  设置文件当前位置
  • file.tell()  返回文件当前位置。
  • file.write(str)  将字符串写入文件,返回的是写入的字符长度。
  • file.writelines(sequence)   向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。
# 1.将A文件复制到B文件中去(保持原来格式)
def copy_file (inputFile, outputFile, encoding):
    fin = open(inputFile, 'r', encoding=encoding) #以读的方式打开文件
    fout = open(outputFile, 'w', encoding=encoding) #以写得方式打开文件
    for eachLiine in fin.readlines(): #读取文件的每一行
        line = eachLiine.strip() #去除每行的首位空格
        fout.write(line + '\n')
    fin.close()
    fout.close()
 
# 2. 读取文件中的内容,返回List列表 (加载本地词典库)
def read_file_list(inputFile, encoding):
    results = []
    fin = open(inputFile, 'r', encoding=encoding)
    for eachLiine in fin.readlines():
        line = eachLiine.strip().replace('\ufeff', '')
        results.append(line)
    fin.close()
    return results
 
# 3.读取文件,返回文件内容
def read_file(path):
    with open(path, 'r+', encoding='UTF-8') as f:
        str = f.read()
    return str.strip().replace('\ufeff', '')
 
def func():
    pass
 
 
if __name__ == '__main__':
    copy_file('../data/test1.txt', '../data/text.txt','UTF-8')
    contents = read_file_list('../dict/time.dict','UTF-8')
    print(contents)

1.3 txt的读写操作

1.3.1 文件的打开的两种方式

f = open("data.txt","r")   #设置文件对象
f.close() #关闭文件

//------------------------

#为了方便,避免忘记close掉这个文件对象,可以用下面这种方式替代
with open('data.txt',"r") as f:    #设置文件对象
    str = f.read()    #可以是随便对文件的操作

1.3.2 读取的三种方式

1.简单的将文件读取到字符串中

 f = open("data.txt","r")   #设置文件对象
 str = f.read()     #将txt文件的所有内容读入到字符串str中
 f.close()   #将文件关闭

2.按行读取整个文件

#第一种方法
f = open("data.txt","r")   #设置文件对象
line = f.readline()
line = line[:-1]
while line:             #直到读取完文件
    line = f.readline()  #读取一行文件,包括换行符
    line = line[:-1]     #去掉换行符,也可以不去
f.close() #关闭文件


#第二种方法
data = []
for line in open("data.txt","r"): #设置文件对象并读取每一行文件
    data.append(line)               #将每一行文件加入到list中


#第三种方法
f = open("data.txt","r")   #设置文件对象
data = f.readlines()  #直接将文件中按行读到list里,效果与方法2一样
f.close()             #关闭文件

3.将文件读入数组中

import numpy as np
data = np.loadtxt("data.txt")   #将文件中数据加载到data数组里

1.3.3 txt 的写操作

1.单层列表

1 data = ['a','b','c']
2 #单层列表写入文件
3 with open("data.txt","w") as f:
4     f.writelines(data)

2.双层列表

#双层列表写入文件

#第一种方法,每一项用空格隔开,一个列表是一行写入文件
data =[ ['a','b','c'],['a','b','c'],['a','b','c']]
with open("data.txt","w") as f:                                                   #设置文件对象
    for i in data:                                                                 #对于双层列表中的数据
        i = str(i).strip('[').strip(']').replace(',','').replace('\'','')+'\n'  #将其中每一个列表规范化成字符串
        f.write(i)                                                                 #写入文件


#第二种方法,直接将每一项都写入文件
data =[ ['a','b','c'],['a','b','c'],['a','b','c']]
with open("data.txt","w") as f:                                                   #设置文件对象
    for i in data:                                                                 #对于双层列表中的数据
        f.writelines(i)                                                            #写入文件

3.数据写入


#将数组写入文件
import numpy as np
 
#第一种方法
np.savetxt("data.txt",data)     #将数组中数据写入到data.txt文件
#第二种方法
np.save("data.txt",data)        #将数组中数据写入到data.txt文件

二、画图

Python 画图主要是调用 matplotlib

本文作为学习过程中对matplotlib一些常用知识点的整理,方便查找。

2.0 matplotlib图标正常显示中文

为了在图表中能够显示中文和负号等,需要下面一段设置:

import matplotlib.pyplot as plt

plt.rcParams['font.sas-serig']=['SimHei'] #用来正常显示中文标签

plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

若报错:`Font family [‘sans-serif‘] not found.Falling back to DejaVu Sans.`

  • python中找存放路径:

    • python3.5

    • import matplotlib

    • print(matplotlib.matplotlib_fname())

      • /home/megvii/.local/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

      • 得到想要的路径:

      • /home/megvii/.local/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf

  • 将下载好的 SimHei拷过去:

    • mv SimHei.ttf /home/megvii/.local/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf/

  • 修改配置文件:

    • vim /home/megvii/.local/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

    • font.family         : sans-serif   
      font.sans-serif     : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif  
      axes.unicode_minus  : False

  • 删除缓存

    • 得到缓存目录:

      • matplotlib.get_cachedir()

        • '/home/megvii/.cache/matplotlib'

    • 删除:

      • rm -rf /home/megvii/.cache/matplotlib/

下载:https://www.fontpalace.com/font-download/SimHei/

2.1 为项目设置matplotlib参数

在代码执行过程中,有两种方式更改参数:

使用参数字典(rcParams)
调用matplotlib.rc()命令 通过传入关键字元祖,修改参数
如果不想每次使用matplotlib时都在代码部分进行配置,可以修改matplotlib的文件参数。可以用matplot.get_config()命令来找到当前用户的配置文件目录
配置文件包括以下配置项:

  1. axex: 设置坐标轴边界和表面的颜色、坐标刻度值大小和网格的显示
  2. backend: 设置目标暑促TkAgg和GTKAgg
  3. figure: 控制dpi、边界颜色、图形大小、和子区( subplot)设置
  4. font: 字体集(font family)、字体大小和样式设置
  5. grid: 设置网格颜色和线性
  6. legend: 设置图例和其中的文本的显示
  7. line: 设置线条(颜色、线型、宽度等)和标记
  8. patch: 是填充2D空间的图形对象,如多边形和圆。控制线宽、颜色和抗锯齿设置等。
  9. savefig: 可以对保存的图形进行单独设置。例如,设置渲染的文件的背景为白色。
  10. verbose: 设置matplotlib在执行期间信息输出,如silent、helpful、debug和debug-annoying。
  11. xticks和yticks: 为x,y轴的主刻度和次刻度设置颜色、大小、方向,以及标签大小。

线条标记

标记maker描述标记描述
‘o’圆圈‘.’
‘D’菱形‘s’正方形
‘h’六边形1‘*’星号
‘H’六边形2‘d’小菱形
‘_’水平线‘v’一角朝下的三角形
‘8’八边形‘<’一角朝左的三角形
‘p’五边形‘>’一角朝右的三角形
‘,’像素‘^’一角朝上的三角形
‘+’加号‘\竖线
‘None’,’’,’ ‘‘x’X

颜色

可以通过调用matplotlib.pyplot.colors()得到matplotlib支持的所有颜色。

别名颜色别名颜色
b蓝色g绿色
r红色y黄色
c青色k黑色
m洋红色w白色

如果这两种颜色不够用,还可以通过两种其他方式来定义颜色值:

  • 使用HTML十六进制字符串 color='eeefff' 使用合法的HTML颜色名字(’red’,’chartreuse’等)。
  • 也可以传入一个归一化到[0,1]的RGB元祖。 color=(0.3,0.3,0.4)

背景色

  • 通过向如matplotlib.pyplot.axes()或者matplotlib.pyplot.subplot()这样的方法提供一个axisbg参数,可以指定坐标这的背景色。
  • subplot(111,axisbg=(0.1843,0.3098,0.3098)

基础

如果你向plot()指令提供了一维的数组或列表,那么matplotlib将默认它是一系列的y值,并自动为你生成x的值。默认的x向量从0开始并且具有和y同样的长度,因此x的数据是[0,1,2,3].

图片来自:绘图: matplotlib核心剖析

2.2 绘图信息

2.2.1 确定坐标范围

plt.axi s([xmin, xmax, ymin, ymax])

上面例子里的axis()命令给定了坐标范围。

xlim(xmin, xmax)ylim(ymin, ymax)来调整x,y坐标范围

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
 
x = np.arange(-5.0, 5.0, 0.02)
y1 = np.sin(x)
 
plt.figure(1)
plt.subplot(211)
plt.plot(x, y1)
 
plt.subplot(212)
#设置x轴范围
xlim(-2.5, 2.5)
#设置y轴范围
ylim(-1, 1)
plt.plot(x, y1)

2.2.2  叠加图

import numpy as np
import matplotlib.pyplot as plt
 
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
 
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

2.2.3 产生多张图

行+列+第几张图

你可以多次使用figure命令来产生多个图,其中,图片号按顺序增加。这里,要注意一个概念当前图和当前坐标。所有绘图操作仅对当前图和当前坐标有效。通常,你并不需要考虑这些事,下面的这个例子为大家演示这一细节。

figure感觉就是给图像ID,之后可以索引定位到它。

import matplotlib.pyplot as plt
plt.figure(1)                # 第一张图
plt.subplot(211)             # 第一张图中的第一张子图
plt.plot([1,2,3])
plt.subplot(212)             # 第一张图中的第二张子图
plt.plot([4,5,6])
 
 
plt.figure(2)                # 第二张图
plt.plot([4,5,6])            # 默认创建子图subplot(111)
 
plt.figure(1)                # 切换到figure 1 ; 子图subplot(212)仍旧是当前图
plt.subplot(211)             # 令子图subplot(211)成为figure1的当前图
plt.title('Easy as 1,2,3')   # 添加subplot 211 的标题

2.2.4 plt.text()添加文字说明

  • text()可以在图中的任意位置添加文字,并支持LaTex语法
  • xlable(), ylable()用于添加x轴和y轴标签
  • title()用于添加图的题目
import numpy as np
import matplotlib.pyplot as plt
 
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
 
# 数据的直方图
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
 
 
plt.xlabel('Smarts')
plt.ylabel('Probability')
#添加标题
plt.title('Histogram of IQ')
#添加文字
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

2.2.5 plt.annotate()文本注释

import numpy as np
import matplotlib.pyplot as plt
 
ax = plt.subplot(111)
 
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
 
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )
 
plt.ylim(-2,2)
plt.show()

在数据可视化的过程中,图片中的文字经常被用来注释图中的一些特征。使用annotate()方法可以很方便地添加此类注释。在使用annotate时,要考虑两个点的坐标:被注释的地方xy(x, y)和插入文本的地方xytext(x, y)。DataHub-Python 数据可视化入门1

2.2.6 plt.xticks()/plt.yticks()设置轴记号

当我们设置记号的时候,我们可以同时设置记号的标签。注意这里使用了 LaTeX。Matplotlib 教程

# 导入 matplotlib 的所有内容(nympy 可以用 np 这个名字来使用)
from pylab import *
 
# 创建一个 8 * 6 点(point)的图,并设置分辨率为 80
figure(figsize=(8,6), dpi=80)
 
# 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块)
subplot(1,1,1)
 
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
 
# 绘制余弦曲线,使用蓝色的、连续的、宽度为 1 (像素)的线条
plot(X, C, color="blue", linewidth=1.0, linestyle="-")
 
# 绘制正弦曲线,使用绿色的、连续的、宽度为 1 (像素)的线条
plot(X, S, color="r", lw=4.0, linestyle="-")
 
plt.axis([-4,4,-1.2,1.2])
# 设置轴记号
 
xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
       [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
 
yticks([-1, 0, +1],
       [r'$-1$', r'$0$', r'$+1$'])
# 在屏幕上显示
show()

2.2.7 plt.subplot()

plt.subplot(2,3,1)表示把图标分割成2*3的网格。也可以简写plt.subplot(231)。其中,第一个参数是行数,第二个参数是列数,第三个参数表示图形的标号。

2.2.8 plt.axes()

我们先来看什么是Figure和Axes对象。在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个,或者多个Axes对象。每个Axes对象都是一个拥有自己坐标系统的绘图区域。其逻辑关系如下^3:

plt.axes-官方文档

axes() by itself creates a default full subplot(111) window axis.
axes(rect, axisbg=’w’) where rect = [left, bottom, width, height] in normalized (0, 1) units. axisbg is the background color for the axis, default white.
axes(h) where h is an axes instance makes h the current axis. An Axes instance is returned.
rect=[左, 下, 宽, 高] 规定的矩形区域,rect矩形简写,这里的数值都是以figure大小为比例,因此,若是要两个axes并排显示,那么axes[2]的左=axes[1].左+axes[1].宽,这样axes[2]才不会和axes[1]重叠。
 

http://matplotlib.org/examples/pylab_examples/axes_demo.html
 
import matplotlib.pyplot as plt
import numpy as np
 
# create some data to use for the plot
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05)               # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt  # colored noise
 
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Gaussian colored noise')
 
# this is an inset axes over the main axes
a = plt.axes([.65, .6, .2, .2], axisbg='y')
n, bins, patches = plt.hist(s, 400, normed=1)
plt.title('Probability')
plt.xticks([])
plt.yticks([])
 
# this is another inset axes over the main axes
a = plt.axes([0.2, 0.6, .2, .2], axisbg='y')
plt.plot(t[:len(r)], r)
plt.title('Impulse response')
plt.xlim(0, 0.2)
plt.xticks([])
plt.yticks([])
 
plt.show()

2.2.9 保存

  • plt.save("path.png")
  • plt.close()  # 不然画图时在原图上绘制

2.3 绘图案例

2.3.1 绘制线

import matplotlib.pyplot as plt
#plt.plot([1,2,3,4])
plt.plot([1,2,3,4],[1,4,9,16])
plt.ylabel("some numbers")
plt.show()

2.3.2 操纵坐标轴和增加网格及标签的函数

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
 
np.random.seed(1000)
y = np.random.standard_normal(10)
plt.plot(y.cumsum())
plt.grid(True) ##增加格点
plt.axis('tight') # 坐标轴适应数据量 axis 设置坐标轴
plt.show()

2.3.3 绘制点

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16],"ro")
plt.ylabel("some numbers")
plt.axis([0,6,0,20])
plt.show()

2.3.4 追加图

import matplotlib.pyplot as plt
import numpy as np
#evenly samply time at 200ms intervals
t =np.arange(0.,5.,0.2)
plt.plot(t,t,"r--",t,t*t,"g^",t,t*t*t,"bs")
plt.ylabel("some numbers")
plt.axis([0,6,0,20])
plt.show()

2.3.5 子图+柱状+点+线

#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.rcParams['font.family'] = 'SimHei'

# 配置图片的比例,x,y
plt.figure(figsize=(9, 3))

N = 5
y = [20, 10, 30, 25, 15]
#x = np.arange(N)
x = [1,2,3,4,5]

#图分为 3,1   3行
plt.subplot(1,3,1)
p1 = plt.bar(x, height=y, width=0.5,)  # 条形图
plt.subplot(1,3,2)
plt.scatter(x,y)	#点
plt.subplot(1,3,3)
plt.plot(x, y)		#线
plt.suptitle('Categorical Plotting')  # 抬头


plt.show()

2.3.6 多个子图

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure()

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)


# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)


# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()

2.3.7 多个图

#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.rcParams['font.family'] = 'SimHei'

# 配置图片的比例,x,y


N = 5
y = [20, 10, 30, 25, 15]
#x = np.arange(N)
x = [1,2,3,4,5]


plt.figure()
p1 = plt.bar(x, height=y, width=0.5,)  # 条形图

plt.figure()
plt.scatter(x,y)	#点

plt.figure()
plt.plot(x, y)		#线

plt.show()

2.4 核心函数

  1. 散点图 scatter
  2. 直方图 plt.hist
  3. 直方图 同一个图中堆叠
  4. 箱型图 boxplot

2.5 金融学图表 matplotlib.finance

1.烛柱图 candlestick

#!/etc/bin/python
#coding=utf-8
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
start = (2014, 5,1)
end = (2014, 7,1)
quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end)
# print quotes[:2]
 
fig, ax = plt.subplots(figsize=(8,5))
fig.subplots_adjust(bottom = 0.2)
mpf.candlestick(ax, quotes, width=0.6, colorup='b',colordown='r')
plt.grid(True)
ax.xaxis_date() #x轴上的日期
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(),rotation=30) #日期倾斜
plt.show()

2.plot_day_summary

该函数提供了一个相当类似的图标类型,使用方法和 candlestick 函数相同,使用类似的参数. 这里开盘价和收盘价不是由彩色矩形表示,而是由两条短水平线表示.

#!/etc/bin/python
#coding=utf-8
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
start = (2014, 5,1)
end = (2014, 7,1)
quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end)
# print quotes[:2]
 
fig, ax = plt.subplots(figsize=(8,5))
fig.subplots_adjust(bottom = 0.2)
mpf.plot_day_summary(ax, quotes,  colorup='b',colordown='r')
plt.grid(True)
ax.xaxis_date() #x轴上的日期
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(),rotation=30) #日期倾斜
plt.show()

3.股价数据和成交量

#!/etc/bin/python
#coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.finance as mpf
start = (2014, 5,1)
end = (2014, 7,1)
quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end)
# print quotes[:2]
 
quotes = np.array(quotes)
fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8,6))
mpf.candlestick(ax1, quotes, width=0.6,colorup='b',colordown='r')
ax1.set_title('Yahoo Inc.')
ax1.set_ylabel('index level')
ax1.grid(True)
ax1.xaxis_date()
plt.bar(quotes[:,0] - 0.25, quotes[:, 5], width=0.5)
 
ax2.set_ylabel('volume')
ax2.grid(True)
ax2.autoscale_view()
plt.setp(plt.gca().get_xticklabels(),rotation=30)
plt.show()

2.5 3D 绘图

#!/etc/bin/python
#coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
 
stike = np.linspace(50, 150, 24)
ttm = np.linspace(0.5, 2.5, 24)
stike, ttm = np.meshgrid(stike, ttm)
print  stike[:2]
 
iv = (stike - 100) ** 2 / (100 * stike) /ttm
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(9,6))
ax = fig.gca(projection='3d')
surf = ax.plot_surface(stike, ttm, iv, rstride=2, cstride=2, cmap=plt.cm.coolwarm, linewidth=0.5, antialiased=True)
ax.set_xlabel('strike')
ax.set_ylabel('time-to-maturity')
ax.set_zlabel('implied volatility')
 
plt.show()

3.参考

https://www.cnblogs.com/sakura3/p/8401240.html
https://www.cnblogs.com/zhizhan/p/5615947.html
https://www.cnblogs.com/chaoren399/p/5792168.html

  • 3
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值