我对Python来说还很陌生,正在尝试创建一个具有三个功能的期权定价类:调用,放置和图形。 call和put函数可以正常工作,但是我无法弄清楚graph函数。我希望p.append从调用函数中获取值,保持除S0等于i之外的所有变量不变。
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class Option():
def __init__(self, S0, K, T, r, sigma, start, stop, N):
self.S0 = S0
self.K = K
self.T = T
self.r = r
self.sigma = sigma
self.start = start
self.stop = stop
self.N = N
def call(self):
d1 = (np.log(self.S0/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (self.S0 * norm.cdf(d1, 0.0, 1.0) - \
self.K * np.exp(-self.r * self.T) * norm.cdf(d2, 0.0, 1.0))
return price
def put(self):
d1 = (np.log(self.S0/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (self.K * np.exp(-self.r * self.T) * norm.cdf(-d2, 0.0, 1.0) - \
self.S0 * norm.cdf(-d1, 0.0, 1.0))
return price
def graphCall(self):
S = np.linspace(self.start, self.stop, self.N)
p = []
for i in S:
p.append()
plt.plot(S, p)
x = Option(100, 50, 3, 0.05, 0.40, 100, 200, 500)
print(x.call())
x.graphCall()
答案 0 :(得分:0)
您可以决定将self.S0
用作调用call
和put
的默认值,但也可以使用其他参数。
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class Option():
def __init__(self, S0, K, T, r, sigma, start, stop, N):
self.S0 = S0
self.K = K
self.T = T
self.r = r
self.sigma = sigma
self.start = start
self.stop = stop
self.N = N
def call(self, s=None):
if s is None:
s=self.S0
d1 = (np.log(s/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (s * norm.cdf(d1, 0.0, 1.0) - \
self.K * np.exp(-self.r * self.T) * norm.cdf(d2, 0.0, 1.0))
return price
def put(self, s=None):
if s is None:
s=self.S0
d1 = (np.log(s/self.K) + \
(self.r + 0.5*self.sigma**2)*self.T)/(self.sigma*np.sqrt(self.T))
d2 = d1 - self.sigma*np.sqrt(self.T)
price = (self.K * np.exp(-self.r * self.T) * norm.cdf(-d2, 0.0, 1.0) - \
s * norm.cdf(-d1, 0.0, 1.0))
return price
def graphCall(self):
S = np.linspace(self.start, self.stop, self.N)
plt.plot(S, self.call(S))
plt.show()
x = Option(100, 50, 3, 0.05, 0.40, 100, 200, 500)
print(x.call())
x.graphCall()