<jupyter_start><jupyter_text>_*Pricing European Put Options*_   IntroductionSuppose a European put option with strike price $K$ and an underlying asset whose spot price at maturity $S_T$ follows a given random distribution.The corresponding payoff function is defined as:$$\max\{K - S_T, 0\}$$In the following, a quantum algorithm based on amplitude estimation is used to estimate the expected payoff, i.e., the fair price before discounting, for the option:$$\mathbb{E}\left[ \max\{K - S_T, 0\} \right]$$as well as the corresponding $\Delta$, i.e., the derivative of the option price with respect to the spot price, defined as:$$\Delta = -\mathbb{P}\left[S_T \leq K\right]$$The approximation of the objective function and a general introduction to option pricing and risk analysis on quantum computers are given in the following papers:- Quantum Risk Analysis. <NAME>. 2018.- Option Pricing using Quantum Computers. Stamatopoulos et al. 2019.<jupyter_code>import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np

from qiskit import Aer
from qiskit.aqua.algorithms import IterativeAmplitudeEstimation
from qiskit.aqua.components.uncertainty_models import LogNormalDistribution
from qiskit.aqua.components.uncertainty_problems import UnivariateProblem
from qiskit.aqua.components.uncertainty_problems import UnivariatePiecewiseLinearObjective as PwlObjective<jupyter_output><empty_output><jupyter_text>Uncertainty ModelWe construct a circuit factory to load a log-normal random distribution into a quantum state.The distribution is truncated to a given interval $[low, high]$ and discretized using $2^n$ grid points, where $n$ denotes the number of qubits used.The unitary operator corresponding to the circuit factory implements the following: $$\big|0\rangle_{n} \mapsto \big|\psi\rangle_{n} = \sum_{i=0}^{2^n-1} \sqrt{p_i}\big|i\rangle_{n},$$where $p_i$ denote the probabilities corresponding to the truncated and discretized distribution and where $i$ is mapped to the right interval using the affine map:$$ \{0, \ldots, 2^n-1\} \ni i \mapsto \frac{high - low}{2^n - 1} * i + low \in [low, high].$$<jupyter_code># number of qubits to represent the uncertainty
num_uncertainty_qubits = 3

# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity

# resulting parameters for log-normal distribution
mu = ((r - 0.5 * vol**2) * T + np.log(S))
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2/2)
variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)
stddev = np.sqrt(variance)

# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low  = np.maximum(0, mean - 3*stddev)
high = mean + 3*stddev

# construct circuit factory for uncertainty model
uncertainty_model = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma, low=low, high=high)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()<jupyter_output><empty_output><jupyter_text>Payoff FunctionThe payoff function decreases linearly with an increasing spot price at maturity $S_T$ until it reaches zero for a spot price equal to the strike price $K$, it stays constant to zero for larger spot prices.The implementation uses a comparator, that flips an ancilla qubit from $\big|0\rangle$ to $\big|1\rangle$ if $S_T \leq K$, and this ancilla is used to control the linear part of the payoff function.The linear part itself is then approximated as follows.We exploit the fact that $\sin^2(y + \pi/4) \approx y + 1/2$ for small $|y|$.Thus, for a given approximation scaling factor $c_{approx} \in [0, 1]$ and $x \in [0, 1]$ we consider$$ \sin^2( \pi/2 * c_{approx} * ( x - 1/2 ) + \pi/4) \approx \pi/2 * c_{approx} * ( x - 1/2 ) + 1/2 $$ for small $c_{approx}$.We can easily construct an operator that acts as $$\big|x\rangle \big|0\rangle \mapsto \big|x\rangle \left( \cos(a*x+b) \big|0\rangle + \sin(a*x+b) \big|1\rangle \right),$$using controlled Y-rotations.Eventually, we are interested in the probability of measuring $\big|1\rangle$ in the last qubit, which corresponds to$\sin^2(a*x+b)$.Together with the approximation above, this allows to approximate the values of interest.The smaller we choose $c_{approx}$, the better the approximation.However, since we are then estimating a property scaled by $c_{approx}$, the number of evaluation qubits $m$ needs to be adjusted accordingly.For more details on the approximation, we refer to:Quantum Risk Analysis. <NAME>. 2018.<jupyter_code># set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2.126

# set the approximation scaling for the payoff function
c_approx = 0.25

# setup piecewise linear objective fcuntion
breakpoints = [uncertainty_model.low, strike_price]
slopes = [-1, 0]
offsets = [strike_price - uncertainty_model.low, 0]
f_min = 0
f_max = strike_price - uncertainty_model.low
european_put_objective = PwlObjective(
    uncertainty_model.num_target_qubits, 
    uncertainty_model.low, 
    uncertainty_model.high,
    breakpoints,
    slopes,
    offsets,
    f_min,
    f_max,
    c_approx
)

# construct circuit factory for payoff function
european_put = UnivariateProblem(
    uncertainty_model,
    european_put_objective
)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, strike_price - x)
plt.plot(x, y, 'ro-')
plt.grid()
plt.title('Payoff Function', size=15)
plt.xlabel('Spot Price', size=15)
plt.ylabel('Payoff', size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price])
print('exact expected value:\t%.4f' % exact_value)
print('exact delta value:   \t%.4f' % exact_delta)<jupyter_output>exact expected value:	0.1709
exact delta value:   	-0.8193<jupyter_text>Evaluate Expected Payoff<jupyter_code># set target precision and confidence level
epsilon = 0.01
alpha = 0.05

# construct amplitude estimation 
ae = IterativeAmplitudeEstimation(epsilon=epsilon, alpha=alpha, a_factory=european_put)
result = ae.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100)
conf_int = np.array(result['confidence_interval'])
print('Exact value:        \t%.4f' % exact_value)
print('Estimated value:    \t%.4f' % (result['estimation']))
print('Confidence interval:\t[%.4f, %.4f]' % tuple(conf_int))<jupyter_output>Exact value:        	0.1709
Estimated value:    	0.1773
Confidence interval:	[0.1712, 0.1835]<jupyter_text>Evaluate DeltaThe Delta is a bit simpler to evaluate than the expected payoff.Similarly to the expected payoff, we use a comparator circuit and an ancilla qubit to identify the cases where $S_T \leq K$.However, since we are only interested in the (negative) probability of this condition being true, we can directly use this ancilla qubit as the objective qubit in amplitude estimation without any further approximation.<jupyter_code># setup piecewise linear objective fcuntion
breakpoints = [uncertainty_model.low, strike_price]
slopes = [0, 0]
offsets = [1, 0]
f_min = 0
f_max = 1
c_approx = 1
european_delta_objective = PwlObjective(
    uncertainty_model.num_target_qubits, 
    uncertainty_model.low, 
    uncertainty_model.high,
    breakpoints,
    slopes,
    offsets,
    f_min,
    f_max,
    c_approx
)

# construct circuit factory for payoff function
european_put_delta = UnivariateProblem(
    uncertainty_model,
    european_delta_objective
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05

# construct amplitude estimation 
ae_delta = IterativeAmplitudeEstimation(epsilon=epsilon, alpha=alpha, a_factory=european_put_delta)
result_delta = ae_delta.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100)
conf_int = -np.array(result_delta['confidence_interval'])[::-1]
print('Exact delta:    \t%.4f' % exact_delta)
print('Esimated value: \t%.4f' % -result_delta['estimation'])
print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10531865042174321, 'fraction_numerical': 0.021438612933458293, 'mean_word_length': 5.146148308135349, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '11295', 'license': 'Apache-2.0', 'n_tokens_mistral': 2834, 'n_tokens_neox': 2653, 'n_words': 903, 'path': 'tutorials/finance/04_european_put_option_pricing.ipynb', 'repo_name': 'prasad-kumkar/qiskit-tutorials', 'size': '8552'}