top of page
Yoga at Home

EXERCÍCIOS DE DERIVATIVOS

Falta um problema com EWMA, ARCH e GARCH.

Mini-Case: Bruce Honiball’s Invention

gibb river bank.png

Brealey, Myers and Allen,"Principles of Corporate Finance", 12th Ed., McGraw-Hill Education, 2017.

VaR Calculation for a PUT OPTION, a CALL OPTION and the PORTFOLIO

question 8 from Chapter 3 book Miller -

Question 8 from "Chapter 3 - Market Risk: Value at Risk" by M. B. Miller, “Quantitative Financial Risk Management”, Wiley, 2019.

O Problema de Comprar uma CALL OPTION
problema de derivativo para ARNEPy.png

Zvi Bodie, Alex Kane and Alan Marcus, "Investments", 11th Edition, McGraw-Hill, 2017.

Binomial Trees

#
# A popular numerical method to value options is the binomial option pricing model
# pioneered by Cox, Ross, and Rubinstein (1979). This method relies on
# representing the possible future evolution of an asset by a (recombining) tree.
#

 

#
# In this model, as in the Black-Scholes-Merton (1973) setup, there is a risky asset,
# an index or stock, and a riskless asset, a bond. The relevant time interval from
# today until the maturity of the option is divided, in general, into equidistant
# subintervals of length dt (Delta t). 
#

#
# The code that follows presents a Python implementation that creates a
# recombining tree based on some fixed numerical parameters for the model:
#

import math
import numpy as np
import numba
import time

S0 = 36. # Initial value of the risky asset.
T = 1.0 # Time horizon for the binomial tree simulation.
r = 0.06 # Constant short rate.

# Eu chamaria de constant risk-free interest rate, sendo em % per annum
sigma = 0.2 # Constant volatility factor. # Também em % per annum !!!

def simulate_tree(M):
    dt = T / M # Length of the time intervals.
    u = math.exp(sigma * math.sqrt(dt)) # Factors for the upward and downward movements.
    d = 1 / u # Factors for the upward and downward movements.
    S = np.zeros((M + 1, M + 1))
    S[0, 0] = S0
    z = 1
    for t in range(1, M + 1):
        for i in range(z):
            S[i, t] = S[i, t-1] * u
            S[i+1, t] = S[i, t-1] * d
        z = 1 + z
    return S

 

#
#
# Contrary to what happens in typical tree plots, an upward movement is
# represented in the ndarray object as a sideways movement, which decreases the
# ndarray size considerably:
#
#

np.set_printoptions(formatter={'float':lambda x: '%6.2f' % x})

simulate_tree(4)

#

# Out[99]: array([[ 36.00, 39.79, 43.97, 48.59, 53.71],
#                           [  0.00, 32.57, 36.00, 39.79, 43.97],
#                          [  0.00,   0.00, 29.47, 32.57, 36.00],
#                         [  0.00,   0.00,   0.00, 26.67, 29.47],
#                        [  0.00,   0.00,   0.00,   0.00, 24.13]])

#

start_time = time.time()
simulate_tree(500)
print("--- %s seconds ---" % (time.time() - start_time))

# CPU times: user 148 ms, sys: 4.49 ms, total: 152 ms
# Wall time: 154 ms

#
# With some trickery, such a binomial tree can be created with NumPy based on
# fully vectorized code:
#
# In the NumPy case, the code is a bit more compact.
#
# However, more importantly, NumPy vectorization achieves a speedup
# of an order of magnitude (Wall time: 154 ms and Wall time: 12.9 ms)

# while not using more memory:
#

def simulate_tree_np(M):
    dt = T / M
    up = np.arange(M + 1)
    up = np.resize(up, (M + 1, M + 1))
    down = up.transpose() * 2
    S = S0 * np.exp(sigma * math.sqrt(dt) * (up - down))
    # Tree for four time intervals (upper-right triangle of values)
   
# Ou seja, só importa a parte triangular superior direita da Matriz S
    return S

start_time = time.time()
simulate_tree_np(500)
print("--- %s seconds ---" % (time.time() - start_time))

# %time simulate_tree_np(500)
# Wall time: 3.95 ms

#

 

#

