为什么我的代码绘制的图形只显示空白?

时间:2020-07-26 00:45:34

标签: python matplotlib

这是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()

结果是这样的代码:

enter image description here

我该如何解决?

1 个答案:

答案 0 :(得分:1)

  • 有两个问题
    1. math.log仅接受大小为1的数组
      • 删除了math模块并切换到numpy方法
    2. 函数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()

enter image description here