简体   繁体   English

为 Python 中的期权定价绘制蒙特卡洛模拟

[英]Plotting Monte Carlo Simulations for option pricing in Python

I am trying to show the monte carlo barrier prices for different number of simultations in the x axis.我试图在 x 轴上显示不同模拟次数的蒙特卡洛障碍价格。 This is what i tried so far but i'm getting the error -> ValueError: x and y must have same first dimension, but have shapes (10,) and (5,).到目前为止,这是我尝试过的方法,但出现错误 -> ValueError:x 和 y 必须具有相同的第一维,但形状为 (10,) 和 (5,)。 I am new to python and as hard as i try i cannot find the error我是 python 的新手,尽管我很努力,但我找不到错误

import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt

def mc_single_barrier_do(S0, K, T, H, r, vol, N, M):

    # Constants
    dt = T / N  # change in time
    nudt = (r - 0.5 * vol ** 2) * dt  # deterministic component
    volsdt = vol * np.sqrt(dt)  # diffusion coefficient
    erdt = np.exp(r * dt)  # discount factor

     # Standard Error Placeholders
    sum_CT = 0
    sum_CT2 = 0
     # Monte Carlo Method
    for i in range(M):

        # Barrier Crossed Flag
        BARRIER = False
        St = S0

        for j in range(N):
            epsilon = np.random.normal()
            Stn = St * np.exp(nudt + volsdt * epsilon)
            St = Stn
            Ptn = np.exp(-2. * (H - St) * (H - Stn) / (St ** 2. * volsdt ** 2.))
            Pt = Ptn
            if Pt >= npr.uniform():
                BARRIER = True
        if np.amin(St) > H and BARRIER == False:
            CT = np.maximum(St - K, 0)

        else:
            CT = 0.

        sum_CT = sum_CT + CT
        sum_CT2 = sum_CT2 + CT * CT

    C0_MC = np.exp(-r * T) * sum_CT / M
    return C0_MC


def sim_iterator(max_sample, N, S0, T, r, vol, K, H, method):

    assert (method in ['MC', 'AV', 'CV'])
    
    mean_payoffs = np.zeros(int(np.ceil(max_sample / 10)))
    
    if method == 'MC':
        for n_sample in range(10, max_sample + 1, 10):
            payoffs = mc_single_barrier_do(n_sample, S0, K, T, H, r, vol, N)
            mean_payoffs[int(n_sample / 10 - 1)] = np.mean(payoffs)
        
    return mean_payoffs

r = 0.1
vol = 0.2
T = 2
N = 20
dt = T / N
S0 = 50
K = 50
H = 45
max_sample = 100

MC_price_estimates = sim_iterator(S0, T, r, vol, K, H, max_sample, N, method='MC')
x_axis1 = range(10, max_sample + 1, 10)
plt.plot(x_axis1, MC_price_estimates)
plt.xlabel("No. of Simulations")
plt.ylabel("Estimated option price")
plt.title("Ordinary Monte Carlo Method")
plt.legend()
plt.show()

in your function definition you used:在您使用的 function 定义中:

def sim_iterator(max_sample, N, S0, T, r, vol, K, H, method):

while when using the function you used:而在使用 function 时,您使用了:

MC_price_estimates = sim_iterator(S0, T, r, vol, K, H, max_sample, N, method='MC')

python has positional arguments, which means the arguments are mapped according to their position, not their name, so in the first position is mapped to the first argument, which means S0 in the second line was mapped to max_sample in the first line, just fix the arguments arrangement, or use keyword arguments S0=S0 . python 的位置是 arguments,这意味着 arguments 是根据它们的 position 映射的,而不是它们的名称,所以在第一个 position 被映射到第一个参数,这意味着第二行中的S0被映射到第一行中的max_sample ,只需修复arguments 排列,或使用关键字 arguments S0=S0

MC_price_estimates = sim_iterator(S0=S0, T=T, r=r, vol=vol, K=K, H=H, max_sample=max_sample, N=N, method='MC')

this is what your code will look like when you fix all arguments to be keyword arguments.当您将所有 arguments 固定为关键字 arguments 时,这就是您的代码的样子。

def mc_single_barrier_do(S0, K, T, H, r, vol, N, M):
    # Constants
    dt = T / N  # change in time
    nudt = (r - 0.5 * vol ** 2) * dt  # deterministic component
    volsdt = vol * np.sqrt(dt)  # diffusion coefficient
    erdt = np.exp(r * dt)  # discount factor

    # Standard Error Placeholders
    sum_CT = 0
    sum_CT2 = 0
    # Monte Carlo Method
    for i in range(M):

        # Barrier Crossed Flag
        BARRIER = False
        St = S0

        for j in range(N):
            epsilon = np.random.normal()
            Stn = St * np.exp(nudt + volsdt * epsilon)
            St = Stn
            Ptn = np.exp(-2. * (H - St) * (H - Stn) / (St ** 2. * volsdt ** 2.))
            Pt = Ptn
            if Pt >= npr.uniform():
                BARRIER = True
        if np.amin(St) > H and BARRIER == False:
            CT = np.maximum(St - K, 0)

        else:
            CT = 0.

        sum_CT = sum_CT + CT
        sum_CT2 = sum_CT2 + CT * CT

    C0_MC = np.exp(-r * T) * sum_CT / M
    return C0_MC

def sim_iterator(max_sample, N, S0, T, r, vol, K, H, method):
    assert (method in ['MC', 'AV', 'CV'])

    mean_payoffs = np.zeros(int(np.ceil(max_sample / 10)))

    if method == 'MC':
        for n_sample in range(10, max_sample + 1, 10):
            payoffs = mc_single_barrier_do(M=n_sample,S0= S0, K=K, T=T, H=H, r=r, vol=vol, N=N)
            mean_payoffs[int(n_sample / 10 - 1)] = np.mean(payoffs)

    return mean_payoffs


r = 0.1
vol = 0.2
T = 2
N = 20
dt = T / N
S0 = 50
K = 50
H = 45
max_sample = 100

MC_price_estimates = sim_iterator(S0=S0, T=T, r=r, vol=vol, K=K, H=H, max_sample=max_sample, N=N, method='MC')
x_axis1 = range(10, max_sample + 1, 10)
plt.plot(x_axis1, MC_price_estimates)
plt.xlabel("No. of Simulations")
plt.ylabel("Estimated option price")
plt.title("Ordinary Monte Carlo Method")
plt.legend()
plt.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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