# Numba (dynamic compilation)
# This financial algorithm should be well suited to optimization through Numba
# dynamic compilation. And indeed, another speedup compared to the NumPy
# version of an order of magnitude is observed. This makes the Numba version
# orders of magnitude faster than the Python (or rather hybrid) version:
#

simulate_tree_nb = numba.jit(simulate_tree)

start_time = time.time()
simulate_tree_nb(500)
print("--- %s seconds ---" % (time.time() - start_time))

# %time simulate_tree_nb(500)
# Wall time: 992 µs

Yves Hilpisch,"Python for Finance: Mastering Data-Driven Finance", O'Reilly Media, 2 edition, January 8, 2019.

Python Program by GPT-4 (on 26 mar 2024) for valuation of European call option in Black-Scholes-Merton model

import numpy as np
from scipy.stats import norm

def black_scholes_call(S, K, T, r, sigma):
    """
    Calculates the Black-Scholes call option price.
    
    Parameters:
    S (float): current price of the underlying asset
    K (float): strike price of the option
    T (float): time to expiration in years
    r (float): risk-free interest rate
    sigma (float): volatility of the underlying asset's returns
    
    Returns:
    float: price of the call option
    """
    d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    call_price = (S * norm.cdf(d1, 0.0, 1.0) - K * np.exp(-r * T) * norm.cdf(d2, 0.0, 1.0))
    return call_price

#end def

 

# Example parameters
 

S = 100   # Current price of the asset
K = 105   # Strike price
T = 1     # Time to expiration in years
r = 0.05  # Risk-free interest rate
sigma = 0.2  # Volatility

 

call_option_price = black_scholes_call(S, K, T, r, sigma)
 

print(f"Call Option Price: {call_option_price}")
 

Monte Carlo valuation of European call option in Black-Scholes-Merton model

#
# Monte Carlo valuation of European call option
# in Black-Scholes-Merton model
# bsm_mcs_euro.py
#

 

#
# Python for Finance, 2nd ed.
# (c) Dr. Yves J. Hilpisch
#

 

import math
import numpy as np

 

# Parameter Values
S0 = 100. # initial index level
K = 105. # strike price
T = 1.0 # time-to-maturity
r = 0.05 # riskless short rate
sigma = 0.2 # volatility
I = 100000 # number of simulations

 

# Valuation Algorithm
z = np.random.standard_normal(I) # pseudo-random numbers

 

# index values at maturity
ST = S0 * np.exp((r - 0.5 * sigma ** 2) * T + sigma * math.sqrt(T) * z)
hT = np.maximum(ST - K, 0) # payoff at maturity

 

C0 = math.exp(-r * T) * np.mean(hT) # Monte Carlo estimator

#É o Cálculo do Valor Presente usando uma taxa de juros "continuously compounded" !

# Result Output
print('Value of the European call option %5.3f.' % C0)

 

Yves Hilpisch,"Python for Finance: Mastering Data-Driven Finance", O'Reilly Media, 2 edition, January 8, 2019.

Problema 22.20 do final do “Capítulo 22 - Value at Risk and Expected Shortfall” do Livro do John C. Hull.

22.20. - A bank has written a call option on one stock and a put option on another stock. For the first option the stock price is 50, the strike price is 51, the volatility is 28% per annum, and the time to maturity is 9 months. For the second option the stock price is 20, the strike price is 19, the volatility is 25% per annum, and the time to maturity is 1 year. Neither stock pays a dividend, the risk-free rate is 6% per annum, and the correlation between stock price returns is 0.4. Calculate a 10-day 99% VaR !

Problema 26.27 do final do “Capítulo 26 - Exotic options” do Livro do John C. Hull.

26.27. - Consider an up-and-out barrier call option on a non-dividend-paying stock when the stock price is 50, the strike price is 50, the volatility is 30%, the risk-free rate is 5%, the time to maturity is 1 year, and the barrier at $80. Use the DerivaGem software to value the option and graph the relationship between (a) the option price and the stock price, (b) the delta and the stock price, (c) the option price and the time to maturity, and (d) the option price and the volatility. Provide an intuitive explanation for the results you get. Show that the delta, gamma, theta, and vega for an up-and-out barrier call option can be either positive or negative.

bottom of page