Example 3: Mathematical Simulation

Overview

This example explores using Artemis to document a Black Scholes mathematical simulation.

Code

import numpy as np 
import scipy.stats as stats

# @card title="Overview" side-color=rgb(0,255,0)
''' @blockdoc
## Black Scholes Calculator
This script computes the Black Scholes price of a European option:

$$C = N(d_1)S_t - N(d_2)Ke^{-rt}$$ 
where $$d_1 = \frac{log(S_t) + (r + \frac{1}{2}\sigma^2)t}{\sigma \sqrt{t}}$$ and $$d_2 = d_1 - \sigma \sqrt{t}$$
'''

# @card title="Model Inputs" side-color=rgb(255,255,0)
# @doc Enter the current stock price $$S$$
# @input number data=S
# @doc Enter the strike price $$K$$
# @input number data=K
# @doc Enter the risk-free rate $$r$$
# @input number data=r

def black_scholes(S, K, r, sigma, tau):
    '''
    Computes the Black Scholes price of a European option
    '''
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * tau) / (sigma * np.sqrt(tau))
    d2 = d1 - sigma * np.sqrt(tau)
    return S * stats.norm.cdf(d1) - K * np.exp(-r * tau) * stats.norm.cdf(d2)

# Compute sweep of black scholes price data for different volatilities and times to maturity
black_scholes_values = []
sigma_values = []
tau_values = []
for sigma in np.linspace(0.1, 0.5, num=10):
    for tau in np.linspace(0.1, 1, num=10):
        black_scholes_values.append(black_scholes(S=100, K=100, r=0.05, sigma=sigma, tau=tau))
        sigma_values.append(sigma)
        tau_values.append(tau)

# @card title="Model Output" side-color=rgb(0,0,255)
# @doc #### Price of a European Option vs Volatility
# @output line_graph_x_y_z title="Price of a European Option" ylabel="Black Scholes Price" data-x=sigma_values data-y=tau_values data-z=black_scholes_values

Result


Did this page help you?