简体   繁体   中英

How do I call this function in python

I am relative new in python. I am trying to replicate some code that I have found in a book.
How do I call the def plot_values(function) . What am I supposed to insert as function when i try to call plot_values() ? I am getting the error

TypeError: plot_values() missing 1 required positional argument: 'function'

Here is the code I try to run:

import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.integrate import quad

mpl.rcParams['font.family'] = 'serif'

#
# Helper Functions
#


def dN(x):
    ''' Probability density function of standard normal random variable x. '''
    return math.exp(-0.5 * x ** 2) / math.sqrt(2 * math.pi)


def N(d):
    ''' Cumulative density function of standard normal random variable x. '''
    return quad(lambda x: dN(x), -20, d, limit=50)[0]


def d1f(St, K, t, T, r, sigma):
    ''' Black-Scholes-Merton d1 function.
        Parameters see e.g. BSM_Call function. '''
    d1 = (math.log(St / K) + (r + (0.5 * sigma ** 2)) * (T - t)) / (sigma * math.sqrt(T - t))
    return d1

#
# Valuation Functions
#


def BSM_call_value(St, K, t, T, r, sigma):
    ''' Calculates Black-Scholes-Merton European call option value.
    Parameters
    ==========
    St : float
        stock/index level at time t
    K : float
        strike price
    t : float
        valuation date
    T : float
        date of maturity/time-to-maturity if t = 0; T > t
    r : float
        constant, risk-less short rate
    sigma : float
        volatility
    Returns
    =======
    call : float
        European call present value at t
    '''
    d1 = d1f(St, K, t, T, r, sigma)
    d2 = d1 - sigma * math.sqrt(T - t)
    call = St * N(d1) - math.exp(-r * (T - t)) * K * N(d2)
    print(call)
    return call


def BSM_put_value(St, K, t, T, r, sigma):
    ''' Calculates Black-Scholes-Merton European put option value.
    Parameters
    ==========
    St : float
        stock/index level at time t
    K : float
        strike price
    t : float
        valuation date
    T : float
        date of maturity/time-to-maturity if t = 0; T > t
    r : float
        constant, risk-less short rate
    sigma : float
        volatility
    Returns
    =======
    put : float
        European put present value at t
    '''
    put = (BSM_call_value(St, K, t, T, r, sigma) -
           St + math.exp(-r * (T - t)) * K)
    return put


#
# Plotting European Option Values
#


def plot_values(function):
    ''' Plots European option values for different parameters c.p. '''
    plt.figure(figsize=(10, 8.3))
    points = 100
    #
    # Model Parameters
    #
    St = 100.0  # index level
    K = 100.0  # option strike
    t = 0.0  # valuation date
    T = 1.0  # maturity date
    r = 0.05  # risk-less short rate
    sigma = 0.2  # volatility

    # C(K) plot
    plt.subplot(221)
    klist = np.linspace(80, 120, points)
    vlist = [function(St, K, t, T, r, sigma) for K in klist]
    plt.plot(klist, vlist)
    plt.xlabel('strike $K$')
    plt.ylabel('present value')

    # C(T) plot
    plt.subplot(222)
    tlist = np.linspace(0.0001, 1, points)
    vlist = [function(St, K, t, T, r, sigma) for T in tlist]
    plt.plot(tlist, vlist)
    plt.xlabel('maturity $T$')

    # C(r) plot
    plt.subplot(223)
    rlist = np.linspace(0, 0.1, points)
    vlist = [function(St, K, t, T, r, sigma) for r in rlist]
    plt.plot(tlist, vlist)
    plt.xlabel('short rate $r$')
    plt.ylabel('present value')
    plt.axis('tight')

    # C(sigma) plot
    plt.subplot(224)
    slist = np.linspace(0.01, 0.5, points)
    vlist = [function(St, K, t, T, r, sigma) for sigma in slist]
    plt.plot(slist, vlist)
    plt.xlabel('volatility $\sigma$')
    plt.tight_layout()

St = 200.00
K = 210.00
t = 1/252
T = 1.00
r = 0.05
sigma = 0.10
BSM_call_value(St, K, t, T, r, sigma)
plot_values()

Your error TypeError: plot_values() missing 1 required positional argument: 'function' give you all the information you need.

plot_values() missing 1 required positional argument mean that you have to send another arguments to the function plot_values. The argument missing is a positional argument called function (positional because you don't have to pass it by keywords. eg. fonction= ).

You have to understand that in Python, everything is an object. You can do:

>>> print('a')
a
>>> my_print = print
>>> my_print('a')
a

This work because your variable my_print is now the function print with another name. And you can send a function like any other variable to a function.

print is a function, but you can manipulate this function like any other variable. See:

>>> print(print)
<built-in function print>

Here, I give to function print the same function as a positional argument, without parenthesis. So it behave like any other types, it print the return of the function str(print), function that try to convert the function into a string. Since it's not possible, it just return the type of the variable and the name.

In order to solve your problem, you should try:

plot_values(d1f)  # 8.057171421323943

or another functions that respect this definition :

def any_fun(St, K, t, T, r, sigma):

which include d1f , BSM_call_value and BSM_put_value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM