这是python代码的附件:
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
import math
def V(S0):
# nx = norm.cdf(x)
K = 1.5
T = 1
sigma = 0.1
rd = 0.03
ry = 0.02
e = math.e
d1 = (math.log((S0 * e ** ((rd - ry) * T)) / K) + (sigma ** 2 * T) / 2) / (sigma * math.sqrt(T))
d2 = (math.log((S0 * e ** ((rd - ry) * T)) / K) - (sigma ** 2 * T) / 2) / (sigma * math.sqrt(T))
nd1 = norm.cdf(d1)
nd2 = norm.cdf(d2)
V = e ** (-rd * T) * (S0 * e ** ((rd - ry) * T) * nd1 - K * nd2)
V2 = np.vectorize(V)
S0 = np.arange(1, 1000, 1)
plt.title('V as a function of S0')
plt.xlabel('S0')
plt.ylabel('V')
plt.plot(S0, V2(S0))
plt.show()
结果是这样的代码:
我该如何解决?
答案 0 :(得分:1)
math.log
仅接受大小为1的数组
math
模块并切换到numpy
方法V
不返回任何内容
return V
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
def V(S0):
# nx = norm.cdf(x)
K = 1.5
T = 1
sigma = 0.1
rd = 0.03
ry = 0.02
e = np.e
d1 = (np.log((S0 * e ** ((rd - ry) * T)) / K) + (sigma ** 2 * T) / 2) / (sigma * np.sqrt(T))
d2 = (np.log((S0 * e ** ((rd - ry) * T)) / K) - (sigma ** 2 * T) / 2) / (sigma * np.sqrt(T))
nd1 = norm.cdf(d1)
nd2 = norm.cdf(d2)
V = e ** (-rd * T) * (S0 * e ** ((rd - ry) * T) * nd1 - K * nd2)
return V # return V added
V2 = np.vectorize(V)
S0 = np.arange(1, 1000, 1)
plt.title('V as a function of S0')
plt.xlabel('S0')
plt.ylabel('V')
plt.plot(S0, V2(S0))
plt.show